CustomScpExplorer.cpp 400 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998
  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. FEditorManager = new TEditorManager();
  210. FEditorManager->OnFileChange = ExecutedFileChanged;
  211. FEditorManager->OnFileReload = ExecutedFileReload;
  212. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  213. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  214. FLocalEditors = new TList();
  215. FQueueStatus = NULL;
  216. FQueueStatusSection = new TCriticalSection();
  217. FQueueStatusInvalidated = false;
  218. FQueueItemInvalidated = false;
  219. FQueueStatusUpdating = false;
  220. FQueueActedItem = NULL;
  221. FQueueController = new TQueueController(QueueView3);
  222. FQueueScrollOnDragOver = new TListViewScrollOnDragOver(QueueView3, true);
  223. FUserActionTimer = new TTimer(this);
  224. FUserActionTimer->Enabled = false;
  225. FUserActionTimer->Interval = 10;
  226. FUserActionTimer->OnTimer = UserActionTimer;
  227. FNotes = new TStringList();
  228. FNoteTimer = new TTimer(this);
  229. FNoteTimer->Enabled = false;
  230. FNoteTimer->OnTimer = NoteTimer;
  231. FOnNoteClick = NULL;
  232. FOle32Library = LoadLibrary(L"Ole32.dll");
  233. FDragMoveCursor = FOle32Library != NULL ?
  234. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  235. UseSystemSettings(this);
  236. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  237. static_cast<TObject*>(GetComponent(fcTransferList)));
  238. DebugAssert(TransferList != NULL);
  239. FTransferListHoverIndex = -1;
  240. TransferList->OnChange = TransferListChange;
  241. TransferList->OnDrawItem = TransferListDrawItem;
  242. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))), true);
  243. SetSubmenu(NonVisualDataModule->ColorMenuItem, true);
  244. UseDesktopFont(SessionsPageControl);
  245. UpdateSessionsPageControlHeight();
  246. UseDesktopFont(RemoteDirView);
  247. UseDesktopFont(RemoteDriveView);
  248. UseDesktopFont(QueueView3);
  249. UseDesktopFont(QueueFileList);
  250. UseDesktopFont(QueueLabel);
  251. UseDesktopFont(RemoteStatusBar);
  252. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  253. QueueSplitter->ShowHint = true;
  254. reinterpret_cast<TLabel*>(QueueFileListSplitter)->OnDblClick = QueueFileListSplitterDblClick;
  255. QueueFileListSplitter->ShowHint = true;
  256. RemotePanelSplitter->ShowHint = true;
  257. UpdateImages();
  258. FCustomCommandMenu = CreateTBXPopupMenu(this);
  259. FCustomCommandLocalFileList = NULL;
  260. FCustomCommandRemoteFileList = NULL;
  261. FSessionColors = new TPngImageList(this);
  262. FSessionColors->ColorDepth = cd32Bit;
  263. AddFixedSessionImages();
  264. SessionsPageControl->Images = FSessionColors;
  265. UpdateQueueLabel();
  266. CheckStoreTransition();
  267. CreateHiddenWindow();
  268. StartUpdates();
  269. // Start loading drive data, so that they are ready once we need them for StartCreationDirectoryMonitorsOnEachDrive
  270. // (necessary for "explorer" only, as "commander" loads it for its drive menu)
  271. DriveInfo->NeedData();
  272. }
  273. //---------------------------------------------------------------------------
  274. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  275. {
  276. FInvalid = true;
  277. if (FClipboardTerminal != NULL)
  278. {
  279. ClipboardClear(); // implies ClipboardStop
  280. }
  281. // this has to be one of the very first things to do
  282. StopUpdateThread();
  283. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  284. TTerminalManager::Instance()->ScpExplorer = NULL;
  285. delete FCustomCommandLocalFileList;
  286. delete FCustomCommandRemoteFileList;
  287. delete FCustomCommandMenu;
  288. delete FTrayIcon;
  289. FTrayIcon = NULL;
  290. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  291. delete FEditorManager;
  292. ForceCloseLocalEditors();
  293. delete FLocalEditors;
  294. HideFileFindDialog();
  295. if (FDelayedDeletionTimer)
  296. {
  297. DoDelayedDeletion(NULL);
  298. SAFE_DESTROY(FDelayedDeletionTimer);
  299. }
  300. SAFE_DESTROY(FDelayedDeletionList);
  301. // sometimes we do not get DDEnd so the list is not released
  302. SAFE_DESTROY(FDDFileList);
  303. DebugAssert(FSynchronizeController == NULL);
  304. CloseHandle(FDDExtMutex);
  305. FDDExtMutex = NULL;
  306. FreeLibrary(FOle32Library);
  307. FOle32Library = NULL;
  308. FDragMoveCursor = NULL;
  309. DebugAssert(!FErrorList);
  310. if (FEverShown)
  311. {
  312. // when window is never shown (like when running command-line operation),
  313. // particularly window site is not restored correctly (BoundsRect value set
  314. // in RestoreForm gets lost during handle allocation), so we do not want
  315. // it to be stored
  316. StoreParams();
  317. }
  318. ManagedSession = NULL;
  319. Queue = NULL;
  320. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  321. NonVisualDataModule->ScpExplorer = NULL;
  322. delete FQueueScrollOnDragOver;
  323. FQueueScrollOnDragOver = NULL;
  324. delete FQueueController;
  325. FQueueController = NULL;
  326. delete FQueueStatusSection;
  327. FQueueStatusSection = NULL;
  328. delete FQueueStatus;
  329. FQueueStatus = NULL;
  330. delete FUserActionTimer;
  331. FUserActionTimer = NULL;
  332. delete FNoteTimer;
  333. delete FNotes;
  334. delete FNoteData;
  335. SAFE_DESTROY(FDocks);
  336. SessionsPageControl->Images = NULL;
  337. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  338. SAFE_DESTROY(FSessionColors);
  339. SAFE_DESTROY(FSessionsDragDropFilesEx);
  340. SAFE_DESTROY(FHistoryMenu[0][0]);
  341. SAFE_DESTROY(FHistoryMenu[0][1]);
  342. SAFE_DESTROY(FHistoryMenu[1][0]);
  343. SAFE_DESTROY(FHistoryMenu[1][1]);
  344. if (FHiddenWindow != NULL)
  345. {
  346. DestroyWindow(FHiddenWindow);
  347. FHiddenWindow = NULL;
  348. }
  349. }
  350. //---------------------------------------------------------------------------
  351. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  352. {
  353. std::unique_ptr<TSessionData> Data;
  354. if (!Session.IsEmpty())
  355. {
  356. bool DefaultsOnly;
  357. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  358. }
  359. TTerminalManager * Manager = TTerminalManager::Instance();
  360. for (int Index = 0; Index < Manager->Count; Index++)
  361. {
  362. TTerminal * Terminal = Manager->Sessions[Index];
  363. if (Session.IsEmpty() ||
  364. Manager->IsActiveTerminalForSite(Terminal, Data.get()))
  365. {
  366. if (Path.IsEmpty())
  367. {
  368. Terminal->ClearCaches();
  369. }
  370. else
  371. {
  372. Terminal->DirectoryModified(Path, true);
  373. }
  374. }
  375. }
  376. // We should flag a pending refresh for the background terminals or busy foreground terminals
  377. if (HasActiveTerminal() &&
  378. CanCommandLineFromAnotherInstance() &&
  379. (Session.IsEmpty() || Manager->IsActiveTerminalForSite(Terminal, Data.get())) &&
  380. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  381. {
  382. Terminal->ReloadDirectory();
  383. }
  384. }
  385. //---------------------------------------------------------------------------
  386. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  387. {
  388. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  389. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  390. size_t MessageSize = sizeof(TCopyDataMessage);
  391. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  392. if (Result)
  393. {
  394. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  395. Result = (Message.Version == TCopyDataMessage::Version1);
  396. if (Result)
  397. {
  398. switch (Message.Command)
  399. {
  400. case TCopyDataMessage::CommandCanCommandLine:
  401. Result = CanCommandLineFromAnotherInstance();
  402. if (Result)
  403. {
  404. AppLog(L"Can process command-line from other instance");
  405. }
  406. else
  407. {
  408. AppLog(L"Cannot process command-line from other instance");
  409. }
  410. break;
  411. case TCopyDataMessage::CommandCommandLine:
  412. {
  413. UnicodeString CommandLine(Message.CommandLine);
  414. Result = CommandLineFromAnotherInstance(CommandLine);
  415. }
  416. break;
  417. case TCopyDataMessage::RefreshPanel:
  418. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  419. break;
  420. case TCopyDataMessage::MainWindowCheck:
  421. Result = true;
  422. break;
  423. default:
  424. Result = false;
  425. break;
  426. }
  427. }
  428. }
  429. Message.Result = Result ? 1 : 0;
  430. }
  431. //---------------------------------------------------------------------------
  432. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  433. {
  434. WNDCLASS WindowClass = {0};
  435. WindowClass.lpfnWndProc = DefWindowProc;
  436. WindowClass.hInstance = HInstance;
  437. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  438. FHiddenWindow = NULL;
  439. if (RegisterClass(&WindowClass))
  440. {
  441. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  442. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  443. }
  444. }
  445. //---------------------------------------------------------------------------
  446. bool __fastcall TCustomScpExplorerForm::CanConsole()
  447. {
  448. return
  449. HasActiveTerminal() &&
  450. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  451. }
  452. //---------------------------------------------------------------------------
  453. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  454. {
  455. bool Result = Visible && !NonVisualDataModule->Busy;
  456. return Result;
  457. }
  458. //---------------------------------------------------------------------------
  459. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  460. const UnicodeString & CommandLine)
  461. {
  462. TProgramParams Params(CommandLine);
  463. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  464. if (Result)
  465. {
  466. NonVisualDataModule->StartBusy();
  467. try
  468. {
  469. // this action is initiated from another process,
  470. // so it's likely that our window is not visible,
  471. // and user won't see what is going on
  472. Application->BringToFront();
  473. // reload sessions as we may be asked to open a session
  474. // just stored by another instance
  475. StoredSessions->Reload();
  476. UnicodeString SessionName = Params.Param[1];
  477. std::unique_ptr<TObjectList> DataList(new TObjectList());
  478. try
  479. {
  480. UnicodeString DownloadFile; // unused
  481. int Flags = GetCommandLineParseUrlFlags(&Params);
  482. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  483. }
  484. catch (EAbort &)
  485. {
  486. // Happens when opening session in PuTTY and in other situations,
  487. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  488. // to process the command-line on its own (or to pass it to yet another instance)
  489. }
  490. if (DataList->Count > 0)
  491. {
  492. TTerminalManager * Manager = TTerminalManager::Instance();
  493. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  494. }
  495. }
  496. __finally
  497. {
  498. NonVisualDataModule->EndBusy();
  499. }
  500. }
  501. return Result;
  502. }
  503. //---------------------------------------------------------------------------
  504. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  505. {
  506. TManagedTerminal * Result;
  507. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  508. {
  509. Result = FManagedSession;
  510. }
  511. else
  512. {
  513. Result = NULL;
  514. }
  515. return Result;
  516. }
  517. //---------------------------------------------------------------------------
  518. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  519. {
  520. if (FManagedSession != value)
  521. {
  522. SessionChanging();
  523. DoSetManagedSession(value, false);
  524. }
  525. }
  526. //---------------------------------------------------------------------------
  527. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  528. {
  529. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  530. FManagedSession = value;
  531. {
  532. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect);
  533. FAllowTransferPresetAutoSelect = false;
  534. TAutoFlag SessionChangingFlag(FSessionChanging);
  535. SessionChanged(Replace);
  536. }
  537. if (Terminal != NULL)
  538. {
  539. TransferPresetAutoSelect();
  540. }
  541. // Update app and tab titles, prevented above by FSessionChanging.
  542. UpdateControls();
  543. }
  544. //---------------------------------------------------------------------------
  545. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  546. {
  547. DoSetManagedSession(value, true);
  548. }
  549. //---------------------------------------------------------------------------
  550. void __fastcall TCustomScpExplorerForm::SessionChanging()
  551. {
  552. if (ManagedSession != NULL)
  553. {
  554. UpdateSession(ManagedSession);
  555. }
  556. }
  557. //---------------------------------------------------------------------------
  558. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  559. {
  560. if (ManagedSession != NULL)
  561. {
  562. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  563. }
  564. if (!TTerminalManager::Instance()->Updating)
  565. {
  566. SessionListChanged();
  567. }
  568. if (Terminal != NULL)
  569. {
  570. TObject * State = NULL;
  571. if (WinConfiguration->PreservePanelState)
  572. {
  573. State = Terminal->RemoteExplorerState;
  574. DirView(osRemote)->AnnounceState(State);
  575. }
  576. try
  577. {
  578. if (Replaced)
  579. {
  580. RemoteDirView->ReplaceTerminal(Terminal);
  581. }
  582. else
  583. {
  584. RemoteDirView->Terminal = Terminal;
  585. }
  586. if (Terminal->Active)
  587. {
  588. Terminal->RefreshDirectory();
  589. }
  590. if (State != NULL)
  591. {
  592. DirView(osRemote)->RestoreState(State);
  593. }
  594. }
  595. __finally
  596. {
  597. DirView(osRemote)->AnnounceState(NULL);
  598. }
  599. }
  600. else
  601. {
  602. RemoteDirView->Terminal = NULL;
  603. }
  604. InitStatusBar();
  605. UpdateTransferList();
  606. // Update panels Enable state before refreshing the labels
  607. UpdateControls();
  608. }
  609. //---------------------------------------------------------------------------
  610. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  611. {
  612. if (Queue != value)
  613. {
  614. if (FQueue != NULL)
  615. {
  616. FQueue->OnListUpdate = NULL;
  617. FQueue->OnQueueItemUpdate = NULL;
  618. }
  619. FQueue = value;
  620. if (FQueue != NULL)
  621. {
  622. DebugAssert(FQueue->OnListUpdate == NULL);
  623. FQueue->OnListUpdate = QueueListUpdate;
  624. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  625. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  626. }
  627. QueueChanged();
  628. }
  629. }
  630. //---------------------------------------------------------------------------
  631. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  632. TListItem * Item)
  633. {
  634. if (FQueueActedItem == Item)
  635. {
  636. FQueueActedItem = NULL;
  637. if ((QueueView3->PopupMenu != NULL) &&
  638. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  639. {
  640. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  641. ReleaseCapture();
  642. }
  643. }
  644. if (Item->Data == FPendingQueueActionItem)
  645. {
  646. FPendingQueueActionItem = NULL;
  647. }
  648. }
  649. //---------------------------------------------------------------------------
  650. bool TCustomScpExplorerForm::IsAnythingQueued()
  651. {
  652. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  653. }
  654. //---------------------------------------------------------------------------
  655. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  656. {
  657. {
  658. TGuard Guard(FQueueStatusSection);
  659. FQueueStatusInvalidated = false;
  660. if (FQueue != NULL)
  661. {
  662. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  663. }
  664. }
  665. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  666. {
  667. FMaxQueueLength = FQueueStatus->Count;
  668. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  669. }
  670. {
  671. TAutoFlag Flag(FQueueStatusUpdating);
  672. FQueueController->UpdateQueueStatus(FQueueStatus);
  673. }
  674. UpdateQueueFileList();
  675. SetQueueProgress();
  676. UpdateQueueView();
  677. bool IsEmpty = !IsAnythingQueued();
  678. if (IsEmpty && (Terminal != NULL))
  679. {
  680. TOnceDoneOperation OnceDoneOperation =
  681. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  682. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  683. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  684. {
  685. FQueue->Enabled = false;
  686. }
  687. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  688. {
  689. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  690. }
  691. }
  692. }
  693. //---------------------------------------------------------------------------
  694. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  695. {
  696. UnicodeString Result;
  697. if (FQueueStatus != NULL)
  698. {
  699. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  700. {
  701. TFileOperationProgressType * ProgressData =
  702. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  703. if ((ProgressData != NULL) && ProgressData->InProgress)
  704. {
  705. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  706. }
  707. }
  708. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  709. {
  710. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  711. }
  712. }
  713. return Result;
  714. }
  715. //---------------------------------------------------------------------------
  716. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  717. {
  718. ComponentVisible[fcQueueView] =
  719. !IsLocalBrowserMode() &&
  720. ((WinConfiguration->QueueView.Show == qvShow) ||
  721. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  722. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  723. }
  724. //---------------------------------------------------------------------------
  725. void __fastcall TCustomScpExplorerForm::QueueChanged()
  726. {
  727. if (FQueueStatus != NULL)
  728. {
  729. // UpdateFileList implementation relies on the status being recreated when session changes
  730. delete FQueueStatus;
  731. FQueueStatus = NULL;
  732. }
  733. UpdateQueueStatus(true);
  734. }
  735. //---------------------------------------------------------------------------
  736. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  737. {
  738. if (FQueue == Queue)
  739. {
  740. FQueueStatusInvalidated = true;
  741. }
  742. }
  743. //---------------------------------------------------------------------------
  744. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  745. TQueueItem * Item)
  746. {
  747. if (FQueue == Queue)
  748. {
  749. TGuard Guard(FQueueStatusSection);
  750. // this may be running in parallel with QueueChanged
  751. if (FQueueStatus != NULL)
  752. {
  753. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  754. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  755. {
  756. FRefreshLocalDirectory = (QueueItem == NULL) ||
  757. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  758. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  759. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  760. }
  761. if (QueueItem != NULL)
  762. {
  763. QueueItem->UserData = (void*)true;
  764. FQueueItemInvalidated = true;
  765. }
  766. }
  767. }
  768. }
  769. //---------------------------------------------------------------------------
  770. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  771. {
  772. // during standalone editing, we have no way to see/control queue,
  773. // so we have to always popup prompts automatically
  774. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  775. }
  776. //---------------------------------------------------------------------------
  777. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  778. {
  779. if (FQueueStatus != NULL)
  780. {
  781. bool QueueAutoPopup = IsQueueAutoPopup();
  782. bool NeedRefresh = FQueueController->NeedRefresh();
  783. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  784. FQueueItemInvalidated = false;
  785. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  786. bool Updated = false;
  787. TQueueItemProxy * QueueItem;
  788. bool WasUserAction;
  789. for (int Index = 0; Index < Limit; Index++)
  790. {
  791. bool Update = false;
  792. QueueItem = FQueueStatus->Items[Index];
  793. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  794. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  795. (FPendingQueueActionItem == NULL))
  796. {
  797. FPendingQueueActionItem = QueueItem;
  798. FUserActionTimer->Enabled = true;
  799. }
  800. if ((bool)QueueItem->UserData)
  801. {
  802. QueueItem->UserData = (void*)false;
  803. QueueItem->Update();
  804. Updated = true;
  805. Update = true;
  806. }
  807. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  808. {
  809. Update = true;
  810. }
  811. if (Update)
  812. {
  813. FQueueController->RefreshQueueItem(QueueItem);
  814. }
  815. }
  816. if (Updated)
  817. {
  818. NonVisualDataModule->UpdateNonVisibleActions();
  819. SetQueueProgress();
  820. UpdateQueueFileList();
  821. }
  822. }
  823. }
  824. //---------------------------------------------------------------------------
  825. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  826. {
  827. if (FTaskbarList != NULL)
  828. {
  829. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  830. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  831. }
  832. }
  833. //---------------------------------------------------------------------------
  834. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  835. {
  836. if (Progress >= 0)
  837. {
  838. if (FTaskbarList != NULL)
  839. {
  840. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  841. }
  842. }
  843. else
  844. {
  845. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  846. }
  847. }
  848. //---------------------------------------------------------------------------
  849. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  850. {
  851. int OverallProgress;
  852. // FProgressForm is null when this is called from SetQueueProgress
  853. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  854. {
  855. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  856. }
  857. else if (!ProgressData->IsIndeterminate())
  858. {
  859. OverallProgress = ProgressData->OverallProgress();
  860. }
  861. else
  862. {
  863. OverallProgress = -1;
  864. }
  865. SetTaskbarListProgressValue(OverallProgress);
  866. }
  867. //---------------------------------------------------------------------------
  868. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  869. {
  870. TTerminalManager::Instance()->QueueStatusUpdated();
  871. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  872. {
  873. // Do not animate task bar button, when items are queued, but processing is disabled
  874. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  875. {
  876. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  877. {
  878. TFileOperationProgressType * ProgressData = NULL;
  879. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  880. {
  881. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  882. }
  883. if ((ProgressData != NULL) &&
  884. ProgressData->InProgress)
  885. {
  886. SetTaskbarListProgressValue(ProgressData);
  887. }
  888. else
  889. {
  890. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  891. }
  892. }
  893. else
  894. {
  895. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  896. }
  897. }
  898. else
  899. {
  900. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  901. }
  902. }
  903. UpdateQueueLabel();
  904. }
  905. //---------------------------------------------------------------------------
  906. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  907. {
  908. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  909. if (FQueueStatus != NULL)
  910. {
  911. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  912. if (ActiveAndPendingPrimaryCount > 0)
  913. {
  914. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  915. }
  916. }
  917. QueueLabel->Caption = Caption;
  918. }
  919. //---------------------------------------------------------------------------
  920. void TCustomScpExplorerForm::CheckStoreTransition()
  921. {
  922. if (WinConfiguration->StoreTransition == stInit)
  923. {
  924. if (IsUWP())
  925. {
  926. WinConfiguration->StoreTransition = stStoreFresh;
  927. AppLog(L"Fresh UWP/store installation");
  928. }
  929. else
  930. {
  931. WinConfiguration->StoreTransition = stStandard;
  932. AppLog(L"Fresh standard installation");
  933. }
  934. }
  935. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  936. {
  937. WinConfiguration->StoreTransition = stStoreMigrated;
  938. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  939. AppLog(L"Standard installation migrated to store installation");
  940. }
  941. if (WinConfiguration->StoreTransition == stStoreMigrated)
  942. {
  943. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  944. Toolbar->Parent = MessageDock;
  945. Toolbar->FullSize = true;
  946. Toolbar->Color = Application->HintColor;
  947. TTBXLabelItem * LabelItem;
  948. LabelItem = new TTBXLabelItem(Toolbar);
  949. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  950. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  951. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  952. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  953. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  954. Toolbar->Items->Add(LabelItem);
  955. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  956. LinkItem->FontSettings->Color = LinkColor;
  957. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  958. LinkItem->OnClick = StoreTransitionLinkClick;
  959. Toolbar->Items->Add(LinkItem);
  960. AddMenuSeparator(Toolbar->Items);
  961. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  962. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  963. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  964. CloseItem->OnClick = StoreTransitionCloseClick;
  965. Toolbar->Items->Add(CloseItem);
  966. GiveTBItemPriority(CloseItem);
  967. }
  968. }
  969. //---------------------------------------------------------------------------
  970. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  971. {
  972. ShowHelp(HELP_STORE_TRANSITION);
  973. }
  974. //---------------------------------------------------------------------------
  975. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  976. {
  977. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  978. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  979. delete Toolbar;
  980. WinConfiguration->StoreTransition = stStoreAcknowledged;
  981. UpdateControls();
  982. }
  983. //---------------------------------------------------------------------------
  984. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  985. {
  986. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  987. static_cast<TComponent*>(GetComponent(fcTransferList)));
  988. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  989. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  990. TransferList->Strings->BeginUpdate();
  991. try
  992. {
  993. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  994. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  995. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  996. if (FTransferDropDownHint.IsEmpty())
  997. {
  998. FTransferDropDownHint = TransferDropDown->Hint;
  999. }
  1000. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1001. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1002. TransferDropDown->Text = StripHotkey(Name);
  1003. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1004. (FTransferDropDownHint, StripHotkey(Name),
  1005. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1006. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1007. // update the label, otherwise when it is updated only on the first draw
  1008. // of the list, it is drawn "bold" for some reason
  1009. FTransferListHoverIndex = TransferList->ItemIndex;
  1010. UpdateTransferLabel();
  1011. }
  1012. __finally
  1013. {
  1014. TransferList->Strings->EndUpdate();
  1015. }
  1016. }
  1017. //---------------------------------------------------------------------------
  1018. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1019. {
  1020. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1021. DebugAssert(Toolbar != NULL);
  1022. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1023. }
  1024. //---------------------------------------------------------------------------
  1025. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1026. {
  1027. TForm::UpdateActions();
  1028. if (ComponentVisible[fcCustomCommandsBand])
  1029. {
  1030. UpdateCustomCommandsToolbar();
  1031. }
  1032. }
  1033. //---------------------------------------------------------------------------
  1034. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1035. {
  1036. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1037. }
  1038. //---------------------------------------------------------------------------
  1039. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1040. {
  1041. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1042. {
  1043. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1044. // Without this, the panel turns gray and unused part of header turns black
  1045. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1046. }
  1047. }
  1048. //---------------------------------------------------------------------------
  1049. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1050. {
  1051. Color = GetBtnFaceColor();
  1052. DebugAssert(Configuration && RemoteDirView);
  1053. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1054. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1055. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1056. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1057. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1058. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1059. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1060. UpdateRowSelect(RemoteDirView);
  1061. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1062. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1063. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1064. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1065. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1066. UpdateSessionsPageControlHeight();
  1067. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1068. UpdateToolbarDisplayMode();
  1069. UpdateTransferList();
  1070. if (Terminal != NULL)
  1071. {
  1072. TransferPresetAutoSelect();
  1073. }
  1074. UpdateQueueView();
  1075. UpdateControls();
  1076. // this can be called even before constuctor finishes.
  1077. if (FEditorManager != NULL)
  1078. {
  1079. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1080. }
  1081. // this can be called even before constuctor finishes.
  1082. if (FLocalEditors != NULL)
  1083. {
  1084. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1085. {
  1086. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1087. }
  1088. }
  1089. if (ComponentVisible[fcCustomCommandsBand])
  1090. {
  1091. UpdateCustomCommandsToolbar();
  1092. }
  1093. // show only when keeping queue items forever,
  1094. // otherwise, it's enough to have it in the context menu
  1095. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1096. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1097. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1098. {
  1099. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1100. FFileColorsCurrent = WinConfiguration->FileColors;
  1101. FileColorsChanged();
  1102. }
  1103. }
  1104. //---------------------------------------------------------------------------
  1105. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1106. {
  1107. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1108. DirView->Invalidate();
  1109. }
  1110. //---------------------------------------------------------------------------
  1111. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1112. {
  1113. DoFileColorsChanged(RemoteDirView);
  1114. }
  1115. //---------------------------------------------------------------------------
  1116. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1117. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  1118. void * /*Arg*/)
  1119. {
  1120. if (Token != NULL)
  1121. {
  1122. TForm * Editor = dynamic_cast<TForm*>(Token);
  1123. DebugAssert(Editor != NULL);
  1124. ReconfigureEditorForm(Editor);
  1125. }
  1126. }
  1127. //---------------------------------------------------------------------------
  1128. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1129. {
  1130. WinConfiguration->DDTransferConfirmation = asOn;
  1131. }
  1132. //---------------------------------------------------------------------------
  1133. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1134. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1135. {
  1136. // noop
  1137. }
  1138. //---------------------------------------------------------------------------
  1139. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1140. {
  1141. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1142. }
  1143. //---------------------------------------------------------------------------
  1144. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1145. {
  1146. if (DoNotShowAgain)
  1147. {
  1148. if (DragDrop)
  1149. {
  1150. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1151. {
  1152. PopupTrayBalloon(
  1153. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1154. }
  1155. WinConfiguration->DDTransferConfirmation = asOff;
  1156. }
  1157. else
  1158. {
  1159. WinConfiguration->ConfirmTransferring = false;
  1160. }
  1161. }
  1162. else
  1163. {
  1164. // User explicitly unchecked "do not show again",
  1165. // so show him the dialog the next time
  1166. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1167. {
  1168. WinConfiguration->DDTransferConfirmation = asOn;
  1169. }
  1170. }
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1174. TTransferDirection Direction, TTransferType Type, bool Temp,
  1175. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1176. bool Confirm, bool DragDrop, int Options)
  1177. {
  1178. bool Result = true;
  1179. DebugAssert(HasActiveTerminal());
  1180. // these parameters are known in advance
  1181. int Params =
  1182. FLAGMASK(Type == ttMove, cpDelete);
  1183. bool ToTemp = (Temp && (Direction == tdToLocal));
  1184. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1185. {
  1186. bool DisableNewerOnly =
  1187. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1188. ToTemp;
  1189. Options |=
  1190. FLAGMASK(ToTemp, coTemp) |
  1191. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1192. coDoNotShowAgain;
  1193. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1194. int CopyParamAttrs = (Direction == tdToRemote ?
  1195. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1196. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1197. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1198. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1199. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1200. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1201. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1202. if (Result)
  1203. {
  1204. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1205. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1206. }
  1207. }
  1208. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1209. {
  1210. Configuration->Usage->Inc(L"TransfersOnBackground");
  1211. // these parameter are known only after transfer dialog
  1212. Params |=
  1213. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1214. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1215. Result = false;
  1216. ClearTransferSourceSelection(Direction);
  1217. }
  1218. return Result;
  1219. }
  1220. //---------------------------------------------------------------------------
  1221. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1222. {
  1223. if (FOnFileOperationFinished != NULL)
  1224. {
  1225. FOnFileOperationFinished(Side, UnicodeString(), true);
  1226. }
  1227. else
  1228. {
  1229. if (HasDirView[Side])
  1230. {
  1231. DirView(Side)->SelectAll(smNone);
  1232. }
  1233. }
  1234. }
  1235. //---------------------------------------------------------------------------
  1236. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1237. {
  1238. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1239. ClearOperationSelection(Side);
  1240. }
  1241. //---------------------------------------------------------------------------
  1242. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1243. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1244. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1245. int Params)
  1246. {
  1247. DebugAssert(Queue != NULL);
  1248. bool SingleFile = false;
  1249. if (FileList->Count == 1)
  1250. {
  1251. if (Direction == tdToRemote)
  1252. {
  1253. UnicodeString FileName = FileList->Strings[0];
  1254. SingleFile = FileExists(ApiPath(FileName));
  1255. }
  1256. else
  1257. {
  1258. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1259. SingleFile = !File->IsDirectory;
  1260. }
  1261. }
  1262. TQueueItem * QueueItem;
  1263. if (Direction == tdToRemote)
  1264. {
  1265. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1266. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1267. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1268. }
  1269. else
  1270. {
  1271. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1272. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1273. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1274. }
  1275. AddQueueItem(Queue, QueueItem, Terminal);
  1276. }
  1277. //---------------------------------------------------------------------------
  1278. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1279. {
  1280. if (Queue->IsEmpty)
  1281. {
  1282. Terminal->QueueOperationStart = Now();
  1283. }
  1284. Queue->AddItem(QueueItem);
  1285. }
  1286. //---------------------------------------------------------------------------
  1287. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1288. {
  1289. }
  1290. //---------------------------------------------------------------------------
  1291. void __fastcall TCustomScpExplorerForm::InitControls()
  1292. {
  1293. DebugAssert(FDocks != NULL);
  1294. for (int Index = 0; Index < ComponentCount; Index++)
  1295. {
  1296. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1297. if ((Dock != NULL) && (Dock->Tag == 0))
  1298. {
  1299. FDocks->Add(Dock);
  1300. }
  1301. }
  1302. CollectItemsWithTextDisplayMode(this);
  1303. }
  1304. //---------------------------------------------------------------------------
  1305. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1306. {
  1307. ConfigurationChanged();
  1308. QueuePanel->Height =
  1309. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1310. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1311. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1312. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1313. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1314. QueueFileList->Height =
  1315. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1316. if (QueueFileList->Visible)
  1317. {
  1318. AdjustQueueLayout();
  1319. }
  1320. UpdateCustomCommandsToolbar();
  1321. }
  1322. //---------------------------------------------------------------------------
  1323. void __fastcall TCustomScpExplorerForm::StoreParams()
  1324. {
  1325. int APixelsPerInch = GetControlPixelsPerInch(this);
  1326. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1327. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1328. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1329. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1330. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1331. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1332. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1333. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1334. }
  1335. //---------------------------------------------------------------------------
  1336. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1337. {
  1338. if (!FFormRestored)
  1339. {
  1340. FFormRestored = true;
  1341. RestoreFormParams();
  1342. }
  1343. TForm::CreateParams(Params);
  1344. }
  1345. //---------------------------------------------------------------------------
  1346. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1347. {
  1348. DebugAssert(FDocks != NULL);
  1349. for (int Index = 0; Index < FDocks->Count; Index++)
  1350. {
  1351. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1352. }
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1356. {
  1357. SetDockAllowDrag(true);
  1358. while (!ButtonsStr.IsEmpty())
  1359. {
  1360. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1361. UnicodeString Name = CutToChar(S, L'=', true);
  1362. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1363. {
  1364. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1365. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1366. {
  1367. while (!S.IsEmpty())
  1368. {
  1369. UnicodeString S2 = CutToChar(S, L',', true);
  1370. UnicodeString Name = CutToChar(S2, L':', true);
  1371. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1372. {
  1373. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1374. if (SameText(GetToolbarItemName(Item), Name))
  1375. {
  1376. // forward compatibility
  1377. UnicodeString S3 = CutToChar(S2, L':', true);
  1378. bool Visible = StrToIntDef(S3, 0);
  1379. Item->Visible = Visible;
  1380. }
  1381. }
  1382. }
  1383. }
  1384. }
  1385. }
  1386. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1387. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1388. }
  1389. //---------------------------------------------------------------------------
  1390. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1391. {
  1392. UnicodeString Result;
  1393. SetDockAllowDrag(true);
  1394. Result = ::GetToolbarsLayoutStr(this);
  1395. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1396. return Result;
  1397. }
  1398. //---------------------------------------------------------------------------
  1399. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1400. {
  1401. UnicodeString Result;
  1402. if (Item->Action != NULL)
  1403. {
  1404. Result = Item->Action->Name;
  1405. Result = RemoveSuffix(Result, L"Action", true);
  1406. }
  1407. else
  1408. {
  1409. Result = Item->Name;
  1410. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1411. Result = RemoveSuffix(Result, L"Item", true);
  1412. }
  1413. return Result;
  1414. }
  1415. //---------------------------------------------------------------------------
  1416. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1417. {
  1418. UnicodeString Result;
  1419. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1420. {
  1421. UnicodeString ToolbarStr;
  1422. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1423. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1424. {
  1425. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1426. {
  1427. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1428. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1429. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1430. // and save the changes here only.
  1431. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1432. {
  1433. UnicodeString Name = GetToolbarItemName(Item);
  1434. DebugAssert(Name.Pos(L"TBX") == 0);
  1435. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1436. }
  1437. }
  1438. }
  1439. if (!ToolbarStr.IsEmpty())
  1440. {
  1441. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1442. }
  1443. }
  1444. return Result;
  1445. }
  1446. //---------------------------------------------------------------------------
  1447. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1448. {
  1449. DebugAssert(FProgressForm == NULL);
  1450. bool AllowSkip = HasActiveTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1451. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1452. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1453. FProgressForm->DeleteLocalToRecycleBin =
  1454. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1455. FProgressForm->DeleteRemoteToRecycleBin =
  1456. HasActiveTerminal() &&
  1457. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1458. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1459. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1460. LockWindow();
  1461. // Actually, do not know what hides the progress once the operation finishes
  1462. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1463. SetTaskbarListProgressState(TBPF_NORMAL);
  1464. }
  1465. //---------------------------------------------------------------------------
  1466. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1467. {
  1468. UnlockWindow();
  1469. SAFE_DESTROY(FProgressForm);
  1470. SetQueueProgress();
  1471. }
  1472. //---------------------------------------------------------------------------
  1473. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1474. TFileOperationProgressType & ProgressData)
  1475. {
  1476. // Download to temporary local directory
  1477. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1478. {
  1479. bool Continue = true;
  1480. FPendingTempSpaceWarn = false;
  1481. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1482. if (!Continue)
  1483. {
  1484. Abort();
  1485. }
  1486. }
  1487. // operation is being executed and we still didn't show up progress form
  1488. if (ProgressData.InProgress && !FProgressForm)
  1489. {
  1490. CreateProgressForm(NULL);
  1491. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1492. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1493. }
  1494. // operation is finished (or terminated), so we hide progress form
  1495. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1496. {
  1497. DestroyProgressForm();
  1498. if (ProgressData.Operation == foCalculateSize)
  1499. {
  1500. // When calculating size before transfer, the abort caused by
  1501. // cancel flag set due to "MoveToQueue" below,
  1502. // is not propagated back to us in ExecuteFileOperation,
  1503. // as it is silently swallowed.
  1504. // So we explicitly (re)throw it here.
  1505. if (FMoveToQueue)
  1506. {
  1507. Abort();
  1508. }
  1509. }
  1510. else
  1511. {
  1512. if ((ProgressData.Cancel == csContinue) &&
  1513. !FAutoOperation)
  1514. {
  1515. OperationComplete(ProgressData.StartTime);
  1516. }
  1517. }
  1518. }
  1519. if (FProgressForm &&
  1520. // Can happen only during synchronization, when ending one of the operations
  1521. ProgressData.InProgress)
  1522. {
  1523. FProgressForm->SetProgressData(ProgressData);
  1524. DebugAssert(ProgressData.InProgress);
  1525. SetTaskbarListProgressValue(&ProgressData);
  1526. if (FProgressForm->Cancel > csContinue)
  1527. {
  1528. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1529. if (FProgressForm->Cancel == csCancelFile)
  1530. {
  1531. FProgressForm->ClearCancel();
  1532. }
  1533. // cancel cancels even the move
  1534. FMoveToQueue = false;
  1535. }
  1536. else if (FProgressForm->MoveToQueue)
  1537. {
  1538. FMoveToQueue = true;
  1539. ProgressData.SetCancelAtLeast(csCancel);
  1540. }
  1541. if ((FTransferResumeList != NULL) &&
  1542. ProgressData.InProgress &&
  1543. ProgressData.IsTransfer() &&
  1544. !ProgressData.FullFileName.IsEmpty())
  1545. {
  1546. if ((FTransferResumeList->Count == 0) ||
  1547. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1548. {
  1549. // note that we do not recognize directories from files here
  1550. FTransferResumeList->Add(ProgressData.FullFileName);
  1551. }
  1552. }
  1553. }
  1554. }
  1555. //---------------------------------------------------------------------------
  1556. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1557. const TDateTime & StartTime)
  1558. {
  1559. if (GUIConfiguration->BeepOnFinish &&
  1560. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1561. {
  1562. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1563. DWORD Sound;
  1564. if (!ExtractFileExt(BeepSound).IsEmpty())
  1565. {
  1566. Sound = SND_FILENAME;
  1567. }
  1568. else
  1569. {
  1570. Sound = SND_ALIAS;
  1571. }
  1572. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1573. }
  1574. }
  1575. //---------------------------------------------------------------------------
  1576. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1577. TFileOperationProgressType & ProgressData)
  1578. {
  1579. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1580. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1581. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1582. FileOperationProgress(ProgressData);
  1583. }
  1584. //---------------------------------------------------------------------------
  1585. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1586. {
  1587. UnicodeString Result;
  1588. if (FProgressForm != NULL)
  1589. {
  1590. Result = FProgressForm->ProgressStr();
  1591. }
  1592. return Result;
  1593. }
  1594. //---------------------------------------------------------------------------
  1595. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1596. bool DragDrop)
  1597. {
  1598. return (!DragDrop && (DropSourceControl == NULL)) ||
  1599. (DropSourceControl == DirView(osOther));
  1600. }
  1601. //---------------------------------------------------------------------------
  1602. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1603. {
  1604. TCustomDirView * ADirView = DirView(Side);
  1605. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1606. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1607. // this can happen when local drive is unplugged in the middle of the operation
  1608. if (Item != NULL)
  1609. {
  1610. if (Unselect)
  1611. {
  1612. Item->Selected = false;
  1613. }
  1614. ADirView->MakeProgressVisible(Item);
  1615. }
  1616. return Item;
  1617. }
  1618. //---------------------------------------------------------------------------
  1619. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1620. TFileOperation Operation, TOperationSide Side,
  1621. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1622. TOnceDoneOperation & OnceDoneOperation)
  1623. {
  1624. if (!FAutoOperation)
  1625. {
  1626. // no selection on "/upload", form serves only as event handler
  1627. // (it is not displayed)
  1628. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1629. ((Operation == FPrimaryOperation) ||
  1630. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1631. {
  1632. TOperationSide DViewSide;
  1633. if ((FProgressSide != osCurrent) &&
  1634. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1635. {
  1636. // assume the operation is over the focused panel
  1637. DViewSide = FProgressSide;
  1638. }
  1639. else
  1640. {
  1641. DViewSide = Side;
  1642. }
  1643. if (FOnFileOperationFinished != NULL)
  1644. {
  1645. FOnFileOperationFinished(DViewSide, FileName, Success);
  1646. }
  1647. else
  1648. {
  1649. VisualiseOperationFinished(DViewSide, FileName, Success);
  1650. }
  1651. }
  1652. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1653. {
  1654. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1655. {
  1656. if (Side == osLocal)
  1657. {
  1658. Configuration->Usage->Inc(L"UploadedFiles");
  1659. }
  1660. else
  1661. {
  1662. Configuration->Usage->Inc(L"DownloadedFiles");
  1663. }
  1664. }
  1665. }
  1666. }
  1667. if (Success && (FSynchronizeController != NULL))
  1668. {
  1669. DebugAssert(!IsSideLocalBrowser(osRemote));
  1670. if (Operation == foCopy)
  1671. {
  1672. DebugAssert(Side == osLocal);
  1673. FSynchronizeController->LogOperation(soUpload, FileName);
  1674. }
  1675. else if (Operation == foDelete)
  1676. {
  1677. DebugAssert(Side == osRemote);
  1678. FSynchronizeController->LogOperation(soDelete, FileName);
  1679. }
  1680. }
  1681. if (FProgressForm)
  1682. {
  1683. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1684. }
  1685. }
  1686. //---------------------------------------------------------------------------
  1687. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1688. TFileOperation Operation, TOperationSide Side,
  1689. bool Temp, const UnicodeString & FileName, Boolean Success,
  1690. TOnceDoneOperation & OnceDoneOperation)
  1691. {
  1692. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1693. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1694. OnceDoneOperation);
  1695. }
  1696. //---------------------------------------------------------------------------
  1697. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1698. {
  1699. return false;
  1700. }
  1701. //---------------------------------------------------------------------------
  1702. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1703. {
  1704. return false;
  1705. }
  1706. //---------------------------------------------------------------------------
  1707. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1708. {
  1709. return false;
  1710. }
  1711. //---------------------------------------------------------------------------
  1712. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1713. {
  1714. return NULL;
  1715. }
  1716. //---------------------------------------------------------------------------
  1717. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1718. {
  1719. DebugAssert(GetSide(Side) == osRemote);
  1720. DebugUsedParam(Side);
  1721. return RemoteDirView;
  1722. }
  1723. //---------------------------------------------------------------------------
  1724. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1725. {
  1726. DebugAssert(GetSide(Side) == osRemote);
  1727. DebugUsedParam(Side);
  1728. return RemoteDriveView;
  1729. }
  1730. //---------------------------------------------------------------------------
  1731. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1732. {
  1733. DebugAssert(GetSide(Side) == osRemote);
  1734. DebugUsedParam(Side);
  1735. return HasActiveTerminal();
  1736. }
  1737. //---------------------------------------------------------------------------
  1738. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1739. TOperationSide Side, int FilesOnly)
  1740. {
  1741. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1742. }
  1743. //---------------------------------------------------------------------------
  1744. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1745. TOperationSide Side, int FilesOnly)
  1746. {
  1747. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1748. }
  1749. //---------------------------------------------------------------------------
  1750. struct THistoryItemData
  1751. {
  1752. short int Side;
  1753. short int Index;
  1754. };
  1755. //---------------------------------------------------------------------------
  1756. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1757. {
  1758. DirView(Side)->HistoryGo(Index);
  1759. }
  1760. //---------------------------------------------------------------------------
  1761. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1762. {
  1763. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1764. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1765. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1766. }
  1767. //---------------------------------------------------------------------------
  1768. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1769. bool Back)
  1770. {
  1771. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1772. {
  1773. TCustomDirView * DView = DirView(Side);
  1774. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1775. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1776. if (ICount > 10)
  1777. {
  1778. ICount = 10;
  1779. }
  1780. Menu->Items->Clear();
  1781. THistoryItemData Data;
  1782. Data.Side = Side;
  1783. for (short int i = 1; i <= ICount; i++)
  1784. {
  1785. TTBCustomItem * Item = new TTBXItem(Menu);
  1786. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1787. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1788. Item->Hint = DView->HistoryPath[Data.Index];
  1789. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1790. Item->Tag = *reinterpret_cast<int*>(&Data);
  1791. Item->OnClick = HistoryItemClick;
  1792. Menu->Items->Add(Item);
  1793. }
  1794. }
  1795. }
  1796. //---------------------------------------------------------------------------
  1797. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1798. TOperationSide Side, bool Back)
  1799. {
  1800. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1801. {
  1802. // workaround
  1803. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1804. // operator new allocates memory in Pascal code, but calls inline
  1805. // contructor in C++, leading in problems, the function does
  1806. // both in Pascal code
  1807. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1808. UpdateHistoryMenu(Side, Back);
  1809. }
  1810. return FHistoryMenu[Side == osLocal][Back];
  1811. }
  1812. //---------------------------------------------------------------------------
  1813. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1814. TCustomDirView *Sender)
  1815. {
  1816. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1817. UpdateHistoryMenu(Side, true);
  1818. UpdateHistoryMenu(Side, false);
  1819. }
  1820. //---------------------------------------------------------------------------
  1821. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1822. {
  1823. // remote custom commands can be executed only if the server supports shell commands
  1824. // or have secondary shell
  1825. return HasActiveTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1826. }
  1827. //---------------------------------------------------------------------------
  1828. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1829. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1830. {
  1831. // -1 = hidden, 0 = disabled, 1 = enabled
  1832. int Result;
  1833. TFileCustomCommand RemoteCustomCommand;
  1834. TLocalCustomCommand LocalCustomCommand;
  1835. TFileCustomCommand * NonInteractiveCustomCommand =
  1836. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1837. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1838. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1839. if (FLAGCLEAR(Command.Params, ccLocal))
  1840. {
  1841. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1842. // custom command that does not operate with files can be executed anytime ...
  1843. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1844. {
  1845. // ... but do not show such command in remote file menu
  1846. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1847. {
  1848. Result = AllowedState;
  1849. }
  1850. else
  1851. {
  1852. Result = -1;
  1853. }
  1854. }
  1855. else
  1856. {
  1857. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1858. {
  1859. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1860. }
  1861. else
  1862. {
  1863. Result = -1;
  1864. }
  1865. }
  1866. }
  1867. else
  1868. {
  1869. // custom command that does not operate with files can be executed anytime
  1870. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1871. {
  1872. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1873. }
  1874. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1875. {
  1876. if ((ListType == ccltAll) || (ListType == ccltFile))
  1877. {
  1878. // special case is "diff"-style command that can be executed over any side,
  1879. // if we have both sides
  1880. Result =
  1881. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1882. // directly (instead of EnableSelectedOperation) to pass
  1883. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1884. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1885. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1886. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1887. }
  1888. else if (ListType == ccltBoth)
  1889. {
  1890. DebugAssert(!IsLocalBrowserMode());
  1891. Result = 1;
  1892. }
  1893. else
  1894. {
  1895. Result = -1;
  1896. }
  1897. }
  1898. else
  1899. {
  1900. if ((ListType == ccltAll) ||
  1901. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1902. {
  1903. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1904. }
  1905. else
  1906. {
  1907. Result = -1;
  1908. }
  1909. }
  1910. if ((Result > 0) &&
  1911. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1912. !HasActiveTerminal())
  1913. {
  1914. Result = 0;
  1915. }
  1916. }
  1917. return Result;
  1918. }
  1919. //---------------------------------------------------------------------------
  1920. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1921. TStrings * FileList, const TCustomCommandType & ACommand,
  1922. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1923. {
  1924. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1925. {
  1926. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1927. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1928. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1929. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1930. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1931. bool Capture =
  1932. FLAGSET(ACommand.Params, ccShowResults) ||
  1933. FLAGSET(ACommand.Params, ccCopyResults) ||
  1934. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1935. TCaptureOutputEvent OutputEvent = NULL;
  1936. DebugAssert(FCapturedLog == NULL);
  1937. if (Capture)
  1938. {
  1939. FCapturedLog = new TStringList();
  1940. OutputEvent = TerminalCaptureLog;
  1941. }
  1942. try
  1943. {
  1944. if (!RemoteCustomCommand.IsFileCommand(Command))
  1945. {
  1946. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1947. OutputEvent);
  1948. }
  1949. else
  1950. {
  1951. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1952. }
  1953. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1954. {
  1955. if (FLAGSET(ACommand.Params, ccCopyResults))
  1956. {
  1957. CopyToClipboard(FCapturedLog);
  1958. }
  1959. if (FLAGSET(ACommand.Params, ccShowResults))
  1960. {
  1961. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1962. }
  1963. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1964. {
  1965. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1966. }
  1967. }
  1968. }
  1969. __finally
  1970. {
  1971. SAFE_DESTROY(FCapturedLog);
  1972. }
  1973. }
  1974. }
  1975. //---------------------------------------------------------------------------
  1976. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1977. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1978. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1979. {
  1980. DebugAssert(!IsLocalBrowserMode());
  1981. TStrings * LocalFileList = NULL;
  1982. TStrings * RemoteFileList = NULL;
  1983. TStrings * RemoteFileListFull = NULL;
  1984. try
  1985. {
  1986. if (LocalFileCommand)
  1987. {
  1988. if (ALocalFileList == NULL)
  1989. {
  1990. DebugAssert(HasDirView[osLocal]);
  1991. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1992. // directly (instead of EnableSelectedOperation) to pass
  1993. // false to FocusedFileOnlyWhenFocused
  1994. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  1995. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  1996. }
  1997. else
  1998. {
  1999. LocalFileList = ALocalFileList;
  2000. }
  2001. if (FileListCommand)
  2002. {
  2003. if (LocalFileList->Count != 1)
  2004. {
  2005. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2006. }
  2007. }
  2008. else
  2009. {
  2010. if ((LocalFileList->Count != 1) &&
  2011. (FileList->Count != 1) &&
  2012. (LocalFileList->Count != FileList->Count))
  2013. {
  2014. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2015. }
  2016. }
  2017. }
  2018. UnicodeString RootTempDir;
  2019. UnicodeString TempDir;
  2020. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2021. if (!RemoteFiles)
  2022. {
  2023. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true, true);
  2024. }
  2025. try
  2026. {
  2027. TDateTimes RemoteFileTimes;
  2028. if (RemoteFiles)
  2029. {
  2030. RemoteFileList = FileList;
  2031. }
  2032. else
  2033. {
  2034. RemoteFileList = new TStringList();
  2035. TMakeLocalFileListParams MakeFileListParam;
  2036. MakeFileListParam.FileList = RemoteFileList;
  2037. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2038. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2039. MakeFileListParam.Recursive =
  2040. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2041. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2042. if (!MakeFileListParam.Recursive)
  2043. {
  2044. RemoteFileTimes.clear();
  2045. RemoteFileListFull = new TStringList();
  2046. MakeFileListParam.FileList = RemoteFileListFull;
  2047. MakeFileListParam.Recursive = true;
  2048. MakeFileListParam.IncludeDirs = false;
  2049. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2050. }
  2051. else
  2052. {
  2053. RemoteFileListFull = RemoteFileList;
  2054. }
  2055. }
  2056. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2057. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2058. if (!NonBlocking)
  2059. {
  2060. int Count;
  2061. if (FileListCommand)
  2062. {
  2063. Count = 1;
  2064. }
  2065. else if (LocalFileCommand)
  2066. {
  2067. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2068. }
  2069. else
  2070. {
  2071. Count = RemoteFileList->Count;
  2072. }
  2073. Progress.Start(foCustomCommand, osRemote, Count);
  2074. DebugAssert(FProgressForm != NULL);
  2075. FProgressForm->ReadOnly = true;
  2076. }
  2077. try
  2078. {
  2079. if (FileListCommand)
  2080. {
  2081. UnicodeString LocalFile;
  2082. // MakeFileList does not delimit filenames
  2083. UnicodeString FileList = MakeFileList(RemoteFileList);
  2084. if (LocalFileCommand)
  2085. {
  2086. DebugAssert(LocalFileList->Count == 1);
  2087. LocalFile = LocalFileList->Strings[0];
  2088. }
  2089. TLocalCustomCommand CustomCommand(Data,
  2090. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2091. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2092. if (NonBlocking)
  2093. {
  2094. DebugAssert(!POutput);
  2095. ExecuteShellChecked(ShellCommand);
  2096. }
  2097. else
  2098. {
  2099. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2100. }
  2101. }
  2102. else if (LocalFileCommand)
  2103. {
  2104. if (LocalFileList->Count == 1)
  2105. {
  2106. UnicodeString LocalFile = LocalFileList->Strings[0];
  2107. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2108. {
  2109. UnicodeString FileName = RemoteFileList->Strings[Index];
  2110. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2111. Progress.SetFile(FileNameForProgress);
  2112. TLocalCustomCommand CustomCommand(Data,
  2113. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2114. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2115. TOnceDoneOperation OnceDoneOperation;
  2116. // Do not unselect anything, as it won't work with two panels anyway
  2117. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2118. }
  2119. }
  2120. else if (RemoteFileList->Count == 1)
  2121. {
  2122. UnicodeString FileName = RemoteFileList->Strings[0];
  2123. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2124. {
  2125. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2126. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2127. Progress.SetFile(LocalFileNameOnly);
  2128. TLocalCustomCommand CustomCommand(
  2129. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2130. FileName, LocalFileName, 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
  2138. {
  2139. if (LocalFileList->Count != RemoteFileList->Count)
  2140. {
  2141. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2142. }
  2143. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2144. {
  2145. UnicodeString FileName = RemoteFileList->Strings[Index];
  2146. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2147. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2148. Progress.SetFile(LocalFileNameOnly); // sic
  2149. TLocalCustomCommand CustomCommand(
  2150. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2151. FileName, LocalFileName, L"");
  2152. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2153. TOnceDoneOperation OnceDoneOperation;
  2154. // Do not unselect anything, as it won't work with two panels anyway
  2155. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2156. }
  2157. }
  2158. }
  2159. else
  2160. {
  2161. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2162. {
  2163. UnicodeString FileName = RemoteFileList->Strings[Index];
  2164. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2165. Progress.SetFile(FileNameForProgress);
  2166. TLocalCustomCommand CustomCommand(Data,
  2167. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2168. FileName, L"", L"");
  2169. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2170. TOnceDoneOperation OnceDoneOperation;
  2171. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2172. }
  2173. }
  2174. }
  2175. __finally
  2176. {
  2177. if (!NonBlocking)
  2178. {
  2179. Progress.Stop();
  2180. }
  2181. }
  2182. DebugAssert(!FAutoOperation);
  2183. if (!RemoteFiles)
  2184. {
  2185. TempDir = IncludeTrailingBackslash(TempDir);
  2186. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2187. {
  2188. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2189. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2190. // Skip directories, process only nested files.
  2191. // The check is redundant as FileAge fails for directories anyway.
  2192. !DirectoryExists(FileName))
  2193. {
  2194. UnicodeString RemoteDir =
  2195. UnixExtractFileDir(
  2196. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2197. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  2198. TDateTime NewTime;
  2199. if (FileAge(FileName, NewTime) &&
  2200. (NewTime != RemoteFileTimes[Index]))
  2201. {
  2202. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2203. TemporaryFileCopyParam(CopyParam);
  2204. CopyParam.FileMask = L"";
  2205. FAutoOperation = true;
  2206. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2207. TemporaryFilesList->Add(FileName);
  2208. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2209. }
  2210. }
  2211. }
  2212. }
  2213. }
  2214. __finally
  2215. {
  2216. FAutoOperation = false;
  2217. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2218. {
  2219. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  2220. }
  2221. }
  2222. }
  2223. __finally
  2224. {
  2225. if (RemoteFileList != FileList)
  2226. {
  2227. delete RemoteFileList;
  2228. }
  2229. if (LocalFileList != ALocalFileList)
  2230. {
  2231. delete LocalFileList;
  2232. }
  2233. if (RemoteFileListFull != RemoteFileList)
  2234. {
  2235. delete RemoteFileListFull;
  2236. }
  2237. }
  2238. }
  2239. //---------------------------------------------------------------------------
  2240. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2241. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2242. bool FileListCommand, UnicodeString * POutput)
  2243. {
  2244. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2245. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2246. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2247. {
  2248. UnicodeString FileName = SelectedFileList->Strings[Index];
  2249. if (DirectoryExists(FileName))
  2250. {
  2251. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2252. {
  2253. LocalFileList->Add(FileName);
  2254. }
  2255. if (FLAGSET(ACommand.Params, ccRecursive))
  2256. {
  2257. TMakeLocalFileListParams MakeFileListParam;
  2258. MakeFileListParam.FileList = LocalFileList.get();
  2259. MakeFileListParam.FileTimes = NULL;
  2260. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2261. MakeFileListParam.Recursive = true;
  2262. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2263. }
  2264. }
  2265. else
  2266. {
  2267. LocalFileList->Add(FileName);
  2268. }
  2269. }
  2270. UnicodeString RemotePath;
  2271. if (Terminal != NULL)
  2272. {
  2273. RemotePath = Terminal->CurrentDirectory;
  2274. }
  2275. if (FileListCommand)
  2276. {
  2277. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2278. TLocalCustomCommand CustomCommand(
  2279. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2280. L"", L"", FileList);
  2281. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2282. }
  2283. else
  2284. {
  2285. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2286. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2287. DebugAssert(FProgressForm != NULL);
  2288. FProgressForm->ReadOnly = true;
  2289. try
  2290. {
  2291. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2292. {
  2293. UnicodeString FileName = LocalFileList->Strings[Index];
  2294. Progress.SetFile(FileName);
  2295. TLocalCustomCommand CustomCommand(
  2296. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2297. FileName, L"", L"");
  2298. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2299. TOnceDoneOperation OnceDoneOperation;
  2300. Progress.Finish(FileName, true, OnceDoneOperation);
  2301. }
  2302. }
  2303. __finally
  2304. {
  2305. Progress.Stop();
  2306. }
  2307. }
  2308. }
  2309. //---------------------------------------------------------------------------
  2310. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2311. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2312. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2313. {
  2314. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2315. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2316. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2317. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2318. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2319. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2320. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2321. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2322. std::unique_ptr<UnicodeString> POutput;
  2323. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2324. FLAGSET(ACommand.Params, ccCopyResults))
  2325. {
  2326. POutput.reset(new UnicodeString());
  2327. }
  2328. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  2329. FProgressSide = FCurrentSide;
  2330. if (!LocalCustomCommand.IsFileCommand(Command))
  2331. {
  2332. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2333. }
  2334. // remote files?
  2335. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2336. {
  2337. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2338. }
  2339. // local files
  2340. else
  2341. {
  2342. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2343. }
  2344. if (POutput.get() != NULL)
  2345. {
  2346. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2347. int P = POutput->Pos(sLineBreak);
  2348. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2349. {
  2350. POutput->SetLength(P - 1);
  2351. }
  2352. // Copy even empty output to clipboard
  2353. if (FLAGSET(ACommand.Params, ccCopyResults))
  2354. {
  2355. CopyToClipboard(*POutput);
  2356. }
  2357. // But do not show an empty message box.
  2358. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2359. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2360. !POutput->IsEmpty())
  2361. {
  2362. TClipboardHandler ClipboardHandler;
  2363. ClipboardHandler.Text = *POutput;
  2364. TMessageParams Params;
  2365. TQueryButtonAlias Aliases[1];
  2366. Aliases[0].Button = qaRetry;
  2367. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2368. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2369. Params.Aliases = Aliases;
  2370. Params.AliasesCount = LENOF(Aliases);
  2371. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2372. }
  2373. }
  2374. }
  2375. //---------------------------------------------------------------------------
  2376. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2377. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2378. {
  2379. TCustomCommandData Data;
  2380. UnicodeString Site;
  2381. UnicodeString RemotePath;
  2382. if (HasActiveTerminal())
  2383. {
  2384. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2385. Data = TCustomCommandData(SessionData.get());
  2386. Site = Terminal->SessionData->SessionKey;
  2387. RemotePath = Terminal->CurrentDirectory;
  2388. }
  2389. UnicodeString HelpKeyword = ACommand.HomePage;
  2390. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2391. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2392. {
  2393. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2394. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2395. {
  2396. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2397. }
  2398. else
  2399. {
  2400. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2401. }
  2402. if (!DoCustomCommandOptionsDialog(
  2403. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2404. {
  2405. Abort();
  2406. }
  2407. }
  2408. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2409. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2410. {
  2411. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2412. }
  2413. else
  2414. {
  2415. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2416. }
  2417. }
  2418. //---------------------------------------------------------------------------
  2419. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2420. const TCustomCommandType & Command)
  2421. {
  2422. DebugAssert(FCustomCommandLocalFileList != NULL);
  2423. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2424. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2425. TStrings * LocalFileList = new TStringList();
  2426. TStrings * RemoteFileList = new TStringList();
  2427. try
  2428. {
  2429. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2430. {
  2431. LocalFileList->Clear();
  2432. LocalFileList->AddObject(
  2433. FCustomCommandLocalFileList->Strings[Index],
  2434. FCustomCommandLocalFileList->Objects[Index]);
  2435. RemoteFileList->Clear();
  2436. RemoteFileList->AddObject(
  2437. FCustomCommandRemoteFileList->Strings[Index],
  2438. FCustomCommandRemoteFileList->Objects[Index]);
  2439. CustomCommand(RemoteFileList, Command, LocalFileList);
  2440. }
  2441. }
  2442. __finally
  2443. {
  2444. delete LocalFileList;
  2445. delete RemoteFileList;
  2446. }
  2447. }
  2448. //---------------------------------------------------------------------------
  2449. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2450. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2451. {
  2452. delete FCustomCommandLocalFileList;
  2453. delete FCustomCommandRemoteFileList;
  2454. // takeover ownership,
  2455. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2456. FCustomCommandLocalFileList = LocalFileList;
  2457. FCustomCommandRemoteFileList = RemoteFileList;
  2458. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2459. if (Button != NULL)
  2460. {
  2461. FCustomCommandMenu->Items->Clear();
  2462. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2463. MenuPopup(FCustomCommandMenu, Button);
  2464. }
  2465. else
  2466. {
  2467. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2468. }
  2469. }
  2470. //---------------------------------------------------------------------------
  2471. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2472. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2473. {
  2474. DebugAssert(FCapturedLog != NULL);
  2475. if ((OutputType == cotOutput) || (OutputType == cotError))
  2476. {
  2477. FCapturedLog->Add(AddedLine);
  2478. }
  2479. }
  2480. //---------------------------------------------------------------------------
  2481. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2482. TOperationSide Side)
  2483. {
  2484. return
  2485. (Side == osOther) &&
  2486. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2487. }
  2488. //---------------------------------------------------------------------------
  2489. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2490. TOperationSide Side, TTBXCustomItem * Item,
  2491. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2492. {
  2493. TCustomDirView * DView = DirView(Side);
  2494. bool IsDefault = false;
  2495. if (DView->ItemFocused != NULL)
  2496. {
  2497. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2498. TResolvedDoubleClickAction DefaultAction =
  2499. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2500. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2501. }
  2502. TTBItemOptions O = Item->Options;
  2503. if (IsDefault)
  2504. {
  2505. Item->Options = O << tboDefault;
  2506. }
  2507. else
  2508. {
  2509. Item->Options = O >> tboDefault;
  2510. }
  2511. }
  2512. //---------------------------------------------------------------------------
  2513. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2514. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2515. {
  2516. TCustomDirView * DView = DirView(Side);
  2517. TListItem * Item = DView->ItemFocused;
  2518. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2519. EnableFocusedOperation[Side])
  2520. {
  2521. TPoint ClientPoint;
  2522. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2523. TPoint(0, 0) : MousePos;
  2524. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2525. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2526. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2527. }
  2528. }
  2529. //---------------------------------------------------------------------------
  2530. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2531. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2532. {
  2533. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2534. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2535. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2536. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2537. Handled = true;
  2538. }
  2539. //---------------------------------------------------------------------------
  2540. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2541. {
  2542. }
  2543. //---------------------------------------------------------------------------
  2544. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2545. {
  2546. DebugAssert(FErrorList == NULL);
  2547. if (WinConfiguration->ContinueOnError)
  2548. {
  2549. FErrorList = new TStringList();
  2550. Configuration->Usage->Inc(L"ContinuationsOnError");
  2551. }
  2552. NonVisualDataModule->StartBusy();
  2553. }
  2554. //---------------------------------------------------------------------------
  2555. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2556. {
  2557. NonVisualDataModule->EndBusy();
  2558. if (FErrorList)
  2559. {
  2560. HandleErrorList(FErrorList);
  2561. }
  2562. }
  2563. //---------------------------------------------------------------------------
  2564. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2565. const TCopyParamType & CopyParam)
  2566. {
  2567. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2568. {
  2569. Configuration->Usage->Inc(L"FileMaskUses");
  2570. }
  2571. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2572. {
  2573. Configuration->Usage->Inc(L"OperationMaskUses");
  2574. }
  2575. }
  2576. //---------------------------------------------------------------------------
  2577. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2578. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2579. {
  2580. DebugAssert(!IsLocalBrowserMode());
  2581. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2582. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2583. TTransferOperationParam DefaultParam;
  2584. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2585. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2586. switch (Param.Queue)
  2587. {
  2588. case asOn:
  2589. CopyParam.Queue = true;
  2590. break;
  2591. case asOff:
  2592. CopyParam.Queue = false;
  2593. break;
  2594. case asAuto:
  2595. default:
  2596. // keep default
  2597. break;
  2598. }
  2599. bool Result =
  2600. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2601. if (Result)
  2602. {
  2603. DebugAssert(Terminal);
  2604. bool SelectionRestored = false;
  2605. TCustomDirView * DView = NULL;
  2606. if (HasDirView[Side])
  2607. {
  2608. DView = DirView(Side);
  2609. DView->SaveSelection();
  2610. DView->SaveSelectedNames();
  2611. }
  2612. UpdateCopyParamCounters(CopyParam);
  2613. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2614. DebugAssert(FTransferResumeList == NULL);
  2615. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2616. FMoveToQueue = false;
  2617. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2618. try
  2619. {
  2620. TStrings * PermanentFileList;
  2621. std::unique_ptr<TStrings> PermanentFileListOwner;
  2622. try
  2623. {
  2624. if (Side == osLocal)
  2625. {
  2626. PermanentFileList = FileList;
  2627. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2628. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2629. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2630. if (Operation == foMove)
  2631. {
  2632. ReloadLocalDirectory();
  2633. if (DView != NULL)
  2634. {
  2635. DView->RestoreSelection();
  2636. }
  2637. SelectionRestored = true;
  2638. }
  2639. }
  2640. else
  2641. {
  2642. // Clone the file list as it may refer to current directory files,
  2643. // which get destroyed, when the source directory is reloaded after foMove operation.
  2644. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2645. // But for a hotfix, we are not going to do such a big change.
  2646. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2647. PermanentFileList = PermanentFileListOwner.get();
  2648. try
  2649. {
  2650. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2651. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2652. }
  2653. __finally
  2654. {
  2655. if (Operation == foMove)
  2656. {
  2657. if (DView != NULL)
  2658. {
  2659. DView->RestoreSelection();
  2660. }
  2661. SelectionRestored = true;
  2662. }
  2663. ReloadLocalDirectory(Param.TargetDirectory);
  2664. }
  2665. }
  2666. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2667. if (FMoveToQueue)
  2668. {
  2669. Abort();
  2670. }
  2671. }
  2672. catch (EAbort &)
  2673. {
  2674. if (FMoveToQueue)
  2675. {
  2676. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2677. DebugAssert(CopyParam.TransferSkipList == NULL);
  2678. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2679. if (TransferResumeList->Count > 0)
  2680. {
  2681. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2682. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2683. }
  2684. CopyParam.TransferSkipList = TransferResumeList.release();
  2685. // not really needed, just to keep it consistent with TransferResumeList
  2686. FTransferResumeList = NULL;
  2687. FMoveToQueue = false;
  2688. Configuration->Usage->Inc("MovesToBackground");
  2689. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2690. ClearTransferSourceSelection(Direction);
  2691. }
  2692. throw;
  2693. }
  2694. }
  2695. __finally
  2696. {
  2697. if (!SelectionRestored && (DView != NULL))
  2698. {
  2699. DView->DiscardSavedSelection();
  2700. }
  2701. FTransferResumeList = NULL;
  2702. }
  2703. }
  2704. return Result;
  2705. }
  2706. //---------------------------------------------------------------------------
  2707. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2708. TOperationSide Side, TStrings * FileList, void * Param)
  2709. {
  2710. DebugAssert(FileList->Count);
  2711. // We deliberately do not toggle alternative flag (Param), but use OR,
  2712. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2713. // shortcut of CurrentDeleteAlternativeAction
  2714. bool Alternative =
  2715. bool(Param) || UseAlternativeFunction();
  2716. bool Recycle;
  2717. if (IsSideLocalBrowser(Side))
  2718. {
  2719. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2720. }
  2721. else
  2722. {
  2723. Recycle =
  2724. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2725. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2726. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2727. }
  2728. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2729. if (!Result)
  2730. {
  2731. UnicodeString Query;
  2732. if (FileList->Count == 1)
  2733. {
  2734. if (IsSideLocalBrowser(Side))
  2735. {
  2736. Query = ExtractFileName(FileList->Strings[0]);
  2737. }
  2738. else
  2739. {
  2740. Query = UnixExtractFileName(FileList->Strings[0]);
  2741. }
  2742. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2743. }
  2744. else
  2745. {
  2746. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2747. }
  2748. TMessageParams Params(mpNeverAskAgainCheck);
  2749. Params.ImageName = L"Delete file";
  2750. unsigned int Answer =
  2751. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2752. if (Answer == qaNeverAskAgain)
  2753. {
  2754. Result = true;
  2755. if (Recycle)
  2756. {
  2757. WinConfiguration->ConfirmRecycling = false;
  2758. }
  2759. else
  2760. {
  2761. WinConfiguration->ConfirmDeleting = false;
  2762. }
  2763. }
  2764. else
  2765. {
  2766. Result = (Answer == qaOK);
  2767. }
  2768. }
  2769. if (Result)
  2770. {
  2771. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2772. }
  2773. return Result;
  2774. }
  2775. //---------------------------------------------------------------------------
  2776. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2777. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2778. {
  2779. TAutoBatch AutoBatch(this);
  2780. bool Result;
  2781. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2782. {
  2783. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2784. }
  2785. else if (Operation == foRename)
  2786. {
  2787. DebugAssert(DirView(Side)->ItemFocused);
  2788. DirView(Side)->ItemFocused->EditCaption();
  2789. Result = true;
  2790. }
  2791. else if (Operation == foDelete)
  2792. {
  2793. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2794. }
  2795. else if (Operation == foSetProperties)
  2796. {
  2797. DirView(osRemote)->SaveSelectedNames();
  2798. Result = SetProperties(Side, FileList);
  2799. }
  2800. else if (Operation == foCustomCommand)
  2801. {
  2802. DebugAssert(Param);
  2803. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2804. DirView(osRemote)->SaveSelectedNames();
  2805. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2806. CustomCommand(FileList, *Command, NULL);
  2807. Result = true;
  2808. }
  2809. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2810. {
  2811. DebugAssert(!IsSideLocalBrowser(Side));
  2812. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2813. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2814. }
  2815. else if (Operation == foLock)
  2816. {
  2817. DebugAssert(!IsSideLocalBrowser(Side));
  2818. LockFiles(FileList, true);
  2819. Result = true;
  2820. }
  2821. else if (Operation == foUnlock)
  2822. {
  2823. DebugAssert(!IsSideLocalBrowser(Side));
  2824. LockFiles(FileList, false);
  2825. Result = true;
  2826. }
  2827. else
  2828. {
  2829. DebugFail();
  2830. }
  2831. return Result;
  2832. }
  2833. //---------------------------------------------------------------------------
  2834. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2835. {
  2836. if (Side == osCurrent)
  2837. {
  2838. Side = FCurrentSide;
  2839. }
  2840. return Side;
  2841. }
  2842. //---------------------------------------------------------------------------
  2843. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2844. {
  2845. TOperationSide Result;
  2846. switch (GetSide(Side))
  2847. {
  2848. case osLocal:
  2849. Result = osOther;
  2850. break;
  2851. case osOther:
  2852. Result = osLocal;
  2853. break;
  2854. default:
  2855. DebugFail();
  2856. Abort();
  2857. }
  2858. return Result;
  2859. }
  2860. //---------------------------------------------------------------------------
  2861. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2862. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2863. {
  2864. Side = GetSide(Side);
  2865. bool FullPath = IsSideLocalBrowser(Side);
  2866. TCustomDirView * ADirView = DirView(Side);
  2867. std::unique_ptr<TStringList> FileList(new TStringList());
  2868. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2869. bool ReloadProperties =
  2870. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2871. DebugAlwaysTrue(HasActiveTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2872. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2873. if (Result && ReloadProperties)
  2874. {
  2875. std::unique_ptr<TStringList> FileList2(new TStringList());
  2876. FileList->CaseSensitive = true;
  2877. FileList->Sort();
  2878. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2879. {
  2880. TListItem * Item = ADirView->Items->Item[Index];
  2881. UnicodeString FileName = ADirView->ItemFileName(Item);
  2882. int Index2;
  2883. if (FileList->Find(FileName, Index2))
  2884. {
  2885. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2886. }
  2887. }
  2888. LoadFilesProperties(FileList2.get());
  2889. }
  2890. return Result;
  2891. }
  2892. //---------------------------------------------------------------------------
  2893. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2894. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2895. bool NoConfirmation, void * Param)
  2896. {
  2897. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2898. {
  2899. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2900. {
  2901. DebugAssert(!IsLocalBrowserMode());
  2902. if (GetSide(Side) == osLocal)
  2903. {
  2904. Configuration->Usage->Inc(L"UploadsCommand");
  2905. }
  2906. else
  2907. {
  2908. Configuration->Usage->Inc(L"DownloadsCommand");
  2909. }
  2910. }
  2911. }
  2912. }
  2913. //---------------------------------------------------------------------------
  2914. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2915. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2916. {
  2917. TTransferOperationParam Param;
  2918. if ((WinConfiguration->Interface != ifCommander) ||
  2919. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2920. {
  2921. Flags &= ~cocShortCutHint;
  2922. }
  2923. TCustomDirView * DView = DirView(Side);
  2924. Param.Options =
  2925. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2926. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2927. if (FLAGSET(Flags, cocQueue))
  2928. {
  2929. Param.Queue = asOn;
  2930. }
  2931. else if (FLAGSET(Flags, cocNonQueue))
  2932. {
  2933. Param.Queue = asOff;
  2934. }
  2935. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2936. }
  2937. //---------------------------------------------------------------------------
  2938. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2939. {
  2940. int Count = ErrorList->Count;
  2941. try
  2942. {
  2943. if (ErrorList->Count)
  2944. {
  2945. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2946. if (MessageDialog(Message, qtError,
  2947. qaOK | qaCancel, HELP_NONE) == qaOK)
  2948. {
  2949. unsigned int Answer;
  2950. int Index = 0;
  2951. do
  2952. {
  2953. DebugAssert(Index >= 0 && Index < Count);
  2954. TQueryButtonAlias Aliases[2];
  2955. Aliases[0].Button = qaYes;
  2956. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2957. Aliases[1].Button = qaNo;
  2958. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2959. TMessageParams Params;
  2960. Params.Aliases = Aliases;
  2961. Params.AliasesCount = LENOF(Aliases);
  2962. int No = Index + 1;
  2963. UnicodeString Message = ErrorList->Strings[Index];
  2964. UnicodeString AMainInstructions;
  2965. UnicodeString Details;
  2966. if (ExtractMainInstructions(Message, AMainInstructions))
  2967. {
  2968. Details = Message;
  2969. Message = AMainInstructions;
  2970. }
  2971. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2972. Answer = MoreMessageDialog(
  2973. Message,
  2974. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2975. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2976. qaOK, HELP_NONE, &Params);
  2977. if (Answer == qaNo)
  2978. {
  2979. Index++;
  2980. }
  2981. if (Answer == qaYes)
  2982. {
  2983. Index--;
  2984. }
  2985. }
  2986. while (Answer != qaOK);
  2987. }
  2988. }
  2989. }
  2990. __finally
  2991. {
  2992. TStrings * List = ErrorList;
  2993. ErrorList = NULL;
  2994. for (int i = 0; i < Count; i++)
  2995. {
  2996. delete List->Objects[i];
  2997. }
  2998. delete List;
  2999. }
  3000. }
  3001. //---------------------------------------------------------------------------
  3002. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3003. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3004. {
  3005. // needed for checking filemasks, as there's no directory object
  3006. // associated with the file object
  3007. File->FullFileName = FullFileName;
  3008. TFileMasks::TParams MaskParams;
  3009. MaskParams.Size = File->Size;
  3010. MaskParams.Modification = File->Modification;
  3011. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3012. }
  3013. //---------------------------------------------------------------------------
  3014. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3015. {
  3016. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3017. Side = GetSide(Side);
  3018. TCustomDirView * DView = DirView(Side);
  3019. TListItem * FocusedItem = DView->ItemFocused;
  3020. UnicodeString Name;
  3021. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3022. {
  3023. Name = DView->ItemFileName(FocusedItem);
  3024. }
  3025. else
  3026. {
  3027. Name = LoadStr(NEW_FILE);
  3028. }
  3029. UnicodeString Names = Name;
  3030. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3031. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3032. HELP_EDIT_NEW, History.get(), true, NULL, true, 400))
  3033. {
  3034. while (!Names.IsEmpty())
  3035. {
  3036. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3037. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3038. UnicodeString TargetFileName;
  3039. UnicodeString LocalFileName;
  3040. UnicodeString RootTempDir;
  3041. UnicodeString TempDir;
  3042. UnicodeString RemoteDirectory;
  3043. bool ExistingFile = false;
  3044. if (!IsSideLocalBrowser(Side))
  3045. {
  3046. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3047. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3048. if ((File.get() != NULL) &&
  3049. !File->IsDirectory)
  3050. {
  3051. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3052. ExistingFile = true;
  3053. }
  3054. File.reset(NULL);
  3055. if (!ExistingFile)
  3056. {
  3057. RemoteDirectory = UnixExtractFilePath(Name);
  3058. TemporaryDirectoryForRemoteFiles(
  3059. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3060. TargetFileName = UnixExtractFileName(Name);
  3061. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3062. LocalFileName = TempDir +
  3063. // We probably do not want to trim the VMS version here
  3064. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3065. }
  3066. }
  3067. else
  3068. {
  3069. if (ExtractFilePath(Name).IsEmpty())
  3070. {
  3071. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3072. }
  3073. else
  3074. {
  3075. LocalFileName = ExpandFileName(Name);
  3076. }
  3077. TargetFileName = ExtractFileName(Name);
  3078. }
  3079. if (!ExistingFile)
  3080. {
  3081. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3082. if (NewFile)
  3083. {
  3084. int File = FileCreate(ApiPath(LocalFileName));
  3085. if (File < 0)
  3086. {
  3087. if (!RootTempDir.IsEmpty())
  3088. {
  3089. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3090. }
  3091. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3092. }
  3093. else
  3094. {
  3095. FileClose(File);
  3096. }
  3097. }
  3098. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3099. const TEditorData * ExternalEditor = NULL;
  3100. TFileMasks::TParams MaskParams; // size not known
  3101. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3102. false, MaskParams);
  3103. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3104. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3105. }
  3106. }
  3107. }
  3108. }
  3109. //---------------------------------------------------------------------------
  3110. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3111. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3112. {
  3113. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3114. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3115. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3116. return
  3117. ((ExecuteFileBy == efInternalEditor)) ||
  3118. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3119. }
  3120. //---------------------------------------------------------------------------
  3121. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3122. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3123. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3124. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3125. {
  3126. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3127. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3128. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3129. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3130. Side = GetSide(Side);
  3131. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3132. if (!IsSideLocalBrowser(Side))
  3133. {
  3134. Data->Terminal = Terminal;
  3135. Data->Queue = Queue;
  3136. Data->SessionData = CloneCurrentSessionData();
  3137. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3138. Data->RemoteDirectory = RemoteDirectory;
  3139. Data->SessionName = Terminal->SessionData->SessionName;
  3140. Data->LocalRootDirectory = LocalRootDirectory;
  3141. Data->OriginalFileName = OriginalFileName;
  3142. Data->Command = L""; // will be changed later for external editor
  3143. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3144. if (WinConfiguration->EditorCheckNotModified)
  3145. {
  3146. Data->SourceTimestamp = SourceTimestamp;
  3147. }
  3148. }
  3149. if (ExecuteFileBy == efInternalEditor)
  3150. {
  3151. if (!IsSideLocalBrowser(Side))
  3152. {
  3153. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3154. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3155. TForm * Editor;
  3156. try
  3157. {
  3158. Editor =
  3159. ShowEditorForm(
  3160. FileName, this,
  3161. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3162. SaveAllInternalEditors, AnyInternalEditorModified,
  3163. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3164. }
  3165. catch(...)
  3166. {
  3167. if (!LocalRootDirectory.IsEmpty())
  3168. {
  3169. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3170. }
  3171. throw;
  3172. }
  3173. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3174. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3175. }
  3176. else
  3177. {
  3178. DebugAssert(!StandaloneOperation);
  3179. TForm * Editor =
  3180. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3181. SaveAllInternalEditors, AnyInternalEditorModified,
  3182. L"", false, SessionColor, -1, NewFile);
  3183. FLocalEditors->Add(Editor);
  3184. }
  3185. }
  3186. else
  3187. {
  3188. HANDLE Process;
  3189. if (ExecuteFileBy == efExternalEditor)
  3190. {
  3191. UnicodeString Program, Params, Dir;
  3192. Data->Command = ExternalEditor->ExternalEditor;
  3193. ReformatFileNameCommand(Data->Command);
  3194. SplitCommand(Data->Command, Program, Params, Dir);
  3195. Params = ExpandFileNameCommand(Params, FileName);
  3196. Program = ExpandEnvironmentVariables(Program);
  3197. if (!ExecuteShell(Program, Params, Process))
  3198. {
  3199. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3200. }
  3201. }
  3202. else
  3203. {
  3204. DebugAssert(!IsSideLocalBrowser(Side));
  3205. if (!ExecuteShell(FileName, L"", Process))
  3206. {
  3207. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3208. }
  3209. }
  3210. if (IsSideLocalBrowser(Side) ||
  3211. ((ExecuteFileBy == efShell) &&
  3212. !WinConfiguration->Editor.SDIShellEditor) ||
  3213. ((ExecuteFileBy == efExternalEditor) &&
  3214. !ExternalEditor->SDIExternalEditor))
  3215. {
  3216. // no need for handle
  3217. if (Process != NULL)
  3218. {
  3219. DebugCheck(CloseHandle(Process));
  3220. }
  3221. Process = INVALID_HANDLE_VALUE;
  3222. }
  3223. else
  3224. {
  3225. if (Process == NULL)
  3226. {
  3227. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3228. }
  3229. }
  3230. if (!IsSideLocalBrowser(Side))
  3231. {
  3232. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3233. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3234. }
  3235. }
  3236. }
  3237. //---------------------------------------------------------------------------
  3238. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3239. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3240. void * /*Arg*/)
  3241. {
  3242. if (Token != NULL)
  3243. {
  3244. EditorFormFileSave(static_cast<TForm *>(Token));
  3245. }
  3246. }
  3247. //---------------------------------------------------------------------------
  3248. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3249. {
  3250. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3251. {
  3252. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3253. }
  3254. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3255. }
  3256. //---------------------------------------------------------------------------
  3257. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3258. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3259. void * Arg)
  3260. {
  3261. if ((Token != NULL) &&
  3262. IsEditorFormModified(static_cast<TForm *>(Token)))
  3263. {
  3264. *static_cast<bool *>(Arg) = true;
  3265. }
  3266. }
  3267. //---------------------------------------------------------------------------
  3268. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3269. TObject * /*Sender*/, bool & Modified)
  3270. {
  3271. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3272. {
  3273. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3274. {
  3275. Modified = true;
  3276. }
  3277. }
  3278. if (!Modified)
  3279. {
  3280. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3281. }
  3282. }
  3283. //---------------------------------------------------------------------------
  3284. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3285. {
  3286. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3287. }
  3288. //---------------------------------------------------------------------------
  3289. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3290. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3291. UnicodeString & Result, UnicodeString & RootDirectory)
  3292. {
  3293. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3294. {
  3295. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3296. Result = RootDirectory;
  3297. }
  3298. else
  3299. {
  3300. RootDirectory = L"";
  3301. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3302. Result = IncludeTrailingBackslash(Result);
  3303. }
  3304. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3305. {
  3306. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3307. }
  3308. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3309. {
  3310. UnicodeString ARemoteDirectory = RemoteDirectory;
  3311. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3312. {
  3313. ARemoteDirectory.Delete(1, 1);
  3314. }
  3315. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3316. }
  3317. if (!ForceDirectories(ApiPath(Result)))
  3318. {
  3319. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3320. }
  3321. }
  3322. //---------------------------------------------------------------------------
  3323. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3324. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3325. bool GetTargetNames, bool AutoOperation, bool SimpleTempDir)
  3326. {
  3327. DebugAssert(!IsLocalBrowserMode());
  3328. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3329. if (ForceText)
  3330. {
  3331. CopyParam.TransferMode = tmAscii;
  3332. }
  3333. TemporaryFileCopyParam(CopyParam);
  3334. if (TempDir.IsEmpty())
  3335. {
  3336. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3337. }
  3338. DebugAssert(!FAutoOperation);
  3339. FAutoOperation = AutoOperation;
  3340. Terminal->ExceptionOnFail = true;
  3341. try
  3342. {
  3343. try
  3344. {
  3345. // turn off confirmations, as for MDI editors we may possibly download
  3346. // the same file over
  3347. Terminal->CopyToLocal(
  3348. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3349. if (GetTargetNames)
  3350. {
  3351. for (int i = 0; i < FileList->Count; i++)
  3352. {
  3353. FileList->Strings[i] =
  3354. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3355. }
  3356. }
  3357. }
  3358. catch(...)
  3359. {
  3360. if (!RootTempDir.IsEmpty())
  3361. {
  3362. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3363. }
  3364. throw;
  3365. }
  3366. }
  3367. __finally
  3368. {
  3369. FAutoOperation = false;
  3370. Terminal->ExceptionOnFail = false;
  3371. }
  3372. }
  3373. //---------------------------------------------------------------------------
  3374. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3375. {
  3376. // Do not waste time checking for default editor list the next time,
  3377. // or testing if default editor is not notepad.
  3378. bool TryNextTime = false;
  3379. UnicodeString UsageState;
  3380. if (!WinConfiguration->EditorList->IsDefaultList())
  3381. {
  3382. UsageState = "H";
  3383. }
  3384. else
  3385. {
  3386. UnicodeString Executable;
  3387. UnicodeString ExecutableDescription;
  3388. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3389. {
  3390. UnicodeString Message =
  3391. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3392. unsigned int Answer =
  3393. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3394. if (Answer != qaOK)
  3395. {
  3396. UsageState = "R";
  3397. }
  3398. else
  3399. {
  3400. UsageState = "A";
  3401. TEditorData EditorData;
  3402. EditorData.Editor = edExternal;
  3403. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3404. EditorData.ExternalEditorOptionsAutodetect();
  3405. TEditorList EditorList;
  3406. EditorList = *WinConfiguration->EditorList;
  3407. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3408. WinConfiguration->EditorList = &EditorList;
  3409. }
  3410. }
  3411. }
  3412. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3413. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3414. }
  3415. //---------------------------------------------------------------------------
  3416. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3417. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3418. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3419. {
  3420. if (ExecuteFileBy == efDefaultEditor)
  3421. {
  3422. if (!WinConfiguration->OfferedEditorAutoConfig)
  3423. {
  3424. EditorAutoConfig();
  3425. }
  3426. const TEditorPreferences * Editor =
  3427. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3428. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3429. {
  3430. ExecuteFileBy = efInternalEditor;
  3431. ExternalEditor = NULL;
  3432. }
  3433. else if (Editor->Data->Editor == edOpen)
  3434. {
  3435. ExecuteFileBy = efShell;
  3436. ExternalEditor = NULL;
  3437. }
  3438. else
  3439. {
  3440. ExecuteFileBy = efExternalEditor;
  3441. ExternalEditor = Editor->Data;
  3442. }
  3443. }
  3444. }
  3445. //---------------------------------------------------------------------------
  3446. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3447. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3448. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3449. {
  3450. UnicodeString OriginalFileName;
  3451. UnicodeString LocalRootDirectory;
  3452. UnicodeString RemoteDirectory;
  3453. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3454. IsSideLocalBrowser(Side), MaskParams);
  3455. UnicodeString Counter;
  3456. UnicodeString LocalFileName;
  3457. bool Handled = false;
  3458. if (!IsSideLocalBrowser(Side))
  3459. {
  3460. // We need to trim VMS version here, so that we use name without version
  3461. // when uploading back to create a new version of the file
  3462. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3463. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3464. TObject * Token = NULL;
  3465. UnicodeString LocalDirectory;
  3466. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3467. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3468. LocalDirectory))
  3469. {
  3470. if (Token != NULL)
  3471. {
  3472. TForm * Form = dynamic_cast<TForm *>(Token);
  3473. if (Form->WindowState == wsMinimized)
  3474. {
  3475. ShowWindow(Form->Handle, SW_RESTORE);
  3476. }
  3477. else
  3478. {
  3479. Form->SetFocus();
  3480. }
  3481. Handled = true;
  3482. }
  3483. else
  3484. {
  3485. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3486. }
  3487. }
  3488. if (!Handled)
  3489. {
  3490. TStringList * FileList1 = new TStringList();
  3491. try
  3492. {
  3493. FileList1->AddObject(FullFileName, Object);
  3494. TemporarilyDownloadFiles(FileList1,
  3495. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3496. LocalRootDirectory, LocalDirectory, true, true, false);
  3497. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3498. }
  3499. __finally
  3500. {
  3501. delete FileList1;
  3502. }
  3503. switch (ExecuteFileBy)
  3504. {
  3505. case efShell:
  3506. Counter = "RemoteFilesExecuted";
  3507. break;
  3508. case efInternalEditor:
  3509. Counter = "RemoteFilesOpenedInInternalEditor";
  3510. break;
  3511. case efExternalEditor:
  3512. Counter = "RemoteFilesOpenedInExternalEditor";
  3513. break;
  3514. default:
  3515. DebugFail();
  3516. }
  3517. }
  3518. }
  3519. else
  3520. {
  3521. LocalFileName = FullFileName;
  3522. OriginalFileName = ExtractFileName(FullFileName);
  3523. switch (ExecuteFileBy)
  3524. {
  3525. case efShell:
  3526. Counter = "LocalFilesExecuted";
  3527. break;
  3528. case efInternalEditor:
  3529. Counter = "LocalFilesOpenedInInternalEditor";
  3530. break;
  3531. case efExternalEditor:
  3532. Counter = "LocalFilesOpenedInExternalEditor";
  3533. break;
  3534. default:
  3535. DebugFail();
  3536. }
  3537. }
  3538. if (!Handled)
  3539. {
  3540. Configuration->Usage->Inc(Counter);
  3541. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3542. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3543. }
  3544. }
  3545. //---------------------------------------------------------------------------
  3546. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3547. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3548. bool AllSelected, bool OnFocused)
  3549. {
  3550. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3551. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3552. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3553. Side = GetSide(Side);
  3554. TCustomDirView * DView = DirView(Side);
  3555. TStrings * FileList =
  3556. AllSelected ?
  3557. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3558. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3559. try
  3560. {
  3561. DebugAssert(AllSelected || (FileList->Count == 1));
  3562. for (int i = 0; i < FileList->Count; i++)
  3563. {
  3564. UnicodeString ListFileName = FileList->Strings[i];
  3565. UnicodeString FileNameOnly =
  3566. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3567. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3568. if (!DView->ItemIsDirectory(Item))
  3569. {
  3570. UnicodeString FullFileName;
  3571. if (!IsSideLocalBrowser(Side))
  3572. {
  3573. FullFileName = DirView(Side)->Path + ListFileName;
  3574. }
  3575. else
  3576. {
  3577. FullFileName = ListFileName;
  3578. }
  3579. TObject * Object = FileList->Objects[i];
  3580. TFileMasks::TParams MaskParams;
  3581. MaskParams.Size = DView->ItemFileSize(Item);
  3582. TDateTimePrecision Precision;
  3583. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3584. std::unique_ptr<TRemoteFile> File;
  3585. if (!IsSideLocalBrowser(Side))
  3586. {
  3587. File.reset(Terminal->TryReadFile(FullFileName));
  3588. if (File.get() != NULL)
  3589. {
  3590. File->FullFileName = FullFileName;
  3591. Object = File.get();
  3592. MaskParams.Size = File->Size;
  3593. MaskParams.Modification = File->Modification;
  3594. }
  3595. }
  3596. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3597. }
  3598. }
  3599. }
  3600. __finally
  3601. {
  3602. delete FileList;
  3603. }
  3604. }
  3605. //---------------------------------------------------------------------------
  3606. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3607. {
  3608. CopyParam.FileNameCase = ncNoChange;
  3609. CopyParam.PreserveRights = false;
  3610. CopyParam.PreserveReadOnly = false;
  3611. CopyParam.ReplaceInvalidChars = true;
  3612. CopyParam.IncludeFileMask = TFileMasks();
  3613. CopyParam.NewerOnly = false;
  3614. CopyParam.FileMask = L"";
  3615. }
  3616. //---------------------------------------------------------------------------
  3617. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3618. {
  3619. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3620. }
  3621. //---------------------------------------------------------------------------
  3622. class TEditorUploadQueueItem : public TUploadQueueItem
  3623. {
  3624. public:
  3625. __fastcall TEditorUploadQueueItem(
  3626. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3627. const TCopyParamType * CopyParam, int Params) :
  3628. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, true, false)
  3629. {
  3630. }
  3631. protected:
  3632. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3633. {
  3634. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3635. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3636. }
  3637. };
  3638. //---------------------------------------------------------------------------
  3639. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3640. {
  3641. if (WinConfiguration->EditorCheckNotModified) // optimization
  3642. {
  3643. UnicodeString RemoteFilePath;
  3644. {
  3645. TGuard Guard(FEditorManager->Section);
  3646. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3647. if (DebugAlwaysTrue(Data != NULL) &&
  3648. EditorCheckNotModified(Data))
  3649. {
  3650. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3651. }
  3652. }
  3653. if (!RemoteFilePath.IsEmpty())
  3654. {
  3655. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3656. if (File.get() != NULL)
  3657. {
  3658. TGuard Guard(FEditorManager->Section);
  3659. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3660. if (DebugAlwaysTrue(Data != NULL))
  3661. {
  3662. Data->SourceTimestamp = File->Modification;
  3663. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3664. }
  3665. }
  3666. }
  3667. }
  3668. }
  3669. //---------------------------------------------------------------------------
  3670. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3671. const UnicodeString & FileName, TEditedFileData * Data, HANDLE UploadCompleteEvent, bool & Retry)
  3672. {
  3673. TTerminalManager * Manager = TTerminalManager::Instance();
  3674. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3675. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3676. {
  3677. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3678. Retry = true;
  3679. }
  3680. else if (!IsActiveTerminal(Data->Terminal))
  3681. {
  3682. if (!NonVisualDataModule->Busy)
  3683. {
  3684. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3685. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3686. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3687. if (Data->Terminal == NULL)
  3688. {
  3689. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3690. if (SameSiteTerminal != NULL)
  3691. {
  3692. UnicodeString Message =
  3693. FMTLOAD(EDIT_SESSION_REATTACH,
  3694. (FileNameOnly, Data->SessionName, FileNameOnly));
  3695. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3696. {
  3697. Data->Terminal = SameSiteTerminal;
  3698. Data->Queue = Manager->FindQueueForTerminal(SameSiteTerminal);
  3699. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3700. // We might also overwrite session data
  3701. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3702. }
  3703. else
  3704. {
  3705. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3706. Abort();
  3707. }
  3708. }
  3709. }
  3710. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3711. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3712. {
  3713. UnicodeString Message =
  3714. MainInstructions(
  3715. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3716. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3717. {
  3718. if (Terminal->Disconnected)
  3719. {
  3720. Manager->ActiveSession = Terminal;
  3721. ReconnectSession();
  3722. DebugAssert(Terminal == Data->Terminal);
  3723. Data->Queue = Manager->FindQueueForTerminal(Terminal);
  3724. }
  3725. else
  3726. {
  3727. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3728. }
  3729. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3730. }
  3731. else
  3732. {
  3733. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3734. Abort();
  3735. }
  3736. }
  3737. }
  3738. if (!IsActiveTerminal(Data->Terminal))
  3739. {
  3740. Configuration->Usage->Inc(L"EditInactiveSession");
  3741. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3742. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3743. (ExtractFileName(FileName), Data->SessionName)));
  3744. }
  3745. }
  3746. if (!Retry && EditorCheckNotModified(Data))
  3747. {
  3748. if (NonVisualDataModule->Busy)
  3749. {
  3750. Retry = true;
  3751. }
  3752. else
  3753. {
  3754. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3755. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3756. if (File.get() != NULL)
  3757. {
  3758. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3759. if (File->Modification != Data->SourceTimestamp)
  3760. {
  3761. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3762. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3763. {
  3764. Abort();
  3765. }
  3766. }
  3767. }
  3768. }
  3769. }
  3770. if (!Retry)
  3771. {
  3772. TStrings * FileList = new TStringList();
  3773. try
  3774. {
  3775. FileList->Add(FileName);
  3776. // Consider using the same settings (preset) as when the file was downloaded.
  3777. // More over this does not reflect the actual session that will do the upload.
  3778. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3779. TemporaryFileCopyParam(CopyParam);
  3780. if (Data->ForceText)
  3781. {
  3782. CopyParam.TransferMode = tmAscii;
  3783. }
  3784. // so i do not need to worry if masking algorithm works in all cases
  3785. // ("" means "copy file name", no masking is actually done)
  3786. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3787. {
  3788. CopyParam.FileMask = L"";
  3789. }
  3790. else
  3791. {
  3792. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3793. }
  3794. int Params = cpNoConfirmation | cpTemporary;
  3795. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3796. {
  3797. DebugAssert(Data->Queue != NULL);
  3798. TQueueItem * QueueItem =
  3799. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3800. QueueItem->CompleteEvent = UploadCompleteEvent;
  3801. AddQueueItem(Data->Queue, QueueItem, Data->Terminal);
  3802. }
  3803. else
  3804. {
  3805. if (NonVisualDataModule->Busy)
  3806. {
  3807. Retry = true;
  3808. }
  3809. else
  3810. {
  3811. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3812. SetEvent(UploadCompleteEvent);
  3813. }
  3814. }
  3815. }
  3816. __finally
  3817. {
  3818. delete FileList;
  3819. }
  3820. }
  3821. }
  3822. //---------------------------------------------------------------------------
  3823. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3824. const UnicodeString & FileName, TEditedFileData * Data)
  3825. {
  3826. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3827. DebugAssert(!NonVisualDataModule->Busy);
  3828. if (!IsActiveTerminal(Data->Terminal))
  3829. {
  3830. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3831. (ExtractFileName(FileName), Data->SessionName)));
  3832. }
  3833. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3834. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3835. NonVisualDataModule->StartBusy();
  3836. try
  3837. {
  3838. std::unique_ptr<TRemoteFile> File;
  3839. UnicodeString RemoteFileName =
  3840. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3841. Terminal->ExceptionOnFail = true;
  3842. try
  3843. {
  3844. File.reset(Terminal->ReadFile(RemoteFileName));
  3845. if (!File->HaveFullFileName)
  3846. {
  3847. File->FullFileName = RemoteFileName;
  3848. }
  3849. }
  3850. __finally
  3851. {
  3852. Terminal->ExceptionOnFail = false;
  3853. }
  3854. std::unique_ptr<TStrings> FileList(new TStringList());
  3855. FileList->AddObject(RemoteFileName, File.get());
  3856. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3857. UnicodeString TempDir = ExtractFilePath(FileName);
  3858. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, true, false);
  3859. if (EditorCheckNotModified(Data))
  3860. {
  3861. Data->SourceTimestamp = File->Modification;
  3862. }
  3863. // sanity check, the target file name should be still the same
  3864. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3865. }
  3866. __finally
  3867. {
  3868. NonVisualDataModule->EndBusy();
  3869. // it actually may not exist anymore...
  3870. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3871. }
  3872. }
  3873. //---------------------------------------------------------------------------
  3874. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3875. const TEditedFileData * Data, bool & KeepOpen)
  3876. {
  3877. // Command is set for external editors only (not for "shell" open).
  3878. if (!Data->Command.IsEmpty())
  3879. {
  3880. bool AnyFound = false;
  3881. bool AnyMDI = false;
  3882. bool AnyNonMDI = false;
  3883. bool AnyDetect = false;
  3884. TEditorList * EditorList = new TEditorList();
  3885. try
  3886. {
  3887. *EditorList = *WinConfiguration->EditorList;
  3888. for (int i = 0; i < EditorList->Count; i++)
  3889. {
  3890. const TEditorPreferences * Editor = EditorList->Editors[i];
  3891. if ((Editor->Data->Editor == edExternal) &&
  3892. (Editor->Data->ExternalEditor == Data->Command))
  3893. {
  3894. AnyFound = true;
  3895. if (Editor->Data->SDIExternalEditor)
  3896. {
  3897. AnyNonMDI = true;
  3898. if (Editor->Data->DetectMDIExternalEditor)
  3899. {
  3900. AnyDetect = true;
  3901. }
  3902. }
  3903. else
  3904. {
  3905. AnyMDI = true;
  3906. }
  3907. }
  3908. }
  3909. bool EnableMDI = false;
  3910. bool DisableDetect = false;
  3911. if (AnyMDI)
  3912. {
  3913. KeepOpen = true;
  3914. if (AnyNonMDI)
  3915. {
  3916. // there is at least one instance of the editor with MDI support enabled,
  3917. // and one with disabled, enable it for all instances
  3918. EnableMDI = true;
  3919. }
  3920. }
  3921. else if (AnyFound && !AnyDetect)
  3922. {
  3923. // at least once instance found but all have MDI autodetection disabled
  3924. // => close the file (default action)
  3925. }
  3926. else
  3927. {
  3928. // no instance of the editor has MDI support enabled
  3929. TMessageParams Params;
  3930. if (AnyFound)
  3931. {
  3932. // there is at least one instance of the editor
  3933. Params.Params |= mpNeverAskAgainCheck;
  3934. }
  3935. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3936. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3937. switch (Answer)
  3938. {
  3939. case qaNeverAskAgain:
  3940. DisableDetect = true;
  3941. break;
  3942. case qaNo:
  3943. EnableMDI = true;
  3944. KeepOpen = true;
  3945. break;
  3946. }
  3947. }
  3948. if (AnyFound && (EnableMDI || DisableDetect))
  3949. {
  3950. bool Changed = false;
  3951. for (int i = 0; i < EditorList->Count; i++)
  3952. {
  3953. const TEditorPreferences * Editor = EditorList->Editors[i];
  3954. if ((Editor->Data->Editor == edExternal) &&
  3955. (Editor->Data->ExternalEditor == Data->Command) &&
  3956. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3957. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3958. {
  3959. Changed = true;
  3960. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3961. if (EnableMDI)
  3962. {
  3963. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3964. }
  3965. if (DisableDetect)
  3966. {
  3967. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3968. }
  3969. EditorList->Change(i, UpdatedEditor);
  3970. }
  3971. }
  3972. if (Changed)
  3973. {
  3974. WinConfiguration->EditorList = EditorList;
  3975. }
  3976. }
  3977. }
  3978. __finally
  3979. {
  3980. delete EditorList;
  3981. }
  3982. }
  3983. else
  3984. {
  3985. // "open" case
  3986. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  3987. qaOK, HELP_APP_EARLY_CLOSED);
  3988. }
  3989. }
  3990. //---------------------------------------------------------------------------
  3991. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  3992. {
  3993. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  3994. }
  3995. //---------------------------------------------------------------------------
  3996. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  3997. {
  3998. SideEnter(osRemote);
  3999. }
  4000. //---------------------------------------------------------------------------
  4001. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4002. {
  4003. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4004. SideEnter(osRemote);
  4005. }
  4006. //---------------------------------------------------------------------------
  4007. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4008. {
  4009. FCurrentSide = Side;
  4010. if (Visible)
  4011. {
  4012. UpdateControls();
  4013. }
  4014. }
  4015. //---------------------------------------------------------------------------
  4016. void __fastcall TCustomScpExplorerForm::FileDeleted(TOperationSide Side, const UnicodeString & FileName, bool Success)
  4017. {
  4018. VisualiseOperationFinished(Side, FileName, Success);
  4019. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4020. {
  4021. FDeletedFiles->Add(FileName);
  4022. }
  4023. }
  4024. //---------------------------------------------------------------------------
  4025. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4026. TStrings * FileList, bool Alternative)
  4027. {
  4028. TCustomDirView * DView = DirView(Side);
  4029. DView->SaveSelection();
  4030. DView->SaveSelectedNames();
  4031. DebugAssert(!FAlternativeDelete);
  4032. FAlternativeDelete = Alternative;
  4033. try
  4034. {
  4035. if (!IsSideLocalBrowser(Side))
  4036. {
  4037. DebugAssert(Terminal != NULL);
  4038. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4039. std::unique_ptr<TStrings> PermanentFileList(TRemoteFileList::CloneStrings(FileList));
  4040. std::unique_ptr<TStringList> DeletedFiles(new TStringList());
  4041. DeletedFiles->CaseSensitive = DebugAlwaysTrue(!IsSideLocalBrowser(Side));
  4042. int Params = FLAGMASK(Alternative, dfAlternative);
  4043. try
  4044. {
  4045. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles);
  4046. DebugAssert(FDeletedFiles == NULL);
  4047. FDeletedFiles = DeletedFiles.get();
  4048. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4049. FOnFileOperationFinished = FileDeleted;
  4050. FMoveToQueue = false;
  4051. Terminal->DeleteFiles(FileList, Params);
  4052. // Probably not needed for deleting, just for consistency with transfer code
  4053. if (FMoveToQueue)
  4054. {
  4055. Abort();
  4056. }
  4057. }
  4058. catch (EAbort &)
  4059. {
  4060. if (FMoveToQueue)
  4061. {
  4062. DeletedFiles->Sorted = true;
  4063. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4064. {
  4065. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4066. {
  4067. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4068. DebugAssert(Index == 0);
  4069. PermanentFileList->Delete(Index);
  4070. Index--;
  4071. }
  4072. }
  4073. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4074. TQueueItem * QueueItem = new TDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4075. AddQueueItem(Queue, QueueItem, Terminal);
  4076. ClearOperationSelection(osRemote);
  4077. }
  4078. }
  4079. }
  4080. else
  4081. {
  4082. if (IsLocalBrowserMode())
  4083. {
  4084. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4085. }
  4086. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  4087. FProgressSide = FCurrentSide;
  4088. try
  4089. {
  4090. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  4091. }
  4092. __finally
  4093. {
  4094. ReloadLocalDirectory();
  4095. }
  4096. }
  4097. FAlternativeDelete = false;
  4098. }
  4099. catch(...)
  4100. {
  4101. FAlternativeDelete = false;
  4102. DView->DiscardSavedSelection();
  4103. throw;
  4104. }
  4105. DView->RestoreSelection();
  4106. }
  4107. //---------------------------------------------------------------------------
  4108. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4109. {
  4110. DebugAssert(Terminal);
  4111. DebugAssert(!IsLocalBrowserMode());
  4112. RemoteDirView->SaveSelection();
  4113. RemoteDirView->SaveSelectedNames();
  4114. try
  4115. {
  4116. if (Lock)
  4117. {
  4118. Terminal->LockFiles(FileList);
  4119. }
  4120. else
  4121. {
  4122. Terminal->UnlockFiles(FileList);
  4123. }
  4124. }
  4125. catch(...)
  4126. {
  4127. RemoteDirView->DiscardSavedSelection();
  4128. throw;
  4129. }
  4130. RemoteDirView->RestoreSelection();
  4131. }
  4132. //---------------------------------------------------------------------------
  4133. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4134. {
  4135. bool Result = false;
  4136. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4137. if (IsActiveTerminal(ATerminal))
  4138. {
  4139. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(Directory));
  4140. Result = File && File->IsDirectory;
  4141. }
  4142. return Result;
  4143. }
  4144. //---------------------------------------------------------------------------
  4145. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4146. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4147. bool NoConfirmation, bool Move)
  4148. {
  4149. DebugAssert(Terminal != NULL);
  4150. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4151. DebugAssert(!IsLocalBrowserMode());
  4152. if (Session == NULL)
  4153. {
  4154. Session = Terminal;
  4155. }
  4156. if (Session == Terminal)
  4157. {
  4158. if (RemoteDriveView->DropTarget != NULL)
  4159. {
  4160. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4161. }
  4162. else if (RemoteDirView->DropTarget != NULL)
  4163. {
  4164. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4165. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4166. }
  4167. else
  4168. {
  4169. Target = RemoteDirView->Path;
  4170. }
  4171. }
  4172. else
  4173. {
  4174. Target = GetSessionPath(Session, osRemote);
  4175. }
  4176. Target = UnixIncludeTrailingBackslash(Target);
  4177. if (FileList->Count == 1)
  4178. {
  4179. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4180. }
  4181. else
  4182. {
  4183. FileMask = AnyMask;
  4184. }
  4185. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4186. bool Result = true;
  4187. if (!NoConfirmation)
  4188. {
  4189. bool Multi = (FileList->Count > 1);
  4190. if (Move)
  4191. {
  4192. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4193. }
  4194. else
  4195. {
  4196. std::unique_ptr<TStrings> Sessions(new TStringList);
  4197. std::unique_ptr<TStrings> Directories(new TStringList);
  4198. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4199. for (int Index = 0; Index < SessionList->Count; Index++)
  4200. {
  4201. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4202. if (IsActiveTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4203. {
  4204. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4205. Directories->Add(GetSessionPath(ASession, osRemote));
  4206. }
  4207. }
  4208. TDirectRemoteCopy AllowDirectCopy;
  4209. if (Terminal->IsCapable[fcRemoteCopy] || Terminal->CommandSessionOpened)
  4210. {
  4211. DebugAssert(DirectCopy);
  4212. AllowDirectCopy = drcAllow;
  4213. }
  4214. else if (Terminal->IsCapable[fcSecondaryShell])
  4215. {
  4216. DebugAssert(DirectCopy);
  4217. AllowDirectCopy = drcConfirmCommandSession;
  4218. }
  4219. else
  4220. {
  4221. DebugAssert(!DirectCopy);
  4222. AllowDirectCopy = drcDisallow;
  4223. }
  4224. void * ASession = Session;
  4225. Result = DoRemoteCopyDialog(
  4226. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4227. DoDirectoryExists);
  4228. Session = static_cast<TManagedTerminal *>(ASession);
  4229. }
  4230. }
  4231. return Result;
  4232. }
  4233. //---------------------------------------------------------------------------
  4234. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4235. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4236. {
  4237. DebugAssert(!IsLocalBrowserMode());
  4238. bool DirectCopy;
  4239. UnicodeString Target, FileMask;
  4240. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4241. if (Result)
  4242. {
  4243. if (!Move && !DirectCopy)
  4244. {
  4245. Configuration->Usage->Inc("RemoteCopyTemp");
  4246. UnicodeString RootTempDir;
  4247. UnicodeString TempDir;
  4248. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  4249. TStrings * TemporaryFilesList = new TStringList();
  4250. try
  4251. {
  4252. TMakeLocalFileListParams MakeFileListParam;
  4253. MakeFileListParam.FileList = TemporaryFilesList;
  4254. MakeFileListParam.FileTimes = NULL;
  4255. MakeFileListParam.IncludeDirs = true;
  4256. MakeFileListParam.Recursive = false;
  4257. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4258. TTerminalManager::Instance()->ActiveSession = Session;
  4259. if (TemporaryFilesList->Count > 0)
  4260. {
  4261. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4262. CopyParam.FileMask = FileMask;
  4263. DebugAssert(!FAutoOperation);
  4264. FAutoOperation = true;
  4265. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4266. }
  4267. }
  4268. __finally
  4269. {
  4270. delete TemporaryFilesList;
  4271. FAutoOperation = false;
  4272. if (!RootTempDir.IsEmpty())
  4273. {
  4274. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4275. }
  4276. }
  4277. }
  4278. else
  4279. {
  4280. RemoteDirView->SaveSelection();
  4281. RemoteDirView->SaveSelectedNames();
  4282. try
  4283. {
  4284. if (Move)
  4285. {
  4286. Configuration->Usage->Inc("RemoteMove");
  4287. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4288. }
  4289. else
  4290. {
  4291. Configuration->Usage->Inc("RemoteCopyDirect");
  4292. DebugAssert(DirectCopy);
  4293. DebugAssert(Session == Terminal);
  4294. if (Terminal->IsCapable[fcRemoteCopy] ||
  4295. Terminal->CommandSessionOpened ||
  4296. CommandSessionFallback())
  4297. {
  4298. Terminal->CopyFiles(FileList, Target, FileMask);
  4299. }
  4300. }
  4301. }
  4302. catch(...)
  4303. {
  4304. RemoteDirView->DiscardSavedSelection();
  4305. throw;
  4306. }
  4307. RemoteDirView->RestoreSelection();
  4308. }
  4309. }
  4310. return Result;
  4311. }
  4312. //---------------------------------------------------------------------------
  4313. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4314. const UnicodeString & Path, TRemoteProperties & Properties)
  4315. {
  4316. DebugAssert(!IsLocalBrowserMode());
  4317. Properties.Valid = Properties.Valid << vpEncrypt;
  4318. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4319. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4320. }
  4321. //---------------------------------------------------------------------------
  4322. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4323. {
  4324. Side = GetSide(Side);
  4325. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4326. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4327. UnicodeString Name = LoadStr(NEW_FOLDER);
  4328. int AllowedChanges =
  4329. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4330. bool SaveSettings = false;
  4331. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4332. {
  4333. TWindowLock Lock(this);
  4334. if (!IsSideLocalBrowser(Side))
  4335. {
  4336. if (SaveSettings)
  4337. {
  4338. GUIConfiguration->NewDirectoryProperties = Properties;
  4339. }
  4340. CreateRemoteDirectory(Name, Properties);
  4341. }
  4342. else
  4343. {
  4344. DirView(Side)->CreateDirectory(Name);
  4345. }
  4346. }
  4347. }
  4348. //---------------------------------------------------------------------------
  4349. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4350. {
  4351. TWindowLock Lock(this);
  4352. DirView(Side)->ExecuteHomeDirectory();
  4353. }
  4354. //---------------------------------------------------------------------------
  4355. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4356. {
  4357. DoOpenDirectoryDialog(odBrowse, Side);
  4358. }
  4359. //---------------------------------------------------------------------------
  4360. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4361. {
  4362. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4363. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4364. bool Result = !Path.IsEmpty();
  4365. if (Result)
  4366. {
  4367. TryOpenDirectory(Side, Path);
  4368. }
  4369. return Result;
  4370. }
  4371. //---------------------------------------------------------------------------
  4372. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4373. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4374. bool & Close)
  4375. {
  4376. // terminal can be already closed (e.g. dropped connection)
  4377. if (Terminal != NULL)
  4378. {
  4379. try
  4380. {
  4381. TCalculateSizeParams Params;
  4382. Params.Stats = &Stats;
  4383. Terminal->CalculateFilesSize(FileList, Size, Params);
  4384. }
  4385. catch(...)
  4386. {
  4387. if (!Terminal->Active)
  4388. {
  4389. Close = true;
  4390. }
  4391. throw;
  4392. }
  4393. }
  4394. }
  4395. //---------------------------------------------------------------------------
  4396. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4397. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4398. bool & Close)
  4399. {
  4400. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4401. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4402. {
  4403. Configuration->Usage->Inc(L"ChecksumCalculated");
  4404. try
  4405. {
  4406. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4407. }
  4408. catch(...)
  4409. {
  4410. if (!Terminal->Active)
  4411. {
  4412. Close = true;
  4413. }
  4414. throw;
  4415. }
  4416. }
  4417. }
  4418. //---------------------------------------------------------------------------
  4419. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4420. {
  4421. if (Terminal->LoadFilesProperties(FileList))
  4422. {
  4423. RemoteDirView->Invalidate();
  4424. }
  4425. }
  4426. //---------------------------------------------------------------------------
  4427. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4428. {
  4429. bool Result;
  4430. if (!IsSideLocalBrowser(Side))
  4431. {
  4432. TRemoteTokenList * GroupList = NULL;
  4433. TRemoteTokenList * UserList = NULL;
  4434. try
  4435. {
  4436. TRemoteProperties CurrentProperties;
  4437. LoadFilesProperties(FileList);
  4438. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4439. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4440. if (CapableGroupChanging || CapableOwnerChanging)
  4441. {
  4442. if (CapableGroupChanging)
  4443. {
  4444. GroupList = Terminal->Groups->Duplicate();
  4445. }
  4446. if (CapableOwnerChanging)
  4447. {
  4448. UserList = Terminal->Users->Duplicate();
  4449. }
  4450. TRemoteDirectory * Files = Terminal->Files;
  4451. int Count = Files->Count;
  4452. if (Count > 100)
  4453. {
  4454. Count = 100;
  4455. }
  4456. for (int Index = 0; Index < Count; Index++)
  4457. {
  4458. TRemoteFile * File = Files->Files[Index];
  4459. if (CapableGroupChanging)
  4460. {
  4461. GroupList->AddUnique(File->Group);
  4462. }
  4463. if (CapableOwnerChanging)
  4464. {
  4465. UserList->AddUnique(File->Owner);
  4466. }
  4467. }
  4468. // if we haven't collected tokens for all files in current directory,
  4469. // make sure we collect them at least for all selected files.
  4470. // (note that so far the files in FileList has to be from current direcotry)
  4471. if (Count < Files->Count)
  4472. {
  4473. for (int Index = 0; Index < FileList->Count; Index++)
  4474. {
  4475. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4476. if (CapableGroupChanging)
  4477. {
  4478. GroupList->AddUnique(File->Group);
  4479. }
  4480. if (CapableOwnerChanging)
  4481. {
  4482. UserList->AddUnique(File->Owner);
  4483. }
  4484. }
  4485. }
  4486. }
  4487. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4488. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4489. for (int Index = 0; (Index < FileList->Count) && CapableAclChanging; Index++)
  4490. {
  4491. if (dynamic_cast<TRemoteFile *>(FileList->Objects[Index])->IsDirectory)
  4492. {
  4493. CapableAclChanging = false;
  4494. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4495. }
  4496. }
  4497. int Flags = 0;
  4498. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4499. if (CapableAclChanging) Flags |= cpAcl;
  4500. if (CapableOwnerChanging) Flags |= cpOwner;
  4501. if (CapableGroupChanging) Flags |= cpGroup;
  4502. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4503. if (Terminal->IsCapable[fcCalculatingChecksum] ||
  4504. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles()))
  4505. {
  4506. CalculateChecksumEvent = CalculateChecksum;
  4507. }
  4508. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4509. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4510. TRemoteProperties NewProperties = CurrentProperties;
  4511. Result =
  4512. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4513. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4514. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4515. CalculateSize, CalculateChecksumEvent);
  4516. if (Result)
  4517. {
  4518. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4519. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4520. }
  4521. }
  4522. __finally
  4523. {
  4524. delete GroupList;
  4525. delete UserList;
  4526. }
  4527. }
  4528. else
  4529. {
  4530. DirView(Side)->DisplayPropertiesMenu();
  4531. Result = true;
  4532. }
  4533. return Result;
  4534. }
  4535. //---------------------------------------------------------------------------
  4536. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4537. {
  4538. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4539. {
  4540. FIgnoreNextDialogChar = Key;
  4541. }
  4542. Key = 0;
  4543. }
  4544. //---------------------------------------------------------------------------
  4545. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4546. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4547. {
  4548. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4549. if (Command != NULL)
  4550. {
  4551. KeyProcessed(Key, Shift);
  4552. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4553. {
  4554. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4555. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4556. false, false, const_cast<TCustomCommandType *>(Command));
  4557. }
  4558. }
  4559. }
  4560. //---------------------------------------------------------------------------
  4561. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4562. {
  4563. if (!NonVisualDataModule->Busy)
  4564. {
  4565. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4566. {
  4567. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4568. }
  4569. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4570. {
  4571. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4572. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4573. {
  4574. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4575. // But so far it's not a problem, as it does what we want.
  4576. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4577. if (((Action->ShortCut == KeyShortCut) ||
  4578. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4579. AllowedAction(Action, aaShortCut))
  4580. {
  4581. // Has to be called before the action as the dialog char is already in queue.
  4582. // So when the action consumes message queue, we already need to have the
  4583. // FIgnoreNextDialogChar set
  4584. KeyProcessed(Key, Shift);
  4585. // Reset reference to previous component (when menu/toolbar was clicked).
  4586. // Needed to detect that action was invoked by keyboard shortcut
  4587. // in TNonVisualDataModule::ExplorerActionsExecute
  4588. Action->ActionComponent = NULL;
  4589. Action->Execute();
  4590. return;
  4591. }
  4592. }
  4593. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4594. {
  4595. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4596. {
  4597. KeyProcessed(Key, Shift);
  4598. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4599. return;
  4600. }
  4601. }
  4602. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4603. {
  4604. KeyProcessed(Key, Shift);
  4605. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4606. }
  4607. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4608. if (IsCustomShortCut(CustomShortCut))
  4609. {
  4610. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4611. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4612. if (WinConfiguration->SharedBookmarks != NULL)
  4613. {
  4614. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4615. if ((Bookmark != NULL) &&
  4616. OpenBookmark(FCurrentSide, Bookmark))
  4617. {
  4618. KeyProcessed(Key, Shift);
  4619. }
  4620. }
  4621. }
  4622. }
  4623. }
  4624. TForm::KeyDown(Key, Shift);
  4625. }
  4626. //---------------------------------------------------------------------------
  4627. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4628. {
  4629. bool OpenedTerminal = false;
  4630. UnicodeString ProtocolName;
  4631. UnicodeString ProtocolNameHint;
  4632. UnicodeString SecurityProtocolName;
  4633. UnicodeString DurationHint;
  4634. // See the comment in TScpCommanderForm::UpdateControls()
  4635. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4636. if (ActiveTerminal != NULL)
  4637. {
  4638. // Active is not enough here
  4639. if (ActiveTerminal->Status == ssOpened)
  4640. {
  4641. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4642. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4643. if (FileSystemInfo.ProtocolName.IsEmpty())
  4644. {
  4645. ProtocolName = SessionInfo.ProtocolName;
  4646. }
  4647. else
  4648. {
  4649. ProtocolName = FileSystemInfo.ProtocolName;
  4650. }
  4651. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4652. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4653. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4654. OpenedTerminal = true;
  4655. }
  4656. else if (ActiveTerminal->Status > ssClosed)
  4657. {
  4658. ProtocolName = LoadStr(STATUS_CONNECTING);
  4659. }
  4660. else
  4661. {
  4662. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4663. }
  4664. }
  4665. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4666. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4667. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4668. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4669. if (ProtocolStatusPanel->Caption != ProtocolName)
  4670. {
  4671. ProtocolStatusPanel->Caption = ProtocolName;
  4672. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4673. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4674. }
  4675. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4676. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4677. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4678. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4679. SecurityStatusPanel->Enabled = SecurityEnabled;
  4680. UnicodeString SecurityProtocolHint;
  4681. if (SecurityEnabled)
  4682. {
  4683. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4684. }
  4685. else
  4686. {
  4687. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4688. }
  4689. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4690. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4691. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4692. DurationStatusPanel->Hint = DurationHint;
  4693. UpdateStatusBar();
  4694. }
  4695. //---------------------------------------------------------------------------
  4696. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4697. {
  4698. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4699. DebugAssert(SessionStatusBar != NULL);
  4700. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4701. if (!FNote.IsEmpty())
  4702. {
  4703. NoteStatusPanel->Caption = FNote;
  4704. }
  4705. else
  4706. {
  4707. UpdateStatusPanelText(NoteStatusPanel);
  4708. }
  4709. NoteStatusPanel->Hint = FNoteHints;
  4710. UnicodeString LoginTime;
  4711. // See the comment in TScpCommanderForm::UpdateControls()
  4712. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4713. // Active is not enough here
  4714. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4715. {
  4716. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4717. LoginTime = FormatDateTimeSpan(Configuration->TimeFormat, Now() - SessionInfo.LoginTime);
  4718. }
  4719. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4720. DurationStatusPanel->Caption = LoginTime;
  4721. }
  4722. //---------------------------------------------------------------------------
  4723. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4724. {
  4725. Panel->Caption = L"";
  4726. }
  4727. //---------------------------------------------------------------------------
  4728. void __fastcall TCustomScpExplorerForm::Idle()
  4729. {
  4730. if (FShowing ||
  4731. // Particularly for
  4732. // - Standalone editing
  4733. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4734. // while "keeping remote directory up to date".
  4735. StandaloneOperation)
  4736. {
  4737. FEditorManager->Check();
  4738. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4739. // that needs to know if queue view is visible (and it may be closed after queue update)
  4740. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4741. }
  4742. if (FShowing)
  4743. {
  4744. if (!NonVisualDataModule->Busy &&
  4745. // Menu is opened or drag&drop is going on
  4746. (Mouse->Capture == NULL))
  4747. {
  4748. if (FRefreshRemoteDirectory)
  4749. {
  4750. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4751. {
  4752. Terminal->RefreshDirectory();
  4753. }
  4754. FRefreshRemoteDirectory = false;
  4755. }
  4756. if (FRefreshLocalDirectory)
  4757. {
  4758. ReloadLocalDirectory();
  4759. FRefreshLocalDirectory = false;
  4760. }
  4761. if (WinConfiguration->RefreshRemotePanel)
  4762. {
  4763. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4764. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4765. {
  4766. RemoteDirView->ReloadDirectory();
  4767. }
  4768. }
  4769. }
  4770. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4771. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4772. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4773. // 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.
  4774. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4775. MenuToolbar->Idle();
  4776. }
  4777. if (FShowing || StandaloneOperation)
  4778. {
  4779. if (FQueueStatusInvalidated)
  4780. {
  4781. UpdateQueueStatus(false);
  4782. }
  4783. RefreshQueueItems();
  4784. }
  4785. if (FShowing)
  4786. {
  4787. UpdateStatusBar();
  4788. }
  4789. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4790. {
  4791. FClipboardFakeMonitorsPendingReset = false;
  4792. FClipboardFakeMonitors.reset(NULL);
  4793. }
  4794. FIgnoreNextDialogChar = 0;
  4795. }
  4796. //---------------------------------------------------------------------------
  4797. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4798. {
  4799. try
  4800. {
  4801. FUserActionTimer->Enabled = false;
  4802. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4803. {
  4804. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4805. {
  4806. FPendingQueueActionItem->ProcessUserAction();
  4807. }
  4808. }
  4809. }
  4810. __finally
  4811. {
  4812. FPendingQueueActionItem = NULL;
  4813. }
  4814. }
  4815. //---------------------------------------------------------------------------
  4816. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4817. {
  4818. if (WinConfiguration->MinimizeToTray)
  4819. {
  4820. UpdateTrayIcon();
  4821. FTrayIcon->Visible = true;
  4822. if (Visible)
  4823. {
  4824. ShowWindow(Handle, SW_HIDE);
  4825. }
  4826. }
  4827. }
  4828. //---------------------------------------------------------------------------
  4829. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4830. {
  4831. // WORKAROUND
  4832. // When restoring maximized window from minimization,
  4833. // rarely some controls do not align properly.
  4834. // Two instances seen (both for Commander):
  4835. // - When restoring, window is temporarily narrower (not maximized),
  4836. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4837. // Once maximized already, top dock shinks back, but the session PageControl,
  4838. // do not align up, leaving space between TopDock and PageControl.
  4839. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4840. for (int Index = 0; Index < ControlCount; Index++)
  4841. {
  4842. RealignControl(Controls[Index]);
  4843. }
  4844. if (FTrayIcon->Visible)
  4845. {
  4846. FTrayIcon->Visible = false;
  4847. if (Visible)
  4848. {
  4849. ShowWindow(Handle, SW_SHOW);
  4850. }
  4851. }
  4852. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4853. {
  4854. FNeedSession = false;
  4855. NonVisualDataModule->StartBusy();
  4856. try
  4857. {
  4858. NeedSession(true);
  4859. }
  4860. __finally
  4861. {
  4862. NonVisualDataModule->EndBusy();
  4863. }
  4864. }
  4865. }
  4866. //---------------------------------------------------------------------------
  4867. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4868. {
  4869. FTrayIcon->Hint = GetMainForm()->Caption;
  4870. }
  4871. //---------------------------------------------------------------------------
  4872. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4873. {
  4874. UpdateTrayIcon();
  4875. }
  4876. //---------------------------------------------------------------------------
  4877. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4878. {
  4879. // workaround
  4880. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4881. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4882. // But WM_ACTIVATEAPP message can be received even when
  4883. // the main window is minimized to the tray and internal editor window is focused
  4884. // (after another application was previously active)
  4885. if (::IsIconic(Handle))
  4886. {
  4887. if (!IsAppIconic())
  4888. {
  4889. SetAppIconic(true);
  4890. }
  4891. }
  4892. ::ApplicationRestore();
  4893. Application->BringToFront();
  4894. }
  4895. //---------------------------------------------------------------------------
  4896. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4897. {
  4898. RestoreApp();
  4899. }
  4900. //---------------------------------------------------------------------------
  4901. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4902. {
  4903. if (OpenInNewWindow())
  4904. {
  4905. ExecuteNewInstance(SessionUrl);
  4906. }
  4907. else
  4908. {
  4909. TTerminalManager::Instance()->NewSession(SessionUrl);
  4910. }
  4911. }
  4912. //---------------------------------------------------------------------------
  4913. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4914. {
  4915. NewSession();
  4916. }
  4917. //---------------------------------------------------------------------------
  4918. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4919. {
  4920. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4921. StoredSessions->NewSession(SessionName, SessionData);
  4922. // modified only, explicit
  4923. StoredSessions->Save(false, true);
  4924. // encode session name because of slashes in hierarchical sessions
  4925. return EncodeUrlString(SessionName);
  4926. }
  4927. //---------------------------------------------------------------------------
  4928. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4929. {
  4930. // current working directories become defaults here, what is not right
  4931. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4932. return SaveHiddenDuplicateSession(SessionData.get());
  4933. }
  4934. //---------------------------------------------------------------------------
  4935. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  4936. {
  4937. if (OpenInNewWindow())
  4938. {
  4939. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4940. }
  4941. else
  4942. {
  4943. // current working directories become defaults here, what is not right
  4944. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4945. TTerminalManager * Manager = TTerminalManager::Instance();
  4946. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  4947. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  4948. // We definitelly want these
  4949. ASession->Disconnected = ManagedSession->Disconnected;
  4950. // Not sure about these two
  4951. ASession->Permanent = ManagedSession->Permanent;
  4952. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  4953. Manager->ActiveSession = ASession;
  4954. }
  4955. }
  4956. //---------------------------------------------------------------------------
  4957. void __fastcall TCustomScpExplorerForm::RenameTab()
  4958. {
  4959. UnicodeString Name = ManagedSession->SessionData->SessionName;
  4960. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  4961. // When submitting the default name, do not fix it
  4962. (Name != ManagedSession->SessionData->SessionName))
  4963. {
  4964. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  4965. TSessionData::ValidateName(Name);
  4966. // This is inconsistent with how color (for example) is handled.
  4967. ManagedSession->SessionData->Name = Name;
  4968. UpdateControls();
  4969. // Add/Remove distinguishing paths from sessions of the same name.
  4970. SessionListChanged();
  4971. }
  4972. }
  4973. //---------------------------------------------------------------------------
  4974. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  4975. {
  4976. DebugAssert(Queue != NULL);
  4977. bool Result = Queue->IsEmpty;
  4978. if (!Result)
  4979. {
  4980. SetFocus();
  4981. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  4982. }
  4983. return Result;
  4984. }
  4985. //---------------------------------------------------------------------------
  4986. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  4987. {
  4988. return CanCloseQueue(FQueue);
  4989. }
  4990. //---------------------------------------------------------------------------
  4991. void __fastcall TCustomScpExplorerForm::CloseTab()
  4992. {
  4993. if (CanCloseQueue())
  4994. {
  4995. TTerminalManager::Instance()->FreeActiveTerminal();
  4996. }
  4997. }
  4998. //---------------------------------------------------------------------------
  4999. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5000. {
  5001. if (CanCloseQueue())
  5002. {
  5003. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5004. }
  5005. }
  5006. //---------------------------------------------------------------------------
  5007. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5008. {
  5009. DetachTerminal(Terminal);
  5010. RemoteDirView->Terminal = Terminal;
  5011. UpdateRemotePathComboBox(false);
  5012. InitStatusBar();
  5013. UpdateControls();
  5014. }
  5015. //---------------------------------------------------------------------------
  5016. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5017. {
  5018. InitStatusBar();
  5019. }
  5020. //---------------------------------------------------------------------------
  5021. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5022. {
  5023. if (DebugAlwaysTrue(!Terminal->Active))
  5024. {
  5025. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5026. }
  5027. }
  5028. //---------------------------------------------------------------------------
  5029. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5030. {
  5031. if (OpenInNewWindow())
  5032. {
  5033. // encode session name because of slashes in hierarchical sessions
  5034. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5035. }
  5036. else
  5037. {
  5038. TTerminalManager * Manager = TTerminalManager::Instance();
  5039. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5040. Manager->ActiveSession = Terminal;
  5041. }
  5042. }
  5043. //---------------------------------------------------------------------------
  5044. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5045. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5046. {
  5047. TTerminalManager * Manager = TTerminalManager::Instance();
  5048. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5049. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5050. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5051. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5052. {
  5053. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5054. // FirstSession can be null, if none of the workspace sites exist anymore
  5055. // or if all workspace sessions are not suported by the interface
  5056. // (when trying to open all local-local workspace in "explorer" interface)
  5057. if (FirstSession != NULL)
  5058. {
  5059. if (!ConnectFirstTerminal)
  5060. {
  5061. FirstSession->Disconnected = true;
  5062. FirstSession->DisconnectedTemporarily = true;
  5063. }
  5064. Manager->ActiveSession = FirstSession;
  5065. }
  5066. }
  5067. }
  5068. //---------------------------------------------------------------------------
  5069. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5070. {
  5071. if (OpenInNewWindow())
  5072. {
  5073. ExecuteNewInstance(Name);
  5074. }
  5075. else
  5076. {
  5077. DoOpenFolderOrWorkspace(Name, true, false);
  5078. }
  5079. }
  5080. //---------------------------------------------------------------------------
  5081. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5082. bool &CanClose)
  5083. {
  5084. AppLog(L"Windows close query");
  5085. // See the comment in CloseApp()
  5086. if (NonVisualDataModule->Busy)
  5087. {
  5088. CanClose = false;
  5089. }
  5090. else
  5091. {
  5092. TTerminalManager * Manager = TTerminalManager::Instance();
  5093. int ActiveSessions = 0;
  5094. for (int Index = 0; Index < Manager->Count; Index++)
  5095. {
  5096. if (Manager->Sessions[Index]->Active)
  5097. {
  5098. ActiveSessions++;
  5099. }
  5100. }
  5101. // Confirm, when there's at least one active remote session or
  5102. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5103. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5104. WinConfiguration->ConfirmClosingSession)
  5105. {
  5106. unsigned int Result;
  5107. TMessageParams Params(mpNeverAskAgainCheck);
  5108. UnicodeString Message;
  5109. int Answers = qaOK | qaCancel;
  5110. // The current session is the only active session
  5111. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5112. {
  5113. if (!WinConfiguration->AutoSaveWorkspace)
  5114. {
  5115. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5116. }
  5117. else
  5118. {
  5119. Message = LoadStr(CLOSE_SESSION);
  5120. }
  5121. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5122. }
  5123. // Multiple active sessions or one active session, but it's not the current one
  5124. else if (ActiveSessions > 0)
  5125. {
  5126. if (!WinConfiguration->AutoSaveWorkspace)
  5127. {
  5128. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5129. }
  5130. else
  5131. {
  5132. Message = LoadStr(CLOSE_SESSIONS);
  5133. }
  5134. }
  5135. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5136. else
  5137. {
  5138. DebugAlwaysTrue(Manager->Count > 1);
  5139. DebugAlwaysTrue(!WinConfiguration->AutoSaveWorkspace);
  5140. Message = LoadStr(CLOSE_WORKSPACE);
  5141. }
  5142. UnicodeString Note;
  5143. if (WinConfiguration->AutoSaveWorkspace)
  5144. {
  5145. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5146. }
  5147. else
  5148. {
  5149. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5150. Answers = qaYes | qaNo | qaCancel;
  5151. }
  5152. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5153. SetFocus();
  5154. Result = MessageDialog(Message, qtConfirmation,
  5155. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5156. if (Result == qaNeverAskAgain)
  5157. {
  5158. WinConfiguration->ConfirmClosingSession = false;
  5159. }
  5160. if (Result == qaNo)
  5161. {
  5162. CanClose = SaveWorkspace(true);
  5163. // note that the workspace will be saved redundatly again from FormClose
  5164. }
  5165. else
  5166. {
  5167. CanClose =
  5168. (Result == qaOK) ||
  5169. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5170. (Result == qaNeverAskAgain);
  5171. }
  5172. }
  5173. if (CanClose && HasActiveTerminal())
  5174. {
  5175. CanClose = CanCloseQueue();
  5176. }
  5177. }
  5178. if (CanClose)
  5179. {
  5180. CanClose =
  5181. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5182. FEditorManager->CloseExternalFilesWithoutProcess();
  5183. if (CanClose)
  5184. {
  5185. while (CanClose && (FLocalEditors->Count > 0))
  5186. {
  5187. int PrevCount = FLocalEditors->Count;
  5188. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5189. CanClose = (FLocalEditors->Count < PrevCount);
  5190. }
  5191. if (CanClose)
  5192. {
  5193. CanClose = FEditorManager->Empty(true);
  5194. if (!CanClose)
  5195. {
  5196. SetFocus();
  5197. CanClose =
  5198. (MessageDialog(
  5199. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5200. }
  5201. }
  5202. }
  5203. }
  5204. }
  5205. //---------------------------------------------------------------------------
  5206. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5207. {
  5208. TForm * Form = dynamic_cast<TForm *>(Sender);
  5209. DebugAssert(Form != NULL);
  5210. Form->Close();
  5211. }
  5212. //---------------------------------------------------------------------------
  5213. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5214. {
  5215. TForm * Form = dynamic_cast<TForm *>(Sender);
  5216. delete Form;
  5217. }
  5218. //---------------------------------------------------------------------------
  5219. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5220. {
  5221. while (FLocalEditors->Count > 0)
  5222. {
  5223. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5224. }
  5225. }
  5226. //---------------------------------------------------------------------------
  5227. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5228. TObject *Sender)
  5229. {
  5230. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5231. try
  5232. {
  5233. SetProperties(osRemote, FileList);
  5234. }
  5235. __finally
  5236. {
  5237. delete FileList;
  5238. }
  5239. }
  5240. //---------------------------------------------------------------------------
  5241. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5242. {
  5243. if (value)
  5244. {
  5245. if (Component == fcCustomCommandsBand)
  5246. {
  5247. UpdateCustomCommandsToolbar();
  5248. }
  5249. if (Component == fcQueueFileList)
  5250. {
  5251. DebugAssert(!QueueFileListSplitter->Visible);
  5252. AdjustQueueLayout();
  5253. UpdateQueueFileList();
  5254. }
  5255. }
  5256. }
  5257. //---------------------------------------------------------------------------
  5258. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5259. {
  5260. int MinHeightLimit =
  5261. GetStaticQueuePanelComponentsHeight() +
  5262. QueueFileListSplitter->Height +
  5263. QueueFileList->Height +
  5264. GetMinQueueViewHeight();
  5265. if (QueuePanel->ClientHeight < MinHeightLimit)
  5266. {
  5267. QueuePanel->ClientHeight = MinHeightLimit;
  5268. }
  5269. }
  5270. //---------------------------------------------------------------------------
  5271. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5272. {
  5273. TControl * Control = GetComponent(Component);
  5274. DebugAssert(Control);
  5275. bool Changed = (Control->Visible != value);
  5276. if (Changed)
  5277. {
  5278. ComponentShowing(Component, value);
  5279. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5280. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5281. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5282. if (value)
  5283. {
  5284. int RemainingHeight = Control->Parent->ClientHeight;
  5285. int RemainingWidth = Control->Parent->ClientWidth;
  5286. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5287. {
  5288. TControl * ChildControl = Control->Parent->Controls[i];
  5289. if (ChildControl->Visible)
  5290. {
  5291. switch (ChildControl->Align)
  5292. {
  5293. case alTop:
  5294. case alBottom:
  5295. RemainingHeight -= ChildControl->Height;
  5296. break;
  5297. case alLeft:
  5298. case alRight:
  5299. RemainingWidth -= ChildControl->Width;
  5300. break;
  5301. }
  5302. }
  5303. }
  5304. int Reserve = ScaleByTextHeight(this, 32);
  5305. // queue in explorer, trees in commander
  5306. if (Control->Height > RemainingHeight - Reserve)
  5307. {
  5308. Control->Height = RemainingHeight / 2;
  5309. }
  5310. if (Control->Width > RemainingWidth - Reserve)
  5311. {
  5312. Control->Width = RemainingWidth / 2;
  5313. }
  5314. }
  5315. Control->Visible = value;
  5316. if (WasFocused && Visible)
  5317. {
  5318. DirView(osCurrent)->SetFocus();
  5319. }
  5320. FixControlsPlacement();
  5321. }
  5322. }
  5323. //---------------------------------------------------------------------------
  5324. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5325. {
  5326. TControl * Control = GetComponent(Component);
  5327. if (Control == NULL)
  5328. {
  5329. return false;
  5330. }
  5331. else
  5332. {
  5333. return Control->Visible;
  5334. }
  5335. }
  5336. //---------------------------------------------------------------------------
  5337. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5338. {
  5339. bool Result;
  5340. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5341. {
  5342. Result = !IsUWP();
  5343. }
  5344. else
  5345. {
  5346. Result = true;
  5347. }
  5348. return Result;
  5349. }
  5350. //---------------------------------------------------------------------------
  5351. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5352. {
  5353. if (DirView->ItemFocused != NULL)
  5354. {
  5355. DirView->ItemFocused->MakeVisible(false);
  5356. }
  5357. }
  5358. //---------------------------------------------------------------------------
  5359. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5360. {
  5361. MakeFocusedItemVisible(RemoteDirView);
  5362. QueueSplitter->Visible = QueuePanel->Visible;
  5363. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5364. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5365. TControl * TopControlsOrder[] =
  5366. { TopDock, MessageDock, SessionsPageControl };
  5367. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5368. TControl * QueueControlsOrder[] =
  5369. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5370. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5371. }
  5372. //---------------------------------------------------------------------------
  5373. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5374. {
  5375. switch (Component) {
  5376. case fcStatusBar: return RemoteStatusBar;
  5377. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5378. case fcQueueView: return QueuePanel;
  5379. case fcQueueToolbar: return QueueDock;
  5380. case fcRemoteTree: return RemoteDrivePanel;
  5381. case fcSessionsTabs: return SessionsPageControl;
  5382. case fcQueueFileList: return QueueFileList;
  5383. default: return NULL;
  5384. }
  5385. }
  5386. //---------------------------------------------------------------------------
  5387. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5388. TObject *Sender, TListColumn *Column, TPoint &Point)
  5389. {
  5390. DebugAssert(NonVisualDataModule && Column && Sender);
  5391. NonVisualDataModule->ListColumn = Column;
  5392. TPopupMenu * DirViewColumnMenu;
  5393. if (Sender == DirView(osOther))
  5394. {
  5395. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5396. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5397. bool SizeColumn = (Column->Index == uvSize);
  5398. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5399. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5400. }
  5401. else
  5402. {
  5403. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5404. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5405. bool SizeColumn = (Column->Index == dvSize);
  5406. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5407. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5408. }
  5409. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5410. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5411. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5412. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5413. }
  5414. //---------------------------------------------------------------------------
  5415. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5416. TObject *Sender, TListItem *Item, bool &AllowExec)
  5417. {
  5418. DoDirViewExecFile(Sender, Item, AllowExec);
  5419. }
  5420. //---------------------------------------------------------------------------
  5421. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5422. TListItem * Item, bool & AllowExec)
  5423. {
  5424. DebugAssert(Sender && Item && Configuration);
  5425. DebugAssert(AllowExec);
  5426. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5427. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5428. bool Remote = !IsSideLocalBrowser(Side);
  5429. DebugAssert(Item == ADirView->ItemFocused);
  5430. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5431. TResolvedDoubleClickAction Action;
  5432. if (FForceExecution)
  5433. {
  5434. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5435. }
  5436. else
  5437. {
  5438. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5439. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5440. }
  5441. if (Action == rdcaCopy)
  5442. {
  5443. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5444. UnlockWindow();
  5445. try
  5446. {
  5447. if (IsLocalBrowserMode())
  5448. {
  5449. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5450. }
  5451. else
  5452. {
  5453. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5454. }
  5455. }
  5456. __finally
  5457. {
  5458. LockWindow();
  5459. }
  5460. AllowExec = false;
  5461. }
  5462. else if (Action == rdcaEdit)
  5463. {
  5464. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5465. {
  5466. ExecuteFile(Side, efDefaultEditor);
  5467. AllowExec = false;
  5468. }
  5469. }
  5470. else if (Action == rdcaOpen)
  5471. {
  5472. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5473. {
  5474. ExecuteFile(osRemote, efShell);
  5475. AllowExec = false;
  5476. }
  5477. }
  5478. }
  5479. //---------------------------------------------------------------------------
  5480. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5481. {
  5482. return ((Side == osRemote) || (Side == osCurrent));
  5483. }
  5484. //---------------------------------------------------------------------------
  5485. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5486. {
  5487. DebugFail();
  5488. }
  5489. //---------------------------------------------------------------------------
  5490. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5491. {
  5492. DebugFail();
  5493. }
  5494. //---------------------------------------------------------------------------
  5495. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5496. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5497. {
  5498. TSynchronizeParamType Params;
  5499. Params.LocalDirectory = LocalDirectory;
  5500. Params.RemoteDirectory = RemoteDirectory;
  5501. int UnusedParams =
  5502. (GUIConfiguration->SynchronizeParams &
  5503. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5504. TTerminal::spCaseSensitive));
  5505. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5506. Params.Options = GUIConfiguration->SynchronizeOptions;
  5507. bool SaveSettings = false;
  5508. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5509. &DoSynchronizeTooManyDirectories);
  5510. DebugAssert(FSynchronizeController == NULL);
  5511. FSynchronizeController = &Controller;
  5512. bool Result;
  5513. try
  5514. {
  5515. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5516. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5517. int Options =
  5518. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5519. DebugAssert(FOnFeedSynchronizeError == NULL);
  5520. DebugAssert(FOnSynchronizeAbort == NULL);
  5521. DebugAssert(FSynchronizeTerminal == NULL);
  5522. FSynchronizeTerminal = Terminal;
  5523. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5524. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5525. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5526. if (Result)
  5527. {
  5528. if (SaveSettings)
  5529. {
  5530. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5531. GUIConfiguration->SynchronizeOptions = Params.Options;
  5532. }
  5533. else
  5534. {
  5535. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5536. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5537. FLAGSET(Params.Options, soSynchronize))
  5538. {
  5539. GUIConfiguration->SynchronizeOptions =
  5540. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5541. soSynchronize;
  5542. }
  5543. }
  5544. LocalDirectory = Params.LocalDirectory;
  5545. RemoteDirectory = Params.RemoteDirectory;
  5546. }
  5547. }
  5548. __finally
  5549. {
  5550. FSynchronizeController = NULL;
  5551. DebugAssert(FOnFeedSynchronizeError == NULL);
  5552. FOnFeedSynchronizeError = NULL;
  5553. DebugAssert(FOnSynchronizeAbort == NULL);
  5554. FOnSynchronizeAbort = NULL;
  5555. FSynchronizeTerminal = NULL;
  5556. }
  5557. return Result;
  5558. }
  5559. //---------------------------------------------------------------------------
  5560. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5561. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5562. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5563. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5564. TSynchronizeOptions * Options, bool Full)
  5565. {
  5566. // Keep-up-to-date mode
  5567. if (Terminal->Status == ssOpened)
  5568. {
  5569. try
  5570. {
  5571. int PParams = Params.Params;
  5572. if (!Full)
  5573. {
  5574. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5575. if (FLAGSET(Params.Options, soRecurse))
  5576. {
  5577. PParams |= TTerminal::spSubDirs;
  5578. }
  5579. }
  5580. else
  5581. {
  5582. // if keepuptodate is non-recursive,
  5583. // full sync before has to be non-recursive as well
  5584. if (FLAGCLEAR(Params.Options, soRecurse))
  5585. {
  5586. PParams |= TTerminal::spNoRecurse;
  5587. }
  5588. }
  5589. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5590. PParams, Checklist, Options);
  5591. }
  5592. catch (Exception & E)
  5593. {
  5594. if (!Terminal->Active)
  5595. {
  5596. ShowExtendedExceptionEx(Terminal, &E);
  5597. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5598. if (!Terminal->Active)
  5599. {
  5600. throw;
  5601. }
  5602. }
  5603. else
  5604. {
  5605. if (FLAGSET(Params.Options, soContinueOnError) &&
  5606. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5607. {
  5608. // noop, already logged in MoreMessageDialog
  5609. }
  5610. else
  5611. {
  5612. // We get mostly EAbort here, so this is noop.
  5613. // Exception is an error when listing directories while looking for differences.
  5614. ShowExtendedExceptionEx(Terminal, &E);
  5615. throw;
  5616. }
  5617. }
  5618. }
  5619. }
  5620. }
  5621. //---------------------------------------------------------------------------
  5622. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5623. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5624. const UnicodeString ErrorStr)
  5625. {
  5626. if (!Directory.IsEmpty())
  5627. {
  5628. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5629. }
  5630. else
  5631. {
  5632. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5633. }
  5634. }
  5635. //---------------------------------------------------------------------------
  5636. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5637. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5638. {
  5639. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5640. {
  5641. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5642. }
  5643. else
  5644. {
  5645. TMessageParams Params(mpNeverAskAgainCheck);
  5646. unsigned int Result = MessageDialog(
  5647. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5648. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5649. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5650. {
  5651. MaxDirectories *= 2;
  5652. if (Result == qaNeverAskAgain)
  5653. {
  5654. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5655. }
  5656. }
  5657. else
  5658. {
  5659. Abort();
  5660. }
  5661. }
  5662. }
  5663. //---------------------------------------------------------------------------
  5664. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5665. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5666. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5667. TSynchronizeOptions * Options)
  5668. {
  5669. // Keep-up-to-date mode
  5670. DebugAssert(!FAutoOperation);
  5671. void * BatchStorage;
  5672. BatchStart(BatchStorage);
  5673. FAutoOperation = true;
  5674. bool AnyOperation = false;
  5675. TDateTime StartTime = Now();
  5676. TSynchronizeChecklist * AChecklist = NULL;
  5677. try
  5678. {
  5679. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, -1);
  5680. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5681. {
  5682. FSynchronizeProgressForm->Start();
  5683. }
  5684. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5685. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5686. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5687. Options);
  5688. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5689. SAFE_DESTROY(FSynchronizeProgressForm);
  5690. AnyOperation = (AChecklist->CheckedCount > 0);
  5691. if (AnyOperation)
  5692. {
  5693. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5694. CreateProgressForm(&SynchronizeProgress);
  5695. try
  5696. {
  5697. Terminal->SynchronizeApply(
  5698. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5699. SynchronizeProcessedItem, NULL, NULL, NULL);
  5700. }
  5701. __finally
  5702. {
  5703. DestroyProgressForm();
  5704. }
  5705. }
  5706. }
  5707. __finally
  5708. {
  5709. if (Checklist == NULL)
  5710. {
  5711. delete AChecklist;
  5712. }
  5713. else
  5714. {
  5715. *Checklist = AChecklist;
  5716. }
  5717. FAutoOperation = false;
  5718. SAFE_DESTROY(FSynchronizeProgressForm);
  5719. BatchEnd(BatchStorage);
  5720. ReloadLocalDirectory();
  5721. if (AnyOperation)
  5722. {
  5723. OperationComplete(StartTime);
  5724. }
  5725. }
  5726. }
  5727. //---------------------------------------------------------------------------
  5728. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5729. {
  5730. // can be called from command line
  5731. return Visible &&
  5732. ((DirView(osRemote)->SelCount > 0) ||
  5733. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5734. }
  5735. //---------------------------------------------------------------------------
  5736. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5737. {
  5738. LogSynchronizeEvent(Terminal, Message);
  5739. }
  5740. //---------------------------------------------------------------------------
  5741. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5742. int Params, TSynchronizeOptions & Options)
  5743. {
  5744. DebugAssert(!IsLocalBrowserMode());
  5745. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5746. {
  5747. Options.Filter = new TStringList();
  5748. Options.Filter->CaseSensitive = false;
  5749. Options.Filter->Duplicates = Types::dupAccept;
  5750. if (DirView(osRemote)->SelCount > 0)
  5751. {
  5752. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5753. }
  5754. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5755. {
  5756. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5757. }
  5758. Options.Filter->Sort();
  5759. }
  5760. }
  5761. //---------------------------------------------------------------------------
  5762. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5763. {
  5764. TCopyParamType Defaults;
  5765. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5766. ConfigStorage->AccessMode = smRead;
  5767. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5768. {
  5769. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5770. }
  5771. ConfigStorage.reset(NULL);
  5772. std::unique_ptr<TStringList> Options(new TStringList());
  5773. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5774. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5775. UnicodeString Result;
  5776. if (Options->Count > 0)
  5777. {
  5778. Result =
  5779. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5780. }
  5781. return Result;
  5782. }
  5783. //---------------------------------------------------------------------------
  5784. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5785. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5786. {
  5787. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5788. UnicodeString AdditionalParams =
  5789. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5790. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5791. SerializeCopyParamForCommandLine(CopyParams),
  5792. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5793. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5794. ExecuteNewInstance(SessionName, AdditionalParams);
  5795. }
  5796. //---------------------------------------------------------------------------
  5797. struct TSynchronizeParams
  5798. {
  5799. UnicodeString LocalDirectory;
  5800. UnicodeString RemoteDirectory;
  5801. TSynchronizeMode Mode;
  5802. TSynchronizeChecklist * Checklist;
  5803. int Params;
  5804. TCopyParamType * CopyParam;
  5805. TDateTime CollectElapsed;
  5806. TDateTime * StartTime;
  5807. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5808. };
  5809. //---------------------------------------------------------------------------
  5810. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5811. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5812. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5813. {
  5814. DebugAssert(!FAutoOperation);
  5815. void * BatchStorage;
  5816. BatchStart(BatchStorage);
  5817. FAutoOperation = true;
  5818. TFileOperationStatistics Statistics;
  5819. TDateTime Start = Now();
  5820. try
  5821. {
  5822. Params.OnProcessedItem = OnProcessedItem;
  5823. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5824. CreateProgressForm(&SynchronizeProgress);
  5825. Terminal->SynchronizeApply(
  5826. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5827. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5828. &Statistics);
  5829. }
  5830. __finally
  5831. {
  5832. Params.OnProcessedItem = NULL;
  5833. FAutoOperation = false;
  5834. DestroyProgressForm();
  5835. BatchEnd(BatchStorage);
  5836. ReloadLocalDirectory();
  5837. }
  5838. if (WinConfiguration->SynchronizeSummary)
  5839. {
  5840. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5841. // The statistics should be 0 anyway in this case
  5842. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5843. {
  5844. Message += L"\n";
  5845. if (Statistics.FilesUploaded > 0)
  5846. {
  5847. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5848. }
  5849. if (Statistics.FilesDownloaded > 0)
  5850. {
  5851. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5852. }
  5853. if (Statistics.FilesDeletedLocal > 0)
  5854. {
  5855. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5856. }
  5857. if (Statistics.FilesDeletedRemote > 0)
  5858. {
  5859. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5860. }
  5861. }
  5862. TDateTime Elapsed = (Now() - Start);
  5863. Message +=
  5864. L"\n" +
  5865. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Configuration->TimeFormat, Params.CollectElapsed))) + L"\n" +
  5866. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Configuration->TimeFormat, Elapsed)));
  5867. TMessageParams Params(mpNeverAskAgainCheck);
  5868. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5869. if (Result == qaNeverAskAgain)
  5870. {
  5871. WinConfiguration->SynchronizeSummary = false;
  5872. }
  5873. }
  5874. }
  5875. //---------------------------------------------------------------------------
  5876. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5877. {
  5878. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5879. {
  5880. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5881. }
  5882. // Not set in keep-up-to-date mode - Synchronize() method
  5883. if (Token != NULL)
  5884. {
  5885. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5886. if (Params.OnProcessedItem != NULL)
  5887. {
  5888. Params.OnProcessedItem(NULL, ChecklistItem);
  5889. }
  5890. }
  5891. }
  5892. //---------------------------------------------------------------------------
  5893. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5894. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5895. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5896. {
  5897. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5898. *Params.StartTime = Now();
  5899. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5900. }
  5901. //---------------------------------------------------------------------------
  5902. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5903. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5904. {
  5905. // terminal can be already closed (e.g. dropped connection)
  5906. if (Terminal != NULL)
  5907. {
  5908. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5909. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5910. }
  5911. }
  5912. //---------------------------------------------------------------------------
  5913. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5914. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5915. {
  5916. DebugAssert(!IsLocalBrowserMode());
  5917. TAutoBatch AutoBatch(this);
  5918. TAutoFlag AutoOperationFlag(FAutoOperation);
  5919. if (Side == osRemote)
  5920. {
  5921. std::unique_ptr<TStrings> FileList(new TStringList());
  5922. FileList->AddObject(FileName, RemoteFile);
  5923. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5924. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5925. RemoteDirView->SaveSelection();
  5926. RemoteDirView->SaveSelectedNames();
  5927. try
  5928. {
  5929. Terminal->MoveFiles(FileList.get(), Target, FileMask, false);
  5930. }
  5931. catch(...)
  5932. {
  5933. RemoteDirView->DiscardSavedSelection();
  5934. throw;
  5935. }
  5936. RemoteDirView->RestoreSelection();
  5937. }
  5938. else if (DebugAlwaysTrue(Side == osLocal))
  5939. {
  5940. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5941. {
  5942. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5943. }
  5944. UnicodeString Directory = ExtractFileDir(FileName);
  5945. ReloadLocalDirectory(Directory);
  5946. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5947. if (!SamePaths(Directory, NewDirectory))
  5948. {
  5949. ReloadLocalDirectory(NewDirectory);
  5950. }
  5951. }
  5952. }
  5953. //---------------------------------------------------------------------------
  5954. void __fastcall TCustomScpExplorerForm::DoSynchronizeBrowse(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  5955. {
  5956. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  5957. if (Side == osLocal)
  5958. {
  5959. if (Action == TSynchronizeChecklist::saDownloadNew)
  5960. {
  5961. OpenFolderInExplorer(LocalPath);
  5962. }
  5963. else
  5964. {
  5965. OpenFileInExplorer(TPath::Combine(LocalPath, Item->GetFileName()));
  5966. }
  5967. }
  5968. else if (DebugAlwaysTrue(Side == osRemote))
  5969. {
  5970. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  5971. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5972. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  5973. if (!LocalPath.IsEmpty())
  5974. {
  5975. SessionData->LocalDirectory = LocalPath;
  5976. }
  5977. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  5978. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(BROWSE_SWITCH), Item->GetFileName())));
  5979. }
  5980. }
  5981. //---------------------------------------------------------------------------
  5982. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  5983. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  5984. const TCopyParamType * CopyParams)
  5985. {
  5986. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5987. UnicodeString AdditionalParams =
  5988. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5989. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5990. SerializeCopyParamForCommandLine(CopyParams),
  5991. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  5992. LocalDirectory, RemoteDirectory, Mode, Params));
  5993. ExecuteNewInstance(SessionName, AdditionalParams);
  5994. }
  5995. //---------------------------------------------------------------------------
  5996. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  5997. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  5998. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  5999. {
  6000. int Result;
  6001. bool SaveSettings = false;
  6002. int Options =
  6003. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6004. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  6005. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  6006. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  6007. bool Continue =
  6008. (UseDefaults == 0) ||
  6009. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  6010. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults);
  6011. if (Continue)
  6012. {
  6013. Configuration->Usage->Inc(L"Synchronizations");
  6014. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  6015. UpdateCopyParamCounters(CopyParam);
  6016. TSynchronizeOptions SynchronizeOptions;
  6017. GetSynchronizeOptions(Params, SynchronizeOptions);
  6018. if (SaveSettings)
  6019. {
  6020. GUIConfiguration->SynchronizeParams = Params;
  6021. }
  6022. else
  6023. {
  6024. SaveMode = false;
  6025. }
  6026. TDateTime StartTime = Now();
  6027. TSynchronizeChecklist * Checklist = NULL;
  6028. try
  6029. {
  6030. DebugAssert(!FAutoOperation);
  6031. FAutoOperation = true;
  6032. try
  6033. {
  6034. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6035. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6036. int Files = -1;
  6037. if (DataList->Count >= 1)
  6038. {
  6039. Files = StrToIntDef(DataList->Strings[0], Files);
  6040. }
  6041. else
  6042. {
  6043. DataList->Add(UnicodeString());
  6044. }
  6045. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6046. FSynchronizeProgressForm->Start();
  6047. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6048. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6049. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6050. &SynchronizeOptions);
  6051. if (Terminal->SessionData->CacheDirectories)
  6052. {
  6053. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6054. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6055. }
  6056. }
  6057. __finally
  6058. {
  6059. FAutoOperation = false;
  6060. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6061. SAFE_DESTROY(FSynchronizeProgressForm);
  6062. }
  6063. TSynchronizeParams SynchronizeParams;
  6064. SynchronizeParams.LocalDirectory = LocalDirectory;
  6065. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  6066. SynchronizeParams.Mode = Mode;
  6067. SynchronizeParams.CopyParam = &CopyParam;
  6068. SynchronizeParams.Params = Params;
  6069. SynchronizeParams.Checklist = Checklist;
  6070. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6071. SynchronizeParams.StartTime = &StartTime;
  6072. SynchronizeParams.OnProcessedItem = NULL;
  6073. Result = Checklist->Count;
  6074. if (Checklist->Count > 0)
  6075. {
  6076. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6077. {
  6078. if (!DoSynchronizeChecklistDialog(
  6079. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6080. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeBrowse, &SynchronizeParams))
  6081. {
  6082. Result = -1;
  6083. }
  6084. }
  6085. else
  6086. {
  6087. FullSynchronize(SynchronizeParams, NULL, NULL);
  6088. }
  6089. }
  6090. else
  6091. {
  6092. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6093. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6094. }
  6095. }
  6096. __finally
  6097. {
  6098. delete Checklist;
  6099. }
  6100. OperationComplete(StartTime);
  6101. }
  6102. else
  6103. {
  6104. Result = -1;
  6105. }
  6106. return Result;
  6107. }
  6108. //---------------------------------------------------------------------------
  6109. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6110. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6111. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6112. {
  6113. if (Collect)
  6114. {
  6115. DebugAssert(FSynchronizeProgressForm != NULL);
  6116. if (!FSynchronizeProgressForm->Started)
  6117. {
  6118. FSynchronizeProgressForm->Start();
  6119. }
  6120. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6121. SetTaskbarListProgressValue(CompareProgress);
  6122. }
  6123. else
  6124. {
  6125. DebugAssert(FSynchronizeProgressForm == NULL);
  6126. DebugAssert(FProgressForm != NULL);
  6127. }
  6128. }
  6129. //---------------------------------------------------------------------------
  6130. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6131. {
  6132. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6133. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6134. if (File.get() != NULL)
  6135. {
  6136. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6137. Application->ShowMainForm = false;
  6138. Application->Run();
  6139. }
  6140. }
  6141. //---------------------------------------------------------------------------
  6142. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6143. {
  6144. DebugFail();
  6145. }
  6146. //---------------------------------------------------------------------------
  6147. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6148. {
  6149. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6150. SessionData->Assign(ManagedSession->SessionData);
  6151. UpdateSessionData(SessionData.get());
  6152. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6153. if (IsActiveTerminal(ManagedSession))
  6154. {
  6155. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6156. }
  6157. if (!ManagedSession->SessionData->HasSessionName())
  6158. {
  6159. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6160. // once IsWorkspace is cleared
  6161. SessionData->Name = UnicodeString();
  6162. }
  6163. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6164. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6165. SessionData->IsWorkspace = false;
  6166. return SessionData.release();
  6167. }
  6168. //---------------------------------------------------------------------------
  6169. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6170. {
  6171. TSessionData * SessionData = CloneCurrentSessionData();
  6172. try
  6173. {
  6174. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6175. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6176. }
  6177. __finally
  6178. {
  6179. delete SessionData;
  6180. }
  6181. }
  6182. //---------------------------------------------------------------------------
  6183. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6184. {
  6185. TTerminalManager * Manager = TTerminalManager::Instance();
  6186. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6187. if (DebugAlwaysTrue(ManagedSession != NULL))
  6188. {
  6189. // Update ManagedSession->StateData
  6190. UpdateSession(ManagedSession);
  6191. }
  6192. Manager->SaveWorkspace(DataList.get());
  6193. return DataList.release();
  6194. }
  6195. //---------------------------------------------------------------------------
  6196. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6197. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6198. {
  6199. WinConfiguration->LastWorkspace = Name;
  6200. if (!SavePasswords)
  6201. {
  6202. for (int Index = 0; Index < DataList->Count; Index++)
  6203. {
  6204. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6205. if (SessionData->Link.IsEmpty())
  6206. {
  6207. SessionData->ClearSessionPasswords();
  6208. }
  6209. }
  6210. }
  6211. StoredSessions->NewWorkspace(Name, DataList);
  6212. // modified only
  6213. StoredSessions->Save(false, Explicit);
  6214. }
  6215. //---------------------------------------------------------------------------
  6216. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6217. {
  6218. return
  6219. DefaultStr(WinConfiguration->LastWorkspace,
  6220. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6221. }
  6222. //---------------------------------------------------------------------------
  6223. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6224. {
  6225. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6226. bool AnyNonStoredSessionWithPassword = false;
  6227. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6228. bool AllNonStoredSessionsAnonymous = true;
  6229. TTerminalManager * Manager = TTerminalManager::Instance();
  6230. for (int Index = 0; Index < DataList->Count; Index++)
  6231. {
  6232. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6233. if (SessionData->Link.IsEmpty())
  6234. {
  6235. if (SessionData->HasAnySessionPassword())
  6236. {
  6237. AnyNonStoredSessionWithPassword = true;
  6238. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6239. {
  6240. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6241. }
  6242. }
  6243. if (!SameText(SessionData->UserName, AnonymousUserName))
  6244. {
  6245. AllNonStoredSessionsAnonymous = false;
  6246. }
  6247. }
  6248. }
  6249. bool SavePasswords;
  6250. bool * PSavePasswords;
  6251. bool NotRecommendedSavingPasswords =
  6252. !CustomWinConfiguration->UseMasterPassword &&
  6253. !AllNonStoredSessionsAnonymous;
  6254. if (Configuration->DisablePasswordStoring ||
  6255. !AnyNonStoredSessionWithPassword)
  6256. {
  6257. PSavePasswords = NULL;
  6258. SavePasswords = false;
  6259. }
  6260. else
  6261. {
  6262. PSavePasswords = &SavePasswords;
  6263. SavePasswords =
  6264. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6265. !NotRecommendedSavingPasswords;
  6266. }
  6267. UnicodeString Name = WorkspaceName();
  6268. bool CreateShortcut = false;
  6269. bool Result =
  6270. DoSaveWorkspaceDialog(
  6271. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6272. EnableAutoSave);
  6273. if (Result)
  6274. {
  6275. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6276. if (CreateShortcut)
  6277. {
  6278. TOperationVisualizer Visualizer;
  6279. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6280. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6281. }
  6282. if (EnableAutoSave)
  6283. {
  6284. WinConfiguration->AutoSaveWorkspace = true;
  6285. WinConfiguration->AutoWorkspace = Name;
  6286. if (PSavePasswords != NULL)
  6287. {
  6288. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6289. }
  6290. }
  6291. }
  6292. return Result;
  6293. }
  6294. //---------------------------------------------------------------------------
  6295. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6296. {
  6297. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6298. DebugAssert(Session == ManagedSession);
  6299. if (!IsLocalBrowserMode())
  6300. {
  6301. SAFE_DESTROY(Session->RemoteExplorerState);
  6302. if (WinConfiguration->PreservePanelState)
  6303. {
  6304. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6305. }
  6306. }
  6307. UpdateSessionData(Session->StateData);
  6308. }
  6309. //---------------------------------------------------------------------------
  6310. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6311. {
  6312. // Keep in sync with TSessionData::CopyStateData
  6313. DebugAssert(Data != NULL);
  6314. // This is inconsistent with how color (for example) is handled.
  6315. Data->Name = ManagedSession->SessionData->Name;
  6316. if (!IsLocalBrowserMode())
  6317. {
  6318. // cannot use RemoteDirView->Path, because it is empty if connection
  6319. // was already closed
  6320. // also only peek, we may not be connected at all atm
  6321. // so make sure we do not try retrieving current directory from the server
  6322. // (particularly with FTP)
  6323. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6324. if (!ACurrentDirectory.IsEmpty())
  6325. {
  6326. Data->RemoteDirectory = ACurrentDirectory;
  6327. }
  6328. }
  6329. Data->Color = SessionColor;
  6330. }
  6331. //---------------------------------------------------------------------------
  6332. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6333. {
  6334. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6335. DebugAssert(Toolbar != NULL);
  6336. for (int i = 0; i < Toolbar->Items->Count; i++)
  6337. {
  6338. TTBXCustomDropDownItem * DropDownItem;
  6339. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6340. if (DropDownItem != NULL)
  6341. {
  6342. ToolbarItemResize(DropDownItem,
  6343. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6344. Toolbar->NonClientWidth);
  6345. break;
  6346. }
  6347. }
  6348. }
  6349. //---------------------------------------------------------------------------
  6350. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6351. {
  6352. Item->EditWidth = Width;
  6353. }
  6354. //---------------------------------------------------------------------------
  6355. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6356. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6357. {
  6358. for (int i = 0; i < Toolbar->Items->Count; i++)
  6359. {
  6360. TTBXCustomDropDownItem * DropDownItem;
  6361. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6362. if (DropDownItem != NULL)
  6363. {
  6364. ASize.x -= DropDownItem->EditWidth;
  6365. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  6366. }
  6367. }
  6368. }
  6369. //---------------------------------------------------------------------------
  6370. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6371. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6372. {
  6373. if (WinConfiguration->DDWarnLackOfTempSpace)
  6374. {
  6375. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6376. if (!ADrive.IsEmpty())
  6377. {
  6378. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6379. DebugAssert(RequiredSpace >= 0);
  6380. __int64 RequiredWithReserve;
  6381. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6382. if (FreeSpace < RequiredWithReserve)
  6383. {
  6384. unsigned int Result;
  6385. TMessageParams Params(mpNeverAskAgainCheck);
  6386. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6387. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6388. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6389. if (Result == qaNeverAskAgain)
  6390. {
  6391. WinConfiguration->DDWarnLackOfTempSpace = false;
  6392. }
  6393. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6394. }
  6395. }
  6396. }
  6397. }
  6398. //---------------------------------------------------------------------------
  6399. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6400. {
  6401. DoOpenDirectoryDialog(odAddBookmark, Side);
  6402. }
  6403. //---------------------------------------------------------------------------
  6404. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6405. {
  6406. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6407. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6408. try
  6409. {
  6410. TCustomDirView * DView = DirView(Side);
  6411. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6412. {
  6413. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6414. }
  6415. }
  6416. catch (...)
  6417. {
  6418. delete VisitedDirectories;
  6419. throw;
  6420. }
  6421. return VisitedDirectories;
  6422. }
  6423. //---------------------------------------------------------------------------
  6424. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6425. TOpenDirectoryMode Mode, TOperationSide Side)
  6426. {
  6427. bool Continue = true;
  6428. if (Mode == odAddBookmark)
  6429. {
  6430. TMessageParams Params(mpNeverAskAgainCheck);
  6431. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6432. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6433. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6434. unsigned int Answer =
  6435. MessageDialog(Message,
  6436. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6437. if (Answer == qaNeverAskAgain)
  6438. {
  6439. Continue = true;
  6440. WinConfiguration->UseSharedBookmarks = true;
  6441. }
  6442. else if (Answer == qaOK)
  6443. {
  6444. Continue = true;
  6445. WinConfiguration->UseSharedBookmarks = false;
  6446. }
  6447. else
  6448. {
  6449. Continue = false;
  6450. }
  6451. }
  6452. if (Continue)
  6453. {
  6454. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6455. try
  6456. {
  6457. UnicodeString Name = DirView(Side)->PathName;
  6458. bool Repeat;
  6459. do
  6460. {
  6461. Repeat = false;
  6462. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6463. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6464. // do not allow switching to location profiles,
  6465. // if we are not connected
  6466. HasDirView[osLocal] && (Terminal != NULL)))
  6467. {
  6468. TWindowLock Lock(this);
  6469. if (!TryOpenDirectory(Side, Name))
  6470. {
  6471. Repeat = true;
  6472. Mode = odBrowse;
  6473. }
  6474. }
  6475. }
  6476. while (Repeat);
  6477. }
  6478. __finally
  6479. {
  6480. delete VisitedDirectories;
  6481. }
  6482. }
  6483. }
  6484. //---------------------------------------------------------------------------
  6485. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6486. {
  6487. DebugAssert(!Terminal->CommandSessionOpened);
  6488. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6489. }
  6490. //---------------------------------------------------------------------------
  6491. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6492. {
  6493. bool Result = Terminal->IsCapable[Capability] ||
  6494. Terminal->CommandSessionOpened;
  6495. if (!Result)
  6496. {
  6497. DebugAssert(Terminal->IsCapable[fcSecondaryShell]);
  6498. if (!GUIConfiguration->ConfirmCommandSession)
  6499. {
  6500. Result = true;
  6501. }
  6502. else
  6503. {
  6504. TMessageParams Params(mpNeverAskAgainCheck);
  6505. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6506. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6507. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6508. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6509. if (Answer == qaNeverAskAgain)
  6510. {
  6511. GUIConfiguration->ConfirmCommandSession = false;
  6512. Result = true;
  6513. }
  6514. else if (Answer == qaOK)
  6515. {
  6516. Result = true;
  6517. }
  6518. }
  6519. if (Result)
  6520. {
  6521. Result = CommandSessionFallback();
  6522. }
  6523. }
  6524. return Result;
  6525. }
  6526. //---------------------------------------------------------------------------
  6527. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6528. {
  6529. if (EnsureCommandSessionFallback(fcAnyCommand))
  6530. {
  6531. DoConsoleDialog(Terminal, Command);
  6532. }
  6533. }
  6534. //---------------------------------------------------------------------------
  6535. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6536. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6537. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6538. {
  6539. if (!IsSideLocalBrowser(osRemote) &&
  6540. IsFileControl(DropSourceControl, osRemote) &&
  6541. (FDDExtMapFile != NULL))
  6542. {
  6543. Accept = true;
  6544. }
  6545. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6546. DebugAssert(FDDTargetControl != NULL);
  6547. }
  6548. //---------------------------------------------------------------------------
  6549. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6550. _di_IDataObject DataObj, int KeyState,
  6551. const TPoint & Point, int & Effect, bool & Accept)
  6552. {
  6553. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6554. }
  6555. //---------------------------------------------------------------------------
  6556. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6557. _di_IDataObject DataObj, int KeyState,
  6558. const TPoint & Point, int & Effect, bool & Accept)
  6559. {
  6560. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6561. }
  6562. //---------------------------------------------------------------------------
  6563. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6564. TObject * Sender)
  6565. {
  6566. DebugUsedParam(Sender);
  6567. DebugAssert(FDDTargetControl == Sender);
  6568. FDDTargetControl = NULL;
  6569. }
  6570. //---------------------------------------------------------------------------
  6571. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  6572. {
  6573. FileControlDDDragLeave(SessionsPageControl);
  6574. }
  6575. //---------------------------------------------------------------------------
  6576. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  6577. {
  6578. FileControlDDDragLeave(QueueView3);
  6579. }
  6580. //---------------------------------------------------------------------------
  6581. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6582. {
  6583. DebugAssert(!IsSideLocalBrowser(Side));
  6584. DebugUsedParam(Side);
  6585. bool Edit = false;
  6586. TRemoteFile * File = NULL;
  6587. UnicodeString FileName;
  6588. UnicodeString PointTo;
  6589. bool SymbolicLink = true;
  6590. if (RemoteDirView->ItemFocused)
  6591. {
  6592. DebugAssert(RemoteDirView->ItemFocused->Data);
  6593. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6594. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6595. if (Edit)
  6596. {
  6597. FileName = File->FileName;
  6598. PointTo = File->LinkTo;
  6599. }
  6600. else if (!File->IsParentDirectory)
  6601. {
  6602. PointTo = File->FileName;
  6603. }
  6604. }
  6605. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6606. Terminal->IsCapable[fcHardLink]))
  6607. {
  6608. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6609. if (Edit)
  6610. {
  6611. DebugAssert(File->FileName == FileName);
  6612. int Params = dfNoRecursive;
  6613. Terminal->ExceptionOnFail = true;
  6614. try
  6615. {
  6616. Terminal->DeleteFile(L"", File, &Params);
  6617. }
  6618. __finally
  6619. {
  6620. Terminal->ExceptionOnFail = false;
  6621. }
  6622. }
  6623. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6624. }
  6625. }
  6626. //---------------------------------------------------------------------------
  6627. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6628. {
  6629. return
  6630. (IsSideLocalBrowser(Side) ||
  6631. (HasActiveTerminal() &&
  6632. Terminal->ResolvingSymlinks &&
  6633. Terminal->IsCapable[fcSymbolicLink]));
  6634. }
  6635. //---------------------------------------------------------------------------
  6636. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6637. {
  6638. return
  6639. !IsSideLocalBrowser(FCurrentSide) &&
  6640. (RemoteDirView->ItemFocused != NULL) &&
  6641. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6642. Terminal->SessionData->ResolveSymlinks;
  6643. }
  6644. //---------------------------------------------------------------------------
  6645. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6646. {
  6647. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6648. FForceExecution = true;
  6649. try
  6650. {
  6651. DirView(osCurrent)->ExecuteCurrentFile();
  6652. }
  6653. __finally
  6654. {
  6655. FForceExecution = false;
  6656. }
  6657. }
  6658. //---------------------------------------------------------------------------
  6659. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6660. {
  6661. TEditorData ExternalEditor;
  6662. ExternalEditor.Editor = edExternal;
  6663. bool Remember = false;
  6664. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6665. {
  6666. if (Remember)
  6667. {
  6668. TEditorList * EditorList = new TEditorList;
  6669. try
  6670. {
  6671. *EditorList = *WinConfiguration->EditorList;
  6672. bool Found = false;
  6673. int i = 0;
  6674. while (!Found && (i < EditorList->Count))
  6675. {
  6676. const TEditorPreferences * Editor = EditorList->Editors[i];
  6677. if ((Editor->Data->Editor == edExternal) &&
  6678. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6679. {
  6680. Found = true;
  6681. }
  6682. i++;
  6683. }
  6684. if (!Found)
  6685. {
  6686. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6687. WinConfiguration->EditorList = EditorList;
  6688. }
  6689. }
  6690. __finally
  6691. {
  6692. delete EditorList;
  6693. }
  6694. }
  6695. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6696. }
  6697. }
  6698. //---------------------------------------------------------------------------
  6699. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6700. {
  6701. if (FFileFindTerminal == ATerminal)
  6702. {
  6703. FFileFindTerminal = NULL;
  6704. HideFileFindDialog();
  6705. }
  6706. if (FClipboardTerminal == ATerminal)
  6707. {
  6708. ClipboardClear(); // implies ClipboardStop
  6709. }
  6710. if ((FOnSynchronizeAbort != NULL) &&
  6711. (ATerminal == FManagedSession))
  6712. {
  6713. FOnSynchronizeAbort(NULL);
  6714. }
  6715. }
  6716. //---------------------------------------------------------------------------
  6717. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6718. {
  6719. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6720. DetachTerminal(Sender);
  6721. }
  6722. //---------------------------------------------------------------------------
  6723. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6724. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6725. {
  6726. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6727. DebugAssert(Terminal != NULL);
  6728. if (Data->Terminal == Terminal)
  6729. {
  6730. Data->Terminal = NULL;
  6731. }
  6732. }
  6733. //---------------------------------------------------------------------------
  6734. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6735. {
  6736. return NULL;
  6737. }
  6738. //---------------------------------------------------------------------------
  6739. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6740. {
  6741. UpdateControls();
  6742. SessionColor = TColor(0);
  6743. UpdateRemotePathComboBox(false);
  6744. NeedSession(false);
  6745. }
  6746. //---------------------------------------------------------------------------
  6747. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6748. {
  6749. try
  6750. {
  6751. // Cache, as the login dialog can change its value.
  6752. // See also DoShow. Also see TTerminalManager::NewSession.
  6753. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6754. try
  6755. {
  6756. if (ShowLogin)
  6757. {
  6758. bool ReloadSessions = !Startup;
  6759. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6760. }
  6761. }
  6762. __finally
  6763. {
  6764. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6765. // (so there was no chance for the user to open any session yet)
  6766. if ((ShowLogin || !Startup) &&
  6767. !WinConfiguration->KeepOpenWhenNoSession &&
  6768. // this rules out the implicit Commander's local-local browser
  6769. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6770. {
  6771. TerminateApplication();
  6772. }
  6773. }
  6774. }
  6775. catch (EAbort &)
  6776. {
  6777. // swallow
  6778. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6779. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6780. }
  6781. }
  6782. //---------------------------------------------------------------------------
  6783. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6784. {
  6785. TTerminalManager * Manager = TTerminalManager::Instance();
  6786. DebugAssert(!Manager->Updating);
  6787. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6788. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6789. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6790. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6791. try
  6792. {
  6793. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6794. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6795. {
  6796. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6797. }
  6798. for (int Index = 0; Index <= Manager->Count; Index++)
  6799. {
  6800. TThemeTabSheet * TabSheet;
  6801. if (Index >= SessionsPageControl->PageCount)
  6802. {
  6803. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6804. TabSheet->PageControl = SessionsPageControl;
  6805. }
  6806. else
  6807. {
  6808. TabSheet = SessionsPageControl->Pages[Index];
  6809. }
  6810. bool IsSessionTab = (Index < Manager->Count);
  6811. if (IsSessionTab)
  6812. {
  6813. TTerminal * Terminal = Manager->Sessions[Index];
  6814. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6815. TabSheet->CaptionTruncation = tttEllipsis;
  6816. UpdateSessionTab(TabSheet);
  6817. }
  6818. else
  6819. {
  6820. TabSheet->Tag = 0; // not really needed
  6821. TabSheet->Shadowed = false;
  6822. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6823. TabSheet->CaptionTruncation = tttNoText;
  6824. // 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)
  6825. UpdateNewTabTab();
  6826. }
  6827. }
  6828. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6829. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6830. {
  6831. SessionsPageControl->UpdateTabsCaptionTruncation();
  6832. }
  6833. }
  6834. __finally
  6835. {
  6836. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6837. }
  6838. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6839. }
  6840. //---------------------------------------------------------------------------
  6841. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6842. {
  6843. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6844. }
  6845. //---------------------------------------------------------------------------
  6846. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  6847. {
  6848. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6849. UnicodeString TabCaption;
  6850. if (WinConfiguration->SelectiveToolbarText)
  6851. {
  6852. TabCaption = GetNewTabTabCaption();
  6853. }
  6854. TabSheet->BaseCaption = TabCaption;
  6855. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  6856. }
  6857. //---------------------------------------------------------------------------
  6858. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  6859. {
  6860. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  6861. }
  6862. //---------------------------------------------------------------------------
  6863. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  6864. {
  6865. DebugFail();
  6866. return UnicodeString();
  6867. }
  6868. //---------------------------------------------------------------------------
  6869. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  6870. {
  6871. if (DebugAlwaysTrue(TabSheet != NULL))
  6872. {
  6873. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  6874. if (DebugAlwaysTrue(ASession != NULL))
  6875. {
  6876. TColor Color = (ASession == Terminal) ? FSessionColor : ASession->StateData->Color;
  6877. if (ASession->LocalBrowser)
  6878. {
  6879. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  6880. }
  6881. else
  6882. {
  6883. TabSheet->ImageIndex = AddSessionColor(Color);
  6884. }
  6885. TTerminalManager * Manager = TTerminalManager::Instance();
  6886. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  6887. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  6888. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  6889. }
  6890. }
  6891. }
  6892. //---------------------------------------------------------------------------
  6893. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  6894. {
  6895. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  6896. }
  6897. //---------------------------------------------------------------------------
  6898. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6899. {
  6900. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6901. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  6902. bool Result = (Session != NULL);
  6903. if (Result)
  6904. {
  6905. TTerminalManager::Instance()->ActiveSession = Session;
  6906. }
  6907. else
  6908. {
  6909. try
  6910. {
  6911. NewTab();
  6912. }
  6913. __finally
  6914. {
  6915. SessionListChanged();
  6916. }
  6917. FSessionsPageControlNewTabTime = Now();
  6918. }
  6919. return Result;
  6920. }
  6921. //---------------------------------------------------------------------------
  6922. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  6923. {
  6924. TWindowLock Lock(this);
  6925. SessionTabSwitched();
  6926. }
  6927. //---------------------------------------------------------------------------
  6928. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  6929. {
  6930. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  6931. DebugAssert(TransferList != NULL);
  6932. UnicodeString Name;
  6933. if (TransferList->ItemIndex <= 0)
  6934. {
  6935. Name = L"";
  6936. }
  6937. else
  6938. {
  6939. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  6940. }
  6941. if (FCopyParamAutoSelected.IsEmpty())
  6942. {
  6943. // if previous preset was not autoselected, make new preset the "default"
  6944. FCopyParamDefault = Name;
  6945. }
  6946. GUIConfiguration->CopyParamCurrent = Name;
  6947. }
  6948. //---------------------------------------------------------------------------
  6949. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  6950. {
  6951. // sanity check
  6952. bool ExistingPreset =
  6953. (FTransferListHoverIndex >= 0) &&
  6954. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  6955. DebugAssert(ExistingPreset);
  6956. if (ExistingPreset)
  6957. {
  6958. HDC DC = GetDC(0);
  6959. TCanvas * Canvas = new TCanvas();
  6960. try
  6961. {
  6962. Canvas->Handle = DC;
  6963. Canvas->Font = GetToolbarFont(this);
  6964. UnicodeString Name;
  6965. if (FTransferListHoverIndex == 0)
  6966. {
  6967. Name = L"";
  6968. }
  6969. else
  6970. {
  6971. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  6972. }
  6973. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  6974. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  6975. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  6976. static_cast<TObject*>(GetComponent(fcTransferList)));
  6977. UnicodeString InfoStr =
  6978. GUIConfiguration->CopyParamPreset[Name].
  6979. GetInfoStr(L"; ",
  6980. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  6981. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  6982. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  6983. {
  6984. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  6985. {
  6986. InfoStr.SetLength(InfoStr.Length() - 1);
  6987. }
  6988. InfoStr += Ellipsis;
  6989. }
  6990. // UpdateCaption does not cause invalidation of whole submenu, while
  6991. // setting Caption property does.
  6992. // also it probably does not resize the label, even if necessary
  6993. // (we do not want that anyway)
  6994. TransferLabel->UpdateCaption(InfoStr);
  6995. }
  6996. __finally
  6997. {
  6998. Canvas->Handle = NULL;
  6999. ReleaseDC(0, DC);
  7000. delete Canvas;
  7001. }
  7002. }
  7003. }
  7004. //---------------------------------------------------------------------------
  7005. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7006. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7007. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7008. {
  7009. if (FTransferListHoverIndex != AHoverIndex)
  7010. {
  7011. FTransferListHoverIndex = AHoverIndex;
  7012. UpdateTransferLabel();
  7013. }
  7014. }
  7015. //---------------------------------------------------------------------------
  7016. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7017. {
  7018. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7019. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7020. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7021. {
  7022. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7023. {
  7024. if (!NonVisualDataModule->Busy)
  7025. {
  7026. OpenDirectory(GetSide(osCurrent));
  7027. }
  7028. Message.Result = 1;
  7029. }
  7030. else
  7031. {
  7032. TForm::Dispatch(&Message);
  7033. }
  7034. }
  7035. else
  7036. {
  7037. TForm::Dispatch(&Message);
  7038. }
  7039. }
  7040. //---------------------------------------------------------------------------
  7041. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7042. {
  7043. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7044. if ((FIgnoreNextDialogChar != 0) &&
  7045. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7046. {
  7047. Message.Result = 1;
  7048. }
  7049. else
  7050. {
  7051. TForm::Dispatch(&Message);
  7052. }
  7053. FIgnoreNextDialogChar = 0;
  7054. }
  7055. //---------------------------------------------------------------------------
  7056. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7057. {
  7058. // The four low-order bits are used internally by Windows
  7059. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7060. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7061. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7062. // 61730 - restore thru double click - undocumented
  7063. // 61490 - maximize thru double click - undocumented
  7064. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7065. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7066. {
  7067. SysResizing(Cmd);
  7068. }
  7069. TForm::Dispatch(&Message);
  7070. }
  7071. //---------------------------------------------------------------------------
  7072. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7073. {
  7074. AppLog(L"Windows session end query");
  7075. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7076. // Also there no point returning TRUE as we are not able to
  7077. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7078. // Hence the process termination might be safer :)
  7079. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7080. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7081. {
  7082. Message.Result = FALSE;
  7083. }
  7084. else
  7085. {
  7086. Message.Result = TRUE;
  7087. }
  7088. // Do not call default handling as that triggers OnCloseQuery,
  7089. // where our implementation will popup confirmation dialogs, what we do not want,
  7090. // as per Vista guidelines:
  7091. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7092. }
  7093. //---------------------------------------------------------------------------
  7094. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7095. {
  7096. AppLog(L"Windows session end");
  7097. if (Message.EndSession && IsApplicationMinimized())
  7098. {
  7099. // WORKAROUND
  7100. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7101. // when it receives WM_ENDSESSION,
  7102. // but that sometimes (particularly when application is minimized) cause crashes.
  7103. // Crash popups message that blocks log off.
  7104. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7105. // so we call ExitProcess() immediately, not even trying to cleanup.
  7106. // It still causes beep, so there's likely some popup, but it does not block
  7107. // log off.
  7108. ExitProcess(0);
  7109. }
  7110. TForm::Dispatch(&Message);
  7111. }
  7112. #ifdef _DEBUG
  7113. //---------------------------------------------------------------------------
  7114. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  7115. {
  7116. TForm::Dispatch(&Message);
  7117. }
  7118. #endif
  7119. //---------------------------------------------------------------------------
  7120. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7121. {
  7122. }
  7123. //---------------------------------------------------------------------------
  7124. void __fastcall TCustomScpExplorerForm::DoShow()
  7125. {
  7126. // Called from TCustomScpExplorerForm::CMShowingChanged
  7127. // only now are the controls resized finally, so the size constraints
  7128. // will not conflict with possibly very small window size
  7129. RestoreFormParams();
  7130. // This indicates that the form was rescaled after parameters were loaded and
  7131. // as most probably the parameters were actually saved with the current form scaling
  7132. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7133. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7134. // and no rounding problems will occur.
  7135. // See also RestoreForm.
  7136. // (we should be safe to call RestoreParams unconditionally)
  7137. if (PixelsPerInch != Screen->PixelsPerInch)
  7138. {
  7139. RestoreParams();
  7140. }
  7141. FixControlsPlacement();
  7142. if (Position == poDefaultPosOnly)
  7143. {
  7144. CutFormToDesktop(this);
  7145. }
  7146. TForm::DoShow();
  7147. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7148. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7149. // This was previously in NeedSession, where other related code is.
  7150. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7151. // unpleasantly shows briefly.
  7152. if ((ManagedSession == NULL) &&
  7153. !WinConfiguration->ShowLoginWhenNoSession &&
  7154. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7155. // This detects if workspace was saved the last time the main widow was closed
  7156. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7157. {
  7158. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7159. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7160. }
  7161. // Before main window displays
  7162. if (ManagedSession == NULL)
  7163. {
  7164. StartingWithoutSession();
  7165. }
  7166. UpdatePixelsPerInchMainWindowCounter();
  7167. FShowing = true;
  7168. }
  7169. //---------------------------------------------------------------------------
  7170. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7171. {
  7172. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7173. }
  7174. //---------------------------------------------------------------------------
  7175. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7176. {
  7177. SessionListChanged();
  7178. InitStatusBar();
  7179. UpdateControls();
  7180. }
  7181. //---------------------------------------------------------------------------
  7182. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7183. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7184. TNotifyEvent OnBalloonClick, TObject * UserData)
  7185. {
  7186. bool Do;
  7187. UnicodeString Message;
  7188. if (E == NULL)
  7189. {
  7190. Message = Str;
  7191. Do = true;
  7192. }
  7193. else
  7194. {
  7195. Do = ExceptionMessage(E, Message);
  7196. }
  7197. if (Do && WinConfiguration->BalloonNotifications)
  7198. {
  7199. UnicodeString Title;
  7200. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7201. {
  7202. Message = TrimLeft(Message);
  7203. }
  7204. else
  7205. {
  7206. Message = UnformatMessage(Message);
  7207. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7208. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7209. Title = LoadResourceString(Captions[Type]);
  7210. if (Terminal != NULL)
  7211. {
  7212. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7213. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7214. }
  7215. }
  7216. if (Seconds == 0)
  7217. {
  7218. Seconds = WinConfiguration->NotificationsTimeout;
  7219. }
  7220. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7221. }
  7222. }
  7223. //---------------------------------------------------------------------------
  7224. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7225. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7226. UnicodeString HelpKeyword, const TMessageParams * Params,
  7227. TTerminal * Terminal)
  7228. {
  7229. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7230. (FOnFeedSynchronizeError != NULL)) &&
  7231. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7232. {
  7233. if (FOnFeedSynchronizeError != NULL)
  7234. {
  7235. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7236. }
  7237. else
  7238. {
  7239. DebugAssert(FErrorList != NULL);
  7240. TStringList * MoreMessagesCopy = NULL;
  7241. if (MoreMessages)
  7242. {
  7243. MoreMessagesCopy = new TStringList();
  7244. MoreMessagesCopy->Assign(MoreMessages);
  7245. }
  7246. FErrorList->AddObject(Message, MoreMessagesCopy);
  7247. }
  7248. PopupTrayBalloon(Terminal, Message, Type);
  7249. return ContinueAnswer(Answers);
  7250. }
  7251. else
  7252. {
  7253. bool UseBalloon = FTrayIcon->Visible;
  7254. if (UseBalloon)
  7255. {
  7256. PopupTrayBalloon(Terminal, Message, Type);
  7257. }
  7258. unsigned int Result;
  7259. try
  7260. {
  7261. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7262. }
  7263. __finally
  7264. {
  7265. // cancel only balloon we popped up, otherwise we may cancel notification
  7266. // balloon that was there before the message dialog
  7267. // (such as "dd confirmation opt in balloon)
  7268. if (UseBalloon)
  7269. {
  7270. FTrayIcon->CancelBalloon();
  7271. }
  7272. }
  7273. return Result;
  7274. }
  7275. }
  7276. //---------------------------------------------------------------------------
  7277. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7278. TTerminal * Terminal, Exception * E)
  7279. {
  7280. if (FTrayIcon->Visible)
  7281. {
  7282. PopupTrayBalloon(Terminal, L"", qtError, E);
  7283. }
  7284. // particularly prevent opening new session from jump list,
  7285. // while exception is shown
  7286. NonVisualDataModule->StartBusy();
  7287. try
  7288. {
  7289. ShowExtendedExceptionEx(Terminal, E);
  7290. }
  7291. __finally
  7292. {
  7293. NonVisualDataModule->EndBusy();
  7294. FTrayIcon->CancelBalloon();
  7295. }
  7296. }
  7297. //---------------------------------------------------------------------------
  7298. void __fastcall TCustomScpExplorerForm::SessionReady()
  7299. {
  7300. InitStatusBar();
  7301. // cannot rely on active page being page for active terminal,
  7302. // as it can happen that active page is the "new session" page
  7303. // (e.g. when reconnecting active terminal, while login dialog
  7304. // invoked from "new session" page is modal)
  7305. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7306. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7307. }
  7308. //---------------------------------------------------------------------------
  7309. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  7310. TTerminal * Terminal, Exception * E)
  7311. {
  7312. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  7313. if (!Terminal->Active)
  7314. {
  7315. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7316. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7317. {
  7318. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7319. }
  7320. }
  7321. }
  7322. //---------------------------------------------------------------------------
  7323. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  7324. UnicodeString Message, TQueryType Type,
  7325. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7326. {
  7327. if ((E == NULL) ||
  7328. ExceptionMessage(E, Message))
  7329. {
  7330. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7331. if (Important)
  7332. {
  7333. Seconds *= 5;
  7334. }
  7335. UnicodeString NoteMessage(UnformatMessage(Message));
  7336. if (Terminal != NULL)
  7337. {
  7338. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7339. NoteMessage = FORMAT(L"%s: %s",
  7340. (TTerminalManager::Instance()->GetSessionTitle(Session, true), NoteMessage));
  7341. }
  7342. if (WinConfiguration->BalloonNotifications)
  7343. {
  7344. AddNote(NoteMessage);
  7345. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7346. }
  7347. else
  7348. {
  7349. FlashOnBackground();
  7350. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7351. }
  7352. }
  7353. }
  7354. //---------------------------------------------------------------------------
  7355. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7356. {
  7357. RestoreApp();
  7358. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7359. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7360. !NonVisualDataModule->Busy)
  7361. {
  7362. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7363. TTerminalManager::Instance()->ActiveSession = Terminal;
  7364. if (!ComponentVisible[fcQueueView])
  7365. {
  7366. ToggleQueueVisibility();
  7367. GoToQueue();
  7368. }
  7369. }
  7370. }
  7371. //---------------------------------------------------------------------------
  7372. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7373. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7374. {
  7375. UnicodeString Message;
  7376. TNotifyEvent OnClick = NULL;
  7377. TObject * UserData = NULL;
  7378. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7379. switch (Event)
  7380. {
  7381. case qeEmptyButMonitored:
  7382. if ((ATerminal != Terminal) || QueueInvisible)
  7383. {
  7384. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7385. OnClick = QueueEmptyNoteClicked;
  7386. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7387. TerminalNoteData->Terminal = ATerminal;
  7388. UserData = TerminalNoteData;
  7389. }
  7390. break;
  7391. case qeEmpty:
  7392. OperationComplete(ATerminal->QueueOperationStart);
  7393. break;
  7394. case qePendingUserAction:
  7395. if ((ATerminal != Terminal) ||
  7396. (QueueInvisible && !IsQueueAutoPopup()))
  7397. {
  7398. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7399. }
  7400. break;
  7401. default:
  7402. DebugFail();
  7403. }
  7404. if (!Message.IsEmpty())
  7405. {
  7406. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7407. }
  7408. }
  7409. //---------------------------------------------------------------------------
  7410. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7411. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7412. {
  7413. if (FDDExtMapFile != NULL)
  7414. {
  7415. CloseHandle(FDDExtMapFile);
  7416. FDDExtMapFile = NULL;
  7417. }
  7418. if (WinConfiguration->DDFakeFile)
  7419. {
  7420. DDFakeFileInitDrag(FileList, Created);
  7421. }
  7422. }
  7423. //---------------------------------------------------------------------------
  7424. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7425. {
  7426. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7427. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7428. {
  7429. FFakeFileDropTarget = FileName;
  7430. }
  7431. }
  7432. //---------------------------------------------------------------------------
  7433. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7434. {
  7435. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7436. if (!ForceDirectories(ApiPath(Result)))
  7437. {
  7438. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7439. }
  7440. FileSetAttr(ApiPath(Result), faHidden);
  7441. return Result;
  7442. }
  7443. //---------------------------------------------------------------------------
  7444. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7445. bool & Created)
  7446. {
  7447. FFakeFileDropTarget = UnicodeString();
  7448. FDragFakeDirectory = CreateFakeTransferDirectory();
  7449. FileList->AddItem(NULL, FDragFakeDirectory);
  7450. Created = true;
  7451. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7452. {
  7453. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7454. }
  7455. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7456. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7457. {
  7458. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7459. TDragExtCommStruct* CommStruct;
  7460. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7461. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7462. DebugAssert(CommStruct != NULL);
  7463. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7464. CommStruct->Dragging = true;
  7465. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7466. LENOF(CommStruct->DropDest));
  7467. NULL_TERMINATE(CommStruct->DropDest);
  7468. UnmapViewOfFile(CommStruct);
  7469. }
  7470. }
  7471. //---------------------------------------------------------------------------
  7472. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7473. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7474. {
  7475. bool Result;
  7476. DebugAssert(!IsLocalBrowserMode());
  7477. if (Sender == RemoteDirView)
  7478. {
  7479. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7480. }
  7481. else
  7482. {
  7483. DebugAssert(Sender == RemoteDriveView);
  7484. TStrings * FileList = RemoteDriveView->DragFileList();
  7485. try
  7486. {
  7487. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7488. }
  7489. __finally
  7490. {
  7491. delete FileList;
  7492. }
  7493. }
  7494. if (FDDTargetControl == RemoteDriveView)
  7495. {
  7496. RemoteDriveView->UpdateDropTarget();
  7497. }
  7498. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7499. // or from tree view to dir view.
  7500. // foMove happens when file/dir is dragged from remote tree view outside of
  7501. // application via dragex
  7502. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7503. (DropSourceControl == RemoteDriveView))
  7504. {
  7505. RemoteDriveView->UpdateDropSource();
  7506. }
  7507. return Result;
  7508. }
  7509. //---------------------------------------------------------------------------
  7510. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7511. {
  7512. DebugAssert(!IsLocalBrowserMode());
  7513. // This also handles drops of remote files to queue.
  7514. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7515. SAFE_DESTROY(FDDFileList);
  7516. if (!FFakeFileDropTarget.IsEmpty())
  7517. {
  7518. RemoveDir(ApiPath(FFakeFileDropTarget));
  7519. }
  7520. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7521. {
  7522. try
  7523. {
  7524. TDragResult DDResult = (Sender == RemoteDirView) ?
  7525. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7526. // Focus is moved to the target application,
  7527. // but as we are going to present the UI, we need to steal the focus back.
  7528. // This most likely won't work though (windows does not allow application
  7529. // to steal focus most of the time)
  7530. Application->BringToFront();
  7531. // On older version of Windows we never got drMove here, see also comment below.
  7532. // On Windows 10, we get the "move".
  7533. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7534. {
  7535. UnicodeString TargetDirectory;
  7536. TFileOperation Operation;
  7537. // drInvalid may mean drMove, see comment below
  7538. switch (DDResult)
  7539. {
  7540. case drCopy:
  7541. Operation = foCopy;
  7542. break;
  7543. case drMove:
  7544. Operation = foMove;
  7545. break;
  7546. default:
  7547. DebugFail();
  7548. case drInvalid:
  7549. // prefer "copy" for safety
  7550. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7551. break;
  7552. }
  7553. TTransferOperationParam Param;
  7554. UnicodeString CounterName;
  7555. bool ForceQueue;
  7556. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7557. {
  7558. // we get drInvalid both if d&d was intercepted by ddext,
  7559. // and when users drops on no-drop location.
  7560. // we tell the difference by existence of response from ddext,
  7561. // so we ignore absence of response in this case
  7562. if (DDResult != drInvalid)
  7563. {
  7564. // here we know that the extension is installed,
  7565. // as it is checked as soon as drag&drop starts from
  7566. // RemoteFileControlDDCreateDragFileList
  7567. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7568. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7569. {
  7570. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7571. }
  7572. else
  7573. {
  7574. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7575. }
  7576. }
  7577. }
  7578. else
  7579. {
  7580. // download using fake file
  7581. Param.Temp = false;
  7582. Param.DragDrop = true;
  7583. if (ForceQueue)
  7584. {
  7585. Param.Queue = asOn;
  7586. }
  7587. if (Sender == RemoteDirView)
  7588. {
  7589. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7590. }
  7591. if (RemoteFileControlFileOperation(Sender, Operation,
  7592. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7593. {
  7594. Configuration->Usage->Inc(CounterName);
  7595. }
  7596. }
  7597. }
  7598. }
  7599. __finally
  7600. {
  7601. CloseHandle(FDDExtMapFile);
  7602. FDDExtMapFile = NULL;
  7603. delete FDragFakeMonitors;
  7604. FDragFakeMonitors = NULL;
  7605. RemoveDir(ApiPath(FDragFakeDirectory));
  7606. FDragFakeDirectory = L"";
  7607. FFakeFileDropTarget = UnicodeString();
  7608. }
  7609. }
  7610. if (FDragDropSshTerminate.get() != NULL)
  7611. {
  7612. FDragDropSshTerminate->Rethrow();
  7613. }
  7614. }
  7615. //---------------------------------------------------------------------------
  7616. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7617. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7618. {
  7619. // Remember drop effect so we know (when user drops files), if we copy or move
  7620. FLastDropEffect = dwEffect;
  7621. }
  7622. //---------------------------------------------------------------------------
  7623. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7624. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7625. {
  7626. bool Result;
  7627. if (FDDTargetControl == QueueView3)
  7628. {
  7629. Directory = DefaultDownloadTargetDirectory();
  7630. Result = true;
  7631. CounterName = L"DownloadsDragDropQueue";
  7632. ForceQueue = true;
  7633. }
  7634. else if (!FFakeFileDropTarget.IsEmpty())
  7635. {
  7636. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7637. Result = true;
  7638. ForceQueue = false;
  7639. CounterName = L"DownloadsDragDropFakeFile";
  7640. }
  7641. else
  7642. {
  7643. ForceQueue = false;
  7644. Enabled = false;
  7645. try
  7646. {
  7647. int Timer = 0;
  7648. Result = false;
  7649. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7650. {
  7651. {
  7652. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7653. TDragExtCommStruct* CommStruct;
  7654. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7655. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7656. DebugAssert(CommStruct != NULL);
  7657. Result = !CommStruct->Dragging;
  7658. if (Result)
  7659. {
  7660. Directory = ExtractFilePath(CommStruct->DropDest);
  7661. CounterName = L"DownloadsDragDropExternalExt";
  7662. }
  7663. UnmapViewOfFile(CommStruct);
  7664. }
  7665. if (!Result)
  7666. {
  7667. Sleep(50);
  7668. Timer += 50;
  7669. Application->ProcessMessages();
  7670. }
  7671. }
  7672. }
  7673. __finally
  7674. {
  7675. Enabled = true;
  7676. }
  7677. }
  7678. return Result;
  7679. }
  7680. //---------------------------------------------------------------------------
  7681. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7682. const UnicodeString TempDir, int SecDelay)
  7683. {
  7684. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7685. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7686. if (FDelayedDeletionTimer == NULL)
  7687. {
  7688. DebugAssert(HandleAllocated());
  7689. FDelayedDeletionTimer = new TTimer(this);
  7690. FDelayedDeletionTimer->Interval = 10000;
  7691. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7692. }
  7693. else
  7694. {
  7695. FDelayedDeletionTimer->Enabled = true;
  7696. }
  7697. }
  7698. //---------------------------------------------------------------------------
  7699. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7700. {
  7701. DebugAssert(FDelayedDeletionList != NULL);
  7702. TDateTime N = Now();
  7703. TDateTime Alert;
  7704. UnicodeString Directory;
  7705. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7706. {
  7707. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7708. if ((N >= Alert) || (Sender == NULL))
  7709. {
  7710. Directory = FDelayedDeletionList->Strings[Index];
  7711. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7712. {
  7713. FDelayedDeletionList->Delete(Index);
  7714. }
  7715. }
  7716. }
  7717. if (FDelayedDeletionList->Count == 0)
  7718. {
  7719. FDelayedDeletionTimer->Enabled = false;
  7720. }
  7721. }
  7722. //---------------------------------------------------------------------------
  7723. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7724. {
  7725. DebugAssert(!IsLocalBrowserMode());
  7726. if (IsFileControl(FDDTargetControl, osRemote) ||
  7727. (FDDTargetControl == SessionsPageControl))
  7728. {
  7729. TManagedTerminal * TargetTerminal = NULL;
  7730. TFileOperation Operation = foNone;
  7731. if (FDDTargetControl == SessionsPageControl)
  7732. {
  7733. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7734. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7735. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7736. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7737. if (IsActiveTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7738. {
  7739. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7740. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7741. {
  7742. Operation = foRemoteMove;
  7743. }
  7744. else
  7745. {
  7746. Operation = foRemoteCopy;
  7747. }
  7748. }
  7749. }
  7750. else
  7751. {
  7752. if (FLastDropEffect == DROPEFFECT_MOVE)
  7753. {
  7754. Operation = foRemoteMove;
  7755. }
  7756. else if (FLastDropEffect == DROPEFFECT_COPY)
  7757. {
  7758. Operation = foRemoteCopy;
  7759. }
  7760. }
  7761. if (Operation != foNone)
  7762. {
  7763. RemoteFileControlFileOperation(DropSourceControl,
  7764. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7765. }
  7766. // abort drag&drop
  7767. Abort();
  7768. }
  7769. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7770. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7771. (FDDTargetControl != QueueView3))
  7772. {
  7773. DebugAssert(!FDragTempDir.IsEmpty());
  7774. TTransferType Type;
  7775. UnicodeString TempDir = FDragTempDir;
  7776. // We clear FDragTempDir before calling
  7777. // just in case it fail (raises exception)
  7778. FDragTempDir = L"";
  7779. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7780. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7781. // empty directory parameter means temp directory -> don't display it!
  7782. UnicodeString TargetDir = L"";
  7783. int Options = 0;
  7784. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7785. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7786. {
  7787. Abort();
  7788. }
  7789. // TargetDir is set when dropped on local file control
  7790. // (this was workaround for legacy dirview event handling, now it should be
  7791. // made prettier)
  7792. if (TargetDir.IsEmpty())
  7793. {
  7794. TargetDir = TempDir;
  7795. if (ForceDirectories(ApiPath(TargetDir)))
  7796. {
  7797. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7798. FPendingTempSpaceWarn = true;
  7799. try
  7800. {
  7801. FDragDropOperation = true;
  7802. int Params = cpTemporary |
  7803. (Type == ttMove ? cpDelete : 0);
  7804. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7805. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7806. }
  7807. __finally
  7808. {
  7809. FDragDropOperation = false;
  7810. FPendingTempSpaceWarn = false;
  7811. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7812. }
  7813. }
  7814. else
  7815. {
  7816. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7817. }
  7818. }
  7819. }
  7820. }
  7821. //---------------------------------------------------------------------------
  7822. void __fastcall TCustomScpExplorerForm::DDDownload(
  7823. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7824. {
  7825. DebugAssert(!IsLocalBrowserMode());
  7826. TAutoBatch AutoBatch(this);
  7827. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7828. UpdateCopyParamCounters(*CopyParam);
  7829. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7830. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7831. {
  7832. RemoteDriveView->UpdateDropSource();
  7833. }
  7834. }
  7835. //---------------------------------------------------------------------------
  7836. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7837. {
  7838. public:
  7839. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7840. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7841. {
  7842. }
  7843. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7844. {
  7845. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7846. TDataObjectFilesEx::AllowData(FormatEtc);
  7847. }
  7848. };
  7849. //---------------------------------------------------------------------------
  7850. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7851. TObject * Sender, TDataObject *& DataObject)
  7852. {
  7853. if (FDDExtMapFile != NULL)
  7854. {
  7855. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7856. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7857. {
  7858. Abort();
  7859. }
  7860. if (FileList->Count > 0)
  7861. {
  7862. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7863. if (!FilesObject->IsValid(true, true))
  7864. {
  7865. FilesObject->_Release();
  7866. }
  7867. else
  7868. {
  7869. DataObject = FilesObject;
  7870. }
  7871. }
  7872. }
  7873. }
  7874. //---------------------------------------------------------------------------
  7875. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7876. {
  7877. DebugFail();
  7878. }
  7879. //---------------------------------------------------------------------------
  7880. void __fastcall TCustomScpExplorerForm::GoToTree()
  7881. {
  7882. ComponentVisible[fcRemoteTree] = true;
  7883. DriveView(osRemote)->SetFocus();
  7884. }
  7885. //---------------------------------------------------------------------------
  7886. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7887. TPanelExport Export)
  7888. {
  7889. TCustomDirView * DirView = this->DirView(Side);
  7890. std::unique_ptr<TStrings> ExportData(new TStringList());
  7891. switch (Export)
  7892. {
  7893. case pePath:
  7894. ExportData->Add(DirView->PathName);
  7895. break;
  7896. case peFileList:
  7897. case peFullFileList:
  7898. {
  7899. bool FullPath = (Export == peFullFileList);
  7900. DirView->CreateFileList(false, FullPath, ExportData.get());
  7901. for (int Index = 0; Index < ExportData->Count; Index++)
  7902. {
  7903. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7904. {
  7905. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7906. }
  7907. }
  7908. }
  7909. break;
  7910. default:
  7911. DebugFail();
  7912. }
  7913. return ExportData.release();
  7914. }
  7915. //---------------------------------------------------------------------------
  7916. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7917. TPanelExport Export, TPanelExportDestination Destination)
  7918. {
  7919. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7920. PanelExportStore(Side, Export, Destination, ExportData.get());
  7921. }
  7922. //---------------------------------------------------------------------------
  7923. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  7924. TPanelExport /*Export*/, TPanelExportDestination Destination,
  7925. TStrings * ExportData)
  7926. {
  7927. if (Destination == pedClipboard)
  7928. {
  7929. TInstantOperationVisualizer Visualizer;
  7930. CopyToClipboard(ExportData);
  7931. }
  7932. else
  7933. {
  7934. DebugFail();
  7935. }
  7936. }
  7937. //---------------------------------------------------------------------------
  7938. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  7939. {
  7940. TCustomDirView * DirView = this->DirView(Side);
  7941. UnicodeString Mask = DirView->Mask;
  7942. if (DoFilterMaskDialog(DirView, Mask))
  7943. {
  7944. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  7945. Configuration->Usage->Inc(L"Filters");
  7946. }
  7947. }
  7948. //---------------------------------------------------------------------------
  7949. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  7950. {
  7951. return FQueueController->DefaultOperation();
  7952. }
  7953. //---------------------------------------------------------------------------
  7954. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  7955. TQueueOperation Operation, void ** Param)
  7956. {
  7957. switch (Operation)
  7958. {
  7959. case qoPreferences:
  7960. return true;
  7961. case qoGoTo:
  7962. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  7963. case qoOnceEmpty:
  7964. return IsAnythingQueued();
  7965. default:
  7966. return FQueueController->AllowOperation(Operation, Param);
  7967. }
  7968. }
  7969. //---------------------------------------------------------------------------
  7970. void __fastcall TCustomScpExplorerForm::GoToQueue()
  7971. {
  7972. if (DebugAlwaysTrue(QueueView3->Visible))
  7973. {
  7974. QueueView3->SetFocus();
  7975. }
  7976. }
  7977. //---------------------------------------------------------------------------
  7978. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  7979. TQueueOperation Operation, void * Param)
  7980. {
  7981. if (Operation == qoGoTo)
  7982. {
  7983. GoToQueue();
  7984. }
  7985. else if (Operation == qoPreferences)
  7986. {
  7987. PreferencesDialog(pmQueue);
  7988. }
  7989. else
  7990. {
  7991. FQueueController->ExecuteOperation(Operation, Param);
  7992. }
  7993. }
  7994. //---------------------------------------------------------------------------
  7995. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  7996. {
  7997. return (Queue != NULL) && Queue->Enabled;
  7998. }
  7999. //---------------------------------------------------------------------------
  8000. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8001. {
  8002. DebugAssert(Queue != NULL);
  8003. if (Queue != NULL)
  8004. {
  8005. Queue->Enabled = !Queue->Enabled;
  8006. }
  8007. }
  8008. //---------------------------------------------------------------------------
  8009. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8010. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8011. {
  8012. FQueueActedItem = QueueView3->ItemFocused;
  8013. }
  8014. //---------------------------------------------------------------------------
  8015. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8016. {
  8017. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8018. }
  8019. //---------------------------------------------------------------------------
  8020. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8021. {
  8022. return
  8023. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8024. (QueueDock->Visible ? QueueDock->Height : 0) +
  8025. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8026. }
  8027. //---------------------------------------------------------------------------
  8028. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8029. {
  8030. return ScaleByTextHeight(this, 48);
  8031. }
  8032. //---------------------------------------------------------------------------
  8033. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8034. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8035. {
  8036. // when queue is hidden by double-clicking splitter, stray attempt to
  8037. // resize the panel with strange value arrives, make sure it is ignored
  8038. if (ComponentVisible[fcQueueView])
  8039. {
  8040. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8041. if (NewSize > MaxHeightLimit)
  8042. {
  8043. NewSize = MaxHeightLimit;
  8044. }
  8045. int MinHeightLimit =
  8046. GetStaticQueuePanelComponentsHeight() +
  8047. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8048. GetMinQueueViewHeight();
  8049. if (NewSize < MinHeightLimit)
  8050. {
  8051. NewSize = MinHeightLimit;
  8052. }
  8053. }
  8054. else
  8055. {
  8056. Accept = false;
  8057. }
  8058. }
  8059. //---------------------------------------------------------------------------
  8060. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8061. {
  8062. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8063. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8064. if (QueueViewHeight < GetMinQueueViewHeight())
  8065. {
  8066. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8067. }
  8068. }
  8069. //---------------------------------------------------------------------------
  8070. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8071. TDragObject *& /*DragObject*/)
  8072. {
  8073. FQueueActedItem = QueueView3->ItemFocused;
  8074. FQueueScrollOnDragOver->StartDrag();
  8075. }
  8076. //---------------------------------------------------------------------------
  8077. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8078. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8079. {
  8080. FQueueScrollOnDragOver->EndDrag();
  8081. }
  8082. //---------------------------------------------------------------------------
  8083. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8084. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8085. {
  8086. Accept = true;
  8087. if (Source == QueueView3)
  8088. {
  8089. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8090. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8091. if (Accept)
  8092. {
  8093. TQueueItemProxy * QueueItem;
  8094. TQueueItemProxy * DestQueueItem;
  8095. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8096. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8097. Accept = (QueueItem != DestQueueItem) &&
  8098. (QueueItem->Status == TQueueItem::qsPending) &&
  8099. (DestQueueItem->Status == TQueueItem::qsPending);
  8100. }
  8101. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8102. }
  8103. }
  8104. //---------------------------------------------------------------------------
  8105. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8106. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8107. {
  8108. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8109. {
  8110. TQueueItemProxy * QueueItem;
  8111. TQueueItemProxy * DestQueueItem;
  8112. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8113. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8114. QueueItem->Move(DestQueueItem);
  8115. }
  8116. }
  8117. //---------------------------------------------------------------------------
  8118. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8119. {
  8120. if ((QueueView3->ItemFocused == NULL) &&
  8121. (QueueView3->Items->Count > 0))
  8122. {
  8123. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8124. }
  8125. QueueLabelUpdateStatus();
  8126. }
  8127. //---------------------------------------------------------------------------
  8128. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8129. {
  8130. QueueLabelUpdateStatus();
  8131. }
  8132. //---------------------------------------------------------------------------
  8133. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8134. {
  8135. QueueLabel->UpdateStatus();
  8136. }
  8137. //---------------------------------------------------------------------------
  8138. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8139. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8140. {
  8141. if (Selected)
  8142. {
  8143. NonVisualDataModule->UpdateNonVisibleActions();
  8144. }
  8145. }
  8146. //---------------------------------------------------------------------------
  8147. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8148. {
  8149. TDragDropFilesEx * Result = NULL;
  8150. if (Sender == SessionsPageControl)
  8151. {
  8152. Result = FSessionsDragDropFilesEx;
  8153. }
  8154. else if (Sender == QueueView3)
  8155. {
  8156. Result = FQueueDragDropFilesEx;
  8157. }
  8158. else
  8159. {
  8160. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8161. if (DirView != NULL)
  8162. {
  8163. Result = DirView->DragDropFilesEx;
  8164. }
  8165. else
  8166. {
  8167. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8168. if (DriveView != NULL)
  8169. {
  8170. Result = DriveView->DragDropFilesEx;
  8171. }
  8172. }
  8173. }
  8174. DebugAssert(Result != NULL);
  8175. return Result;
  8176. }
  8177. //---------------------------------------------------------------------------
  8178. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8179. {
  8180. return (DView->SelCount == DView->FilesCount);
  8181. }
  8182. //---------------------------------------------------------------------------
  8183. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8184. {
  8185. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8186. }
  8187. //---------------------------------------------------------------------------
  8188. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8189. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8190. {
  8191. DebugAssert(!IsLocalBrowserMode());
  8192. TFileOperation Operation;
  8193. switch (Effect)
  8194. {
  8195. case DROPEFFECT_MOVE:
  8196. Operation = foMove;
  8197. break;
  8198. case DROPEFFECT_COPY:
  8199. // occures on WinXP (reported by user)
  8200. default:
  8201. Operation = foCopy;
  8202. break;
  8203. };
  8204. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8205. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8206. if (DragDropFilesEx->FileList->Count > 0)
  8207. {
  8208. TStrings * FileList = new TStringList();
  8209. try
  8210. {
  8211. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8212. {
  8213. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8214. }
  8215. FDragDropOperation = true;
  8216. TTransferOperationParam Param;
  8217. Param.TargetDirectory = TargetPath;
  8218. // upload, no temp dirs
  8219. Param.Temp = false;
  8220. Param.DragDrop = DragDrop;
  8221. Param.Options =
  8222. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8223. if (ForceQueue)
  8224. {
  8225. Param.Queue = asOn;
  8226. }
  8227. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8228. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8229. {
  8230. if (IsFileControl(DropSourceControl, osLocal))
  8231. {
  8232. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8233. }
  8234. else
  8235. {
  8236. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8237. }
  8238. }
  8239. }
  8240. __finally
  8241. {
  8242. FDragDropOperation = false;
  8243. delete FileList;
  8244. }
  8245. }
  8246. }
  8247. //---------------------------------------------------------------------------
  8248. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8249. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8250. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8251. {
  8252. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8253. }
  8254. //---------------------------------------------------------------------------
  8255. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8256. TObject * Sender, int grfKeyState, int & dwEffect)
  8257. {
  8258. DebugAssert(!IsLocalBrowserMode());
  8259. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8260. if ((dwEffect != DROPEFFECT_NONE) &&
  8261. IsFileControl(DropSourceControl, osRemote))
  8262. {
  8263. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8264. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8265. (RemoteDirView->DropTarget == NULL))
  8266. {
  8267. dwEffect = DROPEFFECT_NONE;
  8268. }
  8269. else
  8270. {
  8271. if (dwEffect == DROPEFFECT_COPY)
  8272. {
  8273. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8274. // currently we support copying always (at least via temporary directory);
  8275. // remove associated checks once this all proves stable and working
  8276. bool CopyCapable = true;
  8277. // if we do not support neither of operations, there's no discussion
  8278. if (!MoveCapable && !CopyCapable)
  8279. {
  8280. dwEffect = DROPEFFECT_NONE;
  8281. }
  8282. else
  8283. {
  8284. // The default effect inside remote panel is move,
  8285. // unless we do not support it, but support copy
  8286. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8287. {
  8288. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8289. }
  8290. else
  8291. {
  8292. // with ctrl-down, we want copy unless it is not supported
  8293. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8294. }
  8295. }
  8296. }
  8297. }
  8298. }
  8299. }
  8300. //---------------------------------------------------------------------------
  8301. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8302. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8303. {
  8304. DebugAssert(!IsLocalBrowserMode());
  8305. if (FDDTotalSize >= 0)
  8306. {
  8307. if (File->IsDirectory)
  8308. {
  8309. FDDTotalSize = -1;
  8310. }
  8311. else
  8312. {
  8313. FDDTotalSize += File->Size;
  8314. }
  8315. }
  8316. DebugAssert(!FDragTempDir.IsEmpty());
  8317. // TODO: this is quite ineffective
  8318. // TODO: what if invalid character replacement is disabled?
  8319. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8320. UnicodeString TransferFileName;
  8321. if (Sender == RemoteDriveView)
  8322. {
  8323. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8324. }
  8325. else
  8326. {
  8327. TransferFileName = File->FileName;
  8328. }
  8329. FDDFileList->AddObject(TransferFileName, File);
  8330. }
  8331. //---------------------------------------------------------------------------
  8332. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8333. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8334. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8335. {
  8336. // sometimes we do not get DDEnd so the list is not released
  8337. SAFE_DESTROY(FDDFileList);
  8338. FDDFileList = new TStringList();
  8339. FDragTempDir = WinConfiguration->TemporaryDir();
  8340. FDDTotalSize = 0;
  8341. FDragDropSshTerminate.reset(NULL);
  8342. }
  8343. //---------------------------------------------------------------------------
  8344. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8345. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  8346. HRESULT & Result)
  8347. {
  8348. if (Result == DRAGDROP_S_DROP)
  8349. {
  8350. try
  8351. {
  8352. GlobalDragImageList->HideDragImage();
  8353. try
  8354. {
  8355. RemoteFileControlDDTargetDrop();
  8356. }
  8357. catch(ESshTerminate & E)
  8358. {
  8359. FDragDropSshTerminate.reset(E.Clone());
  8360. }
  8361. }
  8362. catch (Exception &E)
  8363. {
  8364. // If downloading fails we need to cancel drag&drop, otherwise
  8365. // Explorer shows error
  8366. // But by the way exception probably never reach this point as
  8367. // it's catched on way.
  8368. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8369. Result = DRAGDROP_S_CANCEL;
  8370. ShowExtendedException(Terminal, &E);
  8371. }
  8372. }
  8373. }
  8374. //---------------------------------------------------------------------------
  8375. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8376. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8377. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8378. {
  8379. TFileMasks::TParams MaskParams;
  8380. MaskParams.Size = Size;
  8381. MaskParams.Modification = Modification;
  8382. // this does not re-parse the mask if it is the same as the last time
  8383. FDirViewMatchMask = Masks;
  8384. bool ImplicitMatch;
  8385. Matches =
  8386. // Local and RecurseInclude parameters have no effect as there's no path.
  8387. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8388. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8389. (AllowImplicitMatches || !ImplicitMatch);
  8390. }
  8391. //---------------------------------------------------------------------------
  8392. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8393. TObject * Sender, TListItem * Item, WORD & Indexes)
  8394. {
  8395. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8396. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8397. {
  8398. Indexes |= oiPartial;
  8399. }
  8400. }
  8401. //---------------------------------------------------------------------------
  8402. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8403. {
  8404. return
  8405. DirViewEnabled(osCurrent) &&
  8406. DirView(osCurrent)->CanPasteFromClipBoard();
  8407. }
  8408. //---------------------------------------------------------------------------
  8409. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8410. {
  8411. bool Result = false;
  8412. if (CanPasteToDirViewFromClipBoard())
  8413. {
  8414. Result = true;
  8415. }
  8416. else
  8417. {
  8418. UnicodeString ClipboardText;
  8419. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8420. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8421. {
  8422. if (StoredSessions->IsUrl(ClipboardText))
  8423. {
  8424. Result = true;
  8425. }
  8426. else
  8427. {
  8428. Result = DirViewEnabled(osCurrent);
  8429. }
  8430. }
  8431. }
  8432. return Result;
  8433. }
  8434. //---------------------------------------------------------------------------
  8435. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8436. {
  8437. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8438. if (DoesClipboardContainOurFiles())
  8439. {
  8440. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8441. {
  8442. DebugAssert(!IsLocalBrowserMode());
  8443. TTerminalManager * Manager = TTerminalManager::Instance();
  8444. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8445. Manager->ActiveSession = FClipboardTerminal;
  8446. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8447. }
  8448. }
  8449. else if (CanPasteToDirViewFromClipBoard())
  8450. {
  8451. DirView(osCurrent)->PasteFromClipBoard();
  8452. }
  8453. else
  8454. {
  8455. UnicodeString ClipboardText;
  8456. if (NonEmptyTextFromClipboard(ClipboardText))
  8457. {
  8458. if (StoredSessions->IsUrl(ClipboardText))
  8459. {
  8460. NewSession(ClipboardText);
  8461. }
  8462. else
  8463. {
  8464. DirView(osCurrent)->Path = ClipboardText;
  8465. }
  8466. }
  8467. }
  8468. }
  8469. //---------------------------------------------------------------------------
  8470. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8471. {
  8472. // TBD
  8473. }
  8474. //---------------------------------------------------------------------------
  8475. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8476. {
  8477. TCustomDirView * ADirView = DirView(Side);
  8478. ADirView->SelectAll(Mode);
  8479. ADirView->SetFocus();
  8480. }
  8481. //---------------------------------------------------------------------------
  8482. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8483. {
  8484. TCustomDirView * ADirView = DirView(Side);
  8485. TFileFilter Filter;
  8486. DefaultFileFilter(Filter);
  8487. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8488. {
  8489. Configuration->Usage->Inc(L"MaskSelections");
  8490. ADirView->SelectFiles(Filter, Select);
  8491. ADirView->SetFocus();
  8492. }
  8493. }
  8494. //---------------------------------------------------------------------------
  8495. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8496. {
  8497. TCustomDirView * ADirView = DirView(Side);
  8498. ADirView->RestoreSelectedNames();
  8499. ADirView->SetFocus();
  8500. }
  8501. //---------------------------------------------------------------------------
  8502. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8503. {
  8504. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8505. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8506. {
  8507. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8508. UnicodeString Ext;
  8509. if (!IsSideLocalBrowser(osCurrent))
  8510. {
  8511. Ext = UnixExtractFileExt(FileName);
  8512. }
  8513. else
  8514. {
  8515. Ext = ExtractFileExt(FileName);
  8516. }
  8517. if (Ext.IsEmpty())
  8518. {
  8519. Ext = L".";
  8520. }
  8521. TFileFilter Filter;
  8522. Filter.Masks = FORMAT(L"*%s", (Ext));
  8523. Filter.Directories = false;
  8524. CurrentDirView->SelectFiles(Filter, Select);
  8525. }
  8526. }
  8527. //---------------------------------------------------------------------------
  8528. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8529. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8530. {
  8531. UnicodeString Result;
  8532. if (!FIncrementalSearch.IsEmpty() && (Side == GetSide(osCurrent)))
  8533. {
  8534. Result = FormatIncrementalSearchStatus(FIncrementalSearch, FIncrementalSearchHaveNext);
  8535. }
  8536. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8537. {
  8538. // noop
  8539. }
  8540. else
  8541. {
  8542. Result =
  8543. FMTLOAD(FILE_INFO_FORMAT,
  8544. (FormatBytes(FileInfo.SelectedSize),
  8545. FormatBytes(FileInfo.FilesSize),
  8546. FormatNumber(FileInfo.SelectedCount),
  8547. FormatNumber(FileInfo.FilesCount)));
  8548. }
  8549. return Result;
  8550. }
  8551. //---------------------------------------------------------------------------
  8552. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8553. TTBXStatusPanel * Panel, TOperationSide Side)
  8554. {
  8555. if (Panel->Index == 1)
  8556. {
  8557. ToggleShowHiddenFiles();
  8558. }
  8559. else if (Panel->Index == 2)
  8560. {
  8561. Filter(Side);
  8562. }
  8563. }
  8564. //---------------------------------------------------------------------------
  8565. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8566. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8567. {
  8568. DebugAssert(!StatusBar->SimplePanel);
  8569. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8570. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8571. }
  8572. //---------------------------------------------------------------------------
  8573. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8574. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8575. {
  8576. DebugAssert(StatusBar->Panels->Count >= 3);
  8577. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8578. if (FileInfo.HiddenCount > 0)
  8579. {
  8580. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8581. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8582. }
  8583. else
  8584. {
  8585. HiddenFilesPanel->ViewPriority = 0;
  8586. // not really necessary, just to cleanup no-longer-valid data
  8587. HiddenFilesPanel->Caption = L"";
  8588. }
  8589. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8590. if (FileInfo.FilteredCount > 0)
  8591. {
  8592. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8593. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8594. }
  8595. else
  8596. {
  8597. FilteredFilesPanel->ViewPriority = 0;
  8598. // not really necessary, just to cleanup no-longer-valid data
  8599. FilteredFilesPanel->Caption = L"";
  8600. }
  8601. }
  8602. //---------------------------------------------------------------------------
  8603. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8604. TObject * /*Sender*/)
  8605. {
  8606. if (DirView(osOther)->Enabled)
  8607. {
  8608. DirView(osOther)->SetFocus();
  8609. }
  8610. }
  8611. //---------------------------------------------------------------------------
  8612. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8613. {
  8614. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8615. switch (Config.Show)
  8616. {
  8617. case qvShow:
  8618. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8619. {
  8620. Config.Show = qvHide;
  8621. }
  8622. else
  8623. {
  8624. Config.Show = Config.LastHideShow;
  8625. }
  8626. break;
  8627. case qvHideWhenEmpty:
  8628. if (ComponentVisible[fcQueueView])
  8629. {
  8630. Config.Show = qvHide;
  8631. }
  8632. else
  8633. {
  8634. Config.LastHideShow = Config.Show;
  8635. Config.Show = qvShow;
  8636. }
  8637. break;
  8638. case qvHide:
  8639. Config.LastHideShow = Config.Show;
  8640. Config.Show = qvShow;
  8641. break;
  8642. }
  8643. WinConfiguration->QueueView = Config;
  8644. }
  8645. //---------------------------------------------------------------------------
  8646. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8647. {
  8648. UnicodeString Result;
  8649. if (Terminal != NULL)
  8650. {
  8651. switch (WinConfiguration->PathInCaption)
  8652. {
  8653. case picShort:
  8654. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8655. break;
  8656. case picFull:
  8657. Result = Terminal->CurrentDirectory;
  8658. break;
  8659. }
  8660. }
  8661. return Result;
  8662. }
  8663. //---------------------------------------------------------------------------
  8664. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8665. {
  8666. TColor Result = GetWindowColor(FSessionColor);
  8667. return Result;
  8668. }
  8669. //---------------------------------------------------------------------------
  8670. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8671. {
  8672. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8673. return Result;
  8674. }
  8675. //---------------------------------------------------------------------------
  8676. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8677. {
  8678. if (!FSessionChanging)
  8679. {
  8680. TTerminalManager::Instance()->UpdateAppTitle();
  8681. }
  8682. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8683. // background to gray on Windows 7 (works on Windows 10).
  8684. // See also EnableControl
  8685. if (Showing)
  8686. {
  8687. if (ManagedSession != NULL)
  8688. {
  8689. // Update path when it changes
  8690. if ((SessionsPageControl->ActivePage != NULL) &&
  8691. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8692. {
  8693. UpdateSessionTab(SessionsPageControl->ActivePage);
  8694. }
  8695. }
  8696. NonVisualDataModule->ReconnectSessionAction->Update();
  8697. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8698. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8699. CenterReconnectToolbar();
  8700. bool HasTerminal = HasActiveTerminal();
  8701. RemoteDirView->Enabled = HasTerminal;
  8702. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8703. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8704. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8705. RemoteDriveView->Color = RemoteDirView->Color;
  8706. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8707. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8708. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8709. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8710. QueueFileList->Enabled = QueueView3->Enabled;
  8711. QueueFileList->Color = QueueView3->Color;
  8712. QueueFileList->Font->Color = QueueView3->Font->Color;
  8713. QueueLabelUpdateStatus();
  8714. RemoteDirView->DarkMode = WinConfiguration->UseDarkTheme();
  8715. RemoteDriveView->DarkMode = RemoteDirView->DarkMode;
  8716. if (FImmersiveDarkMode != WinConfiguration->UseDarkTheme())
  8717. {
  8718. UpdateDarkMode();
  8719. }
  8720. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8721. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8722. }
  8723. }
  8724. //---------------------------------------------------------------------------
  8725. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8726. {
  8727. UpdateControls();
  8728. }
  8729. //---------------------------------------------------------------------------
  8730. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8731. TObject * Sender)
  8732. {
  8733. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8734. DebugAssert(DirView != NULL);
  8735. DoDirViewLoaded(DirView);
  8736. TransferPresetAutoSelect();
  8737. }
  8738. //---------------------------------------------------------------------------
  8739. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8740. {
  8741. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8742. // first run after installation
  8743. if (double(Updates.LastCheck) == 0)
  8744. {
  8745. AppLog(L"First run, scheduling updates check for the next run");
  8746. // make sure next time there will be an update (if enabled)
  8747. Updates.LastCheck = TDateTime(1);
  8748. WinConfiguration->Updates = Updates;
  8749. }
  8750. else
  8751. {
  8752. TDateTime Period;
  8753. if (IsUWP() && !IsOfficialPackage())
  8754. {
  8755. Period = DefaultUpdatesPeriod;
  8756. AppLog(L"Thirdparty UWP package, using default updates check period");
  8757. }
  8758. else
  8759. {
  8760. Period = Updates.Period;
  8761. }
  8762. AppLogFmt(L"Updates check period: %.2f", (double(Period)));
  8763. if (double(Period) > 0)
  8764. {
  8765. TDateTime Interval = Now() - Updates.LastCheck;
  8766. AppLogFmt(L"Interval since the last updates check: %.2f", (double(Interval)));
  8767. if (Interval >= Period)
  8768. {
  8769. StartUpdateThread(UpdatesChecked);
  8770. }
  8771. }
  8772. }
  8773. }
  8774. //---------------------------------------------------------------------------
  8775. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8776. {
  8777. AppLog(L"Updates check done");
  8778. UnicodeString Message;
  8779. bool New;
  8780. TQueryType Type;
  8781. GetUpdatesMessage(Message, New, Type, false);
  8782. if (!Message.IsEmpty())
  8783. {
  8784. AppLogFmt(L"Updates check message: %s", (Message));
  8785. if (New)
  8786. {
  8787. AppLog(L"New version detected");
  8788. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8789. }
  8790. if (!New && (Type != qtWarning))
  8791. {
  8792. AppLog(L"Posting non-critical updates note");
  8793. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  8794. }
  8795. else
  8796. {
  8797. AppLog(L"Posting new version or critical message notification");
  8798. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8799. }
  8800. if (New)
  8801. {
  8802. Configuration->Usage->Inc(L"UpdateNotifications");
  8803. }
  8804. }
  8805. }
  8806. //---------------------------------------------------------------------------
  8807. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8808. {
  8809. RestoreApp();
  8810. bool CanDisplay = !NonVisualDataModule->Busy;
  8811. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8812. {
  8813. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8814. }
  8815. if (CanDisplay)
  8816. {
  8817. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8818. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  8819. NonVisualDataModule->StartBusy();
  8820. try
  8821. {
  8822. CheckForUpdates(true);
  8823. }
  8824. __finally
  8825. {
  8826. NonVisualDataModule->EndBusy();
  8827. }
  8828. }
  8829. else
  8830. {
  8831. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  8832. }
  8833. }
  8834. //---------------------------------------------------------------------------
  8835. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  8836. TCopyParamRuleData & Data)
  8837. {
  8838. DebugAssert(Terminal != NULL);
  8839. Data.HostName = Terminal->SessionData->HostNameExpanded;
  8840. Data.UserName = Terminal->SessionData->UserNameExpanded;
  8841. Data.RemoteDirectory = RemoteDirView->PathName;
  8842. }
  8843. //---------------------------------------------------------------------------
  8844. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  8845. {
  8846. // Terminal can be null when we are changing local directory implicitly,
  8847. // because it has been deleted, while no session is connected
  8848. // (Login dialog is open)
  8849. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  8850. {
  8851. DebugAssert(!IsLocalBrowserMode());
  8852. TCopyParamRuleData Data;
  8853. GetTransferPresetAutoSelectData(Data);
  8854. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  8855. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  8856. if (CopyParamIndex < 0)
  8857. {
  8858. // there is no preset that matches autoselection
  8859. // set preset that we consider "default"
  8860. FCopyParamAutoSelected = L""; // forget last autoselected preset
  8861. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  8862. }
  8863. else
  8864. {
  8865. // there is preset matching autoselection
  8866. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  8867. if (CopyParamName == FCopyParamAutoSelected)
  8868. {
  8869. // autoselected the same preset as the last time
  8870. // make no change (i.e. preserve custom user preset, if any)
  8871. }
  8872. else
  8873. {
  8874. // autoselected the different preset then the last time (or there
  8875. // was default preset set)
  8876. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  8877. GUIConfiguration->CopyParamCurrent = CopyParamName;
  8878. }
  8879. }
  8880. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  8881. {
  8882. if (CopyParamIndex >= 0)
  8883. {
  8884. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  8885. }
  8886. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  8887. try
  8888. {
  8889. int Fmt =
  8890. (CopyParamIndex < 0) ?
  8891. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8892. COPY_PARAM_AUTOSELECTED;
  8893. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  8894. Data->Message = MainInstructions(Message);
  8895. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  8896. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  8897. CopyParamAttrs);
  8898. if (CopyParamIndex >= 0)
  8899. {
  8900. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  8901. Info = FORMAT(L"%s\n \n%s", (Info,
  8902. FMTLOAD(COPY_PARAM_RULE,
  8903. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  8904. }
  8905. Data->Message += L"\n\n" + Info;
  8906. if (WinConfiguration->CopyParamAutoSelectNotice)
  8907. {
  8908. TransferPresetNoteMessage(Data, true);
  8909. }
  8910. else
  8911. {
  8912. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  8913. Data = NULL; // ownership passed
  8914. }
  8915. }
  8916. __finally
  8917. {
  8918. delete Data;
  8919. }
  8920. }
  8921. }
  8922. }
  8923. //---------------------------------------------------------------------------
  8924. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  8925. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  8926. {
  8927. DebugAssert(NoteData != NULL);
  8928. DebugAssert(!IsLocalBrowserMode());
  8929. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  8930. TQueryButtonAlias Aliases[1];
  8931. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  8932. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  8933. Params.Aliases = Aliases;
  8934. Params.AliasesCount = LENOF(Aliases);
  8935. unsigned int Result =
  8936. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  8937. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  8938. switch (Result)
  8939. {
  8940. case qaNeverAskAgain:
  8941. DebugAssert(AllowNeverAskAgain);
  8942. WinConfiguration->CopyParamAutoSelectNotice = false;
  8943. break;
  8944. case qaIgnore:
  8945. PreferencesDialog(pmPresets);
  8946. break;
  8947. }
  8948. }
  8949. //---------------------------------------------------------------------------
  8950. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  8951. {
  8952. // as of now useless, as this is used for notes only, never for balloons, ...
  8953. RestoreApp();
  8954. // .. and we should never be busy here
  8955. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  8956. {
  8957. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  8958. }
  8959. }
  8960. //---------------------------------------------------------------------------
  8961. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  8962. TPreferencesMode APreferencesMode)
  8963. {
  8964. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  8965. TCopyParamRuleData Data;
  8966. if (Terminal != NULL)
  8967. {
  8968. PreferencesData.reset(new TPreferencesDialogData());
  8969. GetTransferPresetAutoSelectData(Data);
  8970. PreferencesData->CopyParamRuleData = &Data;
  8971. }
  8972. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  8973. }
  8974. //---------------------------------------------------------------------------
  8975. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  8976. const TCustomCommandType & Command)
  8977. {
  8978. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  8979. {
  8980. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  8981. }
  8982. }
  8983. //---------------------------------------------------------------------------
  8984. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  8985. {
  8986. bool RemoteAllowed = CustomCommandRemoteAllowed();
  8987. TCustomCommandType Command;
  8988. // make sure we use local custom command when remote are not supported
  8989. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  8990. {
  8991. Command = FLastCustomCommand;
  8992. }
  8993. else
  8994. {
  8995. Command.Params = Command.Params | ccLocal;
  8996. }
  8997. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  8998. FEditingFocusedAdHocCommand = OnFocused;
  8999. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9000. int Options =
  9001. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9002. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9003. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9004. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9005. {
  9006. FLastCustomCommand = Command;
  9007. UpdateCustomCommandsToolbar();
  9008. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9009. }
  9010. }
  9011. //---------------------------------------------------------------------------
  9012. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9013. {
  9014. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9015. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9016. DebugAssert(State > 0);
  9017. if (State <= 0)
  9018. {
  9019. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9020. }
  9021. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9022. }
  9023. //---------------------------------------------------------------------------
  9024. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9025. TCustomCommandType & Command, int & State)
  9026. {
  9027. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9028. if (Result)
  9029. {
  9030. Command = FLastCustomCommand;
  9031. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9032. }
  9033. return Result;
  9034. }
  9035. //---------------------------------------------------------------------------
  9036. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9037. {
  9038. ResetIncrementalSearch();
  9039. }
  9040. //---------------------------------------------------------------------------
  9041. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9042. {
  9043. DebugAssert(ComponentVisible[Component]);
  9044. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9045. }
  9046. //---------------------------------------------------------------------------
  9047. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9048. {
  9049. // when queue panel is resized here directly, the status bar is stretched
  9050. // over whole space the panel occupied
  9051. PostComponentHide(fcQueueView);
  9052. }
  9053. //---------------------------------------------------------------------------
  9054. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9055. {
  9056. ComponentVisible[fcQueueFileList] = false;
  9057. }
  9058. //---------------------------------------------------------------------------
  9059. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9060. {
  9061. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9062. RefreshColorMode();
  9063. ResetSysDarkTheme();
  9064. ConfigurationChanged();
  9065. ConfigureInterface();
  9066. // Should be called for all controls
  9067. RemoteDirView->Perform(WM_THEMECHANGED, 0, 0);
  9068. }
  9069. //---------------------------------------------------------------------------
  9070. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9071. {
  9072. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9073. if (!FInvalid &&
  9074. (Message.LParam != 0) &&
  9075. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9076. {
  9077. ThemeChanged();
  9078. }
  9079. TForm::Dispatch(&Message);
  9080. }
  9081. //---------------------------------------------------------------------------
  9082. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9083. {
  9084. TMessage * M = static_cast<TMessage*>(Message);
  9085. switch (M->Msg)
  9086. {
  9087. case CM_DIALOGCHAR:
  9088. CMDialogChar(*M);
  9089. break;
  9090. case WM_APPCOMMAND:
  9091. WMAppCommand(*M);
  9092. break;
  9093. case WM_SYSCOMMAND:
  9094. WMSysCommand(*M);
  9095. break;
  9096. case WM_QUERYENDSESSION:
  9097. WMQueryEndSession(*M);
  9098. break;
  9099. case WM_ENDSESSION:
  9100. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9101. break;
  9102. #ifdef _DEBUG
  9103. case WM_WINDOWPOSCHANGED:
  9104. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  9105. break;
  9106. case CM_CUSTOMSTYLECHANGED:
  9107. TForm::Dispatch(Message);
  9108. break;
  9109. #endif
  9110. case WM_COMPONENT_HIDE:
  9111. {
  9112. Byte Component = static_cast<Byte>(M->WParam);
  9113. // sanity check
  9114. if (ComponentVisible[Component])
  9115. {
  9116. // special treatment
  9117. if (Component == fcQueueView)
  9118. {
  9119. ToggleQueueVisibility();
  9120. DebugAssert(!ComponentVisible[fcQueueView]);
  9121. }
  9122. else
  9123. {
  9124. ComponentVisible[Component] = false;
  9125. }
  9126. }
  9127. }
  9128. break;
  9129. case WM_COPYDATA:
  9130. WMCopyData(*M);
  9131. break;
  9132. case WM_MANAGES_CAPTION:
  9133. // caption managed in TTerminalManager::UpdateAppTitle()
  9134. M->Result = 1;
  9135. break;
  9136. case WM_WANTS_MOUSEWHEEL:
  9137. M->Result = 1;
  9138. break;
  9139. case CM_SHOWINGCHANGED:
  9140. CMShowingChanged(*M);
  9141. break;
  9142. case WM_CLOSE:
  9143. WMClose(*M);
  9144. break;
  9145. case WM_DPICHANGED:
  9146. WMDpiChanged(*M);
  9147. break;
  9148. case CM_DPICHANGED:
  9149. CMDpiChanged(*M);
  9150. break;
  9151. case WM_SETTINGCHANGE:
  9152. WMSettingChange(*M);
  9153. break;
  9154. case CM_DIALOGKEY:
  9155. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9156. break;
  9157. case WM_PASTE_FILES:
  9158. PasteFiles();
  9159. break;
  9160. case WM_IS_HIDDEN:
  9161. // To treat master password prompt as a main window while showing it when workspace is loading while
  9162. // the exporer is showing up (Visible is true already)
  9163. M->Result = !FShowing;
  9164. break;
  9165. case WM_SHOWWINDOW:
  9166. if (M->WParam)
  9167. {
  9168. AddStartupSequence(L"J");
  9169. }
  9170. TForm::Dispatch(Message);
  9171. break;
  9172. default:
  9173. TForm::Dispatch(Message);
  9174. break;
  9175. }
  9176. }
  9177. //---------------------------------------------------------------------------
  9178. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9179. {
  9180. // noop
  9181. }
  9182. //---------------------------------------------------------------------------
  9183. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  9184. {
  9185. TForm::Dispatch(&Message);
  9186. FSessionColors->Clear();
  9187. AddFixedSessionImages();
  9188. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9189. UpdateImages();
  9190. }
  9191. //---------------------------------------------------------------------------
  9192. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9193. {
  9194. TForm::Dispatch(&Message);
  9195. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9196. UpdatePixelsPerInchMainWindowCounter();
  9197. }
  9198. //---------------------------------------------------------------------------
  9199. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9200. {
  9201. AppLog(L"Main window WM_CLOSE");
  9202. // Cannot close window while we are busy.
  9203. // We cannot test this in FormCloseQuery as that is called also from
  9204. // Close(), which is called by CloseApplicationAction. So we can be busy
  9205. // there already even, when it is legitimate to close the application.
  9206. // Possibly a better place to handle this would be WMSysCommand.
  9207. if (NonVisualDataModule->Busy)
  9208. {
  9209. Message.Result = 1;
  9210. }
  9211. else
  9212. {
  9213. TForm::Dispatch(&Message);
  9214. }
  9215. }
  9216. //---------------------------------------------------------------------------
  9217. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9218. {
  9219. if (!FShowingChanged)
  9220. {
  9221. AddStartupSequence(L"D");
  9222. FShowingChanged = true;
  9223. }
  9224. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9225. bool NoSession = (ManagedSession == NULL);
  9226. // This calls TCustomScpExplorerForm::DoShow
  9227. TForm::Dispatch(&Message);
  9228. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9229. if (Showing && !FStarted)
  9230. {
  9231. FStarted = true;
  9232. InterfaceStarted();
  9233. }
  9234. if (Showing && NoSession)
  9235. {
  9236. // When we are starting minimized (i.e. from an installer),
  9237. // postpone showing Login dialog until we get restored.
  9238. // Otherwise the Login dialog (and Authentication window) show restored
  9239. // over invisible (minimized) main window.
  9240. if (WindowState == wsMinimized)
  9241. {
  9242. FNeedSession = true;
  9243. }
  9244. else
  9245. {
  9246. // This happens before application ever goes idle, so the toolbars would
  9247. // stay enabled (initial state) until the Login dialog is dismissed.
  9248. UpdateActions();
  9249. NonVisualDataModule->StartBusy();
  9250. try
  9251. {
  9252. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9253. // otherwise the dialog does not receive focus.
  9254. // With Commander interface the ProcessMessages is called already
  9255. // by TDriveView, but with Explorer interface, we need to call it explicily
  9256. Application->ProcessMessages();
  9257. // do not reload sessions, they have been loaded just now (optimization)
  9258. NeedSession(true);
  9259. }
  9260. __finally
  9261. {
  9262. NonVisualDataModule->EndBusy();
  9263. }
  9264. }
  9265. }
  9266. }
  9267. //---------------------------------------------------------------------------
  9268. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9269. {
  9270. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9271. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9272. }
  9273. //---------------------------------------------------------------------------
  9274. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9275. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9276. int & MaxHeight)
  9277. {
  9278. // workaround for bug in TWinControl.CalcConstraints
  9279. // Check for empty rect (restore from iconic state) is done there only after
  9280. // call to AdjustClientRect, which enlarges the rect (for forms).
  9281. TRect R = GetClientRect();
  9282. // when restoring from iconic state, place no restrictions
  9283. if (IsRectEmpty(R))
  9284. {
  9285. MinWidth = 0;
  9286. MinHeight = 0;
  9287. MaxWidth = 32000;
  9288. MaxHeight = 32000;
  9289. }
  9290. }
  9291. //---------------------------------------------------------------------------
  9292. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9293. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9294. {
  9295. // terminal can be already closed (e.g. dropped connection)
  9296. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9297. {
  9298. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9299. try
  9300. {
  9301. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9302. }
  9303. catch(...)
  9304. {
  9305. if (!Terminal->Active)
  9306. {
  9307. Close = true;
  9308. }
  9309. throw;
  9310. }
  9311. }
  9312. }
  9313. //---------------------------------------------------------------------------
  9314. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9315. {
  9316. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9317. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9318. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9319. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9320. {
  9321. OnGetSpaceAvailable = GetSpaceAvailable;
  9322. }
  9323. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9324. OnGetSpaceAvailable);
  9325. }
  9326. //---------------------------------------------------------------------------
  9327. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9328. {
  9329. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9330. Terminal->FillSessionDataForCode(Data.get());
  9331. return Data.release();
  9332. }
  9333. //---------------------------------------------------------------------------
  9334. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9335. {
  9336. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9337. DoGenerateUrlDialog(Data.get(), Paths);
  9338. }
  9339. //---------------------------------------------------------------------------
  9340. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9341. {
  9342. GenerateUrl(NULL);
  9343. }
  9344. //---------------------------------------------------------------------------
  9345. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9346. {
  9347. std::unique_ptr<TStrings> Paths(new TStringList());
  9348. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9349. GenerateUrl(Paths.get());
  9350. }
  9351. //---------------------------------------------------------------------------
  9352. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9353. {
  9354. FSessionColor = value;
  9355. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9356. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9357. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9358. DebugAssert(ColorItem != NULL);
  9359. ColorItem->Color = C;
  9360. NonVisualDataModule->ColorMenuItem->Color = C;
  9361. UpdateControls();
  9362. }
  9363. //---------------------------------------------------------------------------
  9364. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9365. {
  9366. if (value != FSessionColor)
  9367. {
  9368. UpdateSessionColor(value);
  9369. // Is null when called from LastTerminalClosed
  9370. if (Terminal != NULL)
  9371. {
  9372. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9373. }
  9374. }
  9375. }
  9376. //---------------------------------------------------------------------------
  9377. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9378. {
  9379. bool Result = FNoteTimer->Enabled;
  9380. if (Result)
  9381. {
  9382. // cannot cancel note too early
  9383. bool NotEarly =
  9384. (Now() - FNoteShown >
  9385. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9386. if (Force || NotEarly)
  9387. {
  9388. FNoteTimer->Enabled = false;
  9389. FNote = L"";
  9390. SAFE_DESTROY(FNoteData);
  9391. FOnNoteClick = NULL;
  9392. FNoteHints = FNotes->Text;
  9393. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9394. UpdateStatusBar();
  9395. }
  9396. }
  9397. return Result;
  9398. }
  9399. //---------------------------------------------------------------------------
  9400. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9401. {
  9402. DebugAssert(FNoteTimer->Enabled);
  9403. CancelNote(true);
  9404. }
  9405. //---------------------------------------------------------------------------
  9406. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9407. {
  9408. FNoteHints = FNotes->Text.TrimRight();
  9409. }
  9410. //---------------------------------------------------------------------------
  9411. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9412. {
  9413. int P = Note.Pos(L"\n");
  9414. if (P > 0)
  9415. {
  9416. Note.SetLength(P - 1);
  9417. }
  9418. FNotes->Add(FORMAT(L"[%s] %s",
  9419. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9420. while (FNotes->Count > 10)
  9421. {
  9422. FNotes->Delete(0);
  9423. }
  9424. if (UpdateNow)
  9425. {
  9426. UpdateNoteHints();
  9427. UpdateStatusBar();
  9428. }
  9429. }
  9430. //---------------------------------------------------------------------------
  9431. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  9432. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9433. {
  9434. int P = Note.Pos(L"\n");
  9435. if (P > 0)
  9436. {
  9437. Note.SetLength(P - 1);
  9438. }
  9439. UpdateNoteHints();
  9440. FNote = Note;
  9441. SAFE_DESTROY(FNoteData);
  9442. FNoteData = NoteData;
  9443. FOnNoteClick = OnNoteClick;
  9444. AddNote(Note, false);
  9445. UpdateStatusBar();
  9446. FNoteShown = Now();
  9447. FNoteTimer->Enabled = false;
  9448. if (Seconds == 0)
  9449. {
  9450. Seconds = WinConfiguration->NotificationsTimeout;
  9451. }
  9452. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9453. FNoteTimer->Enabled = true;
  9454. }
  9455. //---------------------------------------------------------------------------
  9456. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9457. {
  9458. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  9459. }
  9460. //---------------------------------------------------------------------------
  9461. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9462. {
  9463. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9464. {
  9465. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9466. }
  9467. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9468. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9469. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))),
  9470. 0, NULL, NULL);
  9471. }
  9472. //---------------------------------------------------------------------------
  9473. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9474. {
  9475. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9476. UnicodeString Note =
  9477. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9478. PostNote(Note, 0, NULL, NULL);
  9479. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9480. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9481. }
  9482. //---------------------------------------------------------------------------
  9483. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9484. {
  9485. WinConfiguration->FormatSizeBytes = Style;
  9486. }
  9487. //---------------------------------------------------------------------------
  9488. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9489. {
  9490. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9491. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9492. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9493. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  9494. }
  9495. //---------------------------------------------------------------------------
  9496. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9497. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9498. {
  9499. if (Panel->Index == 0)
  9500. {
  9501. if (FOnNoteClick != NULL)
  9502. {
  9503. // prevent the user data from being freed by possible call
  9504. // to CancelNote or PostNote during call to OnNoteClick
  9505. std::unique_ptr<TObject> NoteData(FNoteData);
  9506. TNotifyEvent OnNoteClick = FOnNoteClick;
  9507. FNoteData = NULL;
  9508. // need to cancel the note as we are going to delete its user data
  9509. CancelNote(true);
  9510. OnNoteClick(NoteData.get());
  9511. }
  9512. }
  9513. if (HasActiveTerminal() &&
  9514. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9515. {
  9516. FileSystemInfo();
  9517. }
  9518. }
  9519. //---------------------------------------------------------------------------
  9520. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9521. {
  9522. // workaround:
  9523. // 1) for unknown reason, disabling window, while minimized,
  9524. // prevents it from restoring, even if it was enabled again meanwhile
  9525. // 2) when disabling the main window, while another has focus
  9526. // minimize is no longer possible
  9527. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9528. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9529. // Shouldn't we use IsApplicationMinimized() here?
  9530. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9531. {
  9532. Enabled = false;
  9533. }
  9534. FLockLevel++;
  9535. }
  9536. //---------------------------------------------------------------------------
  9537. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9538. {
  9539. DebugAssert(FLockLevel > 0);
  9540. FLockLevel--;
  9541. if (FLockLevel == 0)
  9542. {
  9543. DebugAssert(FLockSuspendLevel == 0);
  9544. Enabled = true;
  9545. }
  9546. }
  9547. //---------------------------------------------------------------------------
  9548. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9549. {
  9550. // We need to make sure that window is enabled when the last modal window closes
  9551. // otherwise focus is not restored correctly.
  9552. // So we re-enable the window when modal window opens and
  9553. // disable it back after is closes
  9554. if (FLockLevel > 0)
  9555. {
  9556. // while we have nesting counter, we know that we never be called
  9557. // recursivelly as Application->OnModalBegin is called only
  9558. // for the top-level modal window
  9559. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9560. {
  9561. // won't be disabled when conditions in LockWindow() were not satisfied
  9562. FDisabledOnLockSuspend = !Enabled;
  9563. // When minimized to tray (or actually when set to SW_HIDE),
  9564. // setting Enabled makes the window focusable even when there's
  9565. // modal window over it
  9566. if (!FTrayIcon->Visible)
  9567. {
  9568. Enabled = true;
  9569. }
  9570. }
  9571. FLockSuspendLevel++;
  9572. }
  9573. }
  9574. //---------------------------------------------------------------------------
  9575. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9576. {
  9577. if (FLockSuspendLevel > 0)
  9578. {
  9579. DebugAssert(FLockLevel > 0);
  9580. FLockSuspendLevel--;
  9581. // see comment in SuspendWindowLock
  9582. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9583. {
  9584. // Note that window can be enabled here, when we were minized to tray when
  9585. // was SuspendWindowLock() called.
  9586. // We should possibly do the same check as in LockWindow(),
  9587. // if it is ever possible that the consitions change between
  9588. // SuspendWindowLock() and ResumeWindowLock()
  9589. Enabled = !FDisabledOnLockSuspend;
  9590. }
  9591. }
  9592. }
  9593. //---------------------------------------------------------------------------
  9594. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9595. {
  9596. TTBXComboBoxItem * RemotePathComboBox =
  9597. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9598. if (!TextOnly)
  9599. {
  9600. TStrings * Items = RemotePathComboBox->Strings;
  9601. Items->BeginUpdate();
  9602. try
  9603. {
  9604. Items->Clear();
  9605. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9606. {
  9607. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9608. while (!IsUnixRootPath(APath))
  9609. {
  9610. int P = APath.LastDelimiter(L'/');
  9611. DebugAssert(P >= 0);
  9612. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9613. APath.SetLength(P - 1);
  9614. }
  9615. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9616. }
  9617. }
  9618. __finally
  9619. {
  9620. Items->EndUpdate();
  9621. }
  9622. }
  9623. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9624. // Setting ItemIndex to -1 does not reset its text
  9625. if (RemotePathComboBox->Strings->Count == 0)
  9626. {
  9627. RemotePathComboBox->Text = L"";
  9628. }
  9629. }
  9630. //---------------------------------------------------------------------------
  9631. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9632. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9633. {
  9634. if (AIndex < 0)
  9635. {
  9636. AIndex = Sender->ItemIndex;
  9637. }
  9638. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9639. }
  9640. //---------------------------------------------------------------------------
  9641. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9642. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9643. int & ImageIndex)
  9644. {
  9645. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9646. }
  9647. //---------------------------------------------------------------------------
  9648. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9649. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9650. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9651. {
  9652. if (!IsLocalBrowserMode())
  9653. {
  9654. ARect.Left += (10 * AIndex);
  9655. }
  9656. }
  9657. //---------------------------------------------------------------------------
  9658. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9659. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9660. {
  9661. AWidth += (10 * AIndex);
  9662. }
  9663. //---------------------------------------------------------------------------
  9664. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9665. {
  9666. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9667. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9668. int Index = RemotePathComboBox->ItemIndex;
  9669. while (Index < RemotePathComboBox->Strings->Count - 1)
  9670. {
  9671. APath = UnixExtractFileDir(APath);
  9672. Index++;
  9673. }
  9674. // VanDyke style paths
  9675. if (APath.IsEmpty())
  9676. {
  9677. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9678. APath = ROOTDIRECTORY;
  9679. }
  9680. if (RemoteDirView->Path != APath)
  9681. {
  9682. RemoteDirView->Path = APath;
  9683. }
  9684. }
  9685. //---------------------------------------------------------------------------
  9686. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9687. {
  9688. DoRemotePathComboBoxItemClick(Sender);
  9689. }
  9690. //---------------------------------------------------------------------------
  9691. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9692. {
  9693. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9694. DebugUsedParam(Sender);
  9695. UpdateRemotePathComboBox(true);
  9696. }
  9697. //---------------------------------------------------------------------------
  9698. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9699. {
  9700. DoRemotePathComboBoxCancel(Sender);
  9701. }
  9702. //---------------------------------------------------------------------------
  9703. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9704. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9705. {
  9706. ResetIncrementalSearch();
  9707. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9708. DebugAssert(DirView != NULL);
  9709. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9710. {
  9711. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9712. // OnEditing is called also from TCustomListView::CanEdit
  9713. if (Edit != NULL)
  9714. {
  9715. EditSelectBaseName(Edit);
  9716. }
  9717. }
  9718. }
  9719. //---------------------------------------------------------------------------
  9720. //---------------------------------------------------------------------------
  9721. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9722. {
  9723. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9724. Result->AutoDetectDnD = false;
  9725. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9726. Result->RenderDataOn = rdoEnterAndDropSync;
  9727. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9728. return Result;
  9729. }
  9730. //---------------------------------------------------------------------------
  9731. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9732. {
  9733. if (IsWin10Build(19041))
  9734. {
  9735. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9736. BOOL DarkMode = FImmersiveDarkMode ? TRUE : FALSE;
  9737. const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
  9738. DwmSetWindowAttribute(Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, &DarkMode, sizeof(DarkMode));
  9739. }
  9740. }
  9741. //---------------------------------------------------------------------------
  9742. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9743. {
  9744. TForm::CreateWnd();
  9745. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9746. UpdateDarkMode();
  9747. if (FSessionsDragDropFilesEx == NULL)
  9748. {
  9749. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9750. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9751. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9752. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9753. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9754. }
  9755. if (FQueueDragDropFilesEx == NULL)
  9756. {
  9757. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9758. // No need to set OnDragOver as we do not have any restrictions
  9759. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9760. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9761. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9762. }
  9763. }
  9764. //---------------------------------------------------------------------------
  9765. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9766. {
  9767. TForm::DestroyWnd();
  9768. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9769. FQueueDragDropFilesEx->DragDropControl = NULL;
  9770. }
  9771. //---------------------------------------------------------------------------
  9772. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9773. {
  9774. SideEnter(FCurrentSide);
  9775. FEverShown = true;
  9776. }
  9777. //---------------------------------------------------------------------------
  9778. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9779. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9780. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9781. {
  9782. if (!NonVisualDataModule->Busy)
  9783. {
  9784. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9785. Configuration->Usage->Inc(L"FileFinds");
  9786. LockWindow(true);
  9787. NonVisualDataModule->StartBusy();
  9788. WinConfiguration->LockedInterface = true;
  9789. try
  9790. {
  9791. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9792. }
  9793. __finally
  9794. {
  9795. WinConfiguration->LockedInterface = false;
  9796. NonVisualDataModule->EndBusy();
  9797. UnlockWindow();
  9798. }
  9799. }
  9800. }
  9801. //---------------------------------------------------------------------------
  9802. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9803. {
  9804. if (!NonVisualDataModule->Busy)
  9805. {
  9806. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9807. SetFocus();
  9808. RemoteDirView->Path = UnixExtractFilePath(Path);
  9809. UnicodeString FileName = UnixExtractFileName(Path);
  9810. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9811. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9812. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  9813. if (Item == NULL)
  9814. {
  9815. ReloadDirectory(osRemote);
  9816. Item = RemoteDirView->FindFileItem(FileName);
  9817. }
  9818. if (Item != NULL)
  9819. {
  9820. RemoteDirView->ItemFocused = Item;
  9821. RemoteDirView->ItemFocused->MakeVisible(false);
  9822. RemoteDirView->SetFocus();
  9823. }
  9824. }
  9825. }
  9826. //---------------------------------------------------------------------------
  9827. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  9828. {
  9829. bool Result = !NonVisualDataModule->Busy;
  9830. if (Result)
  9831. {
  9832. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9833. }
  9834. return Result;
  9835. }
  9836. //---------------------------------------------------------------------------
  9837. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  9838. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9839. {
  9840. if (CanOperateOnFoundFiles(ATerminal))
  9841. {
  9842. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  9843. FOnFileOperationFinished = OnFileOperationFinished;
  9844. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  9845. }
  9846. }
  9847. //---------------------------------------------------------------------------
  9848. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  9849. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9850. {
  9851. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  9852. }
  9853. //---------------------------------------------------------------------------
  9854. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  9855. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9856. {
  9857. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  9858. }
  9859. //---------------------------------------------------------------------------
  9860. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  9861. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9862. {
  9863. if (CanOperateOnFoundFiles(ATerminal))
  9864. {
  9865. for (int Index = 0; Index < FileList->Count; Index++)
  9866. {
  9867. UnicodeString FileName = FileList->Strings[Index];
  9868. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  9869. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  9870. OnFileOperationFinished(osRemote, FileName, true);
  9871. }
  9872. }
  9873. }
  9874. //---------------------------------------------------------------------------
  9875. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  9876. {
  9877. FFileFindTerminal = Terminal;
  9878. ShowFileFindDialog(
  9879. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  9880. DoDownloadFoundFiles, DoEditFoundFiles);
  9881. }
  9882. //---------------------------------------------------------------------------
  9883. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  9884. {
  9885. FTaskbarList = TaskbarList;
  9886. }
  9887. //---------------------------------------------------------------------------
  9888. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  9889. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  9890. {
  9891. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9892. if (Index >= 0)
  9893. {
  9894. if (Button == mbLeft)
  9895. {
  9896. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  9897. // If switching tab (switching session) takes long enough for user
  9898. // to actually release the button, "mouse down" is still raised,
  9899. // but we do not get "mouse up" event, so dragging is not cancelled,
  9900. // prevent that by not beginning dragging in the first place.
  9901. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  9902. if (IsKeyPressed(Key))
  9903. {
  9904. // when user clicks the "+", we get mouse down only after the session
  9905. // is closed, when new session tab is already on X:Y, so dragging
  9906. // starts, prevent that
  9907. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  9908. {
  9909. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9910. if (Terminal != NULL)
  9911. {
  9912. SessionsPageControl->BeginDrag(false);
  9913. }
  9914. }
  9915. }
  9916. }
  9917. else if (Button == mbMiddle)
  9918. {
  9919. // ignore middle-click for "New session tab" and the last local-local tab
  9920. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9921. if ((Session != NULL) && CanCloseSession(Session))
  9922. {
  9923. CloseSessionTab(Index);
  9924. }
  9925. }
  9926. }
  9927. }
  9928. //---------------------------------------------------------------------------
  9929. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  9930. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  9931. {
  9932. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9933. // do not allow dropping on the "+" tab
  9934. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9935. if ((TargetTerminal != NULL) &&
  9936. (SessionsPageControl->ActivePage->PageIndex != Index))
  9937. {
  9938. Configuration->Usage->Inc(L"SessionTabMoves");
  9939. // this is almost redundant as we would recreate tabs in SessionListChanged,
  9940. // but we want to actually prevent that to avoid flicker
  9941. SessionsPageControl->ActivePage->PageIndex = Index;
  9942. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  9943. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  9944. }
  9945. }
  9946. //---------------------------------------------------------------------------
  9947. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  9948. TObject * Sender, TObject * Source, int X, int Y,
  9949. TDragState /*State*/, bool & Accept)
  9950. {
  9951. Accept = (Sender == Source);
  9952. if (Accept)
  9953. {
  9954. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9955. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9956. // do not allow dragging to the "+" tab
  9957. Accept = (Terminal != NULL);
  9958. }
  9959. }
  9960. //---------------------------------------------------------------------------
  9961. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  9962. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  9963. {
  9964. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  9965. if (Index < 0)
  9966. {
  9967. Effect = DROPEFFECT_NONE;
  9968. }
  9969. else
  9970. {
  9971. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9972. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  9973. if (!IsActiveTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  9974. {
  9975. Effect = DROPEFFECT_NONE;
  9976. }
  9977. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  9978. {
  9979. Effect = DROPEFFECT_COPY;
  9980. }
  9981. }
  9982. }
  9983. //---------------------------------------------------------------------------
  9984. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  9985. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  9986. {
  9987. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  9988. // do not allow dropping on local-local, disconnected and the "+" tab
  9989. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  9990. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9991. if (DebugAlwaysTrue(IsActiveTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  9992. {
  9993. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  9994. if (!IsFileControl(DropSourceControl, osRemote))
  9995. {
  9996. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  9997. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  9998. // Why don't we use Terminal->CurrentDirectory directly?
  9999. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10000. // do not force queue, drag drop
  10001. false, true);
  10002. }
  10003. }
  10004. }
  10005. //---------------------------------------------------------------------------
  10006. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10007. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10008. {
  10009. // Downloads are handled in RemoteFileControlDDEnd
  10010. if (!IsFileControl(DropSourceControl, osRemote))
  10011. {
  10012. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10013. Terminal->CurrentDirectory,
  10014. // force queue, drag drop
  10015. true, true);
  10016. }
  10017. }
  10018. //---------------------------------------------------------------------------
  10019. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10020. {
  10021. FShowing = false;
  10022. // Do not save empty workspace
  10023. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10024. {
  10025. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10026. UnicodeString Name = WorkspaceName();
  10027. DoSaveWorkspace(
  10028. Name, DataList.get(),
  10029. !Configuration->DisablePasswordStoring &&
  10030. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10031. WinConfiguration->LastStoredSession = Name;
  10032. }
  10033. AppLog(L"Closing main window");
  10034. }
  10035. //---------------------------------------------------------------------------
  10036. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10037. {
  10038. TManagedTerminal * ManagedTerminal =
  10039. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10040. if (ManagedTerminal != NULL)
  10041. {
  10042. ManagedTerminal->DirectoryLoaded = Now();
  10043. }
  10044. }
  10045. //---------------------------------------------------------------------------
  10046. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10047. TListItem * /*Item*/, bool /*Selected*/)
  10048. {
  10049. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10050. switch (DirView->LastSelectMethod)
  10051. {
  10052. case smKeyboard:
  10053. Configuration->Usage->Inc(L"KeyboardSelections");
  10054. break;
  10055. case smMouse:
  10056. Configuration->Usage->Inc(L"MouseSelections");
  10057. break;
  10058. }
  10059. }
  10060. //---------------------------------------------------------------------------
  10061. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10062. {
  10063. if (Color != 0)
  10064. {
  10065. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10066. }
  10067. else
  10068. {
  10069. return FSessionTabImageIndex;
  10070. }
  10071. }
  10072. //---------------------------------------------------------------------------
  10073. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10074. {
  10075. TPngImageCollectionItem * Item =
  10076. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10077. FSessionColors->AddPng(Item->PngImage);
  10078. return FSessionColors->Count - 1;
  10079. }
  10080. //---------------------------------------------------------------------------
  10081. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10082. {
  10083. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10084. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10085. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10086. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10087. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10088. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10089. }
  10090. //---------------------------------------------------------------------------
  10091. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10092. {
  10093. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10094. }
  10095. //---------------------------------------------------------------------------
  10096. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10097. {
  10098. switch (Side)
  10099. {
  10100. case osLocal:
  10101. return FNewLocalTabTabImageIndex;
  10102. case osRemote:
  10103. case osCurrent:
  10104. return FNewRemoteTabTabImageIndex;
  10105. default:
  10106. DebugFail();
  10107. return -1;
  10108. }
  10109. }
  10110. //---------------------------------------------------------------------------
  10111. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10112. {
  10113. for (int Index = 0; Index < Control->ControlCount; Index++)
  10114. {
  10115. TControl * AControl = Control->Controls[Index];
  10116. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10117. if (WinControl != NULL)
  10118. {
  10119. CollectItemsWithTextDisplayMode(WinControl);
  10120. }
  10121. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10122. if (Toolbar != NULL)
  10123. {
  10124. // we care for top-level items only
  10125. TTBCustomItem * Items = Toolbar->Items;
  10126. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10127. {
  10128. TTBCustomItem * Item = Items->Items[ItemIndex];
  10129. if (((Item->DisplayMode == nbdmImageAndText) ||
  10130. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10131. EligibleForImageDisplayMode(Item))
  10132. {
  10133. FItemsWithTextDisplayMode.insert(Item);
  10134. }
  10135. }
  10136. }
  10137. }
  10138. }
  10139. //---------------------------------------------------------------------------
  10140. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10141. {
  10142. return true;
  10143. }
  10144. //---------------------------------------------------------------------------
  10145. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10146. {
  10147. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10148. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10149. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10150. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10151. bool Result = true;
  10152. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10153. {
  10154. TTBCustomItem * Item = *i;
  10155. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10156. if (Label != NULL)
  10157. {
  10158. // optimization
  10159. if (Label->Visible == SelectiveToolbarText)
  10160. {
  10161. Result = false;
  10162. }
  10163. else
  10164. {
  10165. Label->Visible = SelectiveToolbarText;
  10166. }
  10167. }
  10168. else
  10169. {
  10170. // optimization
  10171. if (Item->DisplayMode == DisplayMode)
  10172. {
  10173. Result = false;
  10174. }
  10175. else
  10176. {
  10177. Item->DisplayMode = DisplayMode;
  10178. }
  10179. }
  10180. ++i;
  10181. }
  10182. UpdateNewTabTab();
  10183. return Result;
  10184. }
  10185. //---------------------------------------------------------------------------
  10186. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10187. {
  10188. DebugFail();
  10189. }
  10190. //---------------------------------------------------------------------------
  10191. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10192. {
  10193. // Among other, a lock level is non zero, while directory is being loaded,
  10194. // even when it happens as a result of dirview navigation,
  10195. // i.e. when TNonVisualDataModule is NOT FBusy.
  10196. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10197. // Among other this prevents a panel auto update to occur while
  10198. // directory is changing.
  10199. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10200. }
  10201. //---------------------------------------------------------------------------
  10202. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10203. {
  10204. // While the window is disabled, we still seem to process menu shortcuts at least,
  10205. // so stop it at least here.
  10206. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10207. bool Result;
  10208. if (Allowed == aaUpdate)
  10209. {
  10210. Result = true;
  10211. }
  10212. else
  10213. {
  10214. Result = !NonVisualDataModule->Busy;
  10215. if (Result && (Allowed == aaShortCut))
  10216. {
  10217. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10218. Action->Update();
  10219. Result = Action->Enabled;
  10220. }
  10221. }
  10222. return Result;
  10223. }
  10224. //---------------------------------------------------------------------------
  10225. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10226. {
  10227. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10228. }
  10229. //---------------------------------------------------------------------------
  10230. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10231. {
  10232. // This is somewhat redundant to LockWindow() call from
  10233. // TTerminalManager::TerminalReadDirectoryProgress.
  10234. // But disabling window is known not to block keyboard shorcuts
  10235. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10236. if (Busy > 0)
  10237. {
  10238. if (NonVisualDataModule->Busy)
  10239. {
  10240. State = false;
  10241. }
  10242. else
  10243. {
  10244. NonVisualDataModule->StartBusy();
  10245. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10246. LockWindow();
  10247. }
  10248. }
  10249. else if (Busy < 0)
  10250. {
  10251. UnlockWindow();
  10252. NonVisualDataModule->EndBusy();
  10253. }
  10254. else
  10255. {
  10256. State = NonVisualDataModule->Busy;
  10257. }
  10258. }
  10259. //---------------------------------------------------------------------------
  10260. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10261. {
  10262. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10263. if (Index >= 0)
  10264. {
  10265. TPopupMenu * PopupMenu = NULL;
  10266. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10267. if (Session != NULL)
  10268. {
  10269. SessionsPageControl->ActivePageIndex = Index;
  10270. if (DebugAlwaysTrue(SessionTabSwitched()))
  10271. {
  10272. // copied from TControl.WMContextMenu
  10273. SendCancelMode(SessionsPageControl);
  10274. // explicit popup instead of using PopupMenu property
  10275. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10276. // while connecting yet not-connected session and hence
  10277. // allowing an access to commands over not-completely connected session
  10278. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10279. }
  10280. }
  10281. else
  10282. {
  10283. if (SupportsLocalBrowser())
  10284. {
  10285. PopupMenu = NonVisualDataModule->NewTabPopup;
  10286. }
  10287. }
  10288. if (PopupMenu != NULL)
  10289. {
  10290. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10291. PopupMenu->PopupComponent = SessionsPageControl;
  10292. PopupMenu->Popup(Point.x, Point.y);
  10293. }
  10294. }
  10295. Handled = true;
  10296. }
  10297. //---------------------------------------------------------------------------
  10298. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10299. {
  10300. return HasActiveTerminal() && Terminal->IsCapable[fcChangePassword];
  10301. }
  10302. //---------------------------------------------------------------------------
  10303. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10304. {
  10305. Configuration->Usage->Inc(L"PasswordChanges");
  10306. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10307. ChangePasswordData->DisableAuthentationsExceptPassword();
  10308. ChangePasswordData->ChangePassword = true;
  10309. std::unique_ptr<TTerminal> ChangePasswordSession(
  10310. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10311. ChangePasswordSession->AutoReadDirectory = false;
  10312. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10313. {
  10314. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10315. }
  10316. else
  10317. {
  10318. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10319. }
  10320. }
  10321. //---------------------------------------------------------------------------
  10322. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10323. {
  10324. // No nice way to assert SSH2
  10325. return HasActiveTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10326. }
  10327. //---------------------------------------------------------------------------
  10328. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10329. {
  10330. TOperationVisualizer OperationVisualizer;
  10331. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10332. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10333. }
  10334. //---------------------------------------------------------------------------
  10335. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  10336. {
  10337. TForm::ChangeScale(M, D);
  10338. int APixelsPerInch = GetControlPixelsPerInch(this);
  10339. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  10340. try
  10341. {
  10342. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  10343. }
  10344. __finally
  10345. {
  10346. GUIConfiguration->ChangeResourceModule(ResourceModule);
  10347. }
  10348. }
  10349. //---------------------------------------------------------------------------
  10350. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10351. {
  10352. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10353. }
  10354. //---------------------------------------------------------------------
  10355. class TPublicControl : public TControl
  10356. {
  10357. friend class TCustomScpExplorerForm;
  10358. };
  10359. //---------------------------------------------------------------------------
  10360. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10361. {
  10362. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10363. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10364. }
  10365. //---------------------------------------------------------------------------
  10366. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10367. {
  10368. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10369. OpenBookmark(Side, Bookmark);
  10370. }
  10371. //---------------------------------------------------------------------------
  10372. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10373. {
  10374. DoBookmarkClick(osLocal, Sender);
  10375. }
  10376. //---------------------------------------------------------------------------
  10377. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10378. {
  10379. DoBookmarkClick(osRemote, Sender);
  10380. }
  10381. //---------------------------------------------------------------------------
  10382. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10383. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10384. {
  10385. if (BookmarkList != NULL)
  10386. {
  10387. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10388. if (IsLocalBrowserMode())
  10389. {
  10390. Side = osLocal;
  10391. }
  10392. if (!WinConfiguration->UseLocationProfiles)
  10393. {
  10394. std::unique_ptr<TStringList> Directories(new TStringList());
  10395. Directories->CaseSensitive = (Side == osRemote);
  10396. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10397. {
  10398. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10399. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10400. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10401. {
  10402. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10403. Item->Caption = EscapeHotkey(Directory);
  10404. Item->ShortCut = Bookmark->ShortCut;
  10405. Item->OnClick = OnBookmarkClick;
  10406. Item->Tag = reinterpret_cast<int>(Bookmark);
  10407. Directories->Add(Directory);
  10408. Menu->Add(Item.release());
  10409. }
  10410. }
  10411. }
  10412. else
  10413. {
  10414. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10415. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10416. {
  10417. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10418. if (!Bookmark->Node.IsEmpty())
  10419. {
  10420. Folders->Add(Bookmark->Node);
  10421. }
  10422. }
  10423. for (int Index = 0; Index < Folders->Count; Index++)
  10424. {
  10425. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10426. Item->Caption = Folders->Strings[Index];
  10427. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10428. Folders->Objects[Index] = Item.get();
  10429. Menu->Add(Item.release());
  10430. }
  10431. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10432. {
  10433. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10434. TTBCustomItem * Parent;
  10435. if (!Bookmark->Node.IsEmpty())
  10436. {
  10437. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10438. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10439. }
  10440. else
  10441. {
  10442. Parent = Menu;
  10443. }
  10444. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10445. Item->Caption = Bookmark->Name;
  10446. Item->ShortCut = Bookmark->ShortCut;
  10447. Item->OnClick = OnBookmarkClick;
  10448. Item->Tag = reinterpret_cast<int>(Bookmark);
  10449. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10450. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10451. {
  10452. // No hint for location profiles that are actually mere "bookmarks"
  10453. }
  10454. else
  10455. {
  10456. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10457. UnicodeString LongHint;
  10458. if (!Bookmark->Local.IsEmpty())
  10459. {
  10460. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10461. }
  10462. if (!Bookmark->Remote.IsEmpty())
  10463. {
  10464. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10465. }
  10466. AddToList(Hint, LongHint, L"|");
  10467. Item->Hint = Hint;
  10468. }
  10469. Parent->Add(Item.release());
  10470. }
  10471. }
  10472. AddMenuSeparator(Menu);
  10473. }
  10474. }
  10475. //---------------------------------------------------------------------------
  10476. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10477. {
  10478. Menu->Clear();
  10479. std::unique_ptr<TTBCustomItem> Item;
  10480. Item.reset(new TTBXItem(Owner));
  10481. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10482. Item->Options = Item->Options << tboDefault;
  10483. Menu->Add(Item.release());
  10484. AddMenuSeparator(Menu);
  10485. if (Terminal != NULL)
  10486. {
  10487. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10488. }
  10489. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10490. Item.reset(new TTBXItem(Owner));
  10491. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10492. Menu->Add(Item.release());
  10493. }
  10494. //---------------------------------------------------------------------------
  10495. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10496. {
  10497. bool Result = true;
  10498. bool Remote = !IsSideLocalBrowser(Side);
  10499. try
  10500. {
  10501. UnicodeString APath = Path;
  10502. if (Remote)
  10503. {
  10504. Terminal->ExceptionOnFail = true;
  10505. }
  10506. else
  10507. {
  10508. APath = ExpandEnvironmentVariables(Path);
  10509. }
  10510. try
  10511. {
  10512. DirView(Side)->Path = APath;
  10513. }
  10514. __finally
  10515. {
  10516. if (Remote)
  10517. {
  10518. Terminal->ExceptionOnFail = false;
  10519. }
  10520. }
  10521. }
  10522. catch (Exception & E)
  10523. {
  10524. if (!Remote || Terminal->Active)
  10525. {
  10526. ShowExtendedExceptionEx(Terminal, &E);
  10527. Result = false;
  10528. }
  10529. else
  10530. {
  10531. throw;
  10532. }
  10533. }
  10534. return Result;
  10535. }
  10536. //---------------------------------------------------------------------------
  10537. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10538. {
  10539. // Make sure there some feedback even when loading tiny local folders
  10540. TInstantOperationVisualizer Visualizer;
  10541. DirView(Side)->ReloadDirectory();
  10542. }
  10543. //---------------------------------------------------------------------------
  10544. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10545. {
  10546. if (Index == SessionsPageControl->TabIndex)
  10547. {
  10548. CloseTab();
  10549. }
  10550. else
  10551. {
  10552. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10553. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10554. TTerminalManager * Manager = TTerminalManager::Instance();
  10555. if (!Terminal->Active)
  10556. {
  10557. Manager->FreeTerminal(Terminal);
  10558. }
  10559. else
  10560. {
  10561. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10562. if (CanCloseQueue(Queue))
  10563. {
  10564. Manager->FreeTerminal(Terminal);
  10565. }
  10566. }
  10567. }
  10568. }
  10569. //---------------------------------------------------------------------------
  10570. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10571. {
  10572. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10573. if (Session == NULL)
  10574. {
  10575. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10576. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10577. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10578. //P = SessionsPageControl->ClientToScreen(P);
  10579. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10580. }
  10581. else
  10582. {
  10583. CloseSessionTab(Index);
  10584. }
  10585. }
  10586. //---------------------------------------------------------------------------
  10587. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10588. {
  10589. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10590. {
  10591. TInstantOperationVisualizer Visualizer;
  10592. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10593. // before we create a new data object
  10594. ClipboardClear();
  10595. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10596. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10597. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10598. // Intermediate variable to WORKAROUND a crash in compiler
  10599. TObjectList * ClipboardFakeMonitors =
  10600. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10601. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10602. if (FClipboardDragDropFilesEx.get() == NULL)
  10603. {
  10604. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10605. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10606. }
  10607. FClipboardDragDropFilesEx->FileList->Clear();
  10608. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10609. FClipboardDragDropFilesEx->CopyToClipboard();
  10610. FClipboardTerminal = Terminal;
  10611. // Need full paths, as cwd can be different once files are pasted
  10612. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10613. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10614. {
  10615. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10616. }
  10617. }
  10618. }
  10619. //---------------------------------------------------------------------------
  10620. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10621. {
  10622. if (OpenClipboard(0))
  10623. {
  10624. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10625. CloseClipboard();
  10626. }
  10627. }
  10628. //---------------------------------------------------------------------------
  10629. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10630. {
  10631. return !FClipboardFakeDirectory.IsEmpty();
  10632. }
  10633. //---------------------------------------------------------------------------
  10634. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10635. {
  10636. RemoveDir(ApiPath(FClipboardFakeDirectory));
  10637. FClipboardFakeDirectory = UnicodeString();
  10638. FClipboardTerminal = NULL;
  10639. if (FDownloadingFromClipboard)
  10640. {
  10641. // We are called by the monitor, so attempt to release it would deadlock
  10642. FClipboardFakeMonitorsPendingReset = true;
  10643. }
  10644. else
  10645. {
  10646. FClipboardFakeMonitors.reset(NULL);
  10647. }
  10648. }
  10649. //---------------------------------------------------------------------------
  10650. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10651. {
  10652. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10653. {
  10654. ClipboardStop();
  10655. }
  10656. }
  10657. //---------------------------------------------------------------------------
  10658. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10659. {
  10660. TTerminalManager * Manager = TTerminalManager::Instance();
  10661. Manager->ActiveSession = FClipboardTerminal;
  10662. TTransferOperationParam Params;
  10663. Params.TargetDirectory = TargetDirectory;
  10664. Params.DragDrop = DragDrop;
  10665. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10666. }
  10667. //---------------------------------------------------------------------------
  10668. void TCustomScpExplorerForm::PasteFiles()
  10669. {
  10670. // Guard against possible race conditions
  10671. if (!FClipboardPasteTarget.IsEmpty())
  10672. {
  10673. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10674. UnicodeString Target = FClipboardPasteTarget;
  10675. FClipboardPasteTarget = EmptyStr;
  10676. // Can fail as it can be e.g. locked by AV, so we retry that later
  10677. bool Removed = RemoveDir(ApiPath(Target));
  10678. try
  10679. {
  10680. if (!NonVisualDataModule->Busy)
  10681. {
  10682. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10683. FClipboardFakeMonitorsPendingReset = false;
  10684. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10685. TAutoFlag Flag(FDownloadingFromClipboard);
  10686. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10687. }
  10688. }
  10689. __finally
  10690. {
  10691. if (!Removed)
  10692. {
  10693. RemoveDir(ApiPath(Target));
  10694. }
  10695. }
  10696. }
  10697. }
  10698. //---------------------------------------------------------------------------
  10699. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10700. {
  10701. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10702. // (as it pumps a Windows message queue while being shutted down)
  10703. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10704. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10705. {
  10706. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10707. FClipboardPasteTarget = FileName;
  10708. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10709. // Postponing removing (or actually whole pasting operation) seems to help.
  10710. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10711. }
  10712. }
  10713. //---------------------------------------------------------------------------
  10714. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10715. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10716. {
  10717. TFileMasks::TParams MaskParams;
  10718. MaskParams.Size = Size;
  10719. MaskParams.Modification = Modification;
  10720. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10721. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10722. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10723. if (!Local && Directory)
  10724. {
  10725. FileName = UnixExcludeTrailingBackslash(FileName);
  10726. }
  10727. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10728. {
  10729. bool ImplicitMatch;
  10730. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10731. !ImplicitMatch)
  10732. {
  10733. Color = Iter->Color;
  10734. break;
  10735. }
  10736. }
  10737. }
  10738. //---------------------------------------------------------------------------
  10739. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10740. {
  10741. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10742. if (!DirView->IsEditing())
  10743. {
  10744. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10745. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10746. // while searching
  10747. if (Key == VK_BACK)
  10748. {
  10749. if (!FIncrementalSearch.IsEmpty())
  10750. {
  10751. if (FIncrementalSearch.Length() == 1)
  10752. {
  10753. ResetIncrementalSearch();
  10754. }
  10755. else
  10756. {
  10757. UnicodeString NewText = FIncrementalSearch.SubString(1, FIncrementalSearch.Length() - 1);
  10758. IncrementalSearch(NewText, false, false);
  10759. }
  10760. Key = 0;
  10761. }
  10762. }
  10763. }
  10764. }
  10765. //---------------------------------------------------------------------------
  10766. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10767. {
  10768. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10769. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10770. {
  10771. // Filter control sequences.
  10772. // When not searching yet, prefer use of the space for toggling file selection
  10773. // (so we cannot incrementally search for a string starting with a space).
  10774. if ((Key > VK_SPACE) ||
  10775. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && !FIncrementalSearch.IsEmpty()))
  10776. {
  10777. IncrementalSearch(FIncrementalSearch + Key, false, false);
  10778. Key = 0;
  10779. }
  10780. }
  10781. }
  10782. //---------------------------------------------------------------------------
  10783. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10784. {
  10785. if (!FIncrementalSearch.IsEmpty())
  10786. {
  10787. FIncrementalSearch = L"";
  10788. DirView(osCurrent)->UpdateStatusBar();
  10789. }
  10790. }
  10791. //---------------------------------------------------------------------------
  10792. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10793. {
  10794. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  10795. if (Item == NULL)
  10796. {
  10797. MessageBeep(MB_ICONHAND);
  10798. }
  10799. else
  10800. {
  10801. TCustomDirView * ADirView = DirView(osCurrent);
  10802. {
  10803. TAutoNestingCounter Guard(FIncrementalSearching);
  10804. ADirView->FocusItem(Item);
  10805. if (ADirView->NortonLike == nlOff)
  10806. {
  10807. if ((ADirView->Selected != Item) ||
  10808. (ADirView->SelCount > 1))
  10809. {
  10810. ADirView->ClearSelection();
  10811. ADirView->Selected = Item;
  10812. }
  10813. }
  10814. }
  10815. FIncrementalSearch = Text;
  10816. Item->MakeVisible(false);
  10817. TListItem * NextItem = SearchFile(Text, true, Reverse);
  10818. FIncrementalSearchHaveNext = (NextItem != NULL) && (NextItem != Item);
  10819. ADirView->UpdateStatusBar();
  10820. }
  10821. }
  10822. //---------------------------------------------------------------------------
  10823. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  10824. {
  10825. int Index = Item->Index;
  10826. if (!Reverse)
  10827. {
  10828. Index++;
  10829. if (Index >= Item->Owner->Count)
  10830. {
  10831. Index = 0;
  10832. }
  10833. }
  10834. else
  10835. {
  10836. Index--;
  10837. if (Index < 0)
  10838. {
  10839. Index = Item->Owner->Count - 1;
  10840. }
  10841. }
  10842. return Item->Owner->Item[Index];
  10843. }
  10844. //---------------------------------------------------------------------------
  10845. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10846. {
  10847. TCustomDirView * ADirView = DirView(osCurrent);
  10848. if (ADirView->Items->Count == 0)
  10849. {
  10850. return NULL;
  10851. }
  10852. else
  10853. {
  10854. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  10855. TListItem * Item = CurrentItem;
  10856. if (SkipCurrent)
  10857. {
  10858. Item = DebugNotNull(GetNextFile(Item, Reverse));
  10859. }
  10860. while (true)
  10861. {
  10862. bool Matches = false;
  10863. switch (WinConfiguration->PanelSearch)
  10864. {
  10865. case isNameStartOnly:
  10866. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  10867. break;
  10868. case isName:
  10869. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  10870. break;
  10871. case isAll:
  10872. int ColCount = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Count : 1;
  10873. int Index = 0;
  10874. while ((Index < ColCount) && !Matches)
  10875. {
  10876. bool Visible = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Visible[Index] : true;
  10877. if (Visible)
  10878. {
  10879. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  10880. }
  10881. Index++;
  10882. }
  10883. break;
  10884. }
  10885. if (Matches)
  10886. {
  10887. return Item;
  10888. }
  10889. Item = GetNextFile(Item, Reverse);
  10890. if (Item == CurrentItem)
  10891. {
  10892. return NULL;
  10893. }
  10894. }
  10895. }
  10896. }
  10897. //---------------------------------------------------------------------------
  10898. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  10899. {
  10900. ResetIncrementalSearch();
  10901. }
  10902. //---------------------------------------------------------------------------
  10903. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  10904. {
  10905. if (Message.CharCode == VK_TAB)
  10906. {
  10907. if (!FIncrementalSearch.IsEmpty())
  10908. {
  10909. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  10910. bool Reverse = Shift.Contains(ssShift);
  10911. IncrementalSearch(FIncrementalSearch, true, Reverse);
  10912. Message.Result = 1;
  10913. return;
  10914. }
  10915. }
  10916. else if (Message.CharCode == VK_ESCAPE)
  10917. {
  10918. if (!FIncrementalSearch.IsEmpty())
  10919. {
  10920. ResetIncrementalSearch();
  10921. Message.Result = 1;
  10922. return;
  10923. }
  10924. }
  10925. TForm::Dispatch(&Message);
  10926. }
  10927. //---------------------------------------------------------------------------
  10928. void __fastcall TCustomScpExplorerForm::Deactivate()
  10929. {
  10930. TForm::Deactivate();
  10931. // E.g. when switching to an internal editor window
  10932. ResetIncrementalSearch();
  10933. }
  10934. //---------------------------------------------------------------------------
  10935. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  10936. {
  10937. // When switching to another application
  10938. ResetIncrementalSearch();
  10939. }
  10940. //---------------------------------------------------------------------------
  10941. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  10942. {
  10943. ResetIncrementalSearch();
  10944. }
  10945. //---------------------------------------------------------------------------
  10946. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  10947. {
  10948. if (FIncrementalSearching <= 0)
  10949. {
  10950. ResetIncrementalSearch();
  10951. }
  10952. }
  10953. //---------------------------------------------------------------------------
  10954. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  10955. {
  10956. CountClicksForWindowPrint(this);
  10957. }
  10958. //---------------------------------------------------------------------------
  10959. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  10960. {
  10961. CenterReconnectToolbar();
  10962. }
  10963. //---------------------------------------------------------------------------
  10964. void TCustomScpExplorerForm::DoBrowseFile(TCustomDirView * DirView, const UnicodeString & FileName)
  10965. {
  10966. if (!FileName.IsEmpty())
  10967. {
  10968. DirView->RestoreFocus(FileName);
  10969. if (DirView->ItemFocused != NULL)
  10970. {
  10971. DirView->ItemFocused->Selected = true;
  10972. }
  10973. }
  10974. }
  10975. //---------------------------------------------------------------------------
  10976. void __fastcall TCustomScpExplorerForm::BrowseFile(const UnicodeString & FileName)
  10977. {
  10978. DoBrowseFile(RemoteDirView, FileName);
  10979. }
  10980. //---------------------------------------------------------------------------
  10981. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  10982. {
  10983. if (!FQueueStatusUpdating)
  10984. {
  10985. bool Refresh;
  10986. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  10987. {
  10988. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  10989. }
  10990. else
  10991. {
  10992. if (FQueueFileList->GetCount() > 0)
  10993. {
  10994. FQueueFileList->Clear();
  10995. Refresh = true;
  10996. }
  10997. }
  10998. int Count = FQueueFileList->GetCount();
  10999. if (QueueFileList->Items->Count != Count)
  11000. {
  11001. DebugAssert(Refresh);
  11002. QueueFileList->Items->Count = Count;
  11003. }
  11004. if (Refresh)
  11005. {
  11006. QueueFileList->Invalidate();
  11007. }
  11008. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  11009. }
  11010. }
  11011. //---------------------------------------------------------------------------
  11012. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  11013. {
  11014. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  11015. }
  11016. //---------------------------------------------------------------------------
  11017. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  11018. {
  11019. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  11020. // See TSynchronizeChecklistDialog::UpdateTimer
  11021. if (QueueFileList->Items->Count > 0)
  11022. {
  11023. QueueFileList->Items->Item[0]->MakeVisible(false);
  11024. }
  11025. UpdateQueueFileList();
  11026. }
  11027. //---------------------------------------------------------------------------
  11028. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  11029. {
  11030. Active = QueueView3->Focused() || QueueFileList->Focused();
  11031. }
  11032. //---------------------------------------------------------------------------
  11033. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11034. {
  11035. QueueLabelUpdateStatus();
  11036. }
  11037. //---------------------------------------------------------------------------
  11038. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11039. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11040. {
  11041. int State = FQueueFileList->GetState(Item->Index);
  11042. if (State == qfsProcessed)
  11043. {
  11044. Sender->Canvas->Font->Color = clGrayText;
  11045. }
  11046. }
  11047. //---------------------------------------------------------------------------
  11048. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11049. {
  11050. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11051. QueueFileList->Column[0]->Width =
  11052. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11053. }
  11054. //---------------------------------------------------------------------------
  11055. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11056. {
  11057. QueueFileListColumnAutoSize();
  11058. }
  11059. //---------------------------------------------------------------------------
  11060. void __fastcall TCustomScpExplorerForm::CloseApp()
  11061. {
  11062. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11063. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11064. // So we clear the flag here.
  11065. DebugAssert(NonVisualDataModule->Busy);
  11066. NonVisualDataModule->EndBusy();
  11067. try
  11068. {
  11069. Close();
  11070. }
  11071. __finally
  11072. {
  11073. NonVisualDataModule->StartBusy();
  11074. }
  11075. }
  11076. //---------------------------------------------------------------------------
  11077. bool __fastcall TCustomScpExplorerForm::IsActiveTerminal(TTerminal * Terminal)
  11078. {
  11079. return (Terminal != NULL) && Terminal->Active;
  11080. }
  11081. //---------------------------------------------------------------------------
  11082. bool __fastcall TCustomScpExplorerForm::HasManagedSession()
  11083. {
  11084. return (ManagedSession != NULL);
  11085. }
  11086. //---------------------------------------------------------------------------
  11087. bool __fastcall TCustomScpExplorerForm::HasActiveTerminal()
  11088. {
  11089. return IsActiveTerminal(Terminal);
  11090. }
  11091. //---------------------------------------------------------------------------
  11092. void TCustomScpExplorerForm::LocalLocalCopy(
  11093. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11094. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11095. {
  11096. DebugFail();
  11097. }
  11098. //---------------------------------------------------------------------------
  11099. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11100. {
  11101. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11102. }
  11103. //---------------------------------------------------------------------------
  11104. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11105. {
  11106. // 1) Changing tab list triggers the OnResize.
  11107. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11108. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11109. {
  11110. // UpdateTabsCaptionTruncation should be enough
  11111. SessionListChanged(true);
  11112. }
  11113. }
  11114. //---------------------------------------------------------------------------
  11115. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11116. {
  11117. if (ASession == ManagedSession)
  11118. {
  11119. UpdateSession(ASession);
  11120. }
  11121. TSessionData * Data = ASession->StateData;
  11122. UnicodeString Result;
  11123. if (Side == osLocal)
  11124. {
  11125. Result = Data->LocalDirectory;
  11126. }
  11127. else if (DebugAlwaysTrue(Side == osOther))
  11128. {
  11129. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11130. }
  11131. return Result;
  11132. }
  11133. //---------------------------------------------------------------------------
  11134. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11135. {
  11136. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11137. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11138. if (Title == Result)
  11139. {
  11140. Result = EmptyStr;
  11141. }
  11142. else
  11143. {
  11144. Result += L"\n";
  11145. }
  11146. return Result;
  11147. }
  11148. //---------------------------------------------------------------------------
  11149. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11150. {
  11151. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11152. if (!ASession->Active)
  11153. {
  11154. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11155. }
  11156. else
  11157. {
  11158. Result += GetSessionPath(ASession, osRemote);
  11159. }
  11160. return Result;
  11161. }
  11162. //---------------------------------------------------------------------------
  11163. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11164. {
  11165. return LoadStr(NEW_REMOTE_TAB_HINT);
  11166. }
  11167. //---------------------------------------------------------------------------
  11168. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11169. {
  11170. if (Index >= 0)
  11171. {
  11172. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11173. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11174. if (TabSession == NULL)
  11175. {
  11176. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11177. if (NewTabTabCaption != TabSheet->Caption)
  11178. {
  11179. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11180. }
  11181. }
  11182. else
  11183. {
  11184. TTerminalManager * Manager = TTerminalManager::Instance();
  11185. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11186. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11187. }
  11188. }
  11189. }
  11190. //---------------------------------------------------------------------------
  11191. typedef std::vector<TListItem *> TListItemsVector;
  11192. struct TCalculateSizeOperation
  11193. {
  11194. TCalculateSizeStats Stats;
  11195. TListItemsVector ListItems;
  11196. size_t Index;
  11197. };
  11198. //---------------------------------------------------------------------------
  11199. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11200. {
  11201. TCalculateSizeOperation CalculateSizeOperation;
  11202. Side = GetSide(Side);
  11203. TCustomDirView * ADirView = DirView(Side);
  11204. bool LocalSide = IsSideLocalBrowser(Side);
  11205. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11206. std::unique_ptr<TStrings> FileList(new TStringList());
  11207. for (int Index = 0; Index < AllFileList->Count; Index++)
  11208. {
  11209. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11210. if (ADirView->ItemIsDirectory(Item))
  11211. {
  11212. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11213. CalculateSizeOperation.ListItems.push_back(Item);
  11214. }
  11215. }
  11216. CalculateSizeOperation.Index = 0;
  11217. __int64 Size = 0;
  11218. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation);
  11219. FCalculateSizeOperation = &CalculateSizeOperation;
  11220. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11221. FOnFileOperationFinished = DirectorySizeCalculated;
  11222. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation);
  11223. FPrimaryOperation = foCalculateSize;
  11224. TCalculatedSizes CalculatedSizes;
  11225. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11226. if (LocalSide)
  11227. {
  11228. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  11229. FProgressSide = Side;
  11230. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11231. }
  11232. else
  11233. {
  11234. TCalculateSizeParams Params;
  11235. Params.Stats = &CalculateSizeOperation.Stats;
  11236. Params.UseCache = true;
  11237. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11238. }
  11239. }
  11240. //---------------------------------------------------------------------------
  11241. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(TOperationSide Side, const UnicodeString & FileName, bool Success)
  11242. {
  11243. DebugAlwaysTrue(FCalculateSizeOperation != NULL);
  11244. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11245. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11246. // optimization
  11247. bool GotExpectedItem =
  11248. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11249. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11250. int Index = -1;
  11251. if (DebugAlwaysTrue(GotExpectedItem))
  11252. {
  11253. Index = FCalculateSizeOperation->Index;
  11254. FCalculateSizeOperation->Index++;
  11255. }
  11256. else
  11257. {
  11258. TListItemsVector::iterator I =
  11259. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11260. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11261. {
  11262. Index = I - FCalculateSizeOperation->ListItems.begin();
  11263. }
  11264. }
  11265. if (DebugAlwaysTrue(Index >= 0) && Success)
  11266. {
  11267. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11268. ADirView->SetItemCalculatedSize(Item, Size);
  11269. }
  11270. }
  11271. //---------------------------------------------------------------------------
  11272. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11273. {
  11274. Accept = false;
  11275. }
  11276. //---------------------------------------------------------------------------
  11277. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11278. {
  11279. // Send Ctrl+Gray+ to the list view
  11280. TKeyboardState KeyState;
  11281. GetKeyboardState(KeyState);
  11282. TKeyboardState NewKeyState;
  11283. memset(NewKeyState, 0, sizeof(NewKeyState));
  11284. NewKeyState[VK_CONTROL] = 0x81;
  11285. SetKeyboardState(NewKeyState);
  11286. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11287. SetKeyboardState(KeyState);
  11288. }
  11289. //---------------------------------------------------------------------------
  11290. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11291. {
  11292. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11293. }