CustomScpExplorer.cpp 398 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945
  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. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  950. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  951. Toolbar->Items->Add(LabelItem);
  952. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  953. LinkItem->FontSettings->Color = LinkColor;
  954. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  955. LinkItem->OnClick = StoreTransitionLinkClick;
  956. Toolbar->Items->Add(LinkItem);
  957. AddMenuSeparator(Toolbar->Items);
  958. TTBCustomItem * CloseItem = new TTBXItem(Toolbar);
  959. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  960. CloseItem->OnClick = StoreTransitionCloseClick;
  961. Toolbar->Items->Add(CloseItem);
  962. GiveTBItemPriority(CloseItem);
  963. }
  964. }
  965. //---------------------------------------------------------------------------
  966. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  967. {
  968. ShowHelp(HELP_STORE_TRANSITION);
  969. }
  970. //---------------------------------------------------------------------------
  971. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  972. {
  973. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  974. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  975. delete Toolbar;
  976. WinConfiguration->StoreTransition = stStoreAcknowledged;
  977. UpdateControls();
  978. }
  979. //---------------------------------------------------------------------------
  980. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  981. {
  982. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  983. static_cast<TComponent*>(GetComponent(fcTransferList)));
  984. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  985. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  986. TransferList->Strings->BeginUpdate();
  987. try
  988. {
  989. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  990. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  991. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  992. if (FTransferDropDownHint.IsEmpty())
  993. {
  994. FTransferDropDownHint = TransferDropDown->Hint;
  995. }
  996. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  997. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  998. TransferDropDown->Text = StripHotkey(Name);
  999. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1000. (FTransferDropDownHint, StripHotkey(Name),
  1001. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1002. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1003. // update the label, otherwise when it is updated only on the first draw
  1004. // of the list, it is drawn "bold" for some reason
  1005. FTransferListHoverIndex = TransferList->ItemIndex;
  1006. UpdateTransferLabel();
  1007. }
  1008. __finally
  1009. {
  1010. TransferList->Strings->EndUpdate();
  1011. }
  1012. }
  1013. //---------------------------------------------------------------------------
  1014. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1015. {
  1016. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1017. DebugAssert(Toolbar != NULL);
  1018. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1019. }
  1020. //---------------------------------------------------------------------------
  1021. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1022. {
  1023. TForm::UpdateActions();
  1024. if (ComponentVisible[fcCustomCommandsBand])
  1025. {
  1026. UpdateCustomCommandsToolbar();
  1027. }
  1028. }
  1029. //---------------------------------------------------------------------------
  1030. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1031. {
  1032. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1033. }
  1034. //---------------------------------------------------------------------------
  1035. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1036. {
  1037. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1038. {
  1039. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1040. // Without this, the panel turns gray and unused part of header turns black
  1041. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1042. }
  1043. }
  1044. //---------------------------------------------------------------------------
  1045. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1046. {
  1047. Color = GetBtnFaceColor();
  1048. DebugAssert(Configuration && RemoteDirView);
  1049. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1050. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1051. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1052. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1053. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1054. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1055. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1056. UpdateRowSelect(RemoteDirView);
  1057. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1058. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1059. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1060. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1061. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1062. UpdateSessionsPageControlHeight();
  1063. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1064. UpdateToolbarDisplayMode();
  1065. UpdateTransferList();
  1066. if (Terminal != NULL)
  1067. {
  1068. TransferPresetAutoSelect();
  1069. }
  1070. UpdateQueueView();
  1071. UpdateControls();
  1072. // this can be called even before constuctor finishes.
  1073. if (FEditorManager != NULL)
  1074. {
  1075. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1076. }
  1077. // this can be called even before constuctor finishes.
  1078. if (FLocalEditors != NULL)
  1079. {
  1080. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1081. {
  1082. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1083. }
  1084. }
  1085. if (ComponentVisible[fcCustomCommandsBand])
  1086. {
  1087. UpdateCustomCommandsToolbar();
  1088. }
  1089. // show only when keeping queue items forever,
  1090. // otherwise, it's enough to have it in the context menu
  1091. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1092. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1093. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1094. {
  1095. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1096. FFileColorsCurrent = WinConfiguration->FileColors;
  1097. FileColorsChanged();
  1098. }
  1099. }
  1100. //---------------------------------------------------------------------------
  1101. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1102. {
  1103. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1104. DirView->Invalidate();
  1105. }
  1106. //---------------------------------------------------------------------------
  1107. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1108. {
  1109. DoFileColorsChanged(RemoteDirView);
  1110. }
  1111. //---------------------------------------------------------------------------
  1112. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1113. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  1114. void * /*Arg*/)
  1115. {
  1116. if (Token != NULL)
  1117. {
  1118. TForm * Editor = dynamic_cast<TForm*>(Token);
  1119. DebugAssert(Editor != NULL);
  1120. ReconfigureEditorForm(Editor);
  1121. }
  1122. }
  1123. //---------------------------------------------------------------------------
  1124. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1125. {
  1126. WinConfiguration->DDTransferConfirmation = asOn;
  1127. }
  1128. //---------------------------------------------------------------------------
  1129. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1130. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1131. {
  1132. // noop
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1136. {
  1137. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1138. }
  1139. //---------------------------------------------------------------------------
  1140. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1141. {
  1142. if (DoNotShowAgain)
  1143. {
  1144. if (DragDrop)
  1145. {
  1146. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1147. {
  1148. PopupTrayBalloon(
  1149. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1150. }
  1151. WinConfiguration->DDTransferConfirmation = asOff;
  1152. }
  1153. else
  1154. {
  1155. WinConfiguration->ConfirmTransferring = false;
  1156. }
  1157. }
  1158. else
  1159. {
  1160. // User explicitly unchecked "do not show again",
  1161. // so show him the dialog the next time
  1162. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1163. {
  1164. WinConfiguration->DDTransferConfirmation = asOn;
  1165. }
  1166. }
  1167. }
  1168. //---------------------------------------------------------------------------
  1169. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1170. TTransferDirection Direction, TTransferType Type, bool Temp,
  1171. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1172. bool Confirm, bool DragDrop, int Options)
  1173. {
  1174. bool Result = true;
  1175. DebugAssert(HasActiveTerminal());
  1176. // these parameters are known in advance
  1177. int Params =
  1178. FLAGMASK(Type == ttMove, cpDelete);
  1179. bool ToTemp = (Temp && (Direction == tdToLocal));
  1180. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1181. {
  1182. bool DisableNewerOnly =
  1183. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1184. ToTemp;
  1185. Options |=
  1186. FLAGMASK(ToTemp, coTemp) |
  1187. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1188. coDoNotShowAgain;
  1189. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1190. int CopyParamAttrs = (Direction == tdToRemote ?
  1191. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1192. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1193. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1194. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1195. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1196. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1197. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1198. if (Result)
  1199. {
  1200. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1201. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1202. }
  1203. }
  1204. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1205. {
  1206. Configuration->Usage->Inc(L"TransfersOnBackground");
  1207. // these parameter are known only after transfer dialog
  1208. Params |=
  1209. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1210. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1211. Result = false;
  1212. ClearTransferSourceSelection(Direction);
  1213. }
  1214. return Result;
  1215. }
  1216. //---------------------------------------------------------------------------
  1217. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1218. {
  1219. if (FOnFileOperationFinished != NULL)
  1220. {
  1221. FOnFileOperationFinished(Side, UnicodeString(), true);
  1222. }
  1223. else
  1224. {
  1225. if (HasDirView[Side])
  1226. {
  1227. DirView(Side)->SelectAll(smNone);
  1228. }
  1229. }
  1230. }
  1231. //---------------------------------------------------------------------------
  1232. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1233. {
  1234. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1235. ClearOperationSelection(Side);
  1236. }
  1237. //---------------------------------------------------------------------------
  1238. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1239. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1240. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1241. int Params)
  1242. {
  1243. DebugAssert(Queue != NULL);
  1244. bool SingleFile = false;
  1245. if (FileList->Count == 1)
  1246. {
  1247. if (Direction == tdToRemote)
  1248. {
  1249. UnicodeString FileName = FileList->Strings[0];
  1250. SingleFile = FileExists(ApiPath(FileName));
  1251. }
  1252. else
  1253. {
  1254. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1255. SingleFile = !File->IsDirectory;
  1256. }
  1257. }
  1258. TQueueItem * QueueItem;
  1259. if (Direction == tdToRemote)
  1260. {
  1261. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1262. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1263. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1264. }
  1265. else
  1266. {
  1267. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1268. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1269. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1270. }
  1271. AddQueueItem(Queue, QueueItem, Terminal);
  1272. }
  1273. //---------------------------------------------------------------------------
  1274. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1275. {
  1276. if (Queue->IsEmpty)
  1277. {
  1278. Terminal->QueueOperationStart = Now();
  1279. }
  1280. Queue->AddItem(QueueItem);
  1281. }
  1282. //---------------------------------------------------------------------------
  1283. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1284. {
  1285. }
  1286. //---------------------------------------------------------------------------
  1287. void __fastcall TCustomScpExplorerForm::InitControls()
  1288. {
  1289. DebugAssert(FDocks != NULL);
  1290. for (int Index = 0; Index < ComponentCount; Index++)
  1291. {
  1292. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1293. if ((Dock != NULL) && (Dock->Tag == 0))
  1294. {
  1295. FDocks->Add(Dock);
  1296. }
  1297. }
  1298. CollectItemsWithTextDisplayMode(this);
  1299. }
  1300. //---------------------------------------------------------------------------
  1301. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1302. {
  1303. ConfigurationChanged();
  1304. QueuePanel->Height =
  1305. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1306. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1307. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1308. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1309. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1310. QueueFileList->Height =
  1311. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1312. if (QueueFileList->Visible)
  1313. {
  1314. AdjustQueueLayout();
  1315. }
  1316. UpdateCustomCommandsToolbar();
  1317. }
  1318. //---------------------------------------------------------------------------
  1319. void __fastcall TCustomScpExplorerForm::StoreParams()
  1320. {
  1321. int APixelsPerInch = GetControlPixelsPerInch(this);
  1322. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1323. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1324. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1325. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1326. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1327. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1328. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1329. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1330. }
  1331. //---------------------------------------------------------------------------
  1332. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1333. {
  1334. if (!FFormRestored)
  1335. {
  1336. FFormRestored = true;
  1337. RestoreFormParams();
  1338. }
  1339. TForm::CreateParams(Params);
  1340. }
  1341. //---------------------------------------------------------------------------
  1342. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1343. {
  1344. DebugAssert(FDocks != NULL);
  1345. for (int Index = 0; Index < FDocks->Count; Index++)
  1346. {
  1347. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1348. }
  1349. }
  1350. //---------------------------------------------------------------------------
  1351. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1352. {
  1353. SetDockAllowDrag(true);
  1354. while (!ButtonsStr.IsEmpty())
  1355. {
  1356. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1357. UnicodeString Name = CutToChar(S, L'=', true);
  1358. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1359. {
  1360. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1361. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1362. {
  1363. while (!S.IsEmpty())
  1364. {
  1365. UnicodeString S2 = CutToChar(S, L',', true);
  1366. UnicodeString Name = CutToChar(S2, L':', true);
  1367. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1368. {
  1369. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1370. if (SameText(GetToolbarItemName(Item), Name))
  1371. {
  1372. // forward compatibility
  1373. UnicodeString S3 = CutToChar(S2, L':', true);
  1374. bool Visible = StrToIntDef(S3, 0);
  1375. Item->Visible = Visible;
  1376. }
  1377. }
  1378. }
  1379. }
  1380. }
  1381. }
  1382. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1383. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1384. }
  1385. //---------------------------------------------------------------------------
  1386. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1387. {
  1388. UnicodeString Result;
  1389. SetDockAllowDrag(true);
  1390. Result = ::GetToolbarsLayoutStr(this);
  1391. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1392. return Result;
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1396. {
  1397. UnicodeString Result;
  1398. if (Item->Action != NULL)
  1399. {
  1400. Result = Item->Action->Name;
  1401. Result = RemoveSuffix(Result, L"Action", true);
  1402. }
  1403. else
  1404. {
  1405. Result = Item->Name;
  1406. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1407. Result = RemoveSuffix(Result, L"Item", true);
  1408. }
  1409. return Result;
  1410. }
  1411. //---------------------------------------------------------------------------
  1412. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1413. {
  1414. UnicodeString Result;
  1415. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1416. {
  1417. UnicodeString ToolbarStr;
  1418. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1419. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1420. {
  1421. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1422. {
  1423. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1424. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1425. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1426. // and save the changes here only.
  1427. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1428. {
  1429. UnicodeString Name = GetToolbarItemName(Item);
  1430. DebugAssert(Name.Pos(L"TBX") == 0);
  1431. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1432. }
  1433. }
  1434. }
  1435. if (!ToolbarStr.IsEmpty())
  1436. {
  1437. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1438. }
  1439. }
  1440. return Result;
  1441. }
  1442. //---------------------------------------------------------------------------
  1443. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1444. {
  1445. DebugAssert(FProgressForm == NULL);
  1446. bool AllowSkip = HasActiveTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1447. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1448. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1449. FProgressForm->DeleteLocalToRecycleBin =
  1450. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1451. FProgressForm->DeleteRemoteToRecycleBin =
  1452. HasActiveTerminal() &&
  1453. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1454. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1455. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1456. LockWindow();
  1457. // Actually, do not know what hides the progress once the operation finishes
  1458. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1459. SetTaskbarListProgressState(TBPF_NORMAL);
  1460. }
  1461. //---------------------------------------------------------------------------
  1462. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1463. {
  1464. SAFE_DESTROY(FProgressForm);
  1465. UnlockWindow();
  1466. SetQueueProgress();
  1467. }
  1468. //---------------------------------------------------------------------------
  1469. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1470. TFileOperationProgressType & ProgressData)
  1471. {
  1472. // Download to temporary local directory
  1473. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1474. {
  1475. bool Continue = true;
  1476. FPendingTempSpaceWarn = false;
  1477. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1478. if (!Continue)
  1479. {
  1480. Abort();
  1481. }
  1482. }
  1483. // operation is being executed and we still didn't show up progress form
  1484. if (ProgressData.InProgress && !FProgressForm)
  1485. {
  1486. CreateProgressForm(NULL);
  1487. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1488. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1489. }
  1490. // operation is finished (or terminated), so we hide progress form
  1491. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1492. {
  1493. DestroyProgressForm();
  1494. if (ProgressData.Operation == foCalculateSize)
  1495. {
  1496. // When calculating size before transfer, the abort caused by
  1497. // cancel flag set due to "MoveToQueue" below,
  1498. // is not propagated back to us in ExecuteFileOperation,
  1499. // as it is silently swallowed.
  1500. // So we explicitly (re)throw it here.
  1501. if (FMoveToQueue)
  1502. {
  1503. Abort();
  1504. }
  1505. }
  1506. else
  1507. {
  1508. if ((ProgressData.Cancel == csContinue) &&
  1509. !FAutoOperation)
  1510. {
  1511. OperationComplete(ProgressData.StartTime);
  1512. }
  1513. }
  1514. }
  1515. if (FProgressForm &&
  1516. // Can happen only during synchronization, when ending one of the operations
  1517. ProgressData.InProgress)
  1518. {
  1519. FProgressForm->SetProgressData(ProgressData);
  1520. DebugAssert(ProgressData.InProgress);
  1521. SetTaskbarListProgressValue(&ProgressData);
  1522. if (FProgressForm->Cancel > csContinue)
  1523. {
  1524. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1525. if (FProgressForm->Cancel == csCancelFile)
  1526. {
  1527. FProgressForm->ClearCancel();
  1528. }
  1529. // cancel cancels even the move
  1530. FMoveToQueue = false;
  1531. }
  1532. else if (FProgressForm->MoveToQueue)
  1533. {
  1534. FMoveToQueue = true;
  1535. ProgressData.SetCancelAtLeast(csCancel);
  1536. }
  1537. if ((FTransferResumeList != NULL) &&
  1538. ProgressData.InProgress &&
  1539. ProgressData.IsTransfer() &&
  1540. !ProgressData.FullFileName.IsEmpty())
  1541. {
  1542. if ((FTransferResumeList->Count == 0) ||
  1543. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1544. {
  1545. // note that we do not recognize directories from files here
  1546. FTransferResumeList->Add(ProgressData.FullFileName);
  1547. }
  1548. }
  1549. }
  1550. }
  1551. //---------------------------------------------------------------------------
  1552. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1553. const TDateTime & StartTime)
  1554. {
  1555. if (GUIConfiguration->BeepOnFinish &&
  1556. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1557. {
  1558. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1559. DWORD Sound;
  1560. if (!ExtractFileExt(BeepSound).IsEmpty())
  1561. {
  1562. Sound = SND_FILENAME;
  1563. }
  1564. else
  1565. {
  1566. Sound = SND_ALIAS;
  1567. }
  1568. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1569. }
  1570. }
  1571. //---------------------------------------------------------------------------
  1572. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1573. TFileOperationProgressType & ProgressData)
  1574. {
  1575. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1576. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1577. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1578. FileOperationProgress(ProgressData);
  1579. }
  1580. //---------------------------------------------------------------------------
  1581. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1582. {
  1583. UnicodeString Result;
  1584. if (FProgressForm != NULL)
  1585. {
  1586. Result = FProgressForm->ProgressStr();
  1587. }
  1588. return Result;
  1589. }
  1590. //---------------------------------------------------------------------------
  1591. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1592. bool DragDrop)
  1593. {
  1594. return (!DragDrop && (DropSourceControl == NULL)) ||
  1595. (DropSourceControl == DirView(osOther));
  1596. }
  1597. //---------------------------------------------------------------------------
  1598. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1599. {
  1600. TCustomDirView * ADirView = DirView(Side);
  1601. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1602. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1603. // this can happen when local drive is unplugged in the middle of the operation
  1604. if (Item != NULL)
  1605. {
  1606. if (Unselect)
  1607. {
  1608. Item->Selected = false;
  1609. }
  1610. ADirView->MakeProgressVisible(Item);
  1611. }
  1612. return Item;
  1613. }
  1614. //---------------------------------------------------------------------------
  1615. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1616. TFileOperation Operation, TOperationSide Side,
  1617. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1618. TOnceDoneOperation & OnceDoneOperation)
  1619. {
  1620. if (!FAutoOperation)
  1621. {
  1622. // no selection on "/upload", form serves only as event handler
  1623. // (it is not displayed)
  1624. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1625. ((Operation == FPrimaryOperation) ||
  1626. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1627. {
  1628. TOperationSide DViewSide;
  1629. if ((FProgressSide != osCurrent) &&
  1630. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1631. {
  1632. // assume the operation is over the focused panel
  1633. DViewSide = FProgressSide;
  1634. }
  1635. else
  1636. {
  1637. DViewSide = Side;
  1638. }
  1639. if (FOnFileOperationFinished != NULL)
  1640. {
  1641. FOnFileOperationFinished(DViewSide, FileName, Success);
  1642. }
  1643. else
  1644. {
  1645. VisualiseOperationFinished(DViewSide, FileName, Success);
  1646. }
  1647. }
  1648. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1649. {
  1650. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1651. {
  1652. if (Side == osLocal)
  1653. {
  1654. Configuration->Usage->Inc(L"UploadedFiles");
  1655. }
  1656. else
  1657. {
  1658. Configuration->Usage->Inc(L"DownloadedFiles");
  1659. }
  1660. }
  1661. }
  1662. }
  1663. if (Success && (FSynchronizeController != NULL))
  1664. {
  1665. DebugAssert(!IsSideLocalBrowser(osRemote));
  1666. if (Operation == foCopy)
  1667. {
  1668. DebugAssert(Side == osLocal);
  1669. FSynchronizeController->LogOperation(soUpload, FileName);
  1670. }
  1671. else if (Operation == foDelete)
  1672. {
  1673. DebugAssert(Side == osRemote);
  1674. FSynchronizeController->LogOperation(soDelete, FileName);
  1675. }
  1676. }
  1677. if (FProgressForm)
  1678. {
  1679. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1680. }
  1681. }
  1682. //---------------------------------------------------------------------------
  1683. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1684. TFileOperation Operation, TOperationSide Side,
  1685. bool Temp, const UnicodeString & FileName, Boolean Success,
  1686. TOnceDoneOperation & OnceDoneOperation)
  1687. {
  1688. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1689. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1690. OnceDoneOperation);
  1691. }
  1692. //---------------------------------------------------------------------------
  1693. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1694. {
  1695. return false;
  1696. }
  1697. //---------------------------------------------------------------------------
  1698. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1699. {
  1700. return false;
  1701. }
  1702. //---------------------------------------------------------------------------
  1703. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1704. {
  1705. return false;
  1706. }
  1707. //---------------------------------------------------------------------------
  1708. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1709. {
  1710. return NULL;
  1711. }
  1712. //---------------------------------------------------------------------------
  1713. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1714. {
  1715. DebugAssert(GetSide(Side) == osRemote);
  1716. DebugUsedParam(Side);
  1717. return RemoteDirView;
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1721. {
  1722. DebugAssert(GetSide(Side) == osRemote);
  1723. DebugUsedParam(Side);
  1724. return RemoteDriveView;
  1725. }
  1726. //---------------------------------------------------------------------------
  1727. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1728. {
  1729. DebugAssert(GetSide(Side) == osRemote);
  1730. DebugUsedParam(Side);
  1731. return HasActiveTerminal();
  1732. }
  1733. //---------------------------------------------------------------------------
  1734. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1735. TOperationSide Side, int FilesOnly)
  1736. {
  1737. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1738. }
  1739. //---------------------------------------------------------------------------
  1740. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1741. TOperationSide Side, int FilesOnly)
  1742. {
  1743. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1744. }
  1745. //---------------------------------------------------------------------------
  1746. struct THistoryItemData
  1747. {
  1748. short int Side;
  1749. short int Index;
  1750. };
  1751. //---------------------------------------------------------------------------
  1752. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1753. {
  1754. DirView(Side)->HistoryGo(Index);
  1755. }
  1756. //---------------------------------------------------------------------------
  1757. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1758. {
  1759. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1760. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1761. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1762. }
  1763. //---------------------------------------------------------------------------
  1764. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1765. bool Back)
  1766. {
  1767. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1768. {
  1769. TCustomDirView * DView = DirView(Side);
  1770. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1771. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1772. if (ICount > 10)
  1773. {
  1774. ICount = 10;
  1775. }
  1776. Menu->Items->Clear();
  1777. THistoryItemData Data;
  1778. Data.Side = Side;
  1779. for (short int i = 1; i <= ICount; i++)
  1780. {
  1781. TTBCustomItem * Item = new TTBXItem(Menu);
  1782. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1783. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1784. Item->Hint = DView->HistoryPath[Data.Index];
  1785. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1786. Item->Tag = *reinterpret_cast<int*>(&Data);
  1787. Item->OnClick = HistoryItemClick;
  1788. Menu->Items->Add(Item);
  1789. }
  1790. }
  1791. }
  1792. //---------------------------------------------------------------------------
  1793. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1794. TOperationSide Side, bool Back)
  1795. {
  1796. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1797. {
  1798. // workaround
  1799. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1800. // operator new allocates memory in Pascal code, but calls inline
  1801. // contructor in C++, leading in problems, the function does
  1802. // both in Pascal code
  1803. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1804. UpdateHistoryMenu(Side, Back);
  1805. }
  1806. return FHistoryMenu[Side == osLocal][Back];
  1807. }
  1808. //---------------------------------------------------------------------------
  1809. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1810. TCustomDirView *Sender)
  1811. {
  1812. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1813. UpdateHistoryMenu(Side, true);
  1814. UpdateHistoryMenu(Side, false);
  1815. }
  1816. //---------------------------------------------------------------------------
  1817. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1818. {
  1819. // remote custom commands can be executed only if the server supports shell commands
  1820. // or have secondary shell
  1821. return HasActiveTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1822. }
  1823. //---------------------------------------------------------------------------
  1824. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1825. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1826. {
  1827. // -1 = hidden, 0 = disabled, 1 = enabled
  1828. int Result;
  1829. TFileCustomCommand RemoteCustomCommand;
  1830. TLocalCustomCommand LocalCustomCommand;
  1831. TFileCustomCommand * NonInteractiveCustomCommand =
  1832. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1833. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1834. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1835. if (FLAGCLEAR(Command.Params, ccLocal))
  1836. {
  1837. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1838. // custom command that does not operate with files can be executed anytime ...
  1839. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1840. {
  1841. // ... but do not show such command in remote file menu
  1842. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1843. {
  1844. Result = AllowedState;
  1845. }
  1846. else
  1847. {
  1848. Result = -1;
  1849. }
  1850. }
  1851. else
  1852. {
  1853. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1854. {
  1855. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1856. }
  1857. else
  1858. {
  1859. Result = -1;
  1860. }
  1861. }
  1862. }
  1863. else
  1864. {
  1865. // custom command that does not operate with files can be executed anytime
  1866. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1867. {
  1868. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1869. }
  1870. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1871. {
  1872. if ((ListType == ccltAll) || (ListType == ccltFile))
  1873. {
  1874. // special case is "diff"-style command that can be executed over any side,
  1875. // if we have both sides
  1876. Result =
  1877. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1878. // directly (instead of EnableSelectedOperation) to pass
  1879. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1880. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1881. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1882. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1883. }
  1884. else if (ListType == ccltBoth)
  1885. {
  1886. DebugAssert(!IsLocalBrowserMode());
  1887. Result = 1;
  1888. }
  1889. else
  1890. {
  1891. Result = -1;
  1892. }
  1893. }
  1894. else
  1895. {
  1896. if ((ListType == ccltAll) ||
  1897. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1898. {
  1899. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1900. }
  1901. else
  1902. {
  1903. Result = -1;
  1904. }
  1905. }
  1906. if ((Result > 0) &&
  1907. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1908. !HasActiveTerminal())
  1909. {
  1910. Result = 0;
  1911. }
  1912. }
  1913. return Result;
  1914. }
  1915. //---------------------------------------------------------------------------
  1916. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1917. TStrings * FileList, const TCustomCommandType & ACommand,
  1918. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1919. {
  1920. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1921. {
  1922. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1923. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1924. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1925. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1926. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1927. bool Capture =
  1928. FLAGSET(ACommand.Params, ccShowResults) ||
  1929. FLAGSET(ACommand.Params, ccCopyResults) ||
  1930. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1931. TCaptureOutputEvent OutputEvent = NULL;
  1932. DebugAssert(FCapturedLog == NULL);
  1933. if (Capture)
  1934. {
  1935. FCapturedLog = new TStringList();
  1936. OutputEvent = TerminalCaptureLog;
  1937. }
  1938. try
  1939. {
  1940. if (!RemoteCustomCommand.IsFileCommand(Command))
  1941. {
  1942. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1943. OutputEvent);
  1944. }
  1945. else
  1946. {
  1947. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1948. }
  1949. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1950. {
  1951. if (FLAGSET(ACommand.Params, ccCopyResults))
  1952. {
  1953. CopyToClipboard(FCapturedLog);
  1954. }
  1955. if (FLAGSET(ACommand.Params, ccShowResults))
  1956. {
  1957. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1958. }
  1959. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1960. {
  1961. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1962. }
  1963. }
  1964. }
  1965. __finally
  1966. {
  1967. SAFE_DESTROY(FCapturedLog);
  1968. }
  1969. }
  1970. }
  1971. //---------------------------------------------------------------------------
  1972. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1973. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1974. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1975. {
  1976. DebugAssert(!IsLocalBrowserMode());
  1977. TStrings * LocalFileList = NULL;
  1978. TStrings * RemoteFileList = NULL;
  1979. TStrings * RemoteFileListFull = NULL;
  1980. try
  1981. {
  1982. if (LocalFileCommand)
  1983. {
  1984. if (ALocalFileList == NULL)
  1985. {
  1986. DebugAssert(HasDirView[osLocal]);
  1987. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1988. // directly (instead of EnableSelectedOperation) to pass
  1989. // false to FocusedFileOnlyWhenFocused
  1990. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  1991. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  1992. }
  1993. else
  1994. {
  1995. LocalFileList = ALocalFileList;
  1996. }
  1997. if (FileListCommand)
  1998. {
  1999. if (LocalFileList->Count != 1)
  2000. {
  2001. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2002. }
  2003. }
  2004. else
  2005. {
  2006. if ((LocalFileList->Count != 1) &&
  2007. (FileList->Count != 1) &&
  2008. (LocalFileList->Count != FileList->Count))
  2009. {
  2010. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2011. }
  2012. }
  2013. }
  2014. UnicodeString RootTempDir;
  2015. UnicodeString TempDir;
  2016. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2017. if (!RemoteFiles)
  2018. {
  2019. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true, true);
  2020. }
  2021. try
  2022. {
  2023. TDateTimes RemoteFileTimes;
  2024. if (RemoteFiles)
  2025. {
  2026. RemoteFileList = FileList;
  2027. }
  2028. else
  2029. {
  2030. RemoteFileList = new TStringList();
  2031. TMakeLocalFileListParams MakeFileListParam;
  2032. MakeFileListParam.FileList = RemoteFileList;
  2033. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2034. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2035. MakeFileListParam.Recursive =
  2036. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2037. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2038. if (!MakeFileListParam.Recursive)
  2039. {
  2040. RemoteFileTimes.clear();
  2041. RemoteFileListFull = new TStringList();
  2042. MakeFileListParam.FileList = RemoteFileListFull;
  2043. MakeFileListParam.Recursive = true;
  2044. MakeFileListParam.IncludeDirs = false;
  2045. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2046. }
  2047. else
  2048. {
  2049. RemoteFileListFull = RemoteFileList;
  2050. }
  2051. }
  2052. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2053. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2054. if (!NonBlocking)
  2055. {
  2056. int Count;
  2057. if (FileListCommand)
  2058. {
  2059. Count = 1;
  2060. }
  2061. else if (LocalFileCommand)
  2062. {
  2063. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2064. }
  2065. else
  2066. {
  2067. Count = RemoteFileList->Count;
  2068. }
  2069. Progress.Start(foCustomCommand, osRemote, Count);
  2070. DebugAssert(FProgressForm != NULL);
  2071. FProgressForm->ReadOnly = true;
  2072. }
  2073. try
  2074. {
  2075. if (FileListCommand)
  2076. {
  2077. UnicodeString LocalFile;
  2078. // MakeFileList does not delimit filenames
  2079. UnicodeString FileList = MakeFileList(RemoteFileList);
  2080. if (LocalFileCommand)
  2081. {
  2082. DebugAssert(LocalFileList->Count == 1);
  2083. LocalFile = LocalFileList->Strings[0];
  2084. }
  2085. TLocalCustomCommand CustomCommand(Data,
  2086. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2087. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2088. if (NonBlocking)
  2089. {
  2090. DebugAssert(!POutput);
  2091. ExecuteShellChecked(ShellCommand);
  2092. }
  2093. else
  2094. {
  2095. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2096. }
  2097. }
  2098. else if (LocalFileCommand)
  2099. {
  2100. if (LocalFileList->Count == 1)
  2101. {
  2102. UnicodeString LocalFile = LocalFileList->Strings[0];
  2103. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2104. {
  2105. UnicodeString FileName = RemoteFileList->Strings[Index];
  2106. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2107. Progress.SetFile(FileNameForProgress);
  2108. TLocalCustomCommand CustomCommand(Data,
  2109. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2110. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2111. TOnceDoneOperation OnceDoneOperation;
  2112. // Do not unselect anything, as it won't work with two panels anyway
  2113. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2114. }
  2115. }
  2116. else if (RemoteFileList->Count == 1)
  2117. {
  2118. UnicodeString FileName = RemoteFileList->Strings[0];
  2119. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2120. {
  2121. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2122. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2123. Progress.SetFile(LocalFileNameOnly);
  2124. TLocalCustomCommand CustomCommand(
  2125. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2126. FileName, LocalFileName, L"");
  2127. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2128. TOnceDoneOperation OnceDoneOperation;
  2129. // Do not unselect anything, as it won't work with two panels anyway
  2130. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2131. }
  2132. }
  2133. else
  2134. {
  2135. if (LocalFileList->Count != RemoteFileList->Count)
  2136. {
  2137. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2138. }
  2139. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2140. {
  2141. UnicodeString FileName = RemoteFileList->Strings[Index];
  2142. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2143. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2144. Progress.SetFile(LocalFileNameOnly); // sic
  2145. TLocalCustomCommand CustomCommand(
  2146. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2147. FileName, LocalFileName, L"");
  2148. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2149. TOnceDoneOperation OnceDoneOperation;
  2150. // Do not unselect anything, as it won't work with two panels anyway
  2151. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2152. }
  2153. }
  2154. }
  2155. else
  2156. {
  2157. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2158. {
  2159. UnicodeString FileName = RemoteFileList->Strings[Index];
  2160. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2161. Progress.SetFile(FileNameForProgress);
  2162. TLocalCustomCommand CustomCommand(Data,
  2163. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2164. FileName, L"", L"");
  2165. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2166. TOnceDoneOperation OnceDoneOperation;
  2167. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2168. }
  2169. }
  2170. }
  2171. __finally
  2172. {
  2173. if (!NonBlocking)
  2174. {
  2175. Progress.Stop();
  2176. }
  2177. }
  2178. DebugAssert(!FAutoOperation);
  2179. if (!RemoteFiles)
  2180. {
  2181. TempDir = IncludeTrailingBackslash(TempDir);
  2182. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2183. {
  2184. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2185. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2186. // Skip directories, process only nested files.
  2187. // The check is redundant as FileAge fails for directories anyway.
  2188. !DirectoryExists(FileName))
  2189. {
  2190. UnicodeString RemoteDir =
  2191. UnixExtractFileDir(
  2192. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2193. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  2194. TDateTime NewTime;
  2195. if (FileAge(FileName, NewTime) &&
  2196. (NewTime != RemoteFileTimes[Index]))
  2197. {
  2198. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2199. TemporaryFileCopyParam(CopyParam);
  2200. CopyParam.FileMask = L"";
  2201. FAutoOperation = true;
  2202. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2203. TemporaryFilesList->Add(FileName);
  2204. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2205. }
  2206. }
  2207. }
  2208. }
  2209. }
  2210. __finally
  2211. {
  2212. FAutoOperation = false;
  2213. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2214. {
  2215. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  2216. }
  2217. }
  2218. }
  2219. __finally
  2220. {
  2221. if (RemoteFileList != FileList)
  2222. {
  2223. delete RemoteFileList;
  2224. }
  2225. if (LocalFileList != ALocalFileList)
  2226. {
  2227. delete LocalFileList;
  2228. }
  2229. if (RemoteFileListFull != RemoteFileList)
  2230. {
  2231. delete RemoteFileListFull;
  2232. }
  2233. }
  2234. }
  2235. //---------------------------------------------------------------------------
  2236. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2237. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2238. bool FileListCommand, UnicodeString * POutput)
  2239. {
  2240. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2241. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2242. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2243. {
  2244. UnicodeString FileName = SelectedFileList->Strings[Index];
  2245. if (DirectoryExists(FileName))
  2246. {
  2247. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2248. {
  2249. LocalFileList->Add(FileName);
  2250. }
  2251. if (FLAGSET(ACommand.Params, ccRecursive))
  2252. {
  2253. TMakeLocalFileListParams MakeFileListParam;
  2254. MakeFileListParam.FileList = LocalFileList.get();
  2255. MakeFileListParam.FileTimes = NULL;
  2256. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2257. MakeFileListParam.Recursive = true;
  2258. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2259. }
  2260. }
  2261. else
  2262. {
  2263. LocalFileList->Add(FileName);
  2264. }
  2265. }
  2266. UnicodeString RemotePath;
  2267. if (Terminal != NULL)
  2268. {
  2269. RemotePath = Terminal->CurrentDirectory;
  2270. }
  2271. if (FileListCommand)
  2272. {
  2273. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2274. TLocalCustomCommand CustomCommand(
  2275. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2276. L"", L"", FileList);
  2277. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2278. }
  2279. else
  2280. {
  2281. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2282. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2283. DebugAssert(FProgressForm != NULL);
  2284. FProgressForm->ReadOnly = true;
  2285. try
  2286. {
  2287. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2288. {
  2289. UnicodeString FileName = LocalFileList->Strings[Index];
  2290. Progress.SetFile(FileName);
  2291. TLocalCustomCommand CustomCommand(
  2292. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2293. FileName, L"", L"");
  2294. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2295. TOnceDoneOperation OnceDoneOperation;
  2296. Progress.Finish(FileName, true, OnceDoneOperation);
  2297. }
  2298. }
  2299. __finally
  2300. {
  2301. Progress.Stop();
  2302. }
  2303. }
  2304. }
  2305. //---------------------------------------------------------------------------
  2306. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2307. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2308. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2309. {
  2310. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2311. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2312. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2313. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2314. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2315. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2316. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2317. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2318. std::unique_ptr<UnicodeString> POutput;
  2319. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2320. FLAGSET(ACommand.Params, ccCopyResults))
  2321. {
  2322. POutput.reset(new UnicodeString());
  2323. }
  2324. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  2325. FProgressSide = FCurrentSide;
  2326. if (!LocalCustomCommand.IsFileCommand(Command))
  2327. {
  2328. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2329. }
  2330. // remote files?
  2331. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2332. {
  2333. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2334. }
  2335. // local files
  2336. else
  2337. {
  2338. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2339. }
  2340. if (POutput.get() != NULL)
  2341. {
  2342. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2343. int P = POutput->Pos(sLineBreak);
  2344. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2345. {
  2346. POutput->SetLength(P - 1);
  2347. }
  2348. // Copy even empty output to clipboard
  2349. if (FLAGSET(ACommand.Params, ccCopyResults))
  2350. {
  2351. CopyToClipboard(*POutput);
  2352. }
  2353. // But do not show an empty message box.
  2354. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2355. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2356. !POutput->IsEmpty())
  2357. {
  2358. TClipboardHandler ClipboardHandler;
  2359. ClipboardHandler.Text = *POutput;
  2360. TMessageParams Params;
  2361. TQueryButtonAlias Aliases[1];
  2362. Aliases[0].Button = qaRetry;
  2363. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2364. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2365. Params.Aliases = Aliases;
  2366. Params.AliasesCount = LENOF(Aliases);
  2367. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2368. }
  2369. }
  2370. }
  2371. //---------------------------------------------------------------------------
  2372. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2373. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2374. {
  2375. TCustomCommandData Data;
  2376. UnicodeString Site;
  2377. UnicodeString RemotePath;
  2378. if (HasActiveTerminal())
  2379. {
  2380. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2381. Data = TCustomCommandData(SessionData.get());
  2382. Site = Terminal->SessionData->SessionKey;
  2383. RemotePath = Terminal->CurrentDirectory;
  2384. }
  2385. UnicodeString HelpKeyword = ACommand.HomePage;
  2386. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2387. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2388. {
  2389. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2390. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2391. {
  2392. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2393. }
  2394. else
  2395. {
  2396. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2397. }
  2398. if (!DoCustomCommandOptionsDialog(
  2399. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2400. {
  2401. Abort();
  2402. }
  2403. }
  2404. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2405. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2406. {
  2407. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2408. }
  2409. else
  2410. {
  2411. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2412. }
  2413. }
  2414. //---------------------------------------------------------------------------
  2415. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2416. const TCustomCommandType & Command)
  2417. {
  2418. DebugAssert(FCustomCommandLocalFileList != NULL);
  2419. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2420. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2421. TStrings * LocalFileList = new TStringList();
  2422. TStrings * RemoteFileList = new TStringList();
  2423. try
  2424. {
  2425. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2426. {
  2427. LocalFileList->Clear();
  2428. LocalFileList->AddObject(
  2429. FCustomCommandLocalFileList->Strings[Index],
  2430. FCustomCommandLocalFileList->Objects[Index]);
  2431. RemoteFileList->Clear();
  2432. RemoteFileList->AddObject(
  2433. FCustomCommandRemoteFileList->Strings[Index],
  2434. FCustomCommandRemoteFileList->Objects[Index]);
  2435. CustomCommand(RemoteFileList, Command, LocalFileList);
  2436. }
  2437. }
  2438. __finally
  2439. {
  2440. delete LocalFileList;
  2441. delete RemoteFileList;
  2442. }
  2443. }
  2444. //---------------------------------------------------------------------------
  2445. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2446. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2447. {
  2448. delete FCustomCommandLocalFileList;
  2449. delete FCustomCommandRemoteFileList;
  2450. // takeover ownership,
  2451. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2452. FCustomCommandLocalFileList = LocalFileList;
  2453. FCustomCommandRemoteFileList = RemoteFileList;
  2454. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2455. if (Button != NULL)
  2456. {
  2457. FCustomCommandMenu->Items->Clear();
  2458. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2459. MenuPopup(FCustomCommandMenu, Button);
  2460. }
  2461. else
  2462. {
  2463. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2464. }
  2465. }
  2466. //---------------------------------------------------------------------------
  2467. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2468. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2469. {
  2470. DebugAssert(FCapturedLog != NULL);
  2471. if ((OutputType == cotOutput) || (OutputType == cotError))
  2472. {
  2473. FCapturedLog->Add(AddedLine);
  2474. }
  2475. }
  2476. //---------------------------------------------------------------------------
  2477. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2478. TOperationSide Side)
  2479. {
  2480. return
  2481. (Side == osOther) &&
  2482. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2483. }
  2484. //---------------------------------------------------------------------------
  2485. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2486. TOperationSide Side, TTBXCustomItem * Item,
  2487. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2488. {
  2489. TCustomDirView * DView = DirView(Side);
  2490. bool IsDefault = false;
  2491. if (DView->ItemFocused != NULL)
  2492. {
  2493. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2494. TResolvedDoubleClickAction DefaultAction =
  2495. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2496. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2497. }
  2498. TTBItemOptions O = Item->Options;
  2499. if (IsDefault)
  2500. {
  2501. Item->Options = O << tboDefault;
  2502. }
  2503. else
  2504. {
  2505. Item->Options = O >> tboDefault;
  2506. }
  2507. }
  2508. //---------------------------------------------------------------------------
  2509. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2510. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2511. {
  2512. TCustomDirView * DView = DirView(Side);
  2513. TListItem * Item = DView->ItemFocused;
  2514. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2515. EnableFocusedOperation[Side])
  2516. {
  2517. TPoint ClientPoint;
  2518. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2519. TPoint(0, 0) : MousePos;
  2520. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2521. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2522. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2523. }
  2524. }
  2525. //---------------------------------------------------------------------------
  2526. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2527. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2528. {
  2529. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2530. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2531. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2532. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2533. Handled = true;
  2534. }
  2535. //---------------------------------------------------------------------------
  2536. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2537. {
  2538. }
  2539. //---------------------------------------------------------------------------
  2540. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2541. {
  2542. DebugAssert(FErrorList == NULL);
  2543. if (WinConfiguration->ContinueOnError)
  2544. {
  2545. FErrorList = new TStringList();
  2546. Configuration->Usage->Inc(L"ContinuationsOnError");
  2547. }
  2548. NonVisualDataModule->StartBusy();
  2549. }
  2550. //---------------------------------------------------------------------------
  2551. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2552. {
  2553. NonVisualDataModule->EndBusy();
  2554. if (FErrorList)
  2555. {
  2556. HandleErrorList(FErrorList);
  2557. }
  2558. }
  2559. //---------------------------------------------------------------------------
  2560. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2561. const TCopyParamType & CopyParam)
  2562. {
  2563. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2564. {
  2565. Configuration->Usage->Inc(L"FileMaskUses");
  2566. }
  2567. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2568. {
  2569. Configuration->Usage->Inc(L"OperationMaskUses");
  2570. }
  2571. }
  2572. //---------------------------------------------------------------------------
  2573. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2574. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2575. {
  2576. DebugAssert(!IsLocalBrowserMode());
  2577. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2578. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2579. TTransferOperationParam DefaultParam;
  2580. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2581. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2582. switch (Param.Queue)
  2583. {
  2584. case asOn:
  2585. CopyParam.Queue = true;
  2586. break;
  2587. case asOff:
  2588. CopyParam.Queue = false;
  2589. break;
  2590. case asAuto:
  2591. default:
  2592. // keep default
  2593. break;
  2594. }
  2595. bool Result =
  2596. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2597. if (Result)
  2598. {
  2599. DebugAssert(Terminal);
  2600. bool SelectionRestored = false;
  2601. TCustomDirView * DView = NULL;
  2602. if (HasDirView[Side])
  2603. {
  2604. DView = DirView(Side);
  2605. DView->SaveSelection();
  2606. DView->SaveSelectedNames();
  2607. }
  2608. UpdateCopyParamCounters(CopyParam);
  2609. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2610. DebugAssert(FTransferResumeList == NULL);
  2611. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2612. FMoveToQueue = false;
  2613. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2614. try
  2615. {
  2616. TStrings * PermanentFileList;
  2617. std::unique_ptr<TStrings> PermanentFileListOwner;
  2618. try
  2619. {
  2620. if (Side == osLocal)
  2621. {
  2622. PermanentFileList = FileList;
  2623. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2624. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2625. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2626. if (Operation == foMove)
  2627. {
  2628. ReloadLocalDirectory();
  2629. if (DView != NULL)
  2630. {
  2631. DView->RestoreSelection();
  2632. }
  2633. SelectionRestored = true;
  2634. }
  2635. }
  2636. else
  2637. {
  2638. // Clone the file list as it may refer to current directory files,
  2639. // which get destroyed, when the source directory is reloaded after foMove operation.
  2640. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2641. // But for a hotfix, we are not going to do such a big change.
  2642. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2643. PermanentFileList = PermanentFileListOwner.get();
  2644. try
  2645. {
  2646. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2647. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2648. }
  2649. __finally
  2650. {
  2651. if (Operation == foMove)
  2652. {
  2653. if (DView != NULL)
  2654. {
  2655. DView->RestoreSelection();
  2656. }
  2657. SelectionRestored = true;
  2658. }
  2659. ReloadLocalDirectory(Param.TargetDirectory);
  2660. }
  2661. }
  2662. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2663. if (FMoveToQueue)
  2664. {
  2665. Abort();
  2666. }
  2667. }
  2668. catch (EAbort &)
  2669. {
  2670. if (FMoveToQueue)
  2671. {
  2672. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2673. DebugAssert(CopyParam.TransferSkipList == NULL);
  2674. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2675. if (TransferResumeList->Count > 0)
  2676. {
  2677. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2678. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2679. }
  2680. CopyParam.TransferSkipList = TransferResumeList.release();
  2681. // not really needed, just to keep it consistent with TransferResumeList
  2682. FTransferResumeList = NULL;
  2683. FMoveToQueue = false;
  2684. Configuration->Usage->Inc("MovesToBackground");
  2685. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2686. ClearTransferSourceSelection(Direction);
  2687. }
  2688. throw;
  2689. }
  2690. }
  2691. __finally
  2692. {
  2693. if (!SelectionRestored && (DView != NULL))
  2694. {
  2695. DView->DiscardSavedSelection();
  2696. }
  2697. FTransferResumeList = NULL;
  2698. }
  2699. }
  2700. return Result;
  2701. }
  2702. //---------------------------------------------------------------------------
  2703. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2704. TOperationSide Side, TStrings * FileList, void * Param)
  2705. {
  2706. DebugAssert(FileList->Count);
  2707. // We deliberately do not toggle alternative flag (Param), but use OR,
  2708. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2709. // shortcut of CurrentDeleteAlternativeAction
  2710. bool Alternative =
  2711. bool(Param) || UseAlternativeFunction();
  2712. bool Recycle;
  2713. if (IsSideLocalBrowser(Side))
  2714. {
  2715. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2716. }
  2717. else
  2718. {
  2719. Recycle =
  2720. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2721. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2722. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2723. }
  2724. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2725. if (!Result)
  2726. {
  2727. UnicodeString Query;
  2728. if (FileList->Count == 1)
  2729. {
  2730. if (IsSideLocalBrowser(Side))
  2731. {
  2732. Query = ExtractFileName(FileList->Strings[0]);
  2733. }
  2734. else
  2735. {
  2736. Query = UnixExtractFileName(FileList->Strings[0]);
  2737. }
  2738. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2739. }
  2740. else
  2741. {
  2742. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2743. }
  2744. TMessageParams Params(mpNeverAskAgainCheck);
  2745. Params.ImageName = L"Delete file";
  2746. unsigned int Answer =
  2747. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2748. if (Answer == qaNeverAskAgain)
  2749. {
  2750. Result = true;
  2751. if (Recycle)
  2752. {
  2753. WinConfiguration->ConfirmRecycling = false;
  2754. }
  2755. else
  2756. {
  2757. WinConfiguration->ConfirmDeleting = false;
  2758. }
  2759. }
  2760. else
  2761. {
  2762. Result = (Answer == qaOK);
  2763. }
  2764. }
  2765. if (Result)
  2766. {
  2767. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2768. }
  2769. return Result;
  2770. }
  2771. //---------------------------------------------------------------------------
  2772. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2773. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2774. {
  2775. TAutoBatch AutoBatch(this);
  2776. bool Result;
  2777. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2778. {
  2779. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2780. }
  2781. else if (Operation == foRename)
  2782. {
  2783. DebugAssert(DirView(Side)->ItemFocused);
  2784. DirView(Side)->ItemFocused->EditCaption();
  2785. Result = true;
  2786. }
  2787. else if (Operation == foDelete)
  2788. {
  2789. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2790. }
  2791. else if (Operation == foSetProperties)
  2792. {
  2793. DirView(osRemote)->SaveSelectedNames();
  2794. Result = SetProperties(Side, FileList);
  2795. }
  2796. else if (Operation == foCustomCommand)
  2797. {
  2798. DebugAssert(Param);
  2799. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2800. DirView(osRemote)->SaveSelectedNames();
  2801. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2802. CustomCommand(FileList, *Command, NULL);
  2803. Result = true;
  2804. }
  2805. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2806. {
  2807. DebugAssert(!IsSideLocalBrowser(Side));
  2808. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2809. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2810. }
  2811. else if (Operation == foLock)
  2812. {
  2813. DebugAssert(!IsSideLocalBrowser(Side));
  2814. LockFiles(FileList, true);
  2815. Result = true;
  2816. }
  2817. else if (Operation == foUnlock)
  2818. {
  2819. DebugAssert(!IsSideLocalBrowser(Side));
  2820. LockFiles(FileList, false);
  2821. Result = true;
  2822. }
  2823. else
  2824. {
  2825. DebugFail();
  2826. }
  2827. return Result;
  2828. }
  2829. //---------------------------------------------------------------------------
  2830. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2831. {
  2832. if (Side == osCurrent)
  2833. {
  2834. Side = FCurrentSide;
  2835. }
  2836. return Side;
  2837. }
  2838. //---------------------------------------------------------------------------
  2839. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2840. {
  2841. TOperationSide Result;
  2842. switch (GetSide(Side))
  2843. {
  2844. case osLocal:
  2845. Result = osOther;
  2846. break;
  2847. case osOther:
  2848. Result = osLocal;
  2849. break;
  2850. default:
  2851. DebugFail();
  2852. Abort();
  2853. }
  2854. return Result;
  2855. }
  2856. //---------------------------------------------------------------------------
  2857. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2858. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2859. {
  2860. Side = GetSide(Side);
  2861. bool FullPath = IsSideLocalBrowser(Side);
  2862. TCustomDirView * ADirView = DirView(Side);
  2863. std::unique_ptr<TStringList> FileList(new TStringList());
  2864. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2865. bool ReloadProperties =
  2866. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2867. DebugAlwaysTrue(HasActiveTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2868. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2869. if (Result && ReloadProperties)
  2870. {
  2871. std::unique_ptr<TStringList> FileList2(new TStringList());
  2872. FileList->CaseSensitive = true;
  2873. FileList->Sort();
  2874. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2875. {
  2876. TListItem * Item = ADirView->Items->Item[Index];
  2877. UnicodeString FileName = ADirView->ItemFileName(Item);
  2878. int Index2;
  2879. if (FileList->Find(FileName, Index2))
  2880. {
  2881. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2882. }
  2883. }
  2884. LoadFilesProperties(FileList2.get());
  2885. }
  2886. return Result;
  2887. }
  2888. //---------------------------------------------------------------------------
  2889. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2890. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2891. bool NoConfirmation, void * Param)
  2892. {
  2893. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2894. {
  2895. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2896. {
  2897. DebugAssert(!IsLocalBrowserMode());
  2898. if (GetSide(Side) == osLocal)
  2899. {
  2900. Configuration->Usage->Inc(L"UploadsCommand");
  2901. }
  2902. else
  2903. {
  2904. Configuration->Usage->Inc(L"DownloadsCommand");
  2905. }
  2906. }
  2907. }
  2908. }
  2909. //---------------------------------------------------------------------------
  2910. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2911. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2912. {
  2913. TTransferOperationParam Param;
  2914. if ((WinConfiguration->Interface != ifCommander) ||
  2915. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2916. {
  2917. Flags &= ~cocShortCutHint;
  2918. }
  2919. TCustomDirView * DView = DirView(Side);
  2920. Param.Options =
  2921. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2922. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2923. if (FLAGSET(Flags, cocQueue))
  2924. {
  2925. Param.Queue = asOn;
  2926. }
  2927. else if (FLAGSET(Flags, cocNonQueue))
  2928. {
  2929. Param.Queue = asOff;
  2930. }
  2931. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2932. }
  2933. //---------------------------------------------------------------------------
  2934. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2935. {
  2936. int Count = ErrorList->Count;
  2937. try
  2938. {
  2939. if (ErrorList->Count)
  2940. {
  2941. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2942. if (MessageDialog(Message, qtError,
  2943. qaOK | qaCancel, HELP_NONE) == qaOK)
  2944. {
  2945. unsigned int Answer;
  2946. int Index = 0;
  2947. do
  2948. {
  2949. DebugAssert(Index >= 0 && Index < Count);
  2950. TQueryButtonAlias Aliases[2];
  2951. Aliases[0].Button = qaYes;
  2952. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2953. Aliases[1].Button = qaNo;
  2954. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2955. TMessageParams Params;
  2956. Params.Aliases = Aliases;
  2957. Params.AliasesCount = LENOF(Aliases);
  2958. int No = Index + 1;
  2959. UnicodeString Message = ErrorList->Strings[Index];
  2960. UnicodeString AMainInstructions;
  2961. UnicodeString Details;
  2962. if (ExtractMainInstructions(Message, AMainInstructions))
  2963. {
  2964. Details = Message;
  2965. Message = AMainInstructions;
  2966. }
  2967. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2968. Answer = MoreMessageDialog(
  2969. Message,
  2970. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2971. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2972. qaOK, HELP_NONE, &Params);
  2973. if (Answer == qaNo)
  2974. {
  2975. Index++;
  2976. }
  2977. if (Answer == qaYes)
  2978. {
  2979. Index--;
  2980. }
  2981. }
  2982. while (Answer != qaOK);
  2983. }
  2984. }
  2985. }
  2986. __finally
  2987. {
  2988. TStrings * List = ErrorList;
  2989. ErrorList = NULL;
  2990. for (int i = 0; i < Count; i++)
  2991. {
  2992. delete List->Objects[i];
  2993. }
  2994. delete List;
  2995. }
  2996. }
  2997. //---------------------------------------------------------------------------
  2998. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  2999. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3000. {
  3001. // needed for checking filemasks, as there's no directory object
  3002. // associated with the file object
  3003. File->FullFileName = FullFileName;
  3004. TFileMasks::TParams MaskParams;
  3005. MaskParams.Size = File->Size;
  3006. MaskParams.Modification = File->Modification;
  3007. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3008. }
  3009. //---------------------------------------------------------------------------
  3010. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3011. {
  3012. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3013. Side = GetSide(Side);
  3014. TCustomDirView * DView = DirView(Side);
  3015. TListItem * FocusedItem = DView->ItemFocused;
  3016. UnicodeString Name;
  3017. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3018. {
  3019. Name = DView->ItemFileName(FocusedItem);
  3020. }
  3021. else
  3022. {
  3023. Name = LoadStr(NEW_FILE);
  3024. }
  3025. UnicodeString Names = Name;
  3026. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3027. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3028. HELP_EDIT_NEW, History.get(), true, NULL, true, 400))
  3029. {
  3030. while (!Names.IsEmpty())
  3031. {
  3032. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3033. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3034. UnicodeString TargetFileName;
  3035. UnicodeString LocalFileName;
  3036. UnicodeString RootTempDir;
  3037. UnicodeString TempDir;
  3038. UnicodeString RemoteDirectory;
  3039. bool ExistingFile = false;
  3040. if (!IsSideLocalBrowser(Side))
  3041. {
  3042. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3043. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3044. if ((File.get() != NULL) &&
  3045. !File->IsDirectory)
  3046. {
  3047. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3048. ExistingFile = true;
  3049. }
  3050. File.reset(NULL);
  3051. if (!ExistingFile)
  3052. {
  3053. RemoteDirectory = UnixExtractFilePath(Name);
  3054. TemporaryDirectoryForRemoteFiles(
  3055. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3056. TargetFileName = UnixExtractFileName(Name);
  3057. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3058. LocalFileName = TempDir +
  3059. // We probably do not want to trim the VMS version here
  3060. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3061. }
  3062. }
  3063. else
  3064. {
  3065. if (ExtractFilePath(Name).IsEmpty())
  3066. {
  3067. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3068. }
  3069. else
  3070. {
  3071. LocalFileName = ExpandFileName(Name);
  3072. }
  3073. TargetFileName = ExtractFileName(Name);
  3074. }
  3075. if (!ExistingFile)
  3076. {
  3077. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3078. if (NewFile)
  3079. {
  3080. int File = FileCreate(ApiPath(LocalFileName));
  3081. if (File < 0)
  3082. {
  3083. if (!RootTempDir.IsEmpty())
  3084. {
  3085. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  3086. }
  3087. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3088. }
  3089. else
  3090. {
  3091. FileClose(File);
  3092. }
  3093. }
  3094. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3095. const TEditorData * ExternalEditor = NULL;
  3096. TFileMasks::TParams MaskParams; // size not known
  3097. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3098. false, MaskParams);
  3099. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3100. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3101. }
  3102. }
  3103. }
  3104. }
  3105. //---------------------------------------------------------------------------
  3106. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3107. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3108. {
  3109. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3110. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3111. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3112. return
  3113. ((ExecuteFileBy == efInternalEditor)) ||
  3114. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3115. }
  3116. //---------------------------------------------------------------------------
  3117. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3118. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3119. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3120. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3121. {
  3122. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3123. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3124. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3125. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3126. Side = GetSide(Side);
  3127. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3128. if (!IsSideLocalBrowser(Side))
  3129. {
  3130. Data->Terminal = Terminal;
  3131. Data->Queue = Queue;
  3132. Data->SessionData = CloneCurrentSessionData();
  3133. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3134. Data->RemoteDirectory = RemoteDirectory;
  3135. Data->SessionName = Terminal->SessionData->SessionName;
  3136. Data->LocalRootDirectory = LocalRootDirectory;
  3137. Data->OriginalFileName = OriginalFileName;
  3138. Data->Command = L""; // will be changed later for external editor
  3139. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3140. if (WinConfiguration->EditorCheckNotModified)
  3141. {
  3142. Data->SourceTimestamp = SourceTimestamp;
  3143. }
  3144. }
  3145. if (ExecuteFileBy == efInternalEditor)
  3146. {
  3147. if (!IsSideLocalBrowser(Side))
  3148. {
  3149. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3150. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3151. TForm * Editor;
  3152. try
  3153. {
  3154. Editor =
  3155. ShowEditorForm(
  3156. FileName, this,
  3157. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3158. SaveAllInternalEditors, AnyInternalEditorModified,
  3159. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3160. }
  3161. catch(...)
  3162. {
  3163. if (!LocalRootDirectory.IsEmpty())
  3164. {
  3165. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory), false);
  3166. }
  3167. throw;
  3168. }
  3169. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3170. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3171. }
  3172. else
  3173. {
  3174. DebugAssert(!StandaloneOperation);
  3175. TForm * Editor =
  3176. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3177. SaveAllInternalEditors, AnyInternalEditorModified,
  3178. L"", false, SessionColor, -1, NewFile);
  3179. FLocalEditors->Add(Editor);
  3180. }
  3181. }
  3182. else
  3183. {
  3184. HANDLE Process;
  3185. if (ExecuteFileBy == efExternalEditor)
  3186. {
  3187. UnicodeString Program, Params, Dir;
  3188. Data->Command = ExternalEditor->ExternalEditor;
  3189. ReformatFileNameCommand(Data->Command);
  3190. SplitCommand(Data->Command, Program, Params, Dir);
  3191. Params = ExpandFileNameCommand(Params, FileName);
  3192. Program = ExpandEnvironmentVariables(Program);
  3193. if (!ExecuteShell(Program, Params, Process))
  3194. {
  3195. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3196. }
  3197. }
  3198. else
  3199. {
  3200. DebugAssert(!IsSideLocalBrowser(Side));
  3201. if (!ExecuteShell(FileName, L"", Process))
  3202. {
  3203. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3204. }
  3205. }
  3206. if (IsSideLocalBrowser(Side) ||
  3207. ((ExecuteFileBy == efShell) &&
  3208. !WinConfiguration->Editor.SDIShellEditor) ||
  3209. ((ExecuteFileBy == efExternalEditor) &&
  3210. !ExternalEditor->SDIExternalEditor))
  3211. {
  3212. // no need for handle
  3213. if (Process != NULL)
  3214. {
  3215. DebugCheck(CloseHandle(Process));
  3216. }
  3217. Process = INVALID_HANDLE_VALUE;
  3218. }
  3219. else
  3220. {
  3221. if (Process == NULL)
  3222. {
  3223. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3224. }
  3225. }
  3226. if (!IsSideLocalBrowser(Side))
  3227. {
  3228. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3229. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3230. }
  3231. }
  3232. }
  3233. //---------------------------------------------------------------------------
  3234. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3235. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3236. void * /*Arg*/)
  3237. {
  3238. if (Token != NULL)
  3239. {
  3240. EditorFormFileSave(static_cast<TForm *>(Token));
  3241. }
  3242. }
  3243. //---------------------------------------------------------------------------
  3244. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3245. {
  3246. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3247. {
  3248. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3249. }
  3250. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3251. }
  3252. //---------------------------------------------------------------------------
  3253. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3254. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3255. void * Arg)
  3256. {
  3257. if ((Token != NULL) &&
  3258. IsEditorFormModified(static_cast<TForm *>(Token)))
  3259. {
  3260. *static_cast<bool *>(Arg) = true;
  3261. }
  3262. }
  3263. //---------------------------------------------------------------------------
  3264. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3265. TObject * /*Sender*/, bool & Modified)
  3266. {
  3267. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3268. {
  3269. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3270. {
  3271. Modified = true;
  3272. }
  3273. }
  3274. if (!Modified)
  3275. {
  3276. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3277. }
  3278. }
  3279. //---------------------------------------------------------------------------
  3280. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3281. {
  3282. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3283. }
  3284. //---------------------------------------------------------------------------
  3285. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3286. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3287. UnicodeString & Result, UnicodeString & RootDirectory)
  3288. {
  3289. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3290. {
  3291. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3292. Result = RootDirectory;
  3293. }
  3294. else
  3295. {
  3296. RootDirectory = L"";
  3297. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3298. Result = IncludeTrailingBackslash(Result);
  3299. }
  3300. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3301. {
  3302. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3303. }
  3304. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3305. {
  3306. UnicodeString ARemoteDirectory = RemoteDirectory;
  3307. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3308. {
  3309. ARemoteDirectory.Delete(1, 1);
  3310. }
  3311. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3312. }
  3313. if (!ForceDirectories(ApiPath(Result)))
  3314. {
  3315. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3316. }
  3317. }
  3318. //---------------------------------------------------------------------------
  3319. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3320. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3321. bool GetTargetNames, bool AutoOperation, bool SimpleTempDir)
  3322. {
  3323. DebugAssert(!IsLocalBrowserMode());
  3324. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3325. if (ForceText)
  3326. {
  3327. CopyParam.TransferMode = tmAscii;
  3328. }
  3329. TemporaryFileCopyParam(CopyParam);
  3330. if (TempDir.IsEmpty())
  3331. {
  3332. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3333. }
  3334. DebugAssert(!FAutoOperation);
  3335. FAutoOperation = AutoOperation;
  3336. Terminal->ExceptionOnFail = true;
  3337. try
  3338. {
  3339. try
  3340. {
  3341. // turn off confirmations, as for MDI editors we may possibly download
  3342. // the same file over
  3343. Terminal->CopyToLocal(
  3344. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3345. if (GetTargetNames)
  3346. {
  3347. for (int i = 0; i < FileList->Count; i++)
  3348. {
  3349. FileList->Strings[i] =
  3350. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3351. }
  3352. }
  3353. }
  3354. catch(...)
  3355. {
  3356. if (!RootTempDir.IsEmpty())
  3357. {
  3358. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  3359. }
  3360. throw;
  3361. }
  3362. }
  3363. __finally
  3364. {
  3365. FAutoOperation = false;
  3366. Terminal->ExceptionOnFail = false;
  3367. }
  3368. }
  3369. //---------------------------------------------------------------------------
  3370. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3371. {
  3372. // Do not waste time checking for default editor list the next time,
  3373. // or testing if default editor is not notepad.
  3374. bool TryNextTime = false;
  3375. UnicodeString UsageState;
  3376. if (!WinConfiguration->EditorList->IsDefaultList())
  3377. {
  3378. UsageState = "H";
  3379. }
  3380. else
  3381. {
  3382. UnicodeString Executable;
  3383. UnicodeString ExecutableDescription;
  3384. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3385. {
  3386. UnicodeString Message =
  3387. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3388. unsigned int Answer =
  3389. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3390. if (Answer != qaOK)
  3391. {
  3392. UsageState = "R";
  3393. }
  3394. else
  3395. {
  3396. UsageState = "A";
  3397. TEditorData EditorData;
  3398. EditorData.Editor = edExternal;
  3399. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3400. EditorData.ExternalEditorOptionsAutodetect();
  3401. TEditorList EditorList;
  3402. EditorList = *WinConfiguration->EditorList;
  3403. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3404. WinConfiguration->EditorList = &EditorList;
  3405. }
  3406. }
  3407. }
  3408. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3409. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3410. }
  3411. //---------------------------------------------------------------------------
  3412. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3413. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3414. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3415. {
  3416. if (ExecuteFileBy == efDefaultEditor)
  3417. {
  3418. if (!WinConfiguration->OfferedEditorAutoConfig)
  3419. {
  3420. EditorAutoConfig();
  3421. }
  3422. const TEditorPreferences * Editor =
  3423. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3424. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3425. {
  3426. ExecuteFileBy = efInternalEditor;
  3427. ExternalEditor = NULL;
  3428. }
  3429. else if (Editor->Data->Editor == edOpen)
  3430. {
  3431. ExecuteFileBy = efShell;
  3432. ExternalEditor = NULL;
  3433. }
  3434. else
  3435. {
  3436. ExecuteFileBy = efExternalEditor;
  3437. ExternalEditor = Editor->Data;
  3438. }
  3439. }
  3440. }
  3441. //---------------------------------------------------------------------------
  3442. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3443. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3444. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3445. {
  3446. UnicodeString OriginalFileName;
  3447. UnicodeString LocalRootDirectory;
  3448. UnicodeString RemoteDirectory;
  3449. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3450. IsSideLocalBrowser(Side), MaskParams);
  3451. UnicodeString Counter;
  3452. UnicodeString LocalFileName;
  3453. bool Handled = false;
  3454. if (!IsSideLocalBrowser(Side))
  3455. {
  3456. // We need to trim VMS version here, so that we use name without version
  3457. // when uploading back to create a new version of the file
  3458. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3459. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3460. TObject * Token = NULL;
  3461. UnicodeString LocalDirectory;
  3462. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3463. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3464. LocalDirectory))
  3465. {
  3466. if (Token != NULL)
  3467. {
  3468. TForm * Form = dynamic_cast<TForm *>(Token);
  3469. if (Form->WindowState == wsMinimized)
  3470. {
  3471. ShowWindow(Form->Handle, SW_RESTORE);
  3472. }
  3473. else
  3474. {
  3475. Form->SetFocus();
  3476. }
  3477. Handled = true;
  3478. }
  3479. else
  3480. {
  3481. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3482. }
  3483. }
  3484. if (!Handled)
  3485. {
  3486. TStringList * FileList1 = new TStringList();
  3487. try
  3488. {
  3489. FileList1->AddObject(FullFileName, Object);
  3490. TemporarilyDownloadFiles(FileList1,
  3491. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3492. LocalRootDirectory, LocalDirectory, true, true, false);
  3493. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3494. }
  3495. __finally
  3496. {
  3497. delete FileList1;
  3498. }
  3499. switch (ExecuteFileBy)
  3500. {
  3501. case efShell:
  3502. Counter = "RemoteFilesExecuted";
  3503. break;
  3504. case efInternalEditor:
  3505. Counter = "RemoteFilesOpenedInInternalEditor";
  3506. break;
  3507. case efExternalEditor:
  3508. Counter = "RemoteFilesOpenedInExternalEditor";
  3509. break;
  3510. default:
  3511. DebugFail();
  3512. }
  3513. }
  3514. }
  3515. else
  3516. {
  3517. LocalFileName = FullFileName;
  3518. OriginalFileName = ExtractFileName(FullFileName);
  3519. switch (ExecuteFileBy)
  3520. {
  3521. case efShell:
  3522. Counter = "LocalFilesExecuted";
  3523. break;
  3524. case efInternalEditor:
  3525. Counter = "LocalFilesOpenedInInternalEditor";
  3526. break;
  3527. case efExternalEditor:
  3528. Counter = "LocalFilesOpenedInExternalEditor";
  3529. break;
  3530. default:
  3531. DebugFail();
  3532. }
  3533. }
  3534. if (!Handled)
  3535. {
  3536. Configuration->Usage->Inc(Counter);
  3537. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3538. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3539. }
  3540. }
  3541. //---------------------------------------------------------------------------
  3542. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3543. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3544. bool AllSelected, bool OnFocused)
  3545. {
  3546. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3547. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3548. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3549. Side = GetSide(Side);
  3550. TCustomDirView * DView = DirView(Side);
  3551. TStrings * FileList =
  3552. AllSelected ?
  3553. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3554. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3555. try
  3556. {
  3557. DebugAssert(AllSelected || (FileList->Count == 1));
  3558. for (int i = 0; i < FileList->Count; i++)
  3559. {
  3560. UnicodeString ListFileName = FileList->Strings[i];
  3561. UnicodeString FileNameOnly =
  3562. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3563. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3564. if (!DView->ItemIsDirectory(Item))
  3565. {
  3566. UnicodeString FullFileName;
  3567. if (!IsSideLocalBrowser(Side))
  3568. {
  3569. FullFileName = DirView(Side)->Path + ListFileName;
  3570. }
  3571. else
  3572. {
  3573. FullFileName = ListFileName;
  3574. }
  3575. TObject * Object = FileList->Objects[i];
  3576. TFileMasks::TParams MaskParams;
  3577. MaskParams.Size = DView->ItemFileSize(Item);
  3578. TDateTimePrecision Precision;
  3579. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3580. std::unique_ptr<TRemoteFile> File;
  3581. if (!IsSideLocalBrowser(Side))
  3582. {
  3583. File.reset(Terminal->TryReadFile(FullFileName));
  3584. if (File.get() != NULL)
  3585. {
  3586. File->FullFileName = FullFileName;
  3587. Object = File.get();
  3588. MaskParams.Size = File->Size;
  3589. MaskParams.Modification = File->Modification;
  3590. }
  3591. }
  3592. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3593. }
  3594. }
  3595. }
  3596. __finally
  3597. {
  3598. delete FileList;
  3599. }
  3600. }
  3601. //---------------------------------------------------------------------------
  3602. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3603. {
  3604. CopyParam.FileNameCase = ncNoChange;
  3605. CopyParam.PreserveRights = false;
  3606. CopyParam.PreserveReadOnly = false;
  3607. CopyParam.ReplaceInvalidChars = true;
  3608. CopyParam.IncludeFileMask = TFileMasks();
  3609. CopyParam.NewerOnly = false;
  3610. CopyParam.FileMask = L"";
  3611. }
  3612. //---------------------------------------------------------------------------
  3613. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3614. {
  3615. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3616. }
  3617. //---------------------------------------------------------------------------
  3618. class TEditorUploadQueueItem : public TUploadQueueItem
  3619. {
  3620. public:
  3621. __fastcall TEditorUploadQueueItem(
  3622. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3623. const TCopyParamType * CopyParam, int Params) :
  3624. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, true, false)
  3625. {
  3626. }
  3627. protected:
  3628. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3629. {
  3630. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3631. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3632. }
  3633. };
  3634. //---------------------------------------------------------------------------
  3635. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3636. {
  3637. if (WinConfiguration->EditorCheckNotModified) // optimization
  3638. {
  3639. UnicodeString RemoteFilePath;
  3640. {
  3641. TGuard Guard(FEditorManager->Section);
  3642. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3643. if (DebugAlwaysTrue(Data != NULL) &&
  3644. EditorCheckNotModified(Data))
  3645. {
  3646. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3647. }
  3648. }
  3649. if (!RemoteFilePath.IsEmpty())
  3650. {
  3651. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3652. if (File.get() != NULL)
  3653. {
  3654. TGuard Guard(FEditorManager->Section);
  3655. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3656. if (DebugAlwaysTrue(Data != NULL))
  3657. {
  3658. Data->SourceTimestamp = File->Modification;
  3659. AppLogFmt(L"Uploaded edited remote file timestamp: %s: ", (StandardTimestamp(Data->SourceTimestamp)));
  3660. }
  3661. }
  3662. }
  3663. }
  3664. }
  3665. //---------------------------------------------------------------------------
  3666. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3667. const UnicodeString & FileName, TEditedFileData * Data, HANDLE UploadCompleteEvent, bool & Retry)
  3668. {
  3669. TTerminalManager * Manager = TTerminalManager::Instance();
  3670. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3671. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3672. {
  3673. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3674. Retry = true;
  3675. }
  3676. else if (!IsActiveTerminal(Data->Terminal))
  3677. {
  3678. if (!NonVisualDataModule->Busy)
  3679. {
  3680. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3681. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3682. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3683. if (Data->Terminal == NULL)
  3684. {
  3685. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3686. if (SameSiteTerminal != NULL)
  3687. {
  3688. UnicodeString Message =
  3689. FMTLOAD(EDIT_SESSION_REATTACH,
  3690. (FileNameOnly, Data->SessionName, FileNameOnly));
  3691. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3692. {
  3693. Data->Terminal = SameSiteTerminal;
  3694. Data->Queue = Manager->FindQueueForTerminal(SameSiteTerminal);
  3695. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3696. // We might also overwrite session data
  3697. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3698. }
  3699. else
  3700. {
  3701. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3702. Abort();
  3703. }
  3704. }
  3705. }
  3706. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3707. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3708. {
  3709. UnicodeString Message =
  3710. MainInstructions(
  3711. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3712. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3713. {
  3714. if (Terminal->Disconnected)
  3715. {
  3716. Manager->ActiveSession = Terminal;
  3717. ReconnectSession();
  3718. DebugAssert(Terminal == Data->Terminal);
  3719. Data->Queue = Manager->FindQueueForTerminal(Terminal);
  3720. }
  3721. else
  3722. {
  3723. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3724. }
  3725. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3726. }
  3727. else
  3728. {
  3729. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3730. Abort();
  3731. }
  3732. }
  3733. }
  3734. if (!IsActiveTerminal(Data->Terminal))
  3735. {
  3736. Configuration->Usage->Inc(L"EditInactiveSession");
  3737. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3738. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3739. (ExtractFileName(FileName), Data->SessionName)));
  3740. }
  3741. }
  3742. if (!Retry && EditorCheckNotModified(Data))
  3743. {
  3744. if (NonVisualDataModule->Busy)
  3745. {
  3746. Retry = true;
  3747. }
  3748. else
  3749. {
  3750. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3751. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3752. if (File.get() != NULL)
  3753. {
  3754. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3755. if (File->Modification != Data->SourceTimestamp)
  3756. {
  3757. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3758. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3759. {
  3760. Abort();
  3761. }
  3762. }
  3763. }
  3764. }
  3765. }
  3766. if (!Retry)
  3767. {
  3768. TStrings * FileList = new TStringList();
  3769. try
  3770. {
  3771. FileList->Add(FileName);
  3772. // Consider using the same settings (preset) as when the file was downloaded.
  3773. // More over this does not reflect the actual session that will do the upload.
  3774. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3775. TemporaryFileCopyParam(CopyParam);
  3776. if (Data->ForceText)
  3777. {
  3778. CopyParam.TransferMode = tmAscii;
  3779. }
  3780. // so i do not need to worry if masking algorithm works in all cases
  3781. // ("" means "copy file name", no masking is actually done)
  3782. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3783. {
  3784. CopyParam.FileMask = L"";
  3785. }
  3786. else
  3787. {
  3788. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3789. }
  3790. int Params = cpNoConfirmation | cpTemporary;
  3791. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3792. {
  3793. DebugAssert(Data->Queue != NULL);
  3794. TQueueItem * QueueItem =
  3795. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3796. QueueItem->CompleteEvent = UploadCompleteEvent;
  3797. AddQueueItem(Data->Queue, QueueItem, Data->Terminal);
  3798. }
  3799. else
  3800. {
  3801. if (NonVisualDataModule->Busy)
  3802. {
  3803. Retry = true;
  3804. }
  3805. else
  3806. {
  3807. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3808. SetEvent(UploadCompleteEvent);
  3809. }
  3810. }
  3811. }
  3812. __finally
  3813. {
  3814. delete FileList;
  3815. }
  3816. }
  3817. }
  3818. //---------------------------------------------------------------------------
  3819. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3820. const UnicodeString & FileName, TEditedFileData * Data)
  3821. {
  3822. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3823. DebugAssert(!NonVisualDataModule->Busy);
  3824. if (!IsActiveTerminal(Data->Terminal))
  3825. {
  3826. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3827. (ExtractFileName(FileName), Data->SessionName)));
  3828. }
  3829. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3830. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3831. NonVisualDataModule->StartBusy();
  3832. try
  3833. {
  3834. std::unique_ptr<TRemoteFile> File;
  3835. UnicodeString RemoteFileName =
  3836. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3837. Terminal->ExceptionOnFail = true;
  3838. try
  3839. {
  3840. File.reset(Terminal->ReadFile(RemoteFileName));
  3841. if (!File->HaveFullFileName)
  3842. {
  3843. File->FullFileName = RemoteFileName;
  3844. }
  3845. }
  3846. __finally
  3847. {
  3848. Terminal->ExceptionOnFail = false;
  3849. }
  3850. std::unique_ptr<TStrings> FileList(new TStringList());
  3851. FileList->AddObject(RemoteFileName, File.get());
  3852. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3853. UnicodeString TempDir = ExtractFilePath(FileName);
  3854. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, true, false);
  3855. if (EditorCheckNotModified(Data))
  3856. {
  3857. Data->SourceTimestamp = File->Modification;
  3858. }
  3859. // sanity check, the target file name should be still the same
  3860. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3861. }
  3862. __finally
  3863. {
  3864. NonVisualDataModule->EndBusy();
  3865. // it actually may not exist anymore...
  3866. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3867. }
  3868. }
  3869. //---------------------------------------------------------------------------
  3870. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3871. const TEditedFileData * Data, bool & KeepOpen)
  3872. {
  3873. // Command is set for external editors only (not for "shell" open).
  3874. if (!Data->Command.IsEmpty())
  3875. {
  3876. bool AnyFound = false;
  3877. bool AnyMDI = false;
  3878. bool AnyNonMDI = false;
  3879. bool AnyDetect = false;
  3880. TEditorList * EditorList = new TEditorList();
  3881. try
  3882. {
  3883. *EditorList = *WinConfiguration->EditorList;
  3884. for (int i = 0; i < EditorList->Count; i++)
  3885. {
  3886. const TEditorPreferences * Editor = EditorList->Editors[i];
  3887. if ((Editor->Data->Editor == edExternal) &&
  3888. (Editor->Data->ExternalEditor == Data->Command))
  3889. {
  3890. AnyFound = true;
  3891. if (Editor->Data->SDIExternalEditor)
  3892. {
  3893. AnyNonMDI = true;
  3894. if (Editor->Data->DetectMDIExternalEditor)
  3895. {
  3896. AnyDetect = true;
  3897. }
  3898. }
  3899. else
  3900. {
  3901. AnyMDI = true;
  3902. }
  3903. }
  3904. }
  3905. bool EnableMDI = false;
  3906. bool DisableDetect = false;
  3907. if (AnyMDI)
  3908. {
  3909. KeepOpen = true;
  3910. if (AnyNonMDI)
  3911. {
  3912. // there is at least one instance of the editor with MDI support enabled,
  3913. // and one with disabled, enable it for all instances
  3914. EnableMDI = true;
  3915. }
  3916. }
  3917. else if (AnyFound && !AnyDetect)
  3918. {
  3919. // at least once instance found but all have MDI autodetection disabled
  3920. // => close the file (default action)
  3921. }
  3922. else
  3923. {
  3924. // no instance of the editor has MDI support enabled
  3925. TMessageParams Params;
  3926. if (AnyFound)
  3927. {
  3928. // there is at least one instance of the editor
  3929. Params.Params |= mpNeverAskAgainCheck;
  3930. }
  3931. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3932. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3933. switch (Answer)
  3934. {
  3935. case qaNeverAskAgain:
  3936. DisableDetect = true;
  3937. break;
  3938. case qaNo:
  3939. EnableMDI = true;
  3940. KeepOpen = true;
  3941. break;
  3942. }
  3943. }
  3944. if (AnyFound && (EnableMDI || DisableDetect))
  3945. {
  3946. bool Changed = false;
  3947. for (int i = 0; i < EditorList->Count; i++)
  3948. {
  3949. const TEditorPreferences * Editor = EditorList->Editors[i];
  3950. if ((Editor->Data->Editor == edExternal) &&
  3951. (Editor->Data->ExternalEditor == Data->Command) &&
  3952. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3953. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3954. {
  3955. Changed = true;
  3956. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3957. if (EnableMDI)
  3958. {
  3959. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3960. }
  3961. if (DisableDetect)
  3962. {
  3963. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3964. }
  3965. EditorList->Change(i, UpdatedEditor);
  3966. }
  3967. }
  3968. if (Changed)
  3969. {
  3970. WinConfiguration->EditorList = EditorList;
  3971. }
  3972. }
  3973. }
  3974. __finally
  3975. {
  3976. delete EditorList;
  3977. }
  3978. }
  3979. else
  3980. {
  3981. // "open" case
  3982. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  3983. qaOK, HELP_APP_EARLY_CLOSED);
  3984. }
  3985. }
  3986. //---------------------------------------------------------------------------
  3987. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  3988. {
  3989. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  3990. }
  3991. //---------------------------------------------------------------------------
  3992. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  3993. {
  3994. SideEnter(osRemote);
  3995. }
  3996. //---------------------------------------------------------------------------
  3997. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  3998. {
  3999. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4000. SideEnter(osRemote);
  4001. }
  4002. //---------------------------------------------------------------------------
  4003. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4004. {
  4005. FCurrentSide = Side;
  4006. if (Visible)
  4007. {
  4008. UpdateControls();
  4009. }
  4010. }
  4011. //---------------------------------------------------------------------------
  4012. void __fastcall TCustomScpExplorerForm::FileDeleted(TOperationSide Side, const UnicodeString & FileName, bool Success)
  4013. {
  4014. VisualiseOperationFinished(Side, FileName, Success);
  4015. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4016. {
  4017. FDeletedFiles->Add(FileName);
  4018. }
  4019. }
  4020. //---------------------------------------------------------------------------
  4021. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4022. TStrings * FileList, bool Alternative)
  4023. {
  4024. TCustomDirView * DView = DirView(Side);
  4025. DView->SaveSelection();
  4026. DView->SaveSelectedNames();
  4027. DebugAssert(!FAlternativeDelete);
  4028. FAlternativeDelete = Alternative;
  4029. try
  4030. {
  4031. if (!IsSideLocalBrowser(Side))
  4032. {
  4033. DebugAssert(Terminal != NULL);
  4034. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4035. std::unique_ptr<TStrings> PermanentFileList(TRemoteFileList::CloneStrings(FileList));
  4036. std::unique_ptr<TStringList> DeletedFiles(new TStringList());
  4037. DeletedFiles->CaseSensitive = DebugAlwaysTrue(!IsSideLocalBrowser(Side));
  4038. int Params = FLAGMASK(Alternative, dfAlternative);
  4039. try
  4040. {
  4041. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles);
  4042. DebugAssert(FDeletedFiles == NULL);
  4043. FDeletedFiles = DeletedFiles.get();
  4044. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4045. FOnFileOperationFinished = FileDeleted;
  4046. FMoveToQueue = false;
  4047. Terminal->DeleteFiles(FileList, Params);
  4048. // Probably not needed for deleting, just for consistency with transfer code
  4049. if (FMoveToQueue)
  4050. {
  4051. Abort();
  4052. }
  4053. }
  4054. catch (EAbort &)
  4055. {
  4056. if (FMoveToQueue)
  4057. {
  4058. DeletedFiles->Sorted = true;
  4059. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4060. {
  4061. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4062. {
  4063. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4064. DebugAssert(Index == 0);
  4065. PermanentFileList->Delete(Index);
  4066. Index--;
  4067. }
  4068. }
  4069. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4070. TQueueItem * QueueItem = new TDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4071. AddQueueItem(Queue, QueueItem, Terminal);
  4072. ClearOperationSelection(osRemote);
  4073. }
  4074. }
  4075. }
  4076. else
  4077. {
  4078. if (IsLocalBrowserMode())
  4079. {
  4080. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4081. }
  4082. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  4083. FProgressSide = FCurrentSide;
  4084. try
  4085. {
  4086. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  4087. }
  4088. __finally
  4089. {
  4090. ReloadLocalDirectory();
  4091. }
  4092. }
  4093. FAlternativeDelete = false;
  4094. }
  4095. catch(...)
  4096. {
  4097. FAlternativeDelete = false;
  4098. DView->DiscardSavedSelection();
  4099. throw;
  4100. }
  4101. DView->RestoreSelection();
  4102. }
  4103. //---------------------------------------------------------------------------
  4104. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4105. {
  4106. DebugAssert(Terminal);
  4107. DebugAssert(!IsLocalBrowserMode());
  4108. RemoteDirView->SaveSelection();
  4109. RemoteDirView->SaveSelectedNames();
  4110. try
  4111. {
  4112. if (Lock)
  4113. {
  4114. Terminal->LockFiles(FileList);
  4115. }
  4116. else
  4117. {
  4118. Terminal->UnlockFiles(FileList);
  4119. }
  4120. }
  4121. catch(...)
  4122. {
  4123. RemoteDirView->DiscardSavedSelection();
  4124. throw;
  4125. }
  4126. RemoteDirView->RestoreSelection();
  4127. }
  4128. //---------------------------------------------------------------------------
  4129. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4130. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4131. bool NoConfirmation, bool Move)
  4132. {
  4133. DebugAssert(Terminal != NULL);
  4134. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4135. DebugAssert(!IsLocalBrowserMode());
  4136. if (Session == NULL)
  4137. {
  4138. Session = Terminal;
  4139. }
  4140. if (Session == Terminal)
  4141. {
  4142. if (RemoteDriveView->DropTarget != NULL)
  4143. {
  4144. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4145. }
  4146. else if (RemoteDirView->DropTarget != NULL)
  4147. {
  4148. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4149. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4150. }
  4151. else
  4152. {
  4153. Target = RemoteDirView->Path;
  4154. }
  4155. }
  4156. else
  4157. {
  4158. Target = GetSessionPath(Session, osRemote);
  4159. }
  4160. Target = UnixIncludeTrailingBackslash(Target);
  4161. if (FileList->Count == 1)
  4162. {
  4163. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4164. }
  4165. else
  4166. {
  4167. FileMask = AnyMask;
  4168. }
  4169. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4170. bool Result = true;
  4171. if (!NoConfirmation)
  4172. {
  4173. bool Multi = (FileList->Count > 1);
  4174. if (Move)
  4175. {
  4176. Result = DoRemoteMoveDialog(Multi, Target, FileMask);
  4177. }
  4178. else
  4179. {
  4180. std::unique_ptr<TStrings> Sessions(new TStringList);
  4181. std::unique_ptr<TStrings> Directories(new TStringList);
  4182. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4183. for (int Index = 0; Index < SessionList->Count; Index++)
  4184. {
  4185. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4186. if (IsActiveTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4187. {
  4188. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4189. Directories->Add(GetSessionPath(ASession, osRemote));
  4190. }
  4191. }
  4192. TDirectRemoteCopy AllowDirectCopy;
  4193. if (Terminal->IsCapable[fcRemoteCopy] || Terminal->CommandSessionOpened)
  4194. {
  4195. DebugAssert(DirectCopy);
  4196. AllowDirectCopy = drcAllow;
  4197. }
  4198. else if (Terminal->IsCapable[fcSecondaryShell])
  4199. {
  4200. DebugAssert(DirectCopy);
  4201. AllowDirectCopy = drcConfirmCommandSession;
  4202. }
  4203. else
  4204. {
  4205. DebugAssert(!DirectCopy);
  4206. AllowDirectCopy = drcDisallow;
  4207. }
  4208. void * ASession = Session;
  4209. Result = DoRemoteCopyDialog(
  4210. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal);
  4211. Session = static_cast<TManagedTerminal *>(ASession);
  4212. }
  4213. }
  4214. return Result;
  4215. }
  4216. //---------------------------------------------------------------------------
  4217. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4218. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4219. {
  4220. DebugAssert(!IsLocalBrowserMode());
  4221. bool DirectCopy;
  4222. UnicodeString Target, FileMask;
  4223. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4224. if (Result)
  4225. {
  4226. if (!Move && !DirectCopy)
  4227. {
  4228. Configuration->Usage->Inc("RemoteCopyTemp");
  4229. UnicodeString RootTempDir;
  4230. UnicodeString TempDir;
  4231. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  4232. TStrings * TemporaryFilesList = new TStringList();
  4233. try
  4234. {
  4235. TMakeLocalFileListParams MakeFileListParam;
  4236. MakeFileListParam.FileList = TemporaryFilesList;
  4237. MakeFileListParam.FileTimes = NULL;
  4238. MakeFileListParam.IncludeDirs = true;
  4239. MakeFileListParam.Recursive = false;
  4240. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4241. TTerminalManager::Instance()->ActiveSession = Session;
  4242. if (TemporaryFilesList->Count > 0)
  4243. {
  4244. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4245. CopyParam.FileMask = FileMask;
  4246. DebugAssert(!FAutoOperation);
  4247. FAutoOperation = true;
  4248. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4249. }
  4250. }
  4251. __finally
  4252. {
  4253. delete TemporaryFilesList;
  4254. FAutoOperation = false;
  4255. if (!RootTempDir.IsEmpty())
  4256. {
  4257. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  4258. }
  4259. }
  4260. }
  4261. else
  4262. {
  4263. RemoteDirView->SaveSelection();
  4264. RemoteDirView->SaveSelectedNames();
  4265. try
  4266. {
  4267. if (Move)
  4268. {
  4269. Configuration->Usage->Inc("RemoteMove");
  4270. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4271. }
  4272. else
  4273. {
  4274. Configuration->Usage->Inc("RemoteCopyDirect");
  4275. DebugAssert(DirectCopy);
  4276. DebugAssert(Session == Terminal);
  4277. if (Terminal->IsCapable[fcRemoteCopy] ||
  4278. Terminal->CommandSessionOpened ||
  4279. CommandSessionFallback())
  4280. {
  4281. Terminal->CopyFiles(FileList, Target, FileMask);
  4282. }
  4283. }
  4284. }
  4285. catch(...)
  4286. {
  4287. RemoteDirView->DiscardSavedSelection();
  4288. throw;
  4289. }
  4290. RemoteDirView->RestoreSelection();
  4291. }
  4292. }
  4293. return Result;
  4294. }
  4295. //---------------------------------------------------------------------------
  4296. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4297. const UnicodeString & Path, TRemoteProperties & Properties)
  4298. {
  4299. DebugAssert(!IsLocalBrowserMode());
  4300. Properties.Valid = Properties.Valid << vpEncrypt;
  4301. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4302. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4303. }
  4304. //---------------------------------------------------------------------------
  4305. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4306. {
  4307. Side = GetSide(Side);
  4308. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4309. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4310. UnicodeString Name = LoadStr(NEW_FOLDER);
  4311. int AllowedChanges =
  4312. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4313. bool SaveSettings = false;
  4314. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4315. {
  4316. TWindowLock Lock(this);
  4317. if (!IsSideLocalBrowser(Side))
  4318. {
  4319. if (SaveSettings)
  4320. {
  4321. GUIConfiguration->NewDirectoryProperties = Properties;
  4322. }
  4323. CreateRemoteDirectory(Name, Properties);
  4324. }
  4325. else
  4326. {
  4327. DirView(Side)->CreateDirectory(Name);
  4328. }
  4329. }
  4330. }
  4331. //---------------------------------------------------------------------------
  4332. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4333. {
  4334. TWindowLock Lock(this);
  4335. DirView(Side)->ExecuteHomeDirectory();
  4336. }
  4337. //---------------------------------------------------------------------------
  4338. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4339. {
  4340. DoOpenDirectoryDialog(odBrowse, Side);
  4341. }
  4342. //---------------------------------------------------------------------------
  4343. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4344. {
  4345. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4346. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4347. bool Result = !Path.IsEmpty();
  4348. if (Result)
  4349. {
  4350. TryOpenDirectory(Side, Path);
  4351. }
  4352. return Result;
  4353. }
  4354. //---------------------------------------------------------------------------
  4355. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4356. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4357. bool & Close)
  4358. {
  4359. // terminal can be already closed (e.g. dropped connection)
  4360. if (Terminal != NULL)
  4361. {
  4362. try
  4363. {
  4364. TCalculateSizeParams Params;
  4365. Params.Stats = &Stats;
  4366. Terminal->CalculateFilesSize(FileList, Size, Params);
  4367. }
  4368. catch(...)
  4369. {
  4370. if (!Terminal->Active)
  4371. {
  4372. Close = true;
  4373. }
  4374. throw;
  4375. }
  4376. }
  4377. }
  4378. //---------------------------------------------------------------------------
  4379. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4380. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4381. bool & Close)
  4382. {
  4383. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4384. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4385. {
  4386. Configuration->Usage->Inc(L"ChecksumCalculated");
  4387. try
  4388. {
  4389. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4390. }
  4391. catch(...)
  4392. {
  4393. if (!Terminal->Active)
  4394. {
  4395. Close = true;
  4396. }
  4397. throw;
  4398. }
  4399. }
  4400. }
  4401. //---------------------------------------------------------------------------
  4402. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4403. {
  4404. if (Terminal->LoadFilesProperties(FileList))
  4405. {
  4406. RemoteDirView->Invalidate();
  4407. }
  4408. }
  4409. //---------------------------------------------------------------------------
  4410. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4411. {
  4412. bool Result;
  4413. if (!IsSideLocalBrowser(Side))
  4414. {
  4415. TRemoteTokenList * GroupList = NULL;
  4416. TRemoteTokenList * UserList = NULL;
  4417. try
  4418. {
  4419. TRemoteProperties CurrentProperties;
  4420. LoadFilesProperties(FileList);
  4421. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4422. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4423. if (CapableGroupChanging || CapableOwnerChanging)
  4424. {
  4425. if (CapableGroupChanging)
  4426. {
  4427. GroupList = Terminal->Groups->Duplicate();
  4428. }
  4429. if (CapableOwnerChanging)
  4430. {
  4431. UserList = Terminal->Users->Duplicate();
  4432. }
  4433. TRemoteDirectory * Files = Terminal->Files;
  4434. int Count = Files->Count;
  4435. if (Count > 100)
  4436. {
  4437. Count = 100;
  4438. }
  4439. for (int Index = 0; Index < Count; Index++)
  4440. {
  4441. TRemoteFile * File = Files->Files[Index];
  4442. if (CapableGroupChanging)
  4443. {
  4444. GroupList->AddUnique(File->Group);
  4445. }
  4446. if (CapableOwnerChanging)
  4447. {
  4448. UserList->AddUnique(File->Owner);
  4449. }
  4450. }
  4451. // if we haven't collected tokens for all files in current directory,
  4452. // make sure we collect them at least for all selected files.
  4453. // (note that so far the files in FileList has to be from current direcotry)
  4454. if (Count < Files->Count)
  4455. {
  4456. for (int Index = 0; Index < FileList->Count; Index++)
  4457. {
  4458. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4459. if (CapableGroupChanging)
  4460. {
  4461. GroupList->AddUnique(File->Group);
  4462. }
  4463. if (CapableOwnerChanging)
  4464. {
  4465. UserList->AddUnique(File->Owner);
  4466. }
  4467. }
  4468. }
  4469. }
  4470. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4471. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4472. for (int Index = 0; (Index < FileList->Count) && CapableAclChanging; Index++)
  4473. {
  4474. if (dynamic_cast<TRemoteFile *>(FileList->Objects[Index])->IsDirectory)
  4475. {
  4476. CapableAclChanging = false;
  4477. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4478. }
  4479. }
  4480. int Flags = 0;
  4481. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4482. if (CapableAclChanging) Flags |= cpAcl;
  4483. if (CapableOwnerChanging) Flags |= cpOwner;
  4484. if (CapableGroupChanging) Flags |= cpGroup;
  4485. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4486. if (Terminal->IsCapable[fcCalculatingChecksum] ||
  4487. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles()))
  4488. {
  4489. CalculateChecksumEvent = CalculateChecksum;
  4490. }
  4491. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4492. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4493. TRemoteProperties NewProperties = CurrentProperties;
  4494. Result =
  4495. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4496. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4497. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4498. CalculateSize, CalculateChecksumEvent);
  4499. if (Result)
  4500. {
  4501. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4502. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4503. }
  4504. }
  4505. __finally
  4506. {
  4507. delete GroupList;
  4508. delete UserList;
  4509. }
  4510. }
  4511. else
  4512. {
  4513. DirView(Side)->DisplayPropertiesMenu();
  4514. Result = true;
  4515. }
  4516. return Result;
  4517. }
  4518. //---------------------------------------------------------------------------
  4519. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4520. {
  4521. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4522. {
  4523. FIgnoreNextDialogChar = Key;
  4524. }
  4525. Key = 0;
  4526. }
  4527. //---------------------------------------------------------------------------
  4528. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4529. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4530. {
  4531. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4532. if (Command != NULL)
  4533. {
  4534. KeyProcessed(Key, Shift);
  4535. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4536. {
  4537. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4538. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4539. false, false, const_cast<TCustomCommandType *>(Command));
  4540. }
  4541. }
  4542. }
  4543. //---------------------------------------------------------------------------
  4544. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4545. {
  4546. if (!NonVisualDataModule->Busy)
  4547. {
  4548. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4549. {
  4550. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4551. }
  4552. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4553. {
  4554. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4555. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4556. {
  4557. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4558. // But so far it's not a problem, as it does what we want.
  4559. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4560. if (((Action->ShortCut == KeyShortCut) ||
  4561. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4562. AllowedAction(Action, aaShortCut))
  4563. {
  4564. // Has to be called before the action as the dialog char is already in queue.
  4565. // So when the action consumes message queue, we already need to have the
  4566. // FIgnoreNextDialogChar set
  4567. KeyProcessed(Key, Shift);
  4568. // Reset reference to previous component (when menu/toolbar was clicked).
  4569. // Needed to detect that action was invoked by keyboard shortcut
  4570. // in TNonVisualDataModule::ExplorerActionsExecute
  4571. Action->ActionComponent = NULL;
  4572. Action->Execute();
  4573. return;
  4574. }
  4575. }
  4576. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4577. {
  4578. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4579. {
  4580. KeyProcessed(Key, Shift);
  4581. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4582. return;
  4583. }
  4584. }
  4585. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4586. {
  4587. KeyProcessed(Key, Shift);
  4588. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4589. }
  4590. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4591. if (IsCustomShortCut(CustomShortCut))
  4592. {
  4593. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4594. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4595. if (WinConfiguration->SharedBookmarks != NULL)
  4596. {
  4597. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4598. if ((Bookmark != NULL) &&
  4599. OpenBookmark(FCurrentSide, Bookmark))
  4600. {
  4601. KeyProcessed(Key, Shift);
  4602. }
  4603. }
  4604. }
  4605. }
  4606. }
  4607. TForm::KeyDown(Key, Shift);
  4608. }
  4609. //---------------------------------------------------------------------------
  4610. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4611. {
  4612. bool OpenedTerminal = false;
  4613. UnicodeString ProtocolName;
  4614. UnicodeString ProtocolNameHint;
  4615. UnicodeString SecurityProtocolName;
  4616. UnicodeString DurationHint;
  4617. // See the comment in TScpCommanderForm::UpdateControls()
  4618. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4619. if (ActiveTerminal != NULL)
  4620. {
  4621. // Active is not enough here
  4622. if (ActiveTerminal->Status == ssOpened)
  4623. {
  4624. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4625. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4626. if (FileSystemInfo.ProtocolName.IsEmpty())
  4627. {
  4628. ProtocolName = SessionInfo.ProtocolName;
  4629. }
  4630. else
  4631. {
  4632. ProtocolName = FileSystemInfo.ProtocolName;
  4633. }
  4634. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4635. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4636. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4637. OpenedTerminal = true;
  4638. }
  4639. else if (ActiveTerminal->Status > ssClosed)
  4640. {
  4641. ProtocolName = LoadStr(STATUS_CONNECTING);
  4642. }
  4643. else
  4644. {
  4645. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4646. }
  4647. }
  4648. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4649. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4650. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4651. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4652. if (ProtocolStatusPanel->Caption != ProtocolName)
  4653. {
  4654. ProtocolStatusPanel->Caption = ProtocolName;
  4655. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4656. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4657. }
  4658. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4659. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4660. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4661. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4662. SecurityStatusPanel->Enabled = SecurityEnabled;
  4663. UnicodeString SecurityProtocolHint;
  4664. if (SecurityEnabled)
  4665. {
  4666. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4667. }
  4668. else
  4669. {
  4670. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4671. }
  4672. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4673. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4674. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4675. DurationStatusPanel->Hint = DurationHint;
  4676. UpdateStatusBar();
  4677. }
  4678. //---------------------------------------------------------------------------
  4679. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4680. {
  4681. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4682. DebugAssert(SessionStatusBar != NULL);
  4683. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4684. if (!FNote.IsEmpty())
  4685. {
  4686. NoteStatusPanel->Caption = FNote;
  4687. }
  4688. else
  4689. {
  4690. UpdateStatusPanelText(NoteStatusPanel);
  4691. }
  4692. NoteStatusPanel->Hint = FNoteHints;
  4693. UnicodeString LoginTime;
  4694. // See the comment in TScpCommanderForm::UpdateControls()
  4695. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4696. // Active is not enough here
  4697. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4698. {
  4699. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4700. LoginTime = FormatDateTimeSpan(Configuration->TimeFormat, Now() - SessionInfo.LoginTime);
  4701. }
  4702. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4703. DurationStatusPanel->Caption = LoginTime;
  4704. }
  4705. //---------------------------------------------------------------------------
  4706. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4707. {
  4708. Panel->Caption = L"";
  4709. }
  4710. //---------------------------------------------------------------------------
  4711. void __fastcall TCustomScpExplorerForm::Idle()
  4712. {
  4713. if (FShowing ||
  4714. // Particularly for
  4715. // - Standalone editing
  4716. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4717. // while "keeping remote directory up to date".
  4718. StandaloneOperation)
  4719. {
  4720. FEditorManager->Check();
  4721. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4722. // that needs to know if queue view is visible (and it may be closed after queue update)
  4723. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4724. }
  4725. if (FShowing)
  4726. {
  4727. if (!NonVisualDataModule->Busy &&
  4728. // Menu is opened or drag&drop is going on
  4729. (Mouse->Capture == NULL))
  4730. {
  4731. if (FRefreshRemoteDirectory)
  4732. {
  4733. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4734. {
  4735. Terminal->RefreshDirectory();
  4736. }
  4737. FRefreshRemoteDirectory = false;
  4738. }
  4739. if (FRefreshLocalDirectory)
  4740. {
  4741. ReloadLocalDirectory();
  4742. FRefreshLocalDirectory = false;
  4743. }
  4744. if (WinConfiguration->RefreshRemotePanel)
  4745. {
  4746. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4747. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4748. {
  4749. RemoteDirView->ReloadDirectory();
  4750. }
  4751. }
  4752. }
  4753. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4754. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4755. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4756. // 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.
  4757. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4758. MenuToolbar->Idle();
  4759. }
  4760. if (FShowing || StandaloneOperation)
  4761. {
  4762. if (FQueueStatusInvalidated)
  4763. {
  4764. UpdateQueueStatus(false);
  4765. }
  4766. RefreshQueueItems();
  4767. }
  4768. if (FShowing)
  4769. {
  4770. UpdateStatusBar();
  4771. }
  4772. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4773. {
  4774. FClipboardFakeMonitorsPendingReset = false;
  4775. FClipboardFakeMonitors.reset(NULL);
  4776. }
  4777. FIgnoreNextDialogChar = 0;
  4778. }
  4779. //---------------------------------------------------------------------------
  4780. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4781. {
  4782. try
  4783. {
  4784. FUserActionTimer->Enabled = false;
  4785. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4786. {
  4787. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4788. {
  4789. FPendingQueueActionItem->ProcessUserAction();
  4790. }
  4791. }
  4792. }
  4793. __finally
  4794. {
  4795. FPendingQueueActionItem = NULL;
  4796. }
  4797. }
  4798. //---------------------------------------------------------------------------
  4799. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4800. {
  4801. if (WinConfiguration->MinimizeToTray)
  4802. {
  4803. UpdateTrayIcon();
  4804. FTrayIcon->Visible = true;
  4805. if (Visible)
  4806. {
  4807. ShowWindow(Handle, SW_HIDE);
  4808. }
  4809. }
  4810. }
  4811. //---------------------------------------------------------------------------
  4812. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4813. {
  4814. // WORKAROUND
  4815. // When restoring maximized window from minimization,
  4816. // rarely some controls do not align properly.
  4817. // Two instances seen (both for Commander):
  4818. // - When restoring, window is temporarily narrower (not maximized),
  4819. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4820. // Once maximized already, top dock shinks back, but the session PageControl,
  4821. // do not align up, leaving space between TopDock and PageControl.
  4822. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4823. for (int Index = 0; Index < ControlCount; Index++)
  4824. {
  4825. RealignControl(Controls[Index]);
  4826. }
  4827. if (FTrayIcon->Visible)
  4828. {
  4829. FTrayIcon->Visible = false;
  4830. if (Visible)
  4831. {
  4832. ShowWindow(Handle, SW_SHOW);
  4833. }
  4834. }
  4835. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4836. {
  4837. FNeedSession = false;
  4838. NonVisualDataModule->StartBusy();
  4839. try
  4840. {
  4841. NeedSession(true);
  4842. }
  4843. __finally
  4844. {
  4845. NonVisualDataModule->EndBusy();
  4846. }
  4847. }
  4848. }
  4849. //---------------------------------------------------------------------------
  4850. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4851. {
  4852. FTrayIcon->Hint = GetMainForm()->Caption;
  4853. }
  4854. //---------------------------------------------------------------------------
  4855. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4856. {
  4857. UpdateTrayIcon();
  4858. }
  4859. //---------------------------------------------------------------------------
  4860. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4861. {
  4862. // workaround
  4863. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4864. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4865. // But WM_ACTIVATEAPP message can be received even when
  4866. // the main window is minimized to the tray and internal editor window is focused
  4867. // (after another application was previously active)
  4868. if (::IsIconic(Handle))
  4869. {
  4870. if (!IsAppIconic())
  4871. {
  4872. SetAppIconic(true);
  4873. }
  4874. }
  4875. ::ApplicationRestore();
  4876. Application->BringToFront();
  4877. }
  4878. //---------------------------------------------------------------------------
  4879. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4880. {
  4881. RestoreApp();
  4882. }
  4883. //---------------------------------------------------------------------------
  4884. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4885. {
  4886. if (OpenInNewWindow())
  4887. {
  4888. ExecuteNewInstance(SessionUrl);
  4889. }
  4890. else
  4891. {
  4892. TTerminalManager::Instance()->NewSession(SessionUrl);
  4893. }
  4894. }
  4895. //---------------------------------------------------------------------------
  4896. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4897. {
  4898. NewSession();
  4899. }
  4900. //---------------------------------------------------------------------------
  4901. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4902. {
  4903. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4904. StoredSessions->NewSession(SessionName, SessionData);
  4905. // modified only, explicit
  4906. StoredSessions->Save(false, true);
  4907. // encode session name because of slashes in hierarchical sessions
  4908. return EncodeUrlString(SessionName);
  4909. }
  4910. //---------------------------------------------------------------------------
  4911. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4912. {
  4913. // current working directories become defaults here, what is not right
  4914. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4915. return SaveHiddenDuplicateSession(SessionData.get());
  4916. }
  4917. //---------------------------------------------------------------------------
  4918. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  4919. {
  4920. if (OpenInNewWindow())
  4921. {
  4922. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4923. }
  4924. else
  4925. {
  4926. // current working directories become defaults here, what is not right
  4927. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4928. TTerminalManager * Manager = TTerminalManager::Instance();
  4929. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  4930. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  4931. // We definitelly want these
  4932. ASession->Disconnected = ManagedSession->Disconnected;
  4933. // Not sure about these two
  4934. ASession->Permanent = ManagedSession->Permanent;
  4935. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  4936. Manager->ActiveSession = ASession;
  4937. }
  4938. }
  4939. //---------------------------------------------------------------------------
  4940. void __fastcall TCustomScpExplorerForm::RenameTab()
  4941. {
  4942. UnicodeString Name = ManagedSession->SessionData->SessionName;
  4943. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  4944. // When submitting the default name, do not fix it
  4945. (Name != ManagedSession->SessionData->SessionName))
  4946. {
  4947. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  4948. TSessionData::ValidateName(Name);
  4949. // This is inconsistent with how color (for example) is handled.
  4950. ManagedSession->SessionData->Name = Name;
  4951. UpdateControls();
  4952. // Add/Remove distinguishing paths from sessions of the same name.
  4953. SessionListChanged();
  4954. }
  4955. }
  4956. //---------------------------------------------------------------------------
  4957. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  4958. {
  4959. DebugAssert(Queue != NULL);
  4960. bool Result = Queue->IsEmpty;
  4961. if (!Result)
  4962. {
  4963. SetFocus();
  4964. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  4965. }
  4966. return Result;
  4967. }
  4968. //---------------------------------------------------------------------------
  4969. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  4970. {
  4971. return CanCloseQueue(FQueue);
  4972. }
  4973. //---------------------------------------------------------------------------
  4974. void __fastcall TCustomScpExplorerForm::CloseTab()
  4975. {
  4976. if (CanCloseQueue())
  4977. {
  4978. TTerminalManager::Instance()->FreeActiveTerminal();
  4979. }
  4980. }
  4981. //---------------------------------------------------------------------------
  4982. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  4983. {
  4984. if (CanCloseQueue())
  4985. {
  4986. TTerminalManager::Instance()->DisconnectActiveTerminal();
  4987. }
  4988. }
  4989. //---------------------------------------------------------------------------
  4990. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  4991. {
  4992. DetachTerminal(Terminal);
  4993. RemoteDirView->Terminal = Terminal;
  4994. UpdateRemotePathComboBox(false);
  4995. InitStatusBar();
  4996. UpdateControls();
  4997. }
  4998. //---------------------------------------------------------------------------
  4999. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5000. {
  5001. InitStatusBar();
  5002. }
  5003. //---------------------------------------------------------------------------
  5004. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5005. {
  5006. if (DebugAlwaysTrue(!Terminal->Active))
  5007. {
  5008. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5009. }
  5010. }
  5011. //---------------------------------------------------------------------------
  5012. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5013. {
  5014. if (OpenInNewWindow())
  5015. {
  5016. // encode session name because of slashes in hierarchical sessions
  5017. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5018. }
  5019. else
  5020. {
  5021. TTerminalManager * Manager = TTerminalManager::Instance();
  5022. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5023. Manager->ActiveSession = Terminal;
  5024. }
  5025. }
  5026. //---------------------------------------------------------------------------
  5027. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5028. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5029. {
  5030. TTerminalManager * Manager = TTerminalManager::Instance();
  5031. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5032. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5033. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5034. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5035. {
  5036. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5037. // FirstSession can be null, if none of the workspace sites exist anymore
  5038. // or if all workspace sessions are not suported by the interface
  5039. // (when trying to open all local-local workspace in "explorer" interface)
  5040. if (FirstSession != NULL)
  5041. {
  5042. if (!ConnectFirstTerminal)
  5043. {
  5044. FirstSession->Disconnected = true;
  5045. FirstSession->DisconnectedTemporarily = true;
  5046. }
  5047. Manager->ActiveSession = FirstSession;
  5048. }
  5049. }
  5050. }
  5051. //---------------------------------------------------------------------------
  5052. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5053. {
  5054. if (OpenInNewWindow())
  5055. {
  5056. ExecuteNewInstance(Name);
  5057. }
  5058. else
  5059. {
  5060. DoOpenFolderOrWorkspace(Name, true, false);
  5061. }
  5062. }
  5063. //---------------------------------------------------------------------------
  5064. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5065. bool &CanClose)
  5066. {
  5067. // See the comment in CloseApp()
  5068. if (NonVisualDataModule->Busy)
  5069. {
  5070. CanClose = false;
  5071. }
  5072. else
  5073. {
  5074. TTerminalManager * Manager = TTerminalManager::Instance();
  5075. int ActiveSessions = 0;
  5076. for (int Index = 0; Index < Manager->Count; Index++)
  5077. {
  5078. if (Manager->Sessions[Index]->Active)
  5079. {
  5080. ActiveSessions++;
  5081. }
  5082. }
  5083. // Confirm, when there's at least one active remote session or
  5084. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5085. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5086. WinConfiguration->ConfirmClosingSession)
  5087. {
  5088. unsigned int Result;
  5089. TMessageParams Params(mpNeverAskAgainCheck);
  5090. UnicodeString Message;
  5091. int Answers = qaOK | qaCancel;
  5092. // The current session is the only active session
  5093. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5094. {
  5095. if (!WinConfiguration->AutoSaveWorkspace)
  5096. {
  5097. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5098. }
  5099. else
  5100. {
  5101. Message = LoadStr(CLOSE_SESSION);
  5102. }
  5103. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5104. }
  5105. // Multiple active sessions or one active session, but it's not the current one
  5106. else if (ActiveSessions > 0)
  5107. {
  5108. if (!WinConfiguration->AutoSaveWorkspace)
  5109. {
  5110. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5111. }
  5112. else
  5113. {
  5114. Message = LoadStr(CLOSE_SESSIONS);
  5115. }
  5116. }
  5117. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5118. else
  5119. {
  5120. DebugAlwaysTrue(Manager->Count > 1);
  5121. DebugAlwaysTrue(!WinConfiguration->AutoSaveWorkspace);
  5122. Message = LoadStr(CLOSE_WORKSPACE);
  5123. }
  5124. UnicodeString Note;
  5125. if (WinConfiguration->AutoSaveWorkspace)
  5126. {
  5127. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5128. }
  5129. else
  5130. {
  5131. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5132. Answers = qaYes | qaNo | qaCancel;
  5133. }
  5134. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5135. SetFocus();
  5136. Result = MessageDialog(Message, qtConfirmation,
  5137. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5138. if (Result == qaNeverAskAgain)
  5139. {
  5140. WinConfiguration->ConfirmClosingSession = false;
  5141. }
  5142. if (Result == qaNo)
  5143. {
  5144. CanClose = SaveWorkspace(true);
  5145. // note that the workspace will be saved redundatly again from FormClose
  5146. }
  5147. else
  5148. {
  5149. CanClose =
  5150. (Result == qaOK) ||
  5151. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5152. (Result == qaNeverAskAgain);
  5153. }
  5154. }
  5155. if (CanClose && HasActiveTerminal())
  5156. {
  5157. CanClose = CanCloseQueue();
  5158. }
  5159. }
  5160. if (CanClose)
  5161. {
  5162. CanClose =
  5163. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5164. FEditorManager->CloseExternalFilesWithoutProcess();
  5165. if (CanClose)
  5166. {
  5167. while (CanClose && (FLocalEditors->Count > 0))
  5168. {
  5169. int PrevCount = FLocalEditors->Count;
  5170. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5171. CanClose = (FLocalEditors->Count < PrevCount);
  5172. }
  5173. if (CanClose)
  5174. {
  5175. CanClose = FEditorManager->Empty(true);
  5176. if (!CanClose)
  5177. {
  5178. SetFocus();
  5179. CanClose =
  5180. (MessageDialog(
  5181. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5182. }
  5183. }
  5184. }
  5185. }
  5186. }
  5187. //---------------------------------------------------------------------------
  5188. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5189. {
  5190. TForm * Form = dynamic_cast<TForm *>(Sender);
  5191. DebugAssert(Form != NULL);
  5192. Form->Close();
  5193. }
  5194. //---------------------------------------------------------------------------
  5195. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5196. {
  5197. TForm * Form = dynamic_cast<TForm *>(Sender);
  5198. delete Form;
  5199. }
  5200. //---------------------------------------------------------------------------
  5201. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5202. {
  5203. while (FLocalEditors->Count > 0)
  5204. {
  5205. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5206. }
  5207. }
  5208. //---------------------------------------------------------------------------
  5209. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5210. TObject *Sender)
  5211. {
  5212. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5213. try
  5214. {
  5215. SetProperties(osRemote, FileList);
  5216. }
  5217. __finally
  5218. {
  5219. delete FileList;
  5220. }
  5221. }
  5222. //---------------------------------------------------------------------------
  5223. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5224. {
  5225. if (value)
  5226. {
  5227. if (Component == fcCustomCommandsBand)
  5228. {
  5229. UpdateCustomCommandsToolbar();
  5230. }
  5231. if (Component == fcQueueFileList)
  5232. {
  5233. DebugAssert(!QueueFileListSplitter->Visible);
  5234. AdjustQueueLayout();
  5235. UpdateQueueFileList();
  5236. }
  5237. }
  5238. }
  5239. //---------------------------------------------------------------------------
  5240. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5241. {
  5242. int MinHeightLimit =
  5243. GetStaticQueuePanelComponentsHeight() +
  5244. QueueFileListSplitter->Height +
  5245. QueueFileList->Height +
  5246. GetMinQueueViewHeight();
  5247. if (QueuePanel->ClientHeight < MinHeightLimit)
  5248. {
  5249. QueuePanel->ClientHeight = MinHeightLimit;
  5250. }
  5251. }
  5252. //---------------------------------------------------------------------------
  5253. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5254. {
  5255. TControl * Control = GetComponent(Component);
  5256. DebugAssert(Control);
  5257. bool Changed = (Control->Visible != value);
  5258. if (Changed)
  5259. {
  5260. ComponentShowing(Component, value);
  5261. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5262. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5263. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5264. if (value)
  5265. {
  5266. int RemainingHeight = Control->Parent->ClientHeight;
  5267. int RemainingWidth = Control->Parent->ClientWidth;
  5268. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5269. {
  5270. TControl * ChildControl = Control->Parent->Controls[i];
  5271. if (ChildControl->Visible)
  5272. {
  5273. switch (ChildControl->Align)
  5274. {
  5275. case alTop:
  5276. case alBottom:
  5277. RemainingHeight -= ChildControl->Height;
  5278. break;
  5279. case alLeft:
  5280. case alRight:
  5281. RemainingWidth -= ChildControl->Width;
  5282. break;
  5283. }
  5284. }
  5285. }
  5286. int Reserve = ScaleByTextHeight(this, 32);
  5287. // queue in explorer, trees in commander
  5288. if (Control->Height > RemainingHeight - Reserve)
  5289. {
  5290. Control->Height = RemainingHeight / 2;
  5291. }
  5292. if (Control->Width > RemainingWidth - Reserve)
  5293. {
  5294. Control->Width = RemainingWidth / 2;
  5295. }
  5296. }
  5297. Control->Visible = value;
  5298. if (WasFocused && Visible)
  5299. {
  5300. DirView(osCurrent)->SetFocus();
  5301. }
  5302. FixControlsPlacement();
  5303. }
  5304. }
  5305. //---------------------------------------------------------------------------
  5306. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5307. {
  5308. TControl * Control = GetComponent(Component);
  5309. if (Control == NULL)
  5310. {
  5311. return false;
  5312. }
  5313. else
  5314. {
  5315. return Control->Visible;
  5316. }
  5317. }
  5318. //---------------------------------------------------------------------------
  5319. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5320. {
  5321. bool Result;
  5322. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5323. {
  5324. Result = !IsUWP();
  5325. }
  5326. else
  5327. {
  5328. Result = true;
  5329. }
  5330. return Result;
  5331. }
  5332. //---------------------------------------------------------------------------
  5333. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5334. {
  5335. if (DirView->ItemFocused != NULL)
  5336. {
  5337. DirView->ItemFocused->MakeVisible(false);
  5338. }
  5339. }
  5340. //---------------------------------------------------------------------------
  5341. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5342. {
  5343. MakeFocusedItemVisible(RemoteDirView);
  5344. QueueSplitter->Visible = QueuePanel->Visible;
  5345. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5346. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5347. TControl * TopControlsOrder[] =
  5348. { TopDock, MessageDock, SessionsPageControl };
  5349. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5350. TControl * QueueControlsOrder[] =
  5351. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5352. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5353. }
  5354. //---------------------------------------------------------------------------
  5355. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5356. {
  5357. switch (Component) {
  5358. case fcStatusBar: return RemoteStatusBar;
  5359. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5360. case fcQueueView: return QueuePanel;
  5361. case fcQueueToolbar: return QueueDock;
  5362. case fcRemoteTree: return RemoteDrivePanel;
  5363. case fcSessionsTabs: return SessionsPageControl;
  5364. case fcQueueFileList: return QueueFileList;
  5365. default: return NULL;
  5366. }
  5367. }
  5368. //---------------------------------------------------------------------------
  5369. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5370. TObject *Sender, TListColumn *Column, TPoint &Point)
  5371. {
  5372. DebugAssert(NonVisualDataModule && Column && Sender);
  5373. NonVisualDataModule->ListColumn = Column;
  5374. TPopupMenu * DirViewColumnMenu;
  5375. if (Sender == DirView(osOther))
  5376. {
  5377. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5378. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5379. bool SizeColumn = (Column->Index == uvSize);
  5380. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5381. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5382. }
  5383. else
  5384. {
  5385. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5386. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5387. bool SizeColumn = (Column->Index == dvSize);
  5388. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5389. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5390. }
  5391. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5392. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5393. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5394. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5395. }
  5396. //---------------------------------------------------------------------------
  5397. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5398. TObject *Sender, TListItem *Item, bool &AllowExec)
  5399. {
  5400. DoDirViewExecFile(Sender, Item, AllowExec);
  5401. }
  5402. //---------------------------------------------------------------------------
  5403. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5404. TListItem * Item, bool & AllowExec)
  5405. {
  5406. DebugAssert(Sender && Item && Configuration);
  5407. DebugAssert(AllowExec);
  5408. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5409. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5410. bool Remote = !IsSideLocalBrowser(Side);
  5411. DebugAssert(Item == ADirView->ItemFocused);
  5412. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5413. TResolvedDoubleClickAction Action;
  5414. if (FForceExecution)
  5415. {
  5416. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5417. }
  5418. else
  5419. {
  5420. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5421. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5422. }
  5423. if (Action == rdcaCopy)
  5424. {
  5425. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5426. UnlockWindow();
  5427. try
  5428. {
  5429. if (IsLocalBrowserMode())
  5430. {
  5431. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5432. }
  5433. else
  5434. {
  5435. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5436. }
  5437. }
  5438. __finally
  5439. {
  5440. LockWindow();
  5441. }
  5442. AllowExec = false;
  5443. }
  5444. else if (Action == rdcaEdit)
  5445. {
  5446. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5447. {
  5448. ExecuteFile(Side, efDefaultEditor);
  5449. AllowExec = false;
  5450. }
  5451. }
  5452. else if (Action == rdcaOpen)
  5453. {
  5454. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5455. {
  5456. ExecuteFile(osRemote, efShell);
  5457. AllowExec = false;
  5458. }
  5459. }
  5460. }
  5461. //---------------------------------------------------------------------------
  5462. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5463. {
  5464. return ((Side == osRemote) || (Side == osCurrent));
  5465. }
  5466. //---------------------------------------------------------------------------
  5467. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5468. {
  5469. DebugFail();
  5470. }
  5471. //---------------------------------------------------------------------------
  5472. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5473. {
  5474. DebugFail();
  5475. }
  5476. //---------------------------------------------------------------------------
  5477. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5478. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5479. {
  5480. TSynchronizeParamType Params;
  5481. Params.LocalDirectory = LocalDirectory;
  5482. Params.RemoteDirectory = RemoteDirectory;
  5483. int UnusedParams =
  5484. (GUIConfiguration->SynchronizeParams &
  5485. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5486. TTerminal::spCaseSensitive));
  5487. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5488. Params.Options = GUIConfiguration->SynchronizeOptions;
  5489. bool SaveSettings = false;
  5490. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5491. &DoSynchronizeTooManyDirectories);
  5492. DebugAssert(FSynchronizeController == NULL);
  5493. FSynchronizeController = &Controller;
  5494. bool Result;
  5495. try
  5496. {
  5497. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5498. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5499. int Options =
  5500. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5501. DebugAssert(FOnFeedSynchronizeError == NULL);
  5502. DebugAssert(FOnSynchronizeAbort == NULL);
  5503. DebugAssert(FSynchronizeTerminal == NULL);
  5504. FSynchronizeTerminal = Terminal;
  5505. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5506. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5507. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5508. if (Result)
  5509. {
  5510. if (SaveSettings)
  5511. {
  5512. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5513. GUIConfiguration->SynchronizeOptions = Params.Options;
  5514. }
  5515. else
  5516. {
  5517. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5518. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5519. FLAGSET(Params.Options, soSynchronize))
  5520. {
  5521. GUIConfiguration->SynchronizeOptions =
  5522. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5523. soSynchronize;
  5524. }
  5525. }
  5526. LocalDirectory = Params.LocalDirectory;
  5527. RemoteDirectory = Params.RemoteDirectory;
  5528. }
  5529. }
  5530. __finally
  5531. {
  5532. FSynchronizeController = NULL;
  5533. DebugAssert(FOnFeedSynchronizeError == NULL);
  5534. FOnFeedSynchronizeError = NULL;
  5535. DebugAssert(FOnSynchronizeAbort == NULL);
  5536. FOnSynchronizeAbort = NULL;
  5537. FSynchronizeTerminal = NULL;
  5538. }
  5539. return Result;
  5540. }
  5541. //---------------------------------------------------------------------------
  5542. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5543. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5544. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5545. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5546. TSynchronizeOptions * Options, bool Full)
  5547. {
  5548. // Keep-up-to-date mode
  5549. if (Terminal->Status == ssOpened)
  5550. {
  5551. try
  5552. {
  5553. int PParams = Params.Params;
  5554. if (!Full)
  5555. {
  5556. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5557. if (FLAGSET(Params.Options, soRecurse))
  5558. {
  5559. PParams |= TTerminal::spSubDirs;
  5560. }
  5561. }
  5562. else
  5563. {
  5564. // if keepuptodate is non-recursive,
  5565. // full sync before has to be non-recursive as well
  5566. if (FLAGCLEAR(Params.Options, soRecurse))
  5567. {
  5568. PParams |= TTerminal::spNoRecurse;
  5569. }
  5570. }
  5571. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5572. PParams, Checklist, Options);
  5573. }
  5574. catch (Exception & E)
  5575. {
  5576. if (!Terminal->Active)
  5577. {
  5578. ShowExtendedExceptionEx(Terminal, &E);
  5579. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5580. if (!Terminal->Active)
  5581. {
  5582. throw;
  5583. }
  5584. }
  5585. else
  5586. {
  5587. if (FLAGSET(Params.Options, soContinueOnError) &&
  5588. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5589. {
  5590. // noop, already logged in MoreMessageDialog
  5591. }
  5592. else
  5593. {
  5594. // We get mostly EAbort here, so this is noop.
  5595. // Exception is an error when listing directories while looking for differences.
  5596. ShowExtendedExceptionEx(Terminal, &E);
  5597. throw;
  5598. }
  5599. }
  5600. }
  5601. }
  5602. }
  5603. //---------------------------------------------------------------------------
  5604. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5605. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5606. const UnicodeString ErrorStr)
  5607. {
  5608. if (!Directory.IsEmpty())
  5609. {
  5610. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5611. }
  5612. else
  5613. {
  5614. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5615. }
  5616. }
  5617. //---------------------------------------------------------------------------
  5618. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5619. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5620. {
  5621. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5622. {
  5623. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5624. }
  5625. else
  5626. {
  5627. TMessageParams Params(mpNeverAskAgainCheck);
  5628. unsigned int Result = MessageDialog(
  5629. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5630. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5631. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5632. {
  5633. MaxDirectories *= 2;
  5634. if (Result == qaNeverAskAgain)
  5635. {
  5636. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5637. }
  5638. }
  5639. else
  5640. {
  5641. Abort();
  5642. }
  5643. }
  5644. }
  5645. //---------------------------------------------------------------------------
  5646. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5647. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5648. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5649. TSynchronizeOptions * Options)
  5650. {
  5651. // Keep-up-to-date mode
  5652. DebugAssert(!FAutoOperation);
  5653. void * BatchStorage;
  5654. BatchStart(BatchStorage);
  5655. FAutoOperation = true;
  5656. bool AnyOperation = false;
  5657. TDateTime StartTime = Now();
  5658. TSynchronizeChecklist * AChecklist = NULL;
  5659. try
  5660. {
  5661. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, -1);
  5662. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5663. {
  5664. FSynchronizeProgressForm->Start();
  5665. }
  5666. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5667. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5668. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5669. Options);
  5670. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5671. SAFE_DESTROY(FSynchronizeProgressForm);
  5672. AnyOperation = (AChecklist->CheckedCount > 0);
  5673. if (AnyOperation)
  5674. {
  5675. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5676. CreateProgressForm(&SynchronizeProgress);
  5677. try
  5678. {
  5679. Terminal->SynchronizeApply(
  5680. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5681. SynchronizeProcessedItem, NULL, NULL, NULL);
  5682. }
  5683. __finally
  5684. {
  5685. DestroyProgressForm();
  5686. }
  5687. }
  5688. }
  5689. __finally
  5690. {
  5691. if (Checklist == NULL)
  5692. {
  5693. delete AChecklist;
  5694. }
  5695. else
  5696. {
  5697. *Checklist = AChecklist;
  5698. }
  5699. FAutoOperation = false;
  5700. SAFE_DESTROY(FSynchronizeProgressForm);
  5701. BatchEnd(BatchStorage);
  5702. ReloadLocalDirectory();
  5703. if (AnyOperation)
  5704. {
  5705. OperationComplete(StartTime);
  5706. }
  5707. }
  5708. }
  5709. //---------------------------------------------------------------------------
  5710. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5711. {
  5712. // can be called from command line
  5713. return Visible &&
  5714. ((DirView(osRemote)->SelCount > 0) ||
  5715. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5716. }
  5717. //---------------------------------------------------------------------------
  5718. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5719. {
  5720. LogSynchronizeEvent(Terminal, Message);
  5721. }
  5722. //---------------------------------------------------------------------------
  5723. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5724. int Params, TSynchronizeOptions & Options)
  5725. {
  5726. DebugAssert(!IsLocalBrowserMode());
  5727. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5728. {
  5729. Options.Filter = new TStringList();
  5730. Options.Filter->CaseSensitive = false;
  5731. Options.Filter->Duplicates = Types::dupAccept;
  5732. if (DirView(osRemote)->SelCount > 0)
  5733. {
  5734. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5735. }
  5736. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5737. {
  5738. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5739. }
  5740. Options.Filter->Sort();
  5741. }
  5742. }
  5743. //---------------------------------------------------------------------------
  5744. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5745. {
  5746. TCopyParamType Defaults;
  5747. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5748. ConfigStorage->AccessMode = smRead;
  5749. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5750. {
  5751. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5752. }
  5753. ConfigStorage.reset(NULL);
  5754. std::unique_ptr<TStringList> Options(new TStringList());
  5755. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5756. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5757. UnicodeString Result;
  5758. if (Options->Count > 0)
  5759. {
  5760. Result =
  5761. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5762. }
  5763. return Result;
  5764. }
  5765. //---------------------------------------------------------------------------
  5766. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5767. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5768. {
  5769. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5770. UnicodeString AdditionalParams =
  5771. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5772. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5773. SerializeCopyParamForCommandLine(CopyParams),
  5774. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5775. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5776. ExecuteNewInstance(SessionName, AdditionalParams);
  5777. }
  5778. //---------------------------------------------------------------------------
  5779. struct TSynchronizeParams
  5780. {
  5781. UnicodeString LocalDirectory;
  5782. UnicodeString RemoteDirectory;
  5783. TSynchronizeMode Mode;
  5784. TSynchronizeChecklist * Checklist;
  5785. int Params;
  5786. TCopyParamType * CopyParam;
  5787. TDateTime CollectElapsed;
  5788. TDateTime * StartTime;
  5789. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5790. };
  5791. //---------------------------------------------------------------------------
  5792. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5793. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5794. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5795. {
  5796. DebugAssert(!FAutoOperation);
  5797. void * BatchStorage;
  5798. BatchStart(BatchStorage);
  5799. FAutoOperation = true;
  5800. TFileOperationStatistics Statistics;
  5801. TDateTime Start = Now();
  5802. try
  5803. {
  5804. Params.OnProcessedItem = OnProcessedItem;
  5805. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5806. CreateProgressForm(&SynchronizeProgress);
  5807. Terminal->SynchronizeApply(
  5808. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5809. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5810. &Statistics);
  5811. }
  5812. __finally
  5813. {
  5814. Params.OnProcessedItem = NULL;
  5815. FAutoOperation = false;
  5816. DestroyProgressForm();
  5817. BatchEnd(BatchStorage);
  5818. ReloadLocalDirectory();
  5819. }
  5820. if (WinConfiguration->SynchronizeSummary)
  5821. {
  5822. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5823. // The statistics should be 0 anyway in this case
  5824. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5825. {
  5826. Message += L"\n";
  5827. if (Statistics.FilesUploaded > 0)
  5828. {
  5829. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5830. }
  5831. if (Statistics.FilesDownloaded > 0)
  5832. {
  5833. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5834. }
  5835. if (Statistics.FilesDeletedLocal > 0)
  5836. {
  5837. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5838. }
  5839. if (Statistics.FilesDeletedRemote > 0)
  5840. {
  5841. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5842. }
  5843. }
  5844. TDateTime Elapsed = (Now() - Start);
  5845. Message +=
  5846. L"\n" +
  5847. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Configuration->TimeFormat, Params.CollectElapsed))) + L"\n" +
  5848. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Configuration->TimeFormat, Elapsed)));
  5849. TMessageParams Params(mpNeverAskAgainCheck);
  5850. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5851. if (Result == qaNeverAskAgain)
  5852. {
  5853. WinConfiguration->SynchronizeSummary = false;
  5854. }
  5855. }
  5856. }
  5857. //---------------------------------------------------------------------------
  5858. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5859. {
  5860. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5861. {
  5862. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5863. }
  5864. // Not set in keep-up-to-date mode - Synchronize() method
  5865. if (Token != NULL)
  5866. {
  5867. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5868. if (Params.OnProcessedItem != NULL)
  5869. {
  5870. Params.OnProcessedItem(NULL, ChecklistItem);
  5871. }
  5872. }
  5873. }
  5874. //---------------------------------------------------------------------------
  5875. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5876. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5877. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5878. {
  5879. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5880. *Params.StartTime = Now();
  5881. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5882. }
  5883. //---------------------------------------------------------------------------
  5884. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5885. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5886. {
  5887. // terminal can be already closed (e.g. dropped connection)
  5888. if (Terminal != NULL)
  5889. {
  5890. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5891. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5892. }
  5893. }
  5894. //---------------------------------------------------------------------------
  5895. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5896. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5897. {
  5898. DebugAssert(!IsLocalBrowserMode());
  5899. TAutoBatch AutoBatch(this);
  5900. TAutoFlag AutoOperationFlag(FAutoOperation);
  5901. if (Side == osRemote)
  5902. {
  5903. std::unique_ptr<TStrings> FileList(new TStringList());
  5904. FileList->AddObject(FileName, RemoteFile);
  5905. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5906. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5907. RemoteDirView->SaveSelection();
  5908. RemoteDirView->SaveSelectedNames();
  5909. try
  5910. {
  5911. Terminal->MoveFiles(FileList.get(), Target, FileMask, false);
  5912. }
  5913. catch(...)
  5914. {
  5915. RemoteDirView->DiscardSavedSelection();
  5916. throw;
  5917. }
  5918. RemoteDirView->RestoreSelection();
  5919. }
  5920. else if (DebugAlwaysTrue(Side == osLocal))
  5921. {
  5922. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5923. {
  5924. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5925. }
  5926. UnicodeString Directory = ExtractFileDir(FileName);
  5927. ReloadLocalDirectory(Directory);
  5928. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5929. if (!SamePaths(Directory, NewDirectory))
  5930. {
  5931. ReloadLocalDirectory(NewDirectory);
  5932. }
  5933. }
  5934. }
  5935. //---------------------------------------------------------------------------
  5936. void __fastcall TCustomScpExplorerForm::DoSynchronizeBrowse(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  5937. {
  5938. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  5939. if (Side == osLocal)
  5940. {
  5941. if (Action == TSynchronizeChecklist::saDownloadNew)
  5942. {
  5943. OpenFolderInExplorer(LocalPath);
  5944. }
  5945. else
  5946. {
  5947. OpenFileInExplorer(TPath::Combine(LocalPath, Item->GetFileName()));
  5948. }
  5949. }
  5950. else if (DebugAlwaysTrue(Side == osRemote))
  5951. {
  5952. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  5953. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5954. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  5955. if (!LocalPath.IsEmpty())
  5956. {
  5957. SessionData->LocalDirectory = LocalPath;
  5958. }
  5959. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  5960. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(BROWSE_SWITCH), Item->GetFileName())));
  5961. }
  5962. }
  5963. //---------------------------------------------------------------------------
  5964. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  5965. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  5966. const TCopyParamType * CopyParams)
  5967. {
  5968. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5969. UnicodeString AdditionalParams =
  5970. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5971. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5972. SerializeCopyParamForCommandLine(CopyParams),
  5973. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  5974. LocalDirectory, RemoteDirectory, Mode, Params));
  5975. ExecuteNewInstance(SessionName, AdditionalParams);
  5976. }
  5977. //---------------------------------------------------------------------------
  5978. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  5979. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  5980. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  5981. {
  5982. int Result;
  5983. bool SaveSettings = false;
  5984. int Options =
  5985. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  5986. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  5987. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5988. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  5989. bool Continue =
  5990. (UseDefaults == 0) ||
  5991. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  5992. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults);
  5993. if (Continue)
  5994. {
  5995. Configuration->Usage->Inc(L"Synchronizations");
  5996. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  5997. UpdateCopyParamCounters(CopyParam);
  5998. TSynchronizeOptions SynchronizeOptions;
  5999. GetSynchronizeOptions(Params, SynchronizeOptions);
  6000. if (SaveSettings)
  6001. {
  6002. GUIConfiguration->SynchronizeParams = Params;
  6003. }
  6004. else
  6005. {
  6006. SaveMode = false;
  6007. }
  6008. TDateTime StartTime = Now();
  6009. TSynchronizeChecklist * Checklist = NULL;
  6010. try
  6011. {
  6012. DebugAssert(!FAutoOperation);
  6013. FAutoOperation = true;
  6014. try
  6015. {
  6016. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6017. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6018. int Files = -1;
  6019. if (DataList->Count >= 1)
  6020. {
  6021. Files = StrToIntDef(DataList->Strings[0], Files);
  6022. }
  6023. else
  6024. {
  6025. DataList->Add(UnicodeString());
  6026. }
  6027. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6028. FSynchronizeProgressForm->Start();
  6029. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6030. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6031. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6032. &SynchronizeOptions);
  6033. if (Terminal->SessionData->CacheDirectories)
  6034. {
  6035. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6036. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6037. }
  6038. }
  6039. __finally
  6040. {
  6041. FAutoOperation = false;
  6042. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6043. SAFE_DESTROY(FSynchronizeProgressForm);
  6044. }
  6045. TSynchronizeParams SynchronizeParams;
  6046. SynchronizeParams.LocalDirectory = LocalDirectory;
  6047. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  6048. SynchronizeParams.Mode = Mode;
  6049. SynchronizeParams.CopyParam = &CopyParam;
  6050. SynchronizeParams.Params = Params;
  6051. SynchronizeParams.Checklist = Checklist;
  6052. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6053. SynchronizeParams.StartTime = &StartTime;
  6054. SynchronizeParams.OnProcessedItem = NULL;
  6055. Result = Checklist->Count;
  6056. if (Checklist->Count > 0)
  6057. {
  6058. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6059. {
  6060. if (!DoSynchronizeChecklistDialog(
  6061. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6062. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeBrowse, &SynchronizeParams))
  6063. {
  6064. Result = -1;
  6065. }
  6066. }
  6067. else
  6068. {
  6069. FullSynchronize(SynchronizeParams, NULL, NULL);
  6070. }
  6071. }
  6072. else
  6073. {
  6074. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6075. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6076. }
  6077. }
  6078. __finally
  6079. {
  6080. delete Checklist;
  6081. }
  6082. OperationComplete(StartTime);
  6083. }
  6084. else
  6085. {
  6086. Result = -1;
  6087. }
  6088. return Result;
  6089. }
  6090. //---------------------------------------------------------------------------
  6091. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6092. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6093. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6094. {
  6095. if (Collect)
  6096. {
  6097. DebugAssert(FSynchronizeProgressForm != NULL);
  6098. if (!FSynchronizeProgressForm->Started)
  6099. {
  6100. FSynchronizeProgressForm->Start();
  6101. }
  6102. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6103. SetTaskbarListProgressValue(CompareProgress);
  6104. }
  6105. else
  6106. {
  6107. DebugAssert(FSynchronizeProgressForm == NULL);
  6108. DebugAssert(FProgressForm != NULL);
  6109. }
  6110. }
  6111. //---------------------------------------------------------------------------
  6112. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6113. {
  6114. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6115. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6116. if (File.get() != NULL)
  6117. {
  6118. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6119. Application->ShowMainForm = false;
  6120. Application->Run();
  6121. }
  6122. }
  6123. //---------------------------------------------------------------------------
  6124. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6125. {
  6126. DebugFail();
  6127. }
  6128. //---------------------------------------------------------------------------
  6129. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6130. {
  6131. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6132. SessionData->Assign(ManagedSession->SessionData);
  6133. UpdateSessionData(SessionData.get());
  6134. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6135. if (IsActiveTerminal(ManagedSession))
  6136. {
  6137. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6138. }
  6139. if (!ManagedSession->SessionData->HasSessionName())
  6140. {
  6141. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6142. // once IsWorkspace is cleared
  6143. SessionData->Name = UnicodeString();
  6144. }
  6145. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6146. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6147. SessionData->IsWorkspace = false;
  6148. return SessionData.release();
  6149. }
  6150. //---------------------------------------------------------------------------
  6151. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6152. {
  6153. TSessionData * SessionData = CloneCurrentSessionData();
  6154. try
  6155. {
  6156. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6157. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6158. }
  6159. __finally
  6160. {
  6161. delete SessionData;
  6162. }
  6163. }
  6164. //---------------------------------------------------------------------------
  6165. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6166. {
  6167. TTerminalManager * Manager = TTerminalManager::Instance();
  6168. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6169. if (DebugAlwaysTrue(ManagedSession != NULL))
  6170. {
  6171. // Update ManagedSession->StateData
  6172. UpdateSession(ManagedSession);
  6173. }
  6174. Manager->SaveWorkspace(DataList.get());
  6175. return DataList.release();
  6176. }
  6177. //---------------------------------------------------------------------------
  6178. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6179. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6180. {
  6181. WinConfiguration->LastWorkspace = Name;
  6182. if (!SavePasswords)
  6183. {
  6184. for (int Index = 0; Index < DataList->Count; Index++)
  6185. {
  6186. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6187. if (SessionData->Link.IsEmpty())
  6188. {
  6189. SessionData->ClearSessionPasswords();
  6190. }
  6191. }
  6192. }
  6193. StoredSessions->NewWorkspace(Name, DataList);
  6194. // modified only
  6195. StoredSessions->Save(false, Explicit);
  6196. }
  6197. //---------------------------------------------------------------------------
  6198. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6199. {
  6200. return
  6201. DefaultStr(WinConfiguration->LastWorkspace,
  6202. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6203. }
  6204. //---------------------------------------------------------------------------
  6205. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6206. {
  6207. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6208. bool AnyNonStoredSessionWithPassword = false;
  6209. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6210. bool AllNonStoredSessionsAnonymous = true;
  6211. TTerminalManager * Manager = TTerminalManager::Instance();
  6212. for (int Index = 0; Index < DataList->Count; Index++)
  6213. {
  6214. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6215. if (SessionData->Link.IsEmpty())
  6216. {
  6217. if (SessionData->HasAnySessionPassword())
  6218. {
  6219. AnyNonStoredSessionWithPassword = true;
  6220. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6221. {
  6222. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6223. }
  6224. }
  6225. if (!SameText(SessionData->UserName, AnonymousUserName))
  6226. {
  6227. AllNonStoredSessionsAnonymous = false;
  6228. }
  6229. }
  6230. }
  6231. bool SavePasswords;
  6232. bool * PSavePasswords;
  6233. bool NotRecommendedSavingPasswords =
  6234. !CustomWinConfiguration->UseMasterPassword &&
  6235. !AllNonStoredSessionsAnonymous;
  6236. if (Configuration->DisablePasswordStoring ||
  6237. !AnyNonStoredSessionWithPassword)
  6238. {
  6239. PSavePasswords = NULL;
  6240. SavePasswords = false;
  6241. }
  6242. else
  6243. {
  6244. PSavePasswords = &SavePasswords;
  6245. SavePasswords =
  6246. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6247. !NotRecommendedSavingPasswords;
  6248. }
  6249. UnicodeString Name = WorkspaceName();
  6250. bool CreateShortcut = false;
  6251. bool Result =
  6252. DoSaveWorkspaceDialog(
  6253. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6254. EnableAutoSave);
  6255. if (Result)
  6256. {
  6257. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6258. if (CreateShortcut)
  6259. {
  6260. TOperationVisualizer Visualizer;
  6261. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6262. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6263. }
  6264. if (EnableAutoSave)
  6265. {
  6266. WinConfiguration->AutoSaveWorkspace = true;
  6267. WinConfiguration->AutoWorkspace = Name;
  6268. if (PSavePasswords != NULL)
  6269. {
  6270. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6271. }
  6272. }
  6273. }
  6274. return Result;
  6275. }
  6276. //---------------------------------------------------------------------------
  6277. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6278. {
  6279. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6280. DebugAssert(Session == ManagedSession);
  6281. if (!IsLocalBrowserMode())
  6282. {
  6283. SAFE_DESTROY(Session->RemoteExplorerState);
  6284. if (WinConfiguration->PreservePanelState)
  6285. {
  6286. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6287. }
  6288. }
  6289. UpdateSessionData(Session->StateData);
  6290. }
  6291. //---------------------------------------------------------------------------
  6292. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6293. {
  6294. // Keep in sync with TSessionData::CopyStateData
  6295. DebugAssert(Data != NULL);
  6296. // This is inconsistent with how color (for example) is handled.
  6297. Data->Name = ManagedSession->SessionData->Name;
  6298. if (!IsLocalBrowserMode())
  6299. {
  6300. // cannot use RemoteDirView->Path, because it is empty if connection
  6301. // was already closed
  6302. // also only peek, we may not be connected at all atm
  6303. // so make sure we do not try retrieving current directory from the server
  6304. // (particularly with FTP)
  6305. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6306. if (!ACurrentDirectory.IsEmpty())
  6307. {
  6308. Data->RemoteDirectory = ACurrentDirectory;
  6309. }
  6310. }
  6311. Data->Color = SessionColor;
  6312. }
  6313. //---------------------------------------------------------------------------
  6314. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6315. {
  6316. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6317. DebugAssert(Toolbar != NULL);
  6318. for (int i = 0; i < Toolbar->Items->Count; i++)
  6319. {
  6320. TTBXCustomDropDownItem * DropDownItem;
  6321. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6322. if (DropDownItem != NULL)
  6323. {
  6324. ToolbarItemResize(DropDownItem,
  6325. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6326. Toolbar->NonClientWidth);
  6327. break;
  6328. }
  6329. }
  6330. }
  6331. //---------------------------------------------------------------------------
  6332. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6333. {
  6334. Item->EditWidth = Width;
  6335. }
  6336. //---------------------------------------------------------------------------
  6337. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6338. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6339. {
  6340. for (int i = 0; i < Toolbar->Items->Count; i++)
  6341. {
  6342. TTBXCustomDropDownItem * DropDownItem;
  6343. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6344. if (DropDownItem != NULL)
  6345. {
  6346. ASize.x -= DropDownItem->EditWidth;
  6347. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  6348. }
  6349. }
  6350. }
  6351. //---------------------------------------------------------------------------
  6352. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6353. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6354. {
  6355. if (WinConfiguration->DDWarnLackOfTempSpace)
  6356. {
  6357. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6358. if (!ADrive.IsEmpty())
  6359. {
  6360. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6361. DebugAssert(RequiredSpace >= 0);
  6362. __int64 RequiredWithReserve;
  6363. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6364. if (FreeSpace < RequiredWithReserve)
  6365. {
  6366. unsigned int Result;
  6367. TMessageParams Params(mpNeverAskAgainCheck);
  6368. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6369. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6370. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6371. if (Result == qaNeverAskAgain)
  6372. {
  6373. WinConfiguration->DDWarnLackOfTempSpace = false;
  6374. }
  6375. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6376. }
  6377. }
  6378. }
  6379. }
  6380. //---------------------------------------------------------------------------
  6381. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6382. {
  6383. DoOpenDirectoryDialog(odAddBookmark, Side);
  6384. }
  6385. //---------------------------------------------------------------------------
  6386. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6387. {
  6388. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6389. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6390. try
  6391. {
  6392. TCustomDirView * DView = DirView(Side);
  6393. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6394. {
  6395. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6396. }
  6397. }
  6398. catch (...)
  6399. {
  6400. delete VisitedDirectories;
  6401. throw;
  6402. }
  6403. return VisitedDirectories;
  6404. }
  6405. //---------------------------------------------------------------------------
  6406. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6407. TOpenDirectoryMode Mode, TOperationSide Side)
  6408. {
  6409. bool Continue = true;
  6410. if (Mode == odAddBookmark)
  6411. {
  6412. TMessageParams Params(mpNeverAskAgainCheck);
  6413. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6414. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6415. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6416. unsigned int Answer =
  6417. MessageDialog(Message,
  6418. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6419. if (Answer == qaNeverAskAgain)
  6420. {
  6421. Continue = true;
  6422. WinConfiguration->UseSharedBookmarks = true;
  6423. }
  6424. else if (Answer == qaOK)
  6425. {
  6426. Continue = true;
  6427. WinConfiguration->UseSharedBookmarks = false;
  6428. }
  6429. else
  6430. {
  6431. Continue = false;
  6432. }
  6433. }
  6434. if (Continue)
  6435. {
  6436. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6437. try
  6438. {
  6439. UnicodeString Name = DirView(Side)->PathName;
  6440. bool Repeat;
  6441. do
  6442. {
  6443. Repeat = false;
  6444. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6445. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6446. // do not allow switching to location profiles,
  6447. // if we are not connected
  6448. HasDirView[osLocal] && (Terminal != NULL)))
  6449. {
  6450. TWindowLock Lock(this);
  6451. if (!TryOpenDirectory(Side, Name))
  6452. {
  6453. Repeat = true;
  6454. Mode = odBrowse;
  6455. }
  6456. }
  6457. }
  6458. while (Repeat);
  6459. }
  6460. __finally
  6461. {
  6462. delete VisitedDirectories;
  6463. }
  6464. }
  6465. }
  6466. //---------------------------------------------------------------------------
  6467. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6468. {
  6469. DebugAssert(!Terminal->CommandSessionOpened);
  6470. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6471. }
  6472. //---------------------------------------------------------------------------
  6473. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6474. {
  6475. bool Result = Terminal->IsCapable[Capability] ||
  6476. Terminal->CommandSessionOpened;
  6477. if (!Result)
  6478. {
  6479. DebugAssert(Terminal->IsCapable[fcSecondaryShell]);
  6480. if (!GUIConfiguration->ConfirmCommandSession)
  6481. {
  6482. Result = true;
  6483. }
  6484. else
  6485. {
  6486. TMessageParams Params(mpNeverAskAgainCheck);
  6487. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6488. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6489. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6490. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6491. if (Answer == qaNeverAskAgain)
  6492. {
  6493. GUIConfiguration->ConfirmCommandSession = false;
  6494. Result = true;
  6495. }
  6496. else if (Answer == qaOK)
  6497. {
  6498. Result = true;
  6499. }
  6500. }
  6501. if (Result)
  6502. {
  6503. Result = CommandSessionFallback();
  6504. }
  6505. }
  6506. return Result;
  6507. }
  6508. //---------------------------------------------------------------------------
  6509. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6510. {
  6511. if (EnsureCommandSessionFallback(fcAnyCommand))
  6512. {
  6513. DoConsoleDialog(Terminal, Command);
  6514. }
  6515. }
  6516. //---------------------------------------------------------------------------
  6517. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6518. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6519. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6520. {
  6521. if (!IsSideLocalBrowser(osRemote) &&
  6522. IsFileControl(DropSourceControl, osRemote) &&
  6523. (FDDExtMapFile != NULL))
  6524. {
  6525. Accept = true;
  6526. }
  6527. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6528. DebugAssert(FDDTargetControl != NULL);
  6529. }
  6530. //---------------------------------------------------------------------------
  6531. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6532. _di_IDataObject DataObj, int KeyState,
  6533. const TPoint & Point, int & Effect, bool & Accept)
  6534. {
  6535. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6536. }
  6537. //---------------------------------------------------------------------------
  6538. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6539. _di_IDataObject DataObj, int KeyState,
  6540. const TPoint & Point, int & Effect, bool & Accept)
  6541. {
  6542. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6543. }
  6544. //---------------------------------------------------------------------------
  6545. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6546. TObject * Sender)
  6547. {
  6548. DebugUsedParam(Sender);
  6549. DebugAssert(FDDTargetControl == Sender);
  6550. FDDTargetControl = NULL;
  6551. }
  6552. //---------------------------------------------------------------------------
  6553. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  6554. {
  6555. FileControlDDDragLeave(SessionsPageControl);
  6556. }
  6557. //---------------------------------------------------------------------------
  6558. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  6559. {
  6560. FileControlDDDragLeave(QueueView3);
  6561. }
  6562. //---------------------------------------------------------------------------
  6563. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6564. {
  6565. DebugAssert(!IsSideLocalBrowser(Side));
  6566. DebugUsedParam(Side);
  6567. bool Edit = false;
  6568. TRemoteFile * File = NULL;
  6569. UnicodeString FileName;
  6570. UnicodeString PointTo;
  6571. bool SymbolicLink = true;
  6572. if (RemoteDirView->ItemFocused)
  6573. {
  6574. DebugAssert(RemoteDirView->ItemFocused->Data);
  6575. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6576. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6577. if (Edit)
  6578. {
  6579. FileName = File->FileName;
  6580. PointTo = File->LinkTo;
  6581. }
  6582. else if (!File->IsParentDirectory)
  6583. {
  6584. PointTo = File->FileName;
  6585. }
  6586. }
  6587. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6588. Terminal->IsCapable[fcHardLink]))
  6589. {
  6590. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6591. if (Edit)
  6592. {
  6593. DebugAssert(File->FileName == FileName);
  6594. int Params = dfNoRecursive;
  6595. Terminal->ExceptionOnFail = true;
  6596. try
  6597. {
  6598. Terminal->DeleteFile(L"", File, &Params);
  6599. }
  6600. __finally
  6601. {
  6602. Terminal->ExceptionOnFail = false;
  6603. }
  6604. }
  6605. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6606. }
  6607. }
  6608. //---------------------------------------------------------------------------
  6609. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6610. {
  6611. return
  6612. (IsSideLocalBrowser(Side) ||
  6613. (HasActiveTerminal() &&
  6614. Terminal->ResolvingSymlinks &&
  6615. Terminal->IsCapable[fcSymbolicLink]));
  6616. }
  6617. //---------------------------------------------------------------------------
  6618. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6619. {
  6620. return
  6621. !IsSideLocalBrowser(FCurrentSide) &&
  6622. (RemoteDirView->ItemFocused != NULL) &&
  6623. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6624. Terminal->SessionData->ResolveSymlinks;
  6625. }
  6626. //---------------------------------------------------------------------------
  6627. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6628. {
  6629. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6630. FForceExecution = true;
  6631. try
  6632. {
  6633. DirView(osCurrent)->ExecuteCurrentFile();
  6634. }
  6635. __finally
  6636. {
  6637. FForceExecution = false;
  6638. }
  6639. }
  6640. //---------------------------------------------------------------------------
  6641. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6642. {
  6643. TEditorData ExternalEditor;
  6644. ExternalEditor.Editor = edExternal;
  6645. bool Remember = false;
  6646. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6647. {
  6648. if (Remember)
  6649. {
  6650. TEditorList * EditorList = new TEditorList;
  6651. try
  6652. {
  6653. *EditorList = *WinConfiguration->EditorList;
  6654. bool Found = false;
  6655. int i = 0;
  6656. while (!Found && (i < EditorList->Count))
  6657. {
  6658. const TEditorPreferences * Editor = EditorList->Editors[i];
  6659. if ((Editor->Data->Editor == edExternal) &&
  6660. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6661. {
  6662. Found = true;
  6663. }
  6664. i++;
  6665. }
  6666. if (!Found)
  6667. {
  6668. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6669. WinConfiguration->EditorList = EditorList;
  6670. }
  6671. }
  6672. __finally
  6673. {
  6674. delete EditorList;
  6675. }
  6676. }
  6677. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6678. }
  6679. }
  6680. //---------------------------------------------------------------------------
  6681. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6682. {
  6683. if (FFileFindTerminal == ATerminal)
  6684. {
  6685. FFileFindTerminal = NULL;
  6686. HideFileFindDialog();
  6687. }
  6688. if (FClipboardTerminal == ATerminal)
  6689. {
  6690. ClipboardClear(); // implies ClipboardStop
  6691. }
  6692. if ((FOnSynchronizeAbort != NULL) &&
  6693. (ATerminal == FManagedSession))
  6694. {
  6695. FOnSynchronizeAbort(NULL);
  6696. }
  6697. }
  6698. //---------------------------------------------------------------------------
  6699. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6700. {
  6701. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6702. DetachTerminal(Sender);
  6703. }
  6704. //---------------------------------------------------------------------------
  6705. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6706. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6707. {
  6708. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6709. DebugAssert(Terminal != NULL);
  6710. if (Data->Terminal == Terminal)
  6711. {
  6712. Data->Terminal = NULL;
  6713. }
  6714. }
  6715. //---------------------------------------------------------------------------
  6716. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6717. {
  6718. return NULL;
  6719. }
  6720. //---------------------------------------------------------------------------
  6721. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6722. {
  6723. UpdateControls();
  6724. SessionColor = TColor(0);
  6725. UpdateRemotePathComboBox(false);
  6726. NeedSession(false);
  6727. }
  6728. //---------------------------------------------------------------------------
  6729. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6730. {
  6731. try
  6732. {
  6733. // Cache, as the login dialog can change its value.
  6734. // See also DoShow. Also see TTerminalManager::NewSession.
  6735. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6736. try
  6737. {
  6738. if (ShowLogin)
  6739. {
  6740. bool ReloadSessions = !Startup;
  6741. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6742. }
  6743. }
  6744. __finally
  6745. {
  6746. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6747. // (so there was no chance for the user to open any session yet)
  6748. if ((ShowLogin || !Startup) &&
  6749. !WinConfiguration->KeepOpenWhenNoSession &&
  6750. // this rules out the implicit Commander's local-local browser
  6751. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6752. {
  6753. TerminateApplication();
  6754. }
  6755. }
  6756. }
  6757. catch (EAbort &)
  6758. {
  6759. // swallow
  6760. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6761. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6762. }
  6763. }
  6764. //---------------------------------------------------------------------------
  6765. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6766. {
  6767. TTerminalManager * Manager = TTerminalManager::Instance();
  6768. DebugAssert(!Manager->Updating);
  6769. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6770. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6771. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6772. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6773. try
  6774. {
  6775. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6776. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6777. {
  6778. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6779. }
  6780. for (int Index = 0; Index <= Manager->Count; Index++)
  6781. {
  6782. TThemeTabSheet * TabSheet;
  6783. if (Index >= SessionsPageControl->PageCount)
  6784. {
  6785. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6786. TabSheet->PageControl = SessionsPageControl;
  6787. }
  6788. else
  6789. {
  6790. TabSheet = SessionsPageControl->Pages[Index];
  6791. }
  6792. bool IsSessionTab = (Index < Manager->Count);
  6793. if (IsSessionTab)
  6794. {
  6795. TTerminal * Terminal = Manager->Sessions[Index];
  6796. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6797. TabSheet->CaptionTruncation = tttEllipsis;
  6798. UpdateSessionTab(TabSheet);
  6799. }
  6800. else
  6801. {
  6802. TabSheet->Tag = 0; // not really needed
  6803. TabSheet->Shadowed = false;
  6804. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6805. TabSheet->CaptionTruncation = tttNoText;
  6806. // 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)
  6807. UpdateNewTabTab();
  6808. }
  6809. }
  6810. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6811. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6812. {
  6813. SessionsPageControl->UpdateTabsCaptionTruncation();
  6814. }
  6815. }
  6816. __finally
  6817. {
  6818. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6819. }
  6820. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6821. }
  6822. //---------------------------------------------------------------------------
  6823. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6824. {
  6825. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6826. }
  6827. //---------------------------------------------------------------------------
  6828. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  6829. {
  6830. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6831. UnicodeString TabCaption;
  6832. if (WinConfiguration->SelectiveToolbarText)
  6833. {
  6834. TabCaption = GetNewTabTabCaption();
  6835. }
  6836. TabSheet->BaseCaption = TabCaption;
  6837. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  6838. }
  6839. //---------------------------------------------------------------------------
  6840. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  6841. {
  6842. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  6843. }
  6844. //---------------------------------------------------------------------------
  6845. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  6846. {
  6847. DebugFail();
  6848. return UnicodeString();
  6849. }
  6850. //---------------------------------------------------------------------------
  6851. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  6852. {
  6853. if (DebugAlwaysTrue(TabSheet != NULL))
  6854. {
  6855. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  6856. if (DebugAlwaysTrue(ASession != NULL))
  6857. {
  6858. TColor Color = (ASession == Terminal) ? FSessionColor : ASession->StateData->Color;
  6859. if (ASession->LocalBrowser)
  6860. {
  6861. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  6862. }
  6863. else
  6864. {
  6865. TabSheet->ImageIndex = AddSessionColor(Color);
  6866. }
  6867. TTerminalManager * Manager = TTerminalManager::Instance();
  6868. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  6869. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  6870. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  6871. }
  6872. }
  6873. }
  6874. //---------------------------------------------------------------------------
  6875. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  6876. {
  6877. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  6878. }
  6879. //---------------------------------------------------------------------------
  6880. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6881. {
  6882. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6883. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  6884. bool Result = (Session != NULL);
  6885. if (Result)
  6886. {
  6887. TTerminalManager::Instance()->ActiveSession = Session;
  6888. }
  6889. else
  6890. {
  6891. try
  6892. {
  6893. NewTab();
  6894. }
  6895. __finally
  6896. {
  6897. SessionListChanged();
  6898. }
  6899. FSessionsPageControlNewTabTime = Now();
  6900. }
  6901. return Result;
  6902. }
  6903. //---------------------------------------------------------------------------
  6904. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  6905. {
  6906. TWindowLock Lock(this);
  6907. SessionTabSwitched();
  6908. }
  6909. //---------------------------------------------------------------------------
  6910. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  6911. {
  6912. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  6913. DebugAssert(TransferList != NULL);
  6914. UnicodeString Name;
  6915. if (TransferList->ItemIndex <= 0)
  6916. {
  6917. Name = L"";
  6918. }
  6919. else
  6920. {
  6921. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  6922. }
  6923. if (FCopyParamAutoSelected.IsEmpty())
  6924. {
  6925. // if previous preset was not autoselected, make new preset the "default"
  6926. FCopyParamDefault = Name;
  6927. }
  6928. GUIConfiguration->CopyParamCurrent = Name;
  6929. }
  6930. //---------------------------------------------------------------------------
  6931. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  6932. {
  6933. // sanity check
  6934. bool ExistingPreset =
  6935. (FTransferListHoverIndex >= 0) &&
  6936. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  6937. DebugAssert(ExistingPreset);
  6938. if (ExistingPreset)
  6939. {
  6940. HDC DC = GetDC(0);
  6941. TCanvas * Canvas = new TCanvas();
  6942. try
  6943. {
  6944. Canvas->Handle = DC;
  6945. Canvas->Font = GetToolbarFont(this);
  6946. UnicodeString Name;
  6947. if (FTransferListHoverIndex == 0)
  6948. {
  6949. Name = L"";
  6950. }
  6951. else
  6952. {
  6953. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  6954. }
  6955. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  6956. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  6957. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  6958. static_cast<TObject*>(GetComponent(fcTransferList)));
  6959. UnicodeString InfoStr =
  6960. GUIConfiguration->CopyParamPreset[Name].
  6961. GetInfoStr(L"; ",
  6962. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  6963. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  6964. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  6965. {
  6966. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  6967. {
  6968. InfoStr.SetLength(InfoStr.Length() - 1);
  6969. }
  6970. InfoStr += Ellipsis;
  6971. }
  6972. // UpdateCaption does not cause invalidation of whole submenu, while
  6973. // setting Caption property does.
  6974. // also it probably does not resize the label, even if necessary
  6975. // (we do not want that anyway)
  6976. TransferLabel->UpdateCaption(InfoStr);
  6977. }
  6978. __finally
  6979. {
  6980. Canvas->Handle = NULL;
  6981. ReleaseDC(0, DC);
  6982. delete Canvas;
  6983. }
  6984. }
  6985. }
  6986. //---------------------------------------------------------------------------
  6987. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  6988. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  6989. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  6990. {
  6991. if (FTransferListHoverIndex != AHoverIndex)
  6992. {
  6993. FTransferListHoverIndex = AHoverIndex;
  6994. UpdateTransferLabel();
  6995. }
  6996. }
  6997. //---------------------------------------------------------------------------
  6998. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  6999. {
  7000. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7001. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7002. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7003. {
  7004. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7005. {
  7006. if (!NonVisualDataModule->Busy)
  7007. {
  7008. OpenDirectory(GetSide(osCurrent));
  7009. }
  7010. Message.Result = 1;
  7011. }
  7012. else
  7013. {
  7014. TForm::Dispatch(&Message);
  7015. }
  7016. }
  7017. else
  7018. {
  7019. TForm::Dispatch(&Message);
  7020. }
  7021. }
  7022. //---------------------------------------------------------------------------
  7023. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7024. {
  7025. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7026. if ((FIgnoreNextDialogChar != 0) &&
  7027. (toupper(Message.CharCode) == toupper(FIgnoreNextDialogChar)))
  7028. {
  7029. Message.Result = 1;
  7030. }
  7031. else
  7032. {
  7033. TForm::Dispatch(&Message);
  7034. }
  7035. FIgnoreNextDialogChar = 0;
  7036. }
  7037. //---------------------------------------------------------------------------
  7038. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7039. {
  7040. // The four low-order bits are used internally by Windows
  7041. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7042. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7043. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7044. // 61730 - restore thru double click - undocumented
  7045. // 61490 - maximize thru double click - undocumented
  7046. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7047. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7048. {
  7049. SysResizing(Cmd);
  7050. }
  7051. TForm::Dispatch(&Message);
  7052. }
  7053. //---------------------------------------------------------------------------
  7054. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7055. {
  7056. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7057. // Also there no point returning TRUE as we are not able to
  7058. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7059. // Hence the process termination might be safer :)
  7060. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7061. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7062. {
  7063. Message.Result = FALSE;
  7064. }
  7065. else
  7066. {
  7067. Message.Result = TRUE;
  7068. }
  7069. // Do not call default handling as that triggers OnCloseQuery,
  7070. // where our implementation will popup confirmation dialogs, what we do not want,
  7071. // as per Vista guidelines:
  7072. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7073. }
  7074. //---------------------------------------------------------------------------
  7075. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7076. {
  7077. if (Message.EndSession && IsApplicationMinimized())
  7078. {
  7079. // WORKAROUND
  7080. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7081. // when it receives WM_ENDSESSION,
  7082. // but that sometimes (particularly when application is minimized) cause crashes.
  7083. // Crash popups message that blocks log off.
  7084. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7085. // so we call ExitProcess() immediately, not even trying to cleanup.
  7086. // It still causes beep, so there's likely some popup, but it does not block
  7087. // log off.
  7088. ExitProcess(0);
  7089. }
  7090. TForm::Dispatch(&Message);
  7091. }
  7092. #ifdef _DEBUG
  7093. //---------------------------------------------------------------------------
  7094. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  7095. {
  7096. TForm::Dispatch(&Message);
  7097. }
  7098. #endif
  7099. //---------------------------------------------------------------------------
  7100. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7101. {
  7102. }
  7103. //---------------------------------------------------------------------------
  7104. void __fastcall TCustomScpExplorerForm::DoShow()
  7105. {
  7106. // Called from TCustomScpExplorerForm::CMShowingChanged
  7107. // only now are the controls resized finally, so the size constraints
  7108. // will not conflict with possibly very small window size
  7109. RestoreFormParams();
  7110. // This indicates that the form was rescaled after parameters were loaded and
  7111. // as most probably the parameters were actually saved with the current form scaling
  7112. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7113. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7114. // and no rounding problems will occur.
  7115. // See also RestoreForm.
  7116. // (we should be safe to call RestoreParams unconditionally)
  7117. if (PixelsPerInch != Screen->PixelsPerInch)
  7118. {
  7119. RestoreParams();
  7120. }
  7121. FixControlsPlacement();
  7122. if (Position == poDefaultPosOnly)
  7123. {
  7124. CutFormToDesktop(this);
  7125. }
  7126. TForm::DoShow();
  7127. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7128. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7129. // This was previously in NeedSession, where other related code is.
  7130. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7131. // unpleasantly shows briefly.
  7132. if ((ManagedSession == NULL) &&
  7133. !WinConfiguration->ShowLoginWhenNoSession &&
  7134. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7135. // This detects if workspace was saved the last time the main widow was closed
  7136. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7137. {
  7138. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7139. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7140. }
  7141. // Before main window displays
  7142. if (ManagedSession == NULL)
  7143. {
  7144. StartingWithoutSession();
  7145. }
  7146. UpdatePixelsPerInchMainWindowCounter();
  7147. FShowing = true;
  7148. }
  7149. //---------------------------------------------------------------------------
  7150. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7151. {
  7152. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7153. }
  7154. //---------------------------------------------------------------------------
  7155. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7156. {
  7157. SessionListChanged();
  7158. InitStatusBar();
  7159. UpdateControls();
  7160. }
  7161. //---------------------------------------------------------------------------
  7162. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7163. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7164. TNotifyEvent OnBalloonClick, TObject * UserData)
  7165. {
  7166. bool Do;
  7167. UnicodeString Message;
  7168. if (E == NULL)
  7169. {
  7170. Message = Str;
  7171. Do = true;
  7172. }
  7173. else
  7174. {
  7175. Do = ExceptionMessage(E, Message);
  7176. }
  7177. if (Do && WinConfiguration->BalloonNotifications)
  7178. {
  7179. UnicodeString Title;
  7180. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7181. {
  7182. Message = TrimLeft(Message);
  7183. }
  7184. else
  7185. {
  7186. Message = UnformatMessage(Message);
  7187. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7188. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7189. Title = LoadResourceString(Captions[Type]);
  7190. if (Terminal != NULL)
  7191. {
  7192. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7193. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7194. }
  7195. }
  7196. if (Seconds == 0)
  7197. {
  7198. Seconds = WinConfiguration->NotificationsTimeout;
  7199. }
  7200. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7201. }
  7202. }
  7203. //---------------------------------------------------------------------------
  7204. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7205. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7206. UnicodeString HelpKeyword, const TMessageParams * Params,
  7207. TTerminal * Terminal)
  7208. {
  7209. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7210. (FOnFeedSynchronizeError != NULL)) &&
  7211. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7212. {
  7213. if (FOnFeedSynchronizeError != NULL)
  7214. {
  7215. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7216. }
  7217. else
  7218. {
  7219. DebugAssert(FErrorList != NULL);
  7220. TStringList * MoreMessagesCopy = NULL;
  7221. if (MoreMessages)
  7222. {
  7223. MoreMessagesCopy = new TStringList();
  7224. MoreMessagesCopy->Assign(MoreMessages);
  7225. }
  7226. FErrorList->AddObject(Message, MoreMessagesCopy);
  7227. }
  7228. PopupTrayBalloon(Terminal, Message, Type);
  7229. return ContinueAnswer(Answers);
  7230. }
  7231. else
  7232. {
  7233. bool UseBalloon = FTrayIcon->Visible;
  7234. if (UseBalloon)
  7235. {
  7236. PopupTrayBalloon(Terminal, Message, Type);
  7237. }
  7238. unsigned int Result;
  7239. try
  7240. {
  7241. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7242. }
  7243. __finally
  7244. {
  7245. // cancel only balloon we popped up, otherwise we may cancel notification
  7246. // balloon that was there before the message dialog
  7247. // (such as "dd confirmation opt in balloon)
  7248. if (UseBalloon)
  7249. {
  7250. FTrayIcon->CancelBalloon();
  7251. }
  7252. }
  7253. return Result;
  7254. }
  7255. }
  7256. //---------------------------------------------------------------------------
  7257. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7258. TTerminal * Terminal, Exception * E)
  7259. {
  7260. if (FTrayIcon->Visible)
  7261. {
  7262. PopupTrayBalloon(Terminal, L"", qtError, E);
  7263. }
  7264. // particularly prevent opening new session from jump list,
  7265. // while exception is shown
  7266. NonVisualDataModule->StartBusy();
  7267. try
  7268. {
  7269. ShowExtendedExceptionEx(Terminal, E);
  7270. }
  7271. __finally
  7272. {
  7273. NonVisualDataModule->EndBusy();
  7274. FTrayIcon->CancelBalloon();
  7275. }
  7276. }
  7277. //---------------------------------------------------------------------------
  7278. void __fastcall TCustomScpExplorerForm::SessionReady()
  7279. {
  7280. InitStatusBar();
  7281. // cannot rely on active page being page for active terminal,
  7282. // as it can happen that active page is the "new session" page
  7283. // (e.g. when reconnecting active terminal, while login dialog
  7284. // invoked from "new session" page is modal)
  7285. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7286. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7287. }
  7288. //---------------------------------------------------------------------------
  7289. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  7290. TTerminal * Terminal, Exception * E)
  7291. {
  7292. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  7293. if (!Terminal->Active)
  7294. {
  7295. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7296. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7297. {
  7298. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7299. }
  7300. }
  7301. }
  7302. //---------------------------------------------------------------------------
  7303. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  7304. UnicodeString Message, TQueryType Type,
  7305. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7306. {
  7307. if ((E == NULL) ||
  7308. ExceptionMessage(E, Message))
  7309. {
  7310. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7311. if (Important)
  7312. {
  7313. Seconds *= 5;
  7314. }
  7315. UnicodeString NoteMessage(UnformatMessage(Message));
  7316. if (Terminal != NULL)
  7317. {
  7318. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7319. NoteMessage = FORMAT(L"%s: %s",
  7320. (TTerminalManager::Instance()->GetSessionTitle(Session, true), NoteMessage));
  7321. }
  7322. if (WinConfiguration->BalloonNotifications)
  7323. {
  7324. AddNote(NoteMessage);
  7325. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7326. }
  7327. else
  7328. {
  7329. FlashOnBackground();
  7330. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7331. }
  7332. }
  7333. }
  7334. //---------------------------------------------------------------------------
  7335. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7336. {
  7337. RestoreApp();
  7338. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7339. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7340. !NonVisualDataModule->Busy)
  7341. {
  7342. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7343. TTerminalManager::Instance()->ActiveSession = Terminal;
  7344. if (!ComponentVisible[fcQueueView])
  7345. {
  7346. ToggleQueueVisibility();
  7347. GoToQueue();
  7348. }
  7349. }
  7350. }
  7351. //---------------------------------------------------------------------------
  7352. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7353. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7354. {
  7355. UnicodeString Message;
  7356. TNotifyEvent OnClick = NULL;
  7357. TObject * UserData = NULL;
  7358. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7359. switch (Event)
  7360. {
  7361. case qeEmptyButMonitored:
  7362. if ((ATerminal != Terminal) || QueueInvisible)
  7363. {
  7364. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7365. OnClick = QueueEmptyNoteClicked;
  7366. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7367. TerminalNoteData->Terminal = ATerminal;
  7368. UserData = TerminalNoteData;
  7369. }
  7370. break;
  7371. case qeEmpty:
  7372. OperationComplete(ATerminal->QueueOperationStart);
  7373. break;
  7374. case qePendingUserAction:
  7375. if ((ATerminal != Terminal) ||
  7376. (QueueInvisible && !IsQueueAutoPopup()))
  7377. {
  7378. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7379. }
  7380. break;
  7381. default:
  7382. DebugFail();
  7383. }
  7384. if (!Message.IsEmpty())
  7385. {
  7386. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7387. }
  7388. }
  7389. //---------------------------------------------------------------------------
  7390. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7391. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7392. {
  7393. if (FDDExtMapFile != NULL)
  7394. {
  7395. CloseHandle(FDDExtMapFile);
  7396. FDDExtMapFile = NULL;
  7397. }
  7398. if (WinConfiguration->DDFakeFile)
  7399. {
  7400. DDFakeFileInitDrag(FileList, Created);
  7401. }
  7402. }
  7403. //---------------------------------------------------------------------------
  7404. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7405. {
  7406. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7407. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7408. {
  7409. FFakeFileDropTarget = FileName;
  7410. }
  7411. }
  7412. //---------------------------------------------------------------------------
  7413. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7414. {
  7415. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7416. if (!ForceDirectories(ApiPath(Result)))
  7417. {
  7418. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7419. }
  7420. FileSetAttr(ApiPath(Result), faHidden);
  7421. return Result;
  7422. }
  7423. //---------------------------------------------------------------------------
  7424. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7425. bool & Created)
  7426. {
  7427. FFakeFileDropTarget = UnicodeString();
  7428. FDragFakeDirectory = CreateFakeTransferDirectory();
  7429. FileList->AddItem(NULL, FDragFakeDirectory);
  7430. Created = true;
  7431. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7432. {
  7433. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7434. }
  7435. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7436. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7437. {
  7438. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7439. TDragExtCommStruct* CommStruct;
  7440. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7441. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7442. DebugAssert(CommStruct != NULL);
  7443. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7444. CommStruct->Dragging = true;
  7445. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7446. LENOF(CommStruct->DropDest));
  7447. NULL_TERMINATE(CommStruct->DropDest);
  7448. UnmapViewOfFile(CommStruct);
  7449. }
  7450. }
  7451. //---------------------------------------------------------------------------
  7452. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7453. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7454. {
  7455. bool Result;
  7456. DebugAssert(!IsLocalBrowserMode());
  7457. if (Sender == RemoteDirView)
  7458. {
  7459. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7460. }
  7461. else
  7462. {
  7463. DebugAssert(Sender == RemoteDriveView);
  7464. TStrings * FileList = RemoteDriveView->DragFileList();
  7465. try
  7466. {
  7467. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7468. }
  7469. __finally
  7470. {
  7471. delete FileList;
  7472. }
  7473. }
  7474. if (FDDTargetControl == RemoteDriveView)
  7475. {
  7476. RemoteDriveView->UpdateDropTarget();
  7477. }
  7478. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7479. // or from tree view to dir view.
  7480. // foMove happens when file/dir is dragged from remote tree view outside of
  7481. // application via dragex
  7482. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7483. (DropSourceControl == RemoteDriveView))
  7484. {
  7485. RemoteDriveView->UpdateDropSource();
  7486. }
  7487. return Result;
  7488. }
  7489. //---------------------------------------------------------------------------
  7490. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7491. {
  7492. DebugAssert(!IsLocalBrowserMode());
  7493. // This also handles drops of remote files to queue.
  7494. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7495. SAFE_DESTROY(FDDFileList);
  7496. if (!FFakeFileDropTarget.IsEmpty())
  7497. {
  7498. RemoveDir(ApiPath(FFakeFileDropTarget));
  7499. }
  7500. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7501. {
  7502. try
  7503. {
  7504. TDragResult DDResult = (Sender == RemoteDirView) ?
  7505. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7506. // Focus is moved to the target application,
  7507. // but as we are going to present the UI, we need to steal the focus back.
  7508. // This most likely won't work though (windows does not allow application
  7509. // to steal focus most of the time)
  7510. Application->BringToFront();
  7511. // On older version of Windows we never got drMove here, see also comment below.
  7512. // On Windows 10, we get the "move".
  7513. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7514. {
  7515. UnicodeString TargetDirectory;
  7516. TFileOperation Operation;
  7517. // drInvalid may mean drMove, see comment below
  7518. switch (DDResult)
  7519. {
  7520. case drCopy:
  7521. Operation = foCopy;
  7522. break;
  7523. case drMove:
  7524. Operation = foMove;
  7525. break;
  7526. default:
  7527. DebugFail();
  7528. case drInvalid:
  7529. // prefer "copy" for safety
  7530. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7531. break;
  7532. }
  7533. TTransferOperationParam Param;
  7534. UnicodeString CounterName;
  7535. bool ForceQueue;
  7536. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7537. {
  7538. // we get drInvalid both if d&d was intercepted by ddext,
  7539. // and when users drops on no-drop location.
  7540. // we tell the difference by existence of response from ddext,
  7541. // so we ignore absence of response in this case
  7542. if (DDResult != drInvalid)
  7543. {
  7544. // here we know that the extension is installed,
  7545. // as it is checked as soon as drag&drop starts from
  7546. // RemoteFileControlDDCreateDragFileList
  7547. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7548. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7549. {
  7550. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7551. }
  7552. else
  7553. {
  7554. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7555. }
  7556. }
  7557. }
  7558. else
  7559. {
  7560. // download using fake file
  7561. Param.Temp = false;
  7562. Param.DragDrop = true;
  7563. if (ForceQueue)
  7564. {
  7565. Param.Queue = asOn;
  7566. }
  7567. if (Sender == RemoteDirView)
  7568. {
  7569. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7570. }
  7571. if (RemoteFileControlFileOperation(Sender, Operation,
  7572. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7573. {
  7574. Configuration->Usage->Inc(CounterName);
  7575. }
  7576. }
  7577. }
  7578. }
  7579. __finally
  7580. {
  7581. CloseHandle(FDDExtMapFile);
  7582. FDDExtMapFile = NULL;
  7583. delete FDragFakeMonitors;
  7584. FDragFakeMonitors = NULL;
  7585. RemoveDir(ApiPath(FDragFakeDirectory));
  7586. FDragFakeDirectory = L"";
  7587. FFakeFileDropTarget = UnicodeString();
  7588. }
  7589. }
  7590. if (FDragDropSshTerminate.get() != NULL)
  7591. {
  7592. FDragDropSshTerminate->Rethrow();
  7593. }
  7594. }
  7595. //---------------------------------------------------------------------------
  7596. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7597. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7598. {
  7599. // Remember drop effect so we know (when user drops files), if we copy or move
  7600. FLastDropEffect = dwEffect;
  7601. }
  7602. //---------------------------------------------------------------------------
  7603. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7604. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7605. {
  7606. bool Result;
  7607. if (FDDTargetControl == QueueView3)
  7608. {
  7609. Directory = DefaultDownloadTargetDirectory();
  7610. Result = true;
  7611. CounterName = L"DownloadsDragDropQueue";
  7612. ForceQueue = true;
  7613. }
  7614. else if (!FFakeFileDropTarget.IsEmpty())
  7615. {
  7616. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7617. Result = true;
  7618. ForceQueue = false;
  7619. CounterName = L"DownloadsDragDropFakeFile";
  7620. }
  7621. else
  7622. {
  7623. ForceQueue = false;
  7624. Enabled = false;
  7625. try
  7626. {
  7627. int Timer = 0;
  7628. Result = false;
  7629. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7630. {
  7631. {
  7632. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7633. TDragExtCommStruct* CommStruct;
  7634. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7635. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7636. DebugAssert(CommStruct != NULL);
  7637. Result = !CommStruct->Dragging;
  7638. if (Result)
  7639. {
  7640. Directory = ExtractFilePath(CommStruct->DropDest);
  7641. CounterName = L"DownloadsDragDropExternalExt";
  7642. }
  7643. UnmapViewOfFile(CommStruct);
  7644. }
  7645. if (!Result)
  7646. {
  7647. Sleep(50);
  7648. Timer += 50;
  7649. Application->ProcessMessages();
  7650. }
  7651. }
  7652. }
  7653. __finally
  7654. {
  7655. Enabled = true;
  7656. }
  7657. }
  7658. return Result;
  7659. }
  7660. //---------------------------------------------------------------------------
  7661. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7662. const UnicodeString TempDir, int SecDelay)
  7663. {
  7664. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7665. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7666. if (FDelayedDeletionTimer == NULL)
  7667. {
  7668. DebugAssert(HandleAllocated());
  7669. FDelayedDeletionTimer = new TTimer(this);
  7670. FDelayedDeletionTimer->Interval = 10000;
  7671. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7672. }
  7673. else
  7674. {
  7675. FDelayedDeletionTimer->Enabled = true;
  7676. }
  7677. }
  7678. //---------------------------------------------------------------------------
  7679. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7680. {
  7681. DebugAssert(FDelayedDeletionList != NULL);
  7682. TDateTime N = Now();
  7683. TDateTime Alert;
  7684. UnicodeString Directory;
  7685. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7686. {
  7687. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7688. if ((N >= Alert) || (Sender == NULL))
  7689. {
  7690. Directory = FDelayedDeletionList->Strings[Index];
  7691. if (DeleteDirectory(ExcludeTrailingBackslash(Directory)))
  7692. {
  7693. FDelayedDeletionList->Delete(Index);
  7694. }
  7695. }
  7696. }
  7697. if (FDelayedDeletionList->Count == 0)
  7698. {
  7699. FDelayedDeletionTimer->Enabled = false;
  7700. }
  7701. }
  7702. //---------------------------------------------------------------------------
  7703. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7704. {
  7705. DebugAssert(!IsLocalBrowserMode());
  7706. if (IsFileControl(FDDTargetControl, osRemote) ||
  7707. (FDDTargetControl == SessionsPageControl))
  7708. {
  7709. TManagedTerminal * TargetTerminal = NULL;
  7710. TFileOperation Operation = foNone;
  7711. if (FDDTargetControl == SessionsPageControl)
  7712. {
  7713. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7714. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7715. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7716. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7717. if (IsActiveTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7718. {
  7719. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7720. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7721. {
  7722. Operation = foRemoteMove;
  7723. }
  7724. else
  7725. {
  7726. Operation = foRemoteCopy;
  7727. }
  7728. }
  7729. }
  7730. else
  7731. {
  7732. if (FLastDropEffect == DROPEFFECT_MOVE)
  7733. {
  7734. Operation = foRemoteMove;
  7735. }
  7736. else if (FLastDropEffect == DROPEFFECT_COPY)
  7737. {
  7738. Operation = foRemoteCopy;
  7739. }
  7740. }
  7741. if (Operation != foNone)
  7742. {
  7743. RemoteFileControlFileOperation(DropSourceControl,
  7744. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7745. }
  7746. // abort drag&drop
  7747. Abort();
  7748. }
  7749. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7750. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7751. (FDDTargetControl != QueueView3))
  7752. {
  7753. DebugAssert(!FDragTempDir.IsEmpty());
  7754. TTransferType Type;
  7755. UnicodeString TempDir = FDragTempDir;
  7756. // We clear FDragTempDir before calling
  7757. // just in case it fail (raises exception)
  7758. FDragTempDir = L"";
  7759. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7760. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7761. // empty directory parameter means temp directory -> don't display it!
  7762. UnicodeString TargetDir = L"";
  7763. int Options = 0;
  7764. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7765. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7766. {
  7767. Abort();
  7768. }
  7769. // TargetDir is set when dropped on local file control
  7770. // (this was workaround for legacy dirview event handling, now it should be
  7771. // made prettier)
  7772. if (TargetDir.IsEmpty())
  7773. {
  7774. TargetDir = TempDir;
  7775. if (ForceDirectories(ApiPath(TargetDir)))
  7776. {
  7777. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7778. FPendingTempSpaceWarn = true;
  7779. try
  7780. {
  7781. FDragDropOperation = true;
  7782. int Params = cpTemporary |
  7783. (Type == ttMove ? cpDelete : 0);
  7784. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7785. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7786. }
  7787. __finally
  7788. {
  7789. FDragDropOperation = false;
  7790. FPendingTempSpaceWarn = false;
  7791. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7792. }
  7793. }
  7794. else
  7795. {
  7796. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7797. }
  7798. }
  7799. }
  7800. }
  7801. //---------------------------------------------------------------------------
  7802. void __fastcall TCustomScpExplorerForm::DDDownload(
  7803. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7804. {
  7805. DebugAssert(!IsLocalBrowserMode());
  7806. TAutoBatch AutoBatch(this);
  7807. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7808. UpdateCopyParamCounters(*CopyParam);
  7809. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7810. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7811. {
  7812. RemoteDriveView->UpdateDropSource();
  7813. }
  7814. }
  7815. //---------------------------------------------------------------------------
  7816. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7817. {
  7818. public:
  7819. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7820. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7821. {
  7822. }
  7823. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7824. {
  7825. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7826. TDataObjectFilesEx::AllowData(FormatEtc);
  7827. }
  7828. };
  7829. //---------------------------------------------------------------------------
  7830. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7831. TObject * Sender, TDataObject *& DataObject)
  7832. {
  7833. if (FDDExtMapFile != NULL)
  7834. {
  7835. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7836. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7837. {
  7838. Abort();
  7839. }
  7840. if (FileList->Count > 0)
  7841. {
  7842. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7843. if (!FilesObject->IsValid(true, true))
  7844. {
  7845. FilesObject->_Release();
  7846. }
  7847. else
  7848. {
  7849. DataObject = FilesObject;
  7850. }
  7851. }
  7852. }
  7853. }
  7854. //---------------------------------------------------------------------------
  7855. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7856. {
  7857. DebugFail();
  7858. }
  7859. //---------------------------------------------------------------------------
  7860. void __fastcall TCustomScpExplorerForm::GoToTree()
  7861. {
  7862. ComponentVisible[fcRemoteTree] = true;
  7863. DriveView(osRemote)->SetFocus();
  7864. }
  7865. //---------------------------------------------------------------------------
  7866. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7867. TPanelExport Export)
  7868. {
  7869. TCustomDirView * DirView = this->DirView(Side);
  7870. std::unique_ptr<TStrings> ExportData(new TStringList());
  7871. switch (Export)
  7872. {
  7873. case pePath:
  7874. ExportData->Add(DirView->PathName);
  7875. break;
  7876. case peFileList:
  7877. case peFullFileList:
  7878. {
  7879. bool FullPath = (Export == peFullFileList);
  7880. DirView->CreateFileList(false, FullPath, ExportData.get());
  7881. for (int Index = 0; Index < ExportData->Count; Index++)
  7882. {
  7883. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7884. {
  7885. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7886. }
  7887. }
  7888. }
  7889. break;
  7890. default:
  7891. DebugFail();
  7892. }
  7893. return ExportData.release();
  7894. }
  7895. //---------------------------------------------------------------------------
  7896. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7897. TPanelExport Export, TPanelExportDestination Destination)
  7898. {
  7899. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7900. PanelExportStore(Side, Export, Destination, ExportData.get());
  7901. }
  7902. //---------------------------------------------------------------------------
  7903. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  7904. TPanelExport /*Export*/, TPanelExportDestination Destination,
  7905. TStrings * ExportData)
  7906. {
  7907. if (Destination == pedClipboard)
  7908. {
  7909. TInstantOperationVisualizer Visualizer;
  7910. CopyToClipboard(ExportData);
  7911. }
  7912. else
  7913. {
  7914. DebugFail();
  7915. }
  7916. }
  7917. //---------------------------------------------------------------------------
  7918. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  7919. {
  7920. TCustomDirView * DirView = this->DirView(Side);
  7921. UnicodeString Mask = DirView->Mask;
  7922. if (DoFilterMaskDialog(DirView, Mask))
  7923. {
  7924. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  7925. Configuration->Usage->Inc(L"Filters");
  7926. }
  7927. }
  7928. //---------------------------------------------------------------------------
  7929. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  7930. {
  7931. return FQueueController->DefaultOperation();
  7932. }
  7933. //---------------------------------------------------------------------------
  7934. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  7935. TQueueOperation Operation, void ** Param)
  7936. {
  7937. switch (Operation)
  7938. {
  7939. case qoPreferences:
  7940. return true;
  7941. case qoGoTo:
  7942. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  7943. case qoOnceEmpty:
  7944. return IsAnythingQueued();
  7945. default:
  7946. return FQueueController->AllowOperation(Operation, Param);
  7947. }
  7948. }
  7949. //---------------------------------------------------------------------------
  7950. void __fastcall TCustomScpExplorerForm::GoToQueue()
  7951. {
  7952. if (DebugAlwaysTrue(QueueView3->Visible))
  7953. {
  7954. QueueView3->SetFocus();
  7955. }
  7956. }
  7957. //---------------------------------------------------------------------------
  7958. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  7959. TQueueOperation Operation, void * Param)
  7960. {
  7961. if (Operation == qoGoTo)
  7962. {
  7963. GoToQueue();
  7964. }
  7965. else if (Operation == qoPreferences)
  7966. {
  7967. PreferencesDialog(pmQueue);
  7968. }
  7969. else
  7970. {
  7971. FQueueController->ExecuteOperation(Operation, Param);
  7972. }
  7973. }
  7974. //---------------------------------------------------------------------------
  7975. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  7976. {
  7977. return (Queue != NULL) && Queue->Enabled;
  7978. }
  7979. //---------------------------------------------------------------------------
  7980. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  7981. {
  7982. DebugAssert(Queue != NULL);
  7983. if (Queue != NULL)
  7984. {
  7985. Queue->Enabled = !Queue->Enabled;
  7986. }
  7987. }
  7988. //---------------------------------------------------------------------------
  7989. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  7990. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  7991. {
  7992. FQueueActedItem = QueueView3->ItemFocused;
  7993. }
  7994. //---------------------------------------------------------------------------
  7995. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  7996. {
  7997. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  7998. }
  7999. //---------------------------------------------------------------------------
  8000. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8001. {
  8002. return
  8003. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8004. (QueueDock->Visible ? QueueDock->Height : 0) +
  8005. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8006. }
  8007. //---------------------------------------------------------------------------
  8008. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8009. {
  8010. return ScaleByTextHeight(this, 48);
  8011. }
  8012. //---------------------------------------------------------------------------
  8013. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8014. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8015. {
  8016. // when queue is hidden by double-clicking splitter, stray attempt to
  8017. // resize the panel with strange value arrives, make sure it is ignored
  8018. if (ComponentVisible[fcQueueView])
  8019. {
  8020. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8021. if (NewSize > MaxHeightLimit)
  8022. {
  8023. NewSize = MaxHeightLimit;
  8024. }
  8025. int MinHeightLimit =
  8026. GetStaticQueuePanelComponentsHeight() +
  8027. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8028. GetMinQueueViewHeight();
  8029. if (NewSize < MinHeightLimit)
  8030. {
  8031. NewSize = MinHeightLimit;
  8032. }
  8033. }
  8034. else
  8035. {
  8036. Accept = false;
  8037. }
  8038. }
  8039. //---------------------------------------------------------------------------
  8040. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8041. {
  8042. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8043. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8044. if (QueueViewHeight < GetMinQueueViewHeight())
  8045. {
  8046. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8047. }
  8048. }
  8049. //---------------------------------------------------------------------------
  8050. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8051. TDragObject *& /*DragObject*/)
  8052. {
  8053. FQueueActedItem = QueueView3->ItemFocused;
  8054. FQueueScrollOnDragOver->StartDrag();
  8055. }
  8056. //---------------------------------------------------------------------------
  8057. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8058. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8059. {
  8060. FQueueScrollOnDragOver->EndDrag();
  8061. }
  8062. //---------------------------------------------------------------------------
  8063. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8064. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8065. {
  8066. Accept = true;
  8067. if (Source == QueueView3)
  8068. {
  8069. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8070. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8071. if (Accept)
  8072. {
  8073. TQueueItemProxy * QueueItem;
  8074. TQueueItemProxy * DestQueueItem;
  8075. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8076. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8077. Accept = (QueueItem != DestQueueItem) &&
  8078. (QueueItem->Status == TQueueItem::qsPending) &&
  8079. (DestQueueItem->Status == TQueueItem::qsPending);
  8080. }
  8081. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8082. }
  8083. }
  8084. //---------------------------------------------------------------------------
  8085. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8086. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8087. {
  8088. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8089. {
  8090. TQueueItemProxy * QueueItem;
  8091. TQueueItemProxy * DestQueueItem;
  8092. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8093. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8094. QueueItem->Move(DestQueueItem);
  8095. }
  8096. }
  8097. //---------------------------------------------------------------------------
  8098. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8099. {
  8100. if ((QueueView3->ItemFocused == NULL) &&
  8101. (QueueView3->Items->Count > 0))
  8102. {
  8103. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8104. }
  8105. QueueLabelUpdateStatus();
  8106. }
  8107. //---------------------------------------------------------------------------
  8108. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8109. {
  8110. QueueLabelUpdateStatus();
  8111. }
  8112. //---------------------------------------------------------------------------
  8113. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8114. {
  8115. QueueLabel->UpdateStatus();
  8116. }
  8117. //---------------------------------------------------------------------------
  8118. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8119. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8120. {
  8121. if (Selected)
  8122. {
  8123. NonVisualDataModule->UpdateNonVisibleActions();
  8124. }
  8125. }
  8126. //---------------------------------------------------------------------------
  8127. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8128. {
  8129. TDragDropFilesEx * Result = NULL;
  8130. if (Sender == SessionsPageControl)
  8131. {
  8132. Result = FSessionsDragDropFilesEx;
  8133. }
  8134. else if (Sender == QueueView3)
  8135. {
  8136. Result = FQueueDragDropFilesEx;
  8137. }
  8138. else
  8139. {
  8140. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8141. if (DirView != NULL)
  8142. {
  8143. Result = DirView->DragDropFilesEx;
  8144. }
  8145. else
  8146. {
  8147. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8148. if (DriveView != NULL)
  8149. {
  8150. Result = DriveView->DragDropFilesEx;
  8151. }
  8152. }
  8153. }
  8154. DebugAssert(Result != NULL);
  8155. return Result;
  8156. }
  8157. //---------------------------------------------------------------------------
  8158. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8159. {
  8160. return (DView->SelCount == DView->FilesCount);
  8161. }
  8162. //---------------------------------------------------------------------------
  8163. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8164. {
  8165. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8166. }
  8167. //---------------------------------------------------------------------------
  8168. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8169. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8170. {
  8171. DebugAssert(!IsLocalBrowserMode());
  8172. TFileOperation Operation;
  8173. switch (Effect)
  8174. {
  8175. case DROPEFFECT_MOVE:
  8176. Operation = foMove;
  8177. break;
  8178. case DROPEFFECT_COPY:
  8179. // occures on WinXP (reported by user)
  8180. default:
  8181. Operation = foCopy;
  8182. break;
  8183. };
  8184. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8185. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8186. if (DragDropFilesEx->FileList->Count > 0)
  8187. {
  8188. TStrings * FileList = new TStringList();
  8189. try
  8190. {
  8191. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8192. {
  8193. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8194. }
  8195. FDragDropOperation = true;
  8196. TTransferOperationParam Param;
  8197. Param.TargetDirectory = TargetPath;
  8198. // upload, no temp dirs
  8199. Param.Temp = false;
  8200. Param.DragDrop = DragDrop;
  8201. Param.Options =
  8202. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8203. if (ForceQueue)
  8204. {
  8205. Param.Queue = asOn;
  8206. }
  8207. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8208. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8209. {
  8210. if (IsFileControl(DropSourceControl, osLocal))
  8211. {
  8212. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8213. }
  8214. else
  8215. {
  8216. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8217. }
  8218. }
  8219. }
  8220. __finally
  8221. {
  8222. FDragDropOperation = false;
  8223. delete FileList;
  8224. }
  8225. }
  8226. }
  8227. //---------------------------------------------------------------------------
  8228. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8229. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8230. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8231. {
  8232. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8233. }
  8234. //---------------------------------------------------------------------------
  8235. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8236. TObject * Sender, int grfKeyState, int & dwEffect)
  8237. {
  8238. DebugAssert(!IsLocalBrowserMode());
  8239. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8240. if ((dwEffect != DROPEFFECT_NONE) &&
  8241. IsFileControl(DropSourceControl, osRemote))
  8242. {
  8243. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8244. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8245. (RemoteDirView->DropTarget == NULL))
  8246. {
  8247. dwEffect = DROPEFFECT_NONE;
  8248. }
  8249. else
  8250. {
  8251. if (dwEffect == DROPEFFECT_COPY)
  8252. {
  8253. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8254. // currently we support copying always (at least via temporary directory);
  8255. // remove associated checks once this all proves stable and working
  8256. bool CopyCapable = true;
  8257. // if we do not support neither of operations, there's no discussion
  8258. if (!MoveCapable && !CopyCapable)
  8259. {
  8260. dwEffect = DROPEFFECT_NONE;
  8261. }
  8262. else
  8263. {
  8264. // The default effect inside remote panel is move,
  8265. // unless we do not support it, but support copy
  8266. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8267. {
  8268. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8269. }
  8270. else
  8271. {
  8272. // with ctrl-down, we want copy unless it is not supported
  8273. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8274. }
  8275. }
  8276. }
  8277. }
  8278. }
  8279. }
  8280. //---------------------------------------------------------------------------
  8281. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8282. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8283. {
  8284. DebugAssert(!IsLocalBrowserMode());
  8285. if (FDDTotalSize >= 0)
  8286. {
  8287. if (File->IsDirectory)
  8288. {
  8289. FDDTotalSize = -1;
  8290. }
  8291. else
  8292. {
  8293. FDDTotalSize += File->Size;
  8294. }
  8295. }
  8296. DebugAssert(!FDragTempDir.IsEmpty());
  8297. // TODO: this is quite ineffective
  8298. // TODO: what if invalid character replacement is disabled?
  8299. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8300. UnicodeString TransferFileName;
  8301. if (Sender == RemoteDriveView)
  8302. {
  8303. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8304. }
  8305. else
  8306. {
  8307. TransferFileName = File->FileName;
  8308. }
  8309. FDDFileList->AddObject(TransferFileName, File);
  8310. }
  8311. //---------------------------------------------------------------------------
  8312. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8313. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8314. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8315. {
  8316. // sometimes we do not get DDEnd so the list is not released
  8317. SAFE_DESTROY(FDDFileList);
  8318. FDDFileList = new TStringList();
  8319. FDragTempDir = WinConfiguration->TemporaryDir();
  8320. FDDTotalSize = 0;
  8321. FDragDropSshTerminate.reset(NULL);
  8322. }
  8323. //---------------------------------------------------------------------------
  8324. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8325. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  8326. HRESULT & Result)
  8327. {
  8328. if (Result == DRAGDROP_S_DROP)
  8329. {
  8330. try
  8331. {
  8332. GlobalDragImageList->HideDragImage();
  8333. try
  8334. {
  8335. RemoteFileControlDDTargetDrop();
  8336. }
  8337. catch(ESshTerminate & E)
  8338. {
  8339. FDragDropSshTerminate.reset(E.Clone());
  8340. }
  8341. }
  8342. catch (Exception &E)
  8343. {
  8344. // If downloading fails we need to cancel drag&drop, otherwise
  8345. // Explorer shows error
  8346. // But by the way exception probably never reach this point as
  8347. // it's catched on way.
  8348. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8349. Result = DRAGDROP_S_CANCEL;
  8350. ShowExtendedException(Terminal, &E);
  8351. }
  8352. }
  8353. }
  8354. //---------------------------------------------------------------------------
  8355. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8356. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8357. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8358. {
  8359. TFileMasks::TParams MaskParams;
  8360. MaskParams.Size = Size;
  8361. MaskParams.Modification = Modification;
  8362. // this does not re-parse the mask if it is the same as the last time
  8363. FDirViewMatchMask = Masks;
  8364. bool ImplicitMatch;
  8365. Matches =
  8366. // Local and RecurseInclude parameters have no effect as there's no path.
  8367. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8368. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8369. (AllowImplicitMatches || !ImplicitMatch);
  8370. }
  8371. //---------------------------------------------------------------------------
  8372. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8373. TObject * Sender, TListItem * Item, WORD & Indexes)
  8374. {
  8375. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8376. UnicodeString Ext;
  8377. if (dynamic_cast<TUnixDirView *>(DirView) != NULL)
  8378. {
  8379. Ext = UnixExtractFileExt(DirView->ItemFileName(Item));
  8380. }
  8381. else
  8382. {
  8383. Ext = ExtractFileExt(DirView->ItemFileName(Item));
  8384. }
  8385. if (SameText(Ext, Configuration->PartialExt))
  8386. {
  8387. Indexes |= oiPartial;
  8388. }
  8389. }
  8390. //---------------------------------------------------------------------------
  8391. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8392. {
  8393. return
  8394. DirViewEnabled(osCurrent) &&
  8395. DirView(osCurrent)->CanPasteFromClipBoard();
  8396. }
  8397. //---------------------------------------------------------------------------
  8398. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8399. {
  8400. bool Result = false;
  8401. if (CanPasteToDirViewFromClipBoard())
  8402. {
  8403. Result = true;
  8404. }
  8405. else
  8406. {
  8407. UnicodeString ClipboardText;
  8408. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8409. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8410. {
  8411. if (StoredSessions->IsUrl(ClipboardText))
  8412. {
  8413. Result = true;
  8414. }
  8415. else
  8416. {
  8417. Result = DirViewEnabled(osCurrent);
  8418. }
  8419. }
  8420. }
  8421. return Result;
  8422. }
  8423. //---------------------------------------------------------------------------
  8424. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8425. {
  8426. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8427. if (DoesClipboardContainOurFiles())
  8428. {
  8429. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8430. {
  8431. DebugAssert(!IsLocalBrowserMode());
  8432. TTerminalManager * Manager = TTerminalManager::Instance();
  8433. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8434. Manager->ActiveSession = FClipboardTerminal;
  8435. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8436. }
  8437. }
  8438. else if (CanPasteToDirViewFromClipBoard())
  8439. {
  8440. DirView(osCurrent)->PasteFromClipBoard();
  8441. }
  8442. else
  8443. {
  8444. UnicodeString ClipboardText;
  8445. if (NonEmptyTextFromClipboard(ClipboardText))
  8446. {
  8447. if (StoredSessions->IsUrl(ClipboardText))
  8448. {
  8449. NewSession(ClipboardText);
  8450. }
  8451. else
  8452. {
  8453. DirView(osCurrent)->Path = ClipboardText;
  8454. }
  8455. }
  8456. }
  8457. }
  8458. //---------------------------------------------------------------------------
  8459. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8460. {
  8461. // TBD
  8462. }
  8463. //---------------------------------------------------------------------------
  8464. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8465. {
  8466. TCustomDirView * ADirView = DirView(Side);
  8467. ADirView->SelectAll(Mode);
  8468. ADirView->SetFocus();
  8469. }
  8470. //---------------------------------------------------------------------------
  8471. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8472. {
  8473. TCustomDirView * ADirView = DirView(Side);
  8474. TFileFilter Filter;
  8475. DefaultFileFilter(Filter);
  8476. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8477. {
  8478. Configuration->Usage->Inc(L"MaskSelections");
  8479. ADirView->SelectFiles(Filter, Select);
  8480. ADirView->SetFocus();
  8481. }
  8482. }
  8483. //---------------------------------------------------------------------------
  8484. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8485. {
  8486. TCustomDirView * ADirView = DirView(Side);
  8487. ADirView->RestoreSelectedNames();
  8488. ADirView->SetFocus();
  8489. }
  8490. //---------------------------------------------------------------------------
  8491. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8492. {
  8493. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8494. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8495. {
  8496. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8497. UnicodeString Ext;
  8498. if (!IsSideLocalBrowser(osCurrent))
  8499. {
  8500. Ext = UnixExtractFileExt(FileName);
  8501. }
  8502. else
  8503. {
  8504. Ext = ExtractFileExt(FileName);
  8505. }
  8506. if (Ext.IsEmpty())
  8507. {
  8508. Ext = L".";
  8509. }
  8510. TFileFilter Filter;
  8511. Filter.Masks = FORMAT(L"*%s", (Ext));
  8512. Filter.Directories = false;
  8513. CurrentDirView->SelectFiles(Filter, Select);
  8514. }
  8515. }
  8516. //---------------------------------------------------------------------------
  8517. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8518. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8519. {
  8520. UnicodeString Result;
  8521. if (!FIncrementalSearch.IsEmpty() && (Side == GetSide(osCurrent)))
  8522. {
  8523. Result = FormatIncrementalSearchStatus(FIncrementalSearch, FIncrementalSearchHaveNext);
  8524. }
  8525. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8526. {
  8527. // noop
  8528. }
  8529. else
  8530. {
  8531. Result =
  8532. FMTLOAD(FILE_INFO_FORMAT,
  8533. (FormatBytes(FileInfo.SelectedSize),
  8534. FormatBytes(FileInfo.FilesSize),
  8535. FormatNumber(FileInfo.SelectedCount),
  8536. FormatNumber(FileInfo.FilesCount)));
  8537. }
  8538. return Result;
  8539. }
  8540. //---------------------------------------------------------------------------
  8541. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8542. TTBXStatusPanel * Panel, TOperationSide Side)
  8543. {
  8544. if (Panel->Index == 1)
  8545. {
  8546. ToggleShowHiddenFiles();
  8547. }
  8548. else if (Panel->Index == 2)
  8549. {
  8550. Filter(Side);
  8551. }
  8552. }
  8553. //---------------------------------------------------------------------------
  8554. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8555. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8556. {
  8557. DebugAssert(!StatusBar->SimplePanel);
  8558. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8559. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8560. }
  8561. //---------------------------------------------------------------------------
  8562. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8563. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8564. {
  8565. DebugAssert(StatusBar->Panels->Count >= 3);
  8566. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8567. if (FileInfo.HiddenCount > 0)
  8568. {
  8569. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8570. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8571. }
  8572. else
  8573. {
  8574. HiddenFilesPanel->ViewPriority = 0;
  8575. // not really necessary, just to cleanup no-longer-valid data
  8576. HiddenFilesPanel->Caption = L"";
  8577. }
  8578. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8579. if (FileInfo.FilteredCount > 0)
  8580. {
  8581. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8582. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8583. }
  8584. else
  8585. {
  8586. FilteredFilesPanel->ViewPriority = 0;
  8587. // not really necessary, just to cleanup no-longer-valid data
  8588. FilteredFilesPanel->Caption = L"";
  8589. }
  8590. }
  8591. //---------------------------------------------------------------------------
  8592. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8593. TObject * /*Sender*/)
  8594. {
  8595. if (DirView(osOther)->Enabled)
  8596. {
  8597. DirView(osOther)->SetFocus();
  8598. }
  8599. }
  8600. //---------------------------------------------------------------------------
  8601. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8602. {
  8603. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8604. switch (Config.Show)
  8605. {
  8606. case qvShow:
  8607. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8608. {
  8609. Config.Show = qvHide;
  8610. }
  8611. else
  8612. {
  8613. Config.Show = Config.LastHideShow;
  8614. }
  8615. break;
  8616. case qvHideWhenEmpty:
  8617. if (ComponentVisible[fcQueueView])
  8618. {
  8619. Config.Show = qvHide;
  8620. }
  8621. else
  8622. {
  8623. Config.LastHideShow = Config.Show;
  8624. Config.Show = qvShow;
  8625. }
  8626. break;
  8627. case qvHide:
  8628. Config.LastHideShow = Config.Show;
  8629. Config.Show = qvShow;
  8630. break;
  8631. }
  8632. WinConfiguration->QueueView = Config;
  8633. }
  8634. //---------------------------------------------------------------------------
  8635. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8636. {
  8637. UnicodeString Result;
  8638. if (Terminal != NULL)
  8639. {
  8640. switch (WinConfiguration->PathInCaption)
  8641. {
  8642. case picShort:
  8643. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8644. break;
  8645. case picFull:
  8646. Result = Terminal->CurrentDirectory;
  8647. break;
  8648. }
  8649. }
  8650. return Result;
  8651. }
  8652. //---------------------------------------------------------------------------
  8653. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8654. {
  8655. TColor Result = GetWindowColor(FSessionColor);
  8656. return Result;
  8657. }
  8658. //---------------------------------------------------------------------------
  8659. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8660. {
  8661. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8662. return Result;
  8663. }
  8664. //---------------------------------------------------------------------------
  8665. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8666. {
  8667. if (!FSessionChanging)
  8668. {
  8669. TTerminalManager::Instance()->UpdateAppTitle();
  8670. }
  8671. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8672. // background to gray on Windows 7 (works on Windows 10).
  8673. // See also EnableControl
  8674. if (Showing)
  8675. {
  8676. if (ManagedSession != NULL)
  8677. {
  8678. // Update path when it changes
  8679. if ((SessionsPageControl->ActivePage != NULL) &&
  8680. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8681. {
  8682. UpdateSessionTab(SessionsPageControl->ActivePage);
  8683. }
  8684. }
  8685. NonVisualDataModule->ReconnectSessionAction->Update();
  8686. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8687. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8688. CenterReconnectToolbar();
  8689. bool HasTerminal = HasActiveTerminal();
  8690. RemoteDirView->Enabled = HasTerminal;
  8691. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8692. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8693. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8694. RemoteDriveView->Color = RemoteDirView->Color;
  8695. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8696. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8697. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8698. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8699. QueueFileList->Enabled = QueueView3->Enabled;
  8700. QueueFileList->Color = QueueView3->Color;
  8701. QueueFileList->Font->Color = QueueView3->Font->Color;
  8702. QueueLabelUpdateStatus();
  8703. RemoteDirView->DarkMode = WinConfiguration->UseDarkTheme();
  8704. RemoteDriveView->DarkMode = RemoteDirView->DarkMode;
  8705. if (FImmersiveDarkMode != WinConfiguration->UseDarkTheme())
  8706. {
  8707. UpdateDarkMode();
  8708. }
  8709. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8710. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8711. }
  8712. }
  8713. //---------------------------------------------------------------------------
  8714. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8715. {
  8716. UpdateControls();
  8717. }
  8718. //---------------------------------------------------------------------------
  8719. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8720. TObject * Sender)
  8721. {
  8722. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8723. DebugAssert(DirView != NULL);
  8724. DoDirViewLoaded(DirView);
  8725. TransferPresetAutoSelect();
  8726. }
  8727. //---------------------------------------------------------------------------
  8728. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8729. {
  8730. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8731. // first run after installation
  8732. if (double(Updates.LastCheck) == 0)
  8733. {
  8734. AppLog(L"First run, scheduling updates check for the next run");
  8735. // make sure next time there will be an update (if enabled)
  8736. Updates.LastCheck = TDateTime(1);
  8737. WinConfiguration->Updates = Updates;
  8738. }
  8739. else
  8740. {
  8741. TDateTime Period;
  8742. if (IsUWP() && !IsOfficialPackage())
  8743. {
  8744. Period = DefaultUpdatesPeriod;
  8745. AppLog(L"Thirdparty UWP package, using default updates check period");
  8746. }
  8747. else
  8748. {
  8749. Period = Updates.Period;
  8750. }
  8751. AppLogFmt(L"Updates check period: %.2f", (double(Period)));
  8752. if (double(Period) > 0)
  8753. {
  8754. TDateTime Interval = Now() - Updates.LastCheck;
  8755. AppLogFmt(L"Interval since the last updates check: %.2f", (double(Interval)));
  8756. if (Interval >= Period)
  8757. {
  8758. StartUpdateThread(UpdatesChecked);
  8759. }
  8760. }
  8761. }
  8762. }
  8763. //---------------------------------------------------------------------------
  8764. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8765. {
  8766. AppLog(L"Updates check done");
  8767. UnicodeString Message;
  8768. bool New;
  8769. TQueryType Type;
  8770. GetUpdatesMessage(Message, New, Type, false);
  8771. if (!Message.IsEmpty())
  8772. {
  8773. AppLogFmt(L"Updates check message: %s", (Message));
  8774. if (New)
  8775. {
  8776. AppLog(L"New version detected");
  8777. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8778. }
  8779. if (!New && (Type != qtWarning))
  8780. {
  8781. AppLog(L"Posting non-critical updates note");
  8782. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  8783. }
  8784. else
  8785. {
  8786. AppLog(L"Posting new version or critical message notification");
  8787. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8788. }
  8789. if (New)
  8790. {
  8791. Configuration->Usage->Inc(L"UpdateNotifications");
  8792. }
  8793. }
  8794. }
  8795. //---------------------------------------------------------------------------
  8796. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8797. {
  8798. RestoreApp();
  8799. bool CanDisplay = !NonVisualDataModule->Busy;
  8800. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8801. {
  8802. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8803. }
  8804. if (CanDisplay)
  8805. {
  8806. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8807. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  8808. NonVisualDataModule->StartBusy();
  8809. try
  8810. {
  8811. CheckForUpdates(true);
  8812. }
  8813. __finally
  8814. {
  8815. NonVisualDataModule->EndBusy();
  8816. }
  8817. }
  8818. else
  8819. {
  8820. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  8821. }
  8822. }
  8823. //---------------------------------------------------------------------------
  8824. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  8825. TCopyParamRuleData & Data)
  8826. {
  8827. DebugAssert(Terminal != NULL);
  8828. Data.HostName = Terminal->SessionData->HostNameExpanded;
  8829. Data.UserName = Terminal->SessionData->UserNameExpanded;
  8830. Data.RemoteDirectory = RemoteDirView->PathName;
  8831. }
  8832. //---------------------------------------------------------------------------
  8833. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  8834. {
  8835. // Terminal can be null when we are changing local directory implicitly,
  8836. // because it has been deleted, while no session is connected
  8837. // (Login dialog is open)
  8838. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  8839. {
  8840. DebugAssert(!IsLocalBrowserMode());
  8841. TCopyParamRuleData Data;
  8842. GetTransferPresetAutoSelectData(Data);
  8843. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  8844. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  8845. if (CopyParamIndex < 0)
  8846. {
  8847. // there is no preset that matches autoselection
  8848. // set preset that we consider "default"
  8849. FCopyParamAutoSelected = L""; // forget last autoselected preset
  8850. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  8851. }
  8852. else
  8853. {
  8854. // there is preset matching autoselection
  8855. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  8856. if (CopyParamName == FCopyParamAutoSelected)
  8857. {
  8858. // autoselected the same preset as the last time
  8859. // make no change (i.e. preserve custom user preset, if any)
  8860. }
  8861. else
  8862. {
  8863. // autoselected the different preset then the last time (or there
  8864. // was default preset set)
  8865. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  8866. GUIConfiguration->CopyParamCurrent = CopyParamName;
  8867. }
  8868. }
  8869. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  8870. {
  8871. if (CopyParamIndex >= 0)
  8872. {
  8873. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  8874. }
  8875. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  8876. try
  8877. {
  8878. int Fmt =
  8879. (CopyParamIndex < 0) ?
  8880. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8881. COPY_PARAM_AUTOSELECTED;
  8882. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  8883. Data->Message = MainInstructions(Message);
  8884. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  8885. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  8886. CopyParamAttrs);
  8887. if (CopyParamIndex >= 0)
  8888. {
  8889. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  8890. Info = FORMAT(L"%s\n \n%s", (Info,
  8891. FMTLOAD(COPY_PARAM_RULE,
  8892. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  8893. }
  8894. Data->Message += L"\n\n" + Info;
  8895. if (WinConfiguration->CopyParamAutoSelectNotice)
  8896. {
  8897. TransferPresetNoteMessage(Data, true);
  8898. }
  8899. else
  8900. {
  8901. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  8902. Data = NULL; // ownership passed
  8903. }
  8904. }
  8905. __finally
  8906. {
  8907. delete Data;
  8908. }
  8909. }
  8910. }
  8911. }
  8912. //---------------------------------------------------------------------------
  8913. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  8914. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  8915. {
  8916. DebugAssert(NoteData != NULL);
  8917. DebugAssert(!IsLocalBrowserMode());
  8918. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  8919. TQueryButtonAlias Aliases[1];
  8920. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  8921. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  8922. Params.Aliases = Aliases;
  8923. Params.AliasesCount = LENOF(Aliases);
  8924. unsigned int Result =
  8925. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  8926. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  8927. switch (Result)
  8928. {
  8929. case qaNeverAskAgain:
  8930. DebugAssert(AllowNeverAskAgain);
  8931. WinConfiguration->CopyParamAutoSelectNotice = false;
  8932. break;
  8933. case qaIgnore:
  8934. PreferencesDialog(pmPresets);
  8935. break;
  8936. }
  8937. }
  8938. //---------------------------------------------------------------------------
  8939. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  8940. {
  8941. // as of now useless, as this is used for notes only, never for balloons, ...
  8942. RestoreApp();
  8943. // .. and we should never be busy here
  8944. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  8945. {
  8946. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  8947. }
  8948. }
  8949. //---------------------------------------------------------------------------
  8950. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  8951. TPreferencesMode APreferencesMode)
  8952. {
  8953. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  8954. TCopyParamRuleData Data;
  8955. if (Terminal != NULL)
  8956. {
  8957. PreferencesData.reset(new TPreferencesDialogData());
  8958. GetTransferPresetAutoSelectData(Data);
  8959. PreferencesData->CopyParamRuleData = &Data;
  8960. }
  8961. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  8962. }
  8963. //---------------------------------------------------------------------------
  8964. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  8965. const TCustomCommandType & Command)
  8966. {
  8967. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  8968. {
  8969. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  8970. }
  8971. }
  8972. //---------------------------------------------------------------------------
  8973. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  8974. {
  8975. bool RemoteAllowed = CustomCommandRemoteAllowed();
  8976. TCustomCommandType Command;
  8977. // make sure we use local custom command when remote are not supported
  8978. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  8979. {
  8980. Command = FLastCustomCommand;
  8981. }
  8982. else
  8983. {
  8984. Command.Params = Command.Params | ccLocal;
  8985. }
  8986. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  8987. FEditingFocusedAdHocCommand = OnFocused;
  8988. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  8989. int Options =
  8990. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  8991. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  8992. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  8993. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  8994. {
  8995. FLastCustomCommand = Command;
  8996. UpdateCustomCommandsToolbar();
  8997. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  8998. }
  8999. }
  9000. //---------------------------------------------------------------------------
  9001. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9002. {
  9003. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9004. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9005. DebugAssert(State > 0);
  9006. if (State <= 0)
  9007. {
  9008. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9009. }
  9010. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9011. }
  9012. //---------------------------------------------------------------------------
  9013. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9014. TCustomCommandType & Command, int & State)
  9015. {
  9016. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9017. if (Result)
  9018. {
  9019. Command = FLastCustomCommand;
  9020. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9021. }
  9022. return Result;
  9023. }
  9024. //---------------------------------------------------------------------------
  9025. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9026. {
  9027. ResetIncrementalSearch();
  9028. }
  9029. //---------------------------------------------------------------------------
  9030. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9031. {
  9032. DebugAssert(ComponentVisible[Component]);
  9033. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9034. }
  9035. //---------------------------------------------------------------------------
  9036. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9037. {
  9038. // when queue panel is resized here directly, the status bar is stretched
  9039. // over whole space the panel occupied
  9040. PostComponentHide(fcQueueView);
  9041. }
  9042. //---------------------------------------------------------------------------
  9043. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9044. {
  9045. ComponentVisible[fcQueueFileList] = false;
  9046. }
  9047. //---------------------------------------------------------------------------
  9048. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9049. {
  9050. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9051. RefreshColorMode();
  9052. ResetSysDarkTheme();
  9053. ConfigurationChanged();
  9054. ConfigureInterface();
  9055. // Should be called for all controls
  9056. RemoteDirView->Perform(WM_THEMECHANGED, 0, 0);
  9057. }
  9058. //---------------------------------------------------------------------------
  9059. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9060. {
  9061. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9062. if (!FInvalid &&
  9063. (Message.LParam != 0) &&
  9064. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9065. {
  9066. ThemeChanged();
  9067. }
  9068. TForm::Dispatch(&Message);
  9069. }
  9070. //---------------------------------------------------------------------------
  9071. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9072. {
  9073. TMessage * M = static_cast<TMessage*>(Message);
  9074. switch (M->Msg)
  9075. {
  9076. case CM_DIALOGCHAR:
  9077. CMDialogChar(*M);
  9078. break;
  9079. case WM_APPCOMMAND:
  9080. WMAppCommand(*M);
  9081. break;
  9082. case WM_SYSCOMMAND:
  9083. WMSysCommand(*M);
  9084. break;
  9085. case WM_QUERYENDSESSION:
  9086. WMQueryEndSession(*M);
  9087. break;
  9088. case WM_ENDSESSION:
  9089. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9090. break;
  9091. #ifdef _DEBUG
  9092. case WM_WINDOWPOSCHANGED:
  9093. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  9094. break;
  9095. case CM_CUSTOMSTYLECHANGED:
  9096. TForm::Dispatch(Message);
  9097. break;
  9098. #endif
  9099. case WM_COMPONENT_HIDE:
  9100. {
  9101. Byte Component = static_cast<Byte>(M->WParam);
  9102. // sanity check
  9103. if (ComponentVisible[Component])
  9104. {
  9105. // special treatment
  9106. if (Component == fcQueueView)
  9107. {
  9108. ToggleQueueVisibility();
  9109. DebugAssert(!ComponentVisible[fcQueueView]);
  9110. }
  9111. else
  9112. {
  9113. ComponentVisible[Component] = false;
  9114. }
  9115. }
  9116. }
  9117. break;
  9118. case WM_COPYDATA:
  9119. WMCopyData(*M);
  9120. break;
  9121. case WM_MANAGES_CAPTION:
  9122. // caption managed in TTerminalManager::UpdateAppTitle()
  9123. M->Result = 1;
  9124. break;
  9125. case WM_WANTS_MOUSEWHEEL:
  9126. M->Result = 1;
  9127. break;
  9128. case CM_SHOWINGCHANGED:
  9129. CMShowingChanged(*M);
  9130. break;
  9131. case WM_CLOSE:
  9132. WMClose(*M);
  9133. break;
  9134. case WM_DPICHANGED:
  9135. WMDpiChanged(*M);
  9136. break;
  9137. case CM_DPICHANGED:
  9138. CMDpiChanged(*M);
  9139. break;
  9140. case WM_SETTINGCHANGE:
  9141. WMSettingChange(*M);
  9142. break;
  9143. case CM_DIALOGKEY:
  9144. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9145. break;
  9146. case WM_PASTE_FILES:
  9147. PasteFiles();
  9148. break;
  9149. default:
  9150. TForm::Dispatch(Message);
  9151. break;
  9152. }
  9153. }
  9154. //---------------------------------------------------------------------------
  9155. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9156. {
  9157. // noop
  9158. }
  9159. //---------------------------------------------------------------------------
  9160. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  9161. {
  9162. TForm::Dispatch(&Message);
  9163. FSessionColors->Clear();
  9164. AddFixedSessionImages();
  9165. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9166. UpdateImages();
  9167. }
  9168. //---------------------------------------------------------------------------
  9169. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9170. {
  9171. TForm::Dispatch(&Message);
  9172. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9173. UpdatePixelsPerInchMainWindowCounter();
  9174. }
  9175. //---------------------------------------------------------------------------
  9176. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9177. {
  9178. // Cannot close window while we are busy.
  9179. // We cannot test this in FormCloseQuery as that is called also from
  9180. // Close(), which is called by CloseApplicationAction. So we can be busy
  9181. // there already even, when it is legitimate to close the application.
  9182. // Possibly a better place to handle this would be WMSysCommand.
  9183. if (NonVisualDataModule->Busy)
  9184. {
  9185. Message.Result = 1;
  9186. }
  9187. else
  9188. {
  9189. TForm::Dispatch(&Message);
  9190. }
  9191. }
  9192. //---------------------------------------------------------------------------
  9193. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9194. {
  9195. if (!FShowingChanged)
  9196. {
  9197. AddStartupSequence(L"D");
  9198. FShowingChanged = true;
  9199. }
  9200. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9201. bool NoSession = (ManagedSession == NULL);
  9202. // This calls TCustomScpExplorerForm::DoShow
  9203. TForm::Dispatch(&Message);
  9204. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9205. if (Showing && !FStarted)
  9206. {
  9207. FStarted = true;
  9208. InterfaceStarted();
  9209. }
  9210. if (Showing && NoSession)
  9211. {
  9212. // When we are starting minimized (i.e. from an installer),
  9213. // postpone showing Login dialog until we get restored.
  9214. // Otherwise the Login dialog (and Authentication window) show restored
  9215. // over invisible (minimized) main window.
  9216. if (WindowState == wsMinimized)
  9217. {
  9218. FNeedSession = true;
  9219. }
  9220. else
  9221. {
  9222. // This happens before application ever goes idle, so the toolbars would
  9223. // stay enabled (initial state) until the Login dialog is dismissed.
  9224. UpdateActions();
  9225. NonVisualDataModule->StartBusy();
  9226. try
  9227. {
  9228. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9229. // otherwise the dialog does not receive focus.
  9230. // With Commander interface the ProcessMessages is called already
  9231. // by TDriveView, but with Explorer interface, we need to call it explicily
  9232. Application->ProcessMessages();
  9233. // do not reload sessions, they have been loaded just now (optimization)
  9234. NeedSession(true);
  9235. }
  9236. __finally
  9237. {
  9238. NonVisualDataModule->EndBusy();
  9239. }
  9240. }
  9241. }
  9242. }
  9243. //---------------------------------------------------------------------------
  9244. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9245. {
  9246. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9247. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9248. }
  9249. //---------------------------------------------------------------------------
  9250. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9251. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9252. int & MaxHeight)
  9253. {
  9254. // workaround for bug in TWinControl.CalcConstraints
  9255. // Check for empty rect (restore from iconic state) is done there only after
  9256. // call to AdjustClientRect, which enlarges the rect (for forms).
  9257. TRect R = GetClientRect();
  9258. // when restoring from iconic state, place no restrictions
  9259. if (IsRectEmpty(R))
  9260. {
  9261. MinWidth = 0;
  9262. MinHeight = 0;
  9263. MaxWidth = 32000;
  9264. MaxHeight = 32000;
  9265. }
  9266. }
  9267. //---------------------------------------------------------------------------
  9268. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9269. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9270. {
  9271. // terminal can be already closed (e.g. dropped connection)
  9272. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9273. {
  9274. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9275. try
  9276. {
  9277. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9278. }
  9279. catch(...)
  9280. {
  9281. if (!Terminal->Active)
  9282. {
  9283. Close = true;
  9284. }
  9285. throw;
  9286. }
  9287. }
  9288. }
  9289. //---------------------------------------------------------------------------
  9290. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9291. {
  9292. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9293. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9294. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9295. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9296. {
  9297. OnGetSpaceAvailable = GetSpaceAvailable;
  9298. }
  9299. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9300. OnGetSpaceAvailable);
  9301. }
  9302. //---------------------------------------------------------------------------
  9303. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9304. {
  9305. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9306. Terminal->FillSessionDataForCode(Data.get());
  9307. return Data.release();
  9308. }
  9309. //---------------------------------------------------------------------------
  9310. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9311. {
  9312. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9313. DoGenerateUrlDialog(Data.get(), Paths);
  9314. }
  9315. //---------------------------------------------------------------------------
  9316. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9317. {
  9318. GenerateUrl(NULL);
  9319. }
  9320. //---------------------------------------------------------------------------
  9321. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9322. {
  9323. std::unique_ptr<TStrings> Paths(new TStringList());
  9324. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9325. GenerateUrl(Paths.get());
  9326. }
  9327. //---------------------------------------------------------------------------
  9328. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9329. {
  9330. FSessionColor = value;
  9331. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9332. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9333. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9334. DebugAssert(ColorItem != NULL);
  9335. ColorItem->Color = C;
  9336. NonVisualDataModule->ColorMenuItem->Color = C;
  9337. UpdateControls();
  9338. }
  9339. //---------------------------------------------------------------------------
  9340. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9341. {
  9342. if (value != FSessionColor)
  9343. {
  9344. UpdateSessionColor(value);
  9345. // Is null when called from LastTerminalClosed
  9346. if (Terminal != NULL)
  9347. {
  9348. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9349. }
  9350. }
  9351. }
  9352. //---------------------------------------------------------------------------
  9353. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9354. {
  9355. bool Result = FNoteTimer->Enabled;
  9356. if (Result)
  9357. {
  9358. // cannot cancel note too early
  9359. bool NotEarly =
  9360. (Now() - FNoteShown >
  9361. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9362. if (Force || NotEarly)
  9363. {
  9364. FNoteTimer->Enabled = false;
  9365. FNote = L"";
  9366. SAFE_DESTROY(FNoteData);
  9367. FOnNoteClick = NULL;
  9368. FNoteHints = FNotes->Text;
  9369. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9370. UpdateStatusBar();
  9371. }
  9372. }
  9373. return Result;
  9374. }
  9375. //---------------------------------------------------------------------------
  9376. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9377. {
  9378. DebugAssert(FNoteTimer->Enabled);
  9379. CancelNote(true);
  9380. }
  9381. //---------------------------------------------------------------------------
  9382. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9383. {
  9384. FNoteHints = FNotes->Text.TrimRight();
  9385. }
  9386. //---------------------------------------------------------------------------
  9387. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9388. {
  9389. int P = Note.Pos(L"\n");
  9390. if (P > 0)
  9391. {
  9392. Note.SetLength(P - 1);
  9393. }
  9394. FNotes->Add(FORMAT(L"[%s] %s",
  9395. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9396. while (FNotes->Count > 10)
  9397. {
  9398. FNotes->Delete(0);
  9399. }
  9400. if (UpdateNow)
  9401. {
  9402. UpdateNoteHints();
  9403. UpdateStatusBar();
  9404. }
  9405. }
  9406. //---------------------------------------------------------------------------
  9407. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  9408. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9409. {
  9410. int P = Note.Pos(L"\n");
  9411. if (P > 0)
  9412. {
  9413. Note.SetLength(P - 1);
  9414. }
  9415. UpdateNoteHints();
  9416. FNote = Note;
  9417. SAFE_DESTROY(FNoteData);
  9418. FNoteData = NoteData;
  9419. FOnNoteClick = OnNoteClick;
  9420. AddNote(Note, false);
  9421. UpdateStatusBar();
  9422. FNoteShown = Now();
  9423. FNoteTimer->Enabled = false;
  9424. if (Seconds == 0)
  9425. {
  9426. Seconds = WinConfiguration->NotificationsTimeout;
  9427. }
  9428. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9429. FNoteTimer->Enabled = true;
  9430. }
  9431. //---------------------------------------------------------------------------
  9432. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9433. {
  9434. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  9435. }
  9436. //---------------------------------------------------------------------------
  9437. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9438. {
  9439. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9440. {
  9441. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9442. }
  9443. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9444. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9445. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))),
  9446. 0, NULL, NULL);
  9447. }
  9448. //---------------------------------------------------------------------------
  9449. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9450. {
  9451. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9452. UnicodeString Note =
  9453. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9454. PostNote(Note, 0, NULL, NULL);
  9455. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9456. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9457. }
  9458. //---------------------------------------------------------------------------
  9459. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9460. {
  9461. WinConfiguration->FormatSizeBytes = Style;
  9462. }
  9463. //---------------------------------------------------------------------------
  9464. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9465. {
  9466. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9467. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9468. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9469. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  9470. }
  9471. //---------------------------------------------------------------------------
  9472. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9473. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9474. {
  9475. if (Panel->Index == 0)
  9476. {
  9477. if (FOnNoteClick != NULL)
  9478. {
  9479. // prevent the user data from being freed by possible call
  9480. // to CancelNote or PostNote during call to OnNoteClick
  9481. std::unique_ptr<TObject> NoteData(FNoteData);
  9482. TNotifyEvent OnNoteClick = FOnNoteClick;
  9483. FNoteData = NULL;
  9484. // need to cancel the note as we are going to delete its user data
  9485. CancelNote(true);
  9486. OnNoteClick(NoteData.get());
  9487. }
  9488. }
  9489. if (HasActiveTerminal() &&
  9490. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9491. {
  9492. FileSystemInfo();
  9493. }
  9494. }
  9495. //---------------------------------------------------------------------------
  9496. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9497. {
  9498. // workaround:
  9499. // 1) for unknown reason, disabling window, while minimized,
  9500. // prevents it from restoring, even if it was enabled again meanwhile
  9501. // 2) when disabling the main window, while another has focus
  9502. // minimize is no longer possible
  9503. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9504. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9505. // Shouldn't we use IsApplicationMinimized() here?
  9506. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9507. {
  9508. Enabled = false;
  9509. }
  9510. FLockLevel++;
  9511. }
  9512. //---------------------------------------------------------------------------
  9513. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9514. {
  9515. DebugAssert(FLockLevel > 0);
  9516. FLockLevel--;
  9517. if (FLockLevel == 0)
  9518. {
  9519. DebugAssert(FLockSuspendLevel == 0);
  9520. Enabled = true;
  9521. }
  9522. }
  9523. //---------------------------------------------------------------------------
  9524. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9525. {
  9526. // We need to make sure that window is enabled when the last modal window closes
  9527. // otherwise focus is not restored correctly.
  9528. // So we re-enable the window when modal window opens and
  9529. // disable it back after is closes
  9530. if (FLockLevel > 0)
  9531. {
  9532. // while we have nesting counter, we know that we never be called
  9533. // recursivelly as Application->OnModalBegin is called only
  9534. // for the top-level modal window
  9535. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9536. {
  9537. // won't be disabled when conditions in LockWindow() were not satisfied
  9538. FDisabledOnLockSuspend = !Enabled;
  9539. // When minimized to tray (or actually when set to SW_HIDE),
  9540. // setting Enabled makes the window focusable even when there's
  9541. // modal window over it
  9542. if (!FTrayIcon->Visible)
  9543. {
  9544. Enabled = true;
  9545. }
  9546. }
  9547. FLockSuspendLevel++;
  9548. }
  9549. }
  9550. //---------------------------------------------------------------------------
  9551. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9552. {
  9553. if (FLockSuspendLevel > 0)
  9554. {
  9555. DebugAssert(FLockLevel > 0);
  9556. FLockSuspendLevel--;
  9557. // see comment in SuspendWindowLock
  9558. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9559. {
  9560. // Note that window can be enabled here, when we were minized to tray when
  9561. // was SuspendWindowLock() called.
  9562. // We should possibly do the same check as in LockWindow(),
  9563. // if it is ever possible that the consitions change between
  9564. // SuspendWindowLock() and ResumeWindowLock()
  9565. Enabled = !FDisabledOnLockSuspend;
  9566. }
  9567. }
  9568. }
  9569. //---------------------------------------------------------------------------
  9570. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9571. {
  9572. TTBXComboBoxItem * RemotePathComboBox =
  9573. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9574. if (!TextOnly)
  9575. {
  9576. TStrings * Items = RemotePathComboBox->Strings;
  9577. Items->BeginUpdate();
  9578. try
  9579. {
  9580. Items->Clear();
  9581. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9582. {
  9583. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9584. while (!IsUnixRootPath(APath))
  9585. {
  9586. int P = APath.LastDelimiter(L'/');
  9587. DebugAssert(P >= 0);
  9588. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9589. APath.SetLength(P - 1);
  9590. }
  9591. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9592. }
  9593. }
  9594. __finally
  9595. {
  9596. Items->EndUpdate();
  9597. }
  9598. }
  9599. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9600. // Setting ItemIndex to -1 does not reset its text
  9601. if (RemotePathComboBox->Strings->Count == 0)
  9602. {
  9603. RemotePathComboBox->Text = L"";
  9604. }
  9605. }
  9606. //---------------------------------------------------------------------------
  9607. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9608. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9609. {
  9610. if (AIndex < 0)
  9611. {
  9612. AIndex = Sender->ItemIndex;
  9613. }
  9614. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9615. }
  9616. //---------------------------------------------------------------------------
  9617. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9618. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9619. int & ImageIndex)
  9620. {
  9621. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9622. }
  9623. //---------------------------------------------------------------------------
  9624. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9625. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9626. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9627. {
  9628. if (!IsLocalBrowserMode())
  9629. {
  9630. ARect.Left += (10 * AIndex);
  9631. }
  9632. }
  9633. //---------------------------------------------------------------------------
  9634. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9635. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9636. {
  9637. AWidth += (10 * AIndex);
  9638. }
  9639. //---------------------------------------------------------------------------
  9640. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9641. {
  9642. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9643. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9644. int Index = RemotePathComboBox->ItemIndex;
  9645. while (Index < RemotePathComboBox->Strings->Count - 1)
  9646. {
  9647. APath = UnixExtractFileDir(APath);
  9648. Index++;
  9649. }
  9650. // VanDyke style paths
  9651. if (APath.IsEmpty())
  9652. {
  9653. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9654. APath = ROOTDIRECTORY;
  9655. }
  9656. if (RemoteDirView->Path != APath)
  9657. {
  9658. RemoteDirView->Path = APath;
  9659. }
  9660. }
  9661. //---------------------------------------------------------------------------
  9662. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9663. {
  9664. DoRemotePathComboBoxItemClick(Sender);
  9665. }
  9666. //---------------------------------------------------------------------------
  9667. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9668. {
  9669. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9670. DebugUsedParam(Sender);
  9671. UpdateRemotePathComboBox(true);
  9672. }
  9673. //---------------------------------------------------------------------------
  9674. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9675. {
  9676. DoRemotePathComboBoxCancel(Sender);
  9677. }
  9678. //---------------------------------------------------------------------------
  9679. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9680. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9681. {
  9682. ResetIncrementalSearch();
  9683. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9684. DebugAssert(DirView != NULL);
  9685. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9686. {
  9687. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9688. // OnEditing is called also from TCustomListView::CanEdit
  9689. if (Edit != NULL)
  9690. {
  9691. EditSelectBaseName(Edit);
  9692. }
  9693. }
  9694. }
  9695. //---------------------------------------------------------------------------
  9696. //---------------------------------------------------------------------------
  9697. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9698. {
  9699. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9700. Result->AutoDetectDnD = false;
  9701. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9702. Result->RenderDataOn = rdoEnterAndDropSync;
  9703. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9704. return Result;
  9705. }
  9706. //---------------------------------------------------------------------------
  9707. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9708. {
  9709. if (IsWin10Build(19041))
  9710. {
  9711. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9712. BOOL DarkMode = FImmersiveDarkMode ? TRUE : FALSE;
  9713. const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
  9714. DwmSetWindowAttribute(Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, &DarkMode, sizeof(DarkMode));
  9715. }
  9716. }
  9717. //---------------------------------------------------------------------------
  9718. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9719. {
  9720. TForm::CreateWnd();
  9721. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9722. UpdateDarkMode();
  9723. if (FSessionsDragDropFilesEx == NULL)
  9724. {
  9725. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9726. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9727. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9728. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9729. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9730. }
  9731. if (FQueueDragDropFilesEx == NULL)
  9732. {
  9733. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9734. // No need to set OnDragOver as we do not have any restrictions
  9735. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9736. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9737. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9738. }
  9739. }
  9740. //---------------------------------------------------------------------------
  9741. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9742. {
  9743. TForm::DestroyWnd();
  9744. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9745. FQueueDragDropFilesEx->DragDropControl = NULL;
  9746. }
  9747. //---------------------------------------------------------------------------
  9748. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9749. {
  9750. SideEnter(FCurrentSide);
  9751. FEverShown = true;
  9752. }
  9753. //---------------------------------------------------------------------------
  9754. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9755. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9756. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9757. {
  9758. if (!NonVisualDataModule->Busy)
  9759. {
  9760. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9761. Configuration->Usage->Inc(L"FileFinds");
  9762. LockWindow(true);
  9763. NonVisualDataModule->StartBusy();
  9764. WinConfiguration->LockedInterface = true;
  9765. try
  9766. {
  9767. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9768. }
  9769. __finally
  9770. {
  9771. WinConfiguration->LockedInterface = false;
  9772. NonVisualDataModule->EndBusy();
  9773. UnlockWindow();
  9774. }
  9775. }
  9776. }
  9777. //---------------------------------------------------------------------------
  9778. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9779. {
  9780. if (!NonVisualDataModule->Busy)
  9781. {
  9782. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9783. SetFocus();
  9784. RemoteDirView->Path = UnixExtractFilePath(Path);
  9785. UnicodeString FileName = UnixExtractFileName(Path);
  9786. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9787. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9788. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  9789. if (Item == NULL)
  9790. {
  9791. ReloadDirectory(osRemote);
  9792. Item = RemoteDirView->FindFileItem(FileName);
  9793. }
  9794. if (Item != NULL)
  9795. {
  9796. RemoteDirView->ItemFocused = Item;
  9797. RemoteDirView->ItemFocused->MakeVisible(false);
  9798. RemoteDirView->SetFocus();
  9799. }
  9800. }
  9801. }
  9802. //---------------------------------------------------------------------------
  9803. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  9804. {
  9805. bool Result = !NonVisualDataModule->Busy;
  9806. if (Result)
  9807. {
  9808. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9809. }
  9810. return Result;
  9811. }
  9812. //---------------------------------------------------------------------------
  9813. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  9814. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9815. {
  9816. if (CanOperateOnFoundFiles(ATerminal))
  9817. {
  9818. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  9819. FOnFileOperationFinished = OnFileOperationFinished;
  9820. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  9821. }
  9822. }
  9823. //---------------------------------------------------------------------------
  9824. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  9825. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9826. {
  9827. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  9828. }
  9829. //---------------------------------------------------------------------------
  9830. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  9831. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9832. {
  9833. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  9834. }
  9835. //---------------------------------------------------------------------------
  9836. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  9837. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9838. {
  9839. if (CanOperateOnFoundFiles(ATerminal))
  9840. {
  9841. for (int Index = 0; Index < FileList->Count; Index++)
  9842. {
  9843. UnicodeString FileName = FileList->Strings[Index];
  9844. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  9845. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  9846. OnFileOperationFinished(osRemote, FileName, true);
  9847. }
  9848. }
  9849. }
  9850. //---------------------------------------------------------------------------
  9851. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  9852. {
  9853. FFileFindTerminal = Terminal;
  9854. ShowFileFindDialog(
  9855. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  9856. DoDownloadFoundFiles, DoEditFoundFiles);
  9857. }
  9858. //---------------------------------------------------------------------------
  9859. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  9860. {
  9861. FTaskbarList = TaskbarList;
  9862. }
  9863. //---------------------------------------------------------------------------
  9864. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  9865. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  9866. {
  9867. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9868. if (Index >= 0)
  9869. {
  9870. if (Button == mbLeft)
  9871. {
  9872. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  9873. // If switching tab (switching session) takes long enough for user
  9874. // to actually release the button, "mouse down" is still raised,
  9875. // but we do not get "mouse up" event, so dragging is not cancelled,
  9876. // prevent that by not beginning dragging in the first place.
  9877. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  9878. if (IsKeyPressed(Key))
  9879. {
  9880. // when user clicks the "+", we get mouse down only after the session
  9881. // is closed, when new session tab is already on X:Y, so dragging
  9882. // starts, prevent that
  9883. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  9884. {
  9885. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9886. if (Terminal != NULL)
  9887. {
  9888. SessionsPageControl->BeginDrag(false);
  9889. }
  9890. }
  9891. }
  9892. }
  9893. else if (Button == mbMiddle)
  9894. {
  9895. // ignore middle-click for "New session tab" and the last local-local tab
  9896. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9897. if ((Session != NULL) && CanCloseSession(Session))
  9898. {
  9899. CloseSessionTab(Index);
  9900. }
  9901. }
  9902. }
  9903. }
  9904. //---------------------------------------------------------------------------
  9905. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  9906. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  9907. {
  9908. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9909. // do not allow dropping on the "+" tab
  9910. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9911. if ((TargetTerminal != NULL) &&
  9912. (SessionsPageControl->ActivePage->PageIndex != Index))
  9913. {
  9914. Configuration->Usage->Inc(L"SessionTabMoves");
  9915. // this is almost redundant as we would recreate tabs in SessionListChanged,
  9916. // but we want to actually prevent that to avoid flicker
  9917. SessionsPageControl->ActivePage->PageIndex = Index;
  9918. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  9919. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  9920. }
  9921. }
  9922. //---------------------------------------------------------------------------
  9923. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  9924. TObject * Sender, TObject * Source, int X, int Y,
  9925. TDragState /*State*/, bool & Accept)
  9926. {
  9927. Accept = (Sender == Source);
  9928. if (Accept)
  9929. {
  9930. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9931. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9932. // do not allow dragging to the "+" tab
  9933. Accept = (Terminal != NULL);
  9934. }
  9935. }
  9936. //---------------------------------------------------------------------------
  9937. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  9938. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  9939. {
  9940. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  9941. if (Index < 0)
  9942. {
  9943. Effect = DROPEFFECT_NONE;
  9944. }
  9945. else
  9946. {
  9947. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9948. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  9949. if (!IsActiveTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  9950. {
  9951. Effect = DROPEFFECT_NONE;
  9952. }
  9953. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  9954. {
  9955. Effect = DROPEFFECT_COPY;
  9956. }
  9957. }
  9958. }
  9959. //---------------------------------------------------------------------------
  9960. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  9961. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  9962. {
  9963. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  9964. // do not allow dropping on local-local, disconnected and the "+" tab
  9965. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  9966. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9967. if (DebugAlwaysTrue(IsActiveTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  9968. {
  9969. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  9970. if (!IsFileControl(DropSourceControl, osRemote))
  9971. {
  9972. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  9973. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  9974. // Why don't we use Terminal->CurrentDirectory directly?
  9975. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  9976. // do not force queue, drag drop
  9977. false, true);
  9978. }
  9979. }
  9980. }
  9981. //---------------------------------------------------------------------------
  9982. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  9983. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  9984. {
  9985. // Downloads are handled in RemoteFileControlDDEnd
  9986. if (!IsFileControl(DropSourceControl, osRemote))
  9987. {
  9988. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  9989. Terminal->CurrentDirectory,
  9990. // force queue, drag drop
  9991. true, true);
  9992. }
  9993. }
  9994. //---------------------------------------------------------------------------
  9995. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  9996. {
  9997. FShowing = false;
  9998. // Do not save empty workspace
  9999. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10000. {
  10001. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10002. UnicodeString Name = WorkspaceName();
  10003. DoSaveWorkspace(
  10004. Name, DataList.get(),
  10005. !Configuration->DisablePasswordStoring &&
  10006. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10007. WinConfiguration->LastStoredSession = Name;
  10008. }
  10009. }
  10010. //---------------------------------------------------------------------------
  10011. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10012. {
  10013. TManagedTerminal * ManagedTerminal =
  10014. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10015. if (ManagedTerminal != NULL)
  10016. {
  10017. ManagedTerminal->DirectoryLoaded = Now();
  10018. }
  10019. }
  10020. //---------------------------------------------------------------------------
  10021. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10022. TListItem * /*Item*/, bool /*Selected*/)
  10023. {
  10024. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10025. switch (DirView->LastSelectMethod)
  10026. {
  10027. case smKeyboard:
  10028. Configuration->Usage->Inc(L"KeyboardSelections");
  10029. break;
  10030. case smMouse:
  10031. Configuration->Usage->Inc(L"MouseSelections");
  10032. break;
  10033. }
  10034. }
  10035. //---------------------------------------------------------------------------
  10036. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10037. {
  10038. if (Color != 0)
  10039. {
  10040. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10041. }
  10042. else
  10043. {
  10044. return FSessionTabImageIndex;
  10045. }
  10046. }
  10047. //---------------------------------------------------------------------------
  10048. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10049. {
  10050. TPngImageCollectionItem * Item =
  10051. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10052. FSessionColors->AddPng(Item->PngImage);
  10053. return FSessionColors->Count - 1;
  10054. }
  10055. //---------------------------------------------------------------------------
  10056. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10057. {
  10058. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10059. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10060. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10061. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10062. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10063. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10064. }
  10065. //---------------------------------------------------------------------------
  10066. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10067. {
  10068. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10069. }
  10070. //---------------------------------------------------------------------------
  10071. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10072. {
  10073. switch (Side)
  10074. {
  10075. case osLocal:
  10076. return FNewLocalTabTabImageIndex;
  10077. case osRemote:
  10078. case osCurrent:
  10079. return FNewRemoteTabTabImageIndex;
  10080. default:
  10081. DebugFail();
  10082. return -1;
  10083. }
  10084. }
  10085. //---------------------------------------------------------------------------
  10086. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10087. {
  10088. for (int Index = 0; Index < Control->ControlCount; Index++)
  10089. {
  10090. TControl * AControl = Control->Controls[Index];
  10091. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10092. if (WinControl != NULL)
  10093. {
  10094. CollectItemsWithTextDisplayMode(WinControl);
  10095. }
  10096. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10097. if (Toolbar != NULL)
  10098. {
  10099. // we care for top-level items only
  10100. TTBCustomItem * Items = Toolbar->Items;
  10101. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10102. {
  10103. TTBCustomItem * Item = Items->Items[ItemIndex];
  10104. if (((Item->DisplayMode == nbdmImageAndText) ||
  10105. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10106. EligibleForImageDisplayMode(Item))
  10107. {
  10108. FItemsWithTextDisplayMode.insert(Item);
  10109. }
  10110. }
  10111. }
  10112. }
  10113. }
  10114. //---------------------------------------------------------------------------
  10115. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10116. {
  10117. return true;
  10118. }
  10119. //---------------------------------------------------------------------------
  10120. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10121. {
  10122. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10123. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10124. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10125. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10126. bool Result = true;
  10127. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10128. {
  10129. TTBCustomItem * Item = *i;
  10130. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10131. if (Label != NULL)
  10132. {
  10133. // optimization
  10134. if (Label->Visible == SelectiveToolbarText)
  10135. {
  10136. Result = false;
  10137. }
  10138. else
  10139. {
  10140. Label->Visible = SelectiveToolbarText;
  10141. }
  10142. }
  10143. else
  10144. {
  10145. // optimization
  10146. if (Item->DisplayMode == DisplayMode)
  10147. {
  10148. Result = false;
  10149. }
  10150. else
  10151. {
  10152. Item->DisplayMode = DisplayMode;
  10153. }
  10154. }
  10155. ++i;
  10156. }
  10157. UpdateNewTabTab();
  10158. return Result;
  10159. }
  10160. //---------------------------------------------------------------------------
  10161. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10162. {
  10163. DebugFail();
  10164. }
  10165. //---------------------------------------------------------------------------
  10166. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10167. {
  10168. // Among other, a lock level is non zero, while directory is being loaded,
  10169. // even when it happens as a result of dirview navigation,
  10170. // i.e. when TNonVisualDataModule is NOT FBusy.
  10171. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10172. // Among other this prevents a panel auto update to occur while
  10173. // directory is changing.
  10174. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10175. }
  10176. //---------------------------------------------------------------------------
  10177. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10178. {
  10179. // While the window is disabled, we still seem to process menu shortcuts at least,
  10180. // so stop it at least here.
  10181. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10182. bool Result;
  10183. if (Allowed == aaUpdate)
  10184. {
  10185. Result = true;
  10186. }
  10187. else
  10188. {
  10189. Result = !NonVisualDataModule->Busy;
  10190. if (Result && (Allowed == aaShortCut))
  10191. {
  10192. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10193. Action->Update();
  10194. Result = Action->Enabled;
  10195. }
  10196. }
  10197. return Result;
  10198. }
  10199. //---------------------------------------------------------------------------
  10200. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10201. {
  10202. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10203. }
  10204. //---------------------------------------------------------------------------
  10205. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10206. {
  10207. // This is somewhat redundant to LockWindow() call from
  10208. // TTerminalManager::TerminalReadDirectoryProgress.
  10209. // But disabling window is known not to block keyboard shorcuts
  10210. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10211. if (Busy > 0)
  10212. {
  10213. if (NonVisualDataModule->Busy)
  10214. {
  10215. State = false;
  10216. }
  10217. else
  10218. {
  10219. NonVisualDataModule->StartBusy();
  10220. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10221. LockWindow();
  10222. }
  10223. }
  10224. else if (Busy < 0)
  10225. {
  10226. UnlockWindow();
  10227. NonVisualDataModule->EndBusy();
  10228. }
  10229. else
  10230. {
  10231. State = NonVisualDataModule->Busy;
  10232. }
  10233. }
  10234. //---------------------------------------------------------------------------
  10235. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10236. {
  10237. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10238. if (Index >= 0)
  10239. {
  10240. TPopupMenu * PopupMenu = NULL;
  10241. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10242. if (Session != NULL)
  10243. {
  10244. SessionsPageControl->ActivePageIndex = Index;
  10245. if (DebugAlwaysTrue(SessionTabSwitched()))
  10246. {
  10247. // copied from TControl.WMContextMenu
  10248. SendCancelMode(SessionsPageControl);
  10249. // explicit popup instead of using PopupMenu property
  10250. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10251. // while connecting yet not-connected session and hence
  10252. // allowing an access to commands over not-completely connected session
  10253. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10254. }
  10255. }
  10256. else
  10257. {
  10258. if (SupportsLocalBrowser())
  10259. {
  10260. PopupMenu = NonVisualDataModule->NewTabPopup;
  10261. }
  10262. }
  10263. if (PopupMenu != NULL)
  10264. {
  10265. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10266. PopupMenu->PopupComponent = SessionsPageControl;
  10267. PopupMenu->Popup(Point.x, Point.y);
  10268. }
  10269. }
  10270. Handled = true;
  10271. }
  10272. //---------------------------------------------------------------------------
  10273. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10274. {
  10275. return HasActiveTerminal() && Terminal->IsCapable[fcChangePassword];
  10276. }
  10277. //---------------------------------------------------------------------------
  10278. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10279. {
  10280. Configuration->Usage->Inc(L"PasswordChanges");
  10281. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10282. ChangePasswordData->DisableAuthentationsExceptPassword();
  10283. ChangePasswordData->ChangePassword = true;
  10284. std::unique_ptr<TTerminal> ChangePasswordSession(
  10285. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10286. ChangePasswordSession->AutoReadDirectory = false;
  10287. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10288. {
  10289. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10290. }
  10291. else
  10292. {
  10293. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10294. }
  10295. }
  10296. //---------------------------------------------------------------------------
  10297. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10298. {
  10299. // No nice way to assert SSH2
  10300. return HasActiveTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10301. }
  10302. //---------------------------------------------------------------------------
  10303. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10304. {
  10305. TOperationVisualizer OperationVisualizer;
  10306. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10307. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10308. }
  10309. //---------------------------------------------------------------------------
  10310. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  10311. {
  10312. TForm::ChangeScale(M, D);
  10313. int APixelsPerInch = GetControlPixelsPerInch(this);
  10314. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  10315. try
  10316. {
  10317. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  10318. }
  10319. __finally
  10320. {
  10321. GUIConfiguration->ChangeResourceModule(ResourceModule);
  10322. }
  10323. }
  10324. //---------------------------------------------------------------------------
  10325. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10326. {
  10327. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10328. }
  10329. //---------------------------------------------------------------------
  10330. class TPublicControl : public TControl
  10331. {
  10332. friend class TCustomScpExplorerForm;
  10333. };
  10334. //---------------------------------------------------------------------------
  10335. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10336. {
  10337. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10338. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10339. }
  10340. //---------------------------------------------------------------------------
  10341. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10342. {
  10343. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10344. OpenBookmark(Side, Bookmark);
  10345. }
  10346. //---------------------------------------------------------------------------
  10347. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10348. {
  10349. DoBookmarkClick(osLocal, Sender);
  10350. }
  10351. //---------------------------------------------------------------------------
  10352. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10353. {
  10354. DoBookmarkClick(osRemote, Sender);
  10355. }
  10356. //---------------------------------------------------------------------------
  10357. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10358. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10359. {
  10360. if (BookmarkList != NULL)
  10361. {
  10362. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10363. if (IsLocalBrowserMode())
  10364. {
  10365. Side = osLocal;
  10366. }
  10367. if (!WinConfiguration->UseLocationProfiles)
  10368. {
  10369. std::unique_ptr<TStringList> Directories(new TStringList());
  10370. Directories->CaseSensitive = (Side == osRemote);
  10371. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10372. {
  10373. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10374. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10375. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10376. {
  10377. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10378. Item->Caption = EscapeHotkey(Directory);
  10379. Item->ShortCut = Bookmark->ShortCut;
  10380. Item->OnClick = OnBookmarkClick;
  10381. Item->Tag = reinterpret_cast<int>(Bookmark);
  10382. Directories->Add(Directory);
  10383. Menu->Add(Item.release());
  10384. }
  10385. }
  10386. }
  10387. else
  10388. {
  10389. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10390. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10391. {
  10392. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10393. if (!Bookmark->Node.IsEmpty())
  10394. {
  10395. Folders->Add(Bookmark->Node);
  10396. }
  10397. }
  10398. for (int Index = 0; Index < Folders->Count; Index++)
  10399. {
  10400. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10401. Item->Caption = Folders->Strings[Index];
  10402. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10403. Folders->Objects[Index] = Item.get();
  10404. Menu->Add(Item.release());
  10405. }
  10406. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10407. {
  10408. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10409. TTBCustomItem * Parent;
  10410. if (!Bookmark->Node.IsEmpty())
  10411. {
  10412. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10413. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10414. }
  10415. else
  10416. {
  10417. Parent = Menu;
  10418. }
  10419. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10420. Item->Caption = Bookmark->Name;
  10421. Item->ShortCut = Bookmark->ShortCut;
  10422. Item->OnClick = OnBookmarkClick;
  10423. Item->Tag = reinterpret_cast<int>(Bookmark);
  10424. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10425. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10426. {
  10427. // No hint for location profiles that are actually mere "bookmarks"
  10428. }
  10429. else
  10430. {
  10431. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10432. UnicodeString LongHint;
  10433. if (!Bookmark->Local.IsEmpty())
  10434. {
  10435. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10436. }
  10437. if (!Bookmark->Remote.IsEmpty())
  10438. {
  10439. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10440. }
  10441. AddToList(Hint, LongHint, L"|");
  10442. Item->Hint = Hint;
  10443. }
  10444. Parent->Add(Item.release());
  10445. }
  10446. }
  10447. AddMenuSeparator(Menu);
  10448. }
  10449. }
  10450. //---------------------------------------------------------------------------
  10451. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10452. {
  10453. Menu->Clear();
  10454. std::unique_ptr<TTBCustomItem> Item;
  10455. Item.reset(new TTBXItem(Owner));
  10456. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10457. Item->Options = Item->Options << tboDefault;
  10458. Menu->Add(Item.release());
  10459. AddMenuSeparator(Menu);
  10460. if (Terminal != NULL)
  10461. {
  10462. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10463. }
  10464. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10465. Item.reset(new TTBXItem(Owner));
  10466. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10467. Menu->Add(Item.release());
  10468. }
  10469. //---------------------------------------------------------------------------
  10470. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10471. {
  10472. bool Result = true;
  10473. bool Remote = !IsSideLocalBrowser(Side);
  10474. try
  10475. {
  10476. UnicodeString APath = Path;
  10477. if (Remote)
  10478. {
  10479. Terminal->ExceptionOnFail = true;
  10480. }
  10481. else
  10482. {
  10483. APath = ExpandEnvironmentVariables(Path);
  10484. }
  10485. try
  10486. {
  10487. DirView(Side)->Path = APath;
  10488. }
  10489. __finally
  10490. {
  10491. if (Remote)
  10492. {
  10493. Terminal->ExceptionOnFail = false;
  10494. }
  10495. }
  10496. }
  10497. catch (Exception & E)
  10498. {
  10499. if (!Remote || Terminal->Active)
  10500. {
  10501. ShowExtendedExceptionEx(Terminal, &E);
  10502. Result = false;
  10503. }
  10504. else
  10505. {
  10506. throw;
  10507. }
  10508. }
  10509. return Result;
  10510. }
  10511. //---------------------------------------------------------------------------
  10512. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10513. {
  10514. // Make sure there some feedback even when loading tiny local folders
  10515. TInstantOperationVisualizer Visualizer;
  10516. DirView(Side)->ReloadDirectory();
  10517. }
  10518. //---------------------------------------------------------------------------
  10519. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10520. {
  10521. if (Index == SessionsPageControl->TabIndex)
  10522. {
  10523. CloseTab();
  10524. }
  10525. else
  10526. {
  10527. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10528. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10529. TTerminalManager * Manager = TTerminalManager::Instance();
  10530. if (!Terminal->Active)
  10531. {
  10532. Manager->FreeTerminal(Terminal);
  10533. }
  10534. else
  10535. {
  10536. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10537. if (CanCloseQueue(Queue))
  10538. {
  10539. Manager->FreeTerminal(Terminal);
  10540. }
  10541. }
  10542. }
  10543. }
  10544. //---------------------------------------------------------------------------
  10545. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10546. {
  10547. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10548. if (Session == NULL)
  10549. {
  10550. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10551. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10552. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10553. //P = SessionsPageControl->ClientToScreen(P);
  10554. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10555. }
  10556. else
  10557. {
  10558. CloseSessionTab(Index);
  10559. }
  10560. }
  10561. //---------------------------------------------------------------------------
  10562. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10563. {
  10564. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10565. {
  10566. TInstantOperationVisualizer Visualizer;
  10567. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10568. // before we create a new data object
  10569. ClipboardClear();
  10570. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10571. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10572. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10573. // Intermediate variable to WORKAROUND a crash in compiler
  10574. TObjectList * ClipboardFakeMonitors =
  10575. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10576. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10577. if (FClipboardDragDropFilesEx.get() == NULL)
  10578. {
  10579. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10580. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10581. }
  10582. FClipboardDragDropFilesEx->FileList->Clear();
  10583. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10584. FClipboardDragDropFilesEx->CopyToClipboard();
  10585. FClipboardTerminal = Terminal;
  10586. // Need full paths, as cwd can be different once files are pasted
  10587. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10588. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10589. {
  10590. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10591. }
  10592. }
  10593. }
  10594. //---------------------------------------------------------------------------
  10595. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10596. {
  10597. if (OpenClipboard(0))
  10598. {
  10599. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10600. CloseClipboard();
  10601. }
  10602. }
  10603. //---------------------------------------------------------------------------
  10604. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10605. {
  10606. return !FClipboardFakeDirectory.IsEmpty();
  10607. }
  10608. //---------------------------------------------------------------------------
  10609. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10610. {
  10611. RemoveDir(ApiPath(FClipboardFakeDirectory));
  10612. FClipboardFakeDirectory = UnicodeString();
  10613. FClipboardTerminal = NULL;
  10614. if (FDownloadingFromClipboard)
  10615. {
  10616. // We are called by the monitor, so attempt to release it would deadlock
  10617. FClipboardFakeMonitorsPendingReset = true;
  10618. }
  10619. else
  10620. {
  10621. FClipboardFakeMonitors.reset(NULL);
  10622. }
  10623. }
  10624. //---------------------------------------------------------------------------
  10625. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10626. {
  10627. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10628. {
  10629. ClipboardStop();
  10630. }
  10631. }
  10632. //---------------------------------------------------------------------------
  10633. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10634. {
  10635. TTerminalManager * Manager = TTerminalManager::Instance();
  10636. Manager->ActiveSession = FClipboardTerminal;
  10637. TTransferOperationParam Params;
  10638. Params.TargetDirectory = TargetDirectory;
  10639. Params.DragDrop = DragDrop;
  10640. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10641. }
  10642. //---------------------------------------------------------------------------
  10643. void TCustomScpExplorerForm::PasteFiles()
  10644. {
  10645. // Guard against possible race conditions
  10646. if (!FClipboardPasteTarget.IsEmpty())
  10647. {
  10648. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10649. UnicodeString Target = FClipboardPasteTarget;
  10650. FClipboardPasteTarget = EmptyStr;
  10651. // Can fail as it can be e.g. locked by AV, so we retry that later
  10652. bool Removed = RemoveDir(ApiPath(Target));
  10653. try
  10654. {
  10655. if (!NonVisualDataModule->Busy)
  10656. {
  10657. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10658. FClipboardFakeMonitorsPendingReset = false;
  10659. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10660. TAutoFlag Flag(FDownloadingFromClipboard);
  10661. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10662. }
  10663. }
  10664. __finally
  10665. {
  10666. if (!Removed)
  10667. {
  10668. RemoveDir(ApiPath(Target));
  10669. }
  10670. }
  10671. }
  10672. }
  10673. //---------------------------------------------------------------------------
  10674. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10675. {
  10676. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10677. // (as it pumps a Windows message queue while being shutted down)
  10678. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10679. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10680. {
  10681. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10682. FClipboardPasteTarget = FileName;
  10683. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10684. // Postponing removing (or actually whole pasting operation) seems to help.
  10685. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10686. }
  10687. }
  10688. //---------------------------------------------------------------------------
  10689. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10690. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10691. {
  10692. TFileMasks::TParams MaskParams;
  10693. MaskParams.Size = Size;
  10694. MaskParams.Modification = Modification;
  10695. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10696. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10697. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10698. if (!Local && Directory)
  10699. {
  10700. FileName = UnixExcludeTrailingBackslash(FileName);
  10701. }
  10702. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10703. {
  10704. bool ImplicitMatch;
  10705. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10706. !ImplicitMatch)
  10707. {
  10708. Color = Iter->Color;
  10709. break;
  10710. }
  10711. }
  10712. }
  10713. //---------------------------------------------------------------------------
  10714. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10715. {
  10716. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10717. if (!DirView->IsEditing())
  10718. {
  10719. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10720. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10721. // while searching
  10722. if (Key == VK_BACK)
  10723. {
  10724. if (!FIncrementalSearch.IsEmpty())
  10725. {
  10726. if (FIncrementalSearch.Length() == 1)
  10727. {
  10728. ResetIncrementalSearch();
  10729. }
  10730. else
  10731. {
  10732. UnicodeString NewText = FIncrementalSearch.SubString(1, FIncrementalSearch.Length() - 1);
  10733. IncrementalSearch(NewText, false, false);
  10734. }
  10735. Key = 0;
  10736. }
  10737. }
  10738. }
  10739. }
  10740. //---------------------------------------------------------------------------
  10741. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10742. {
  10743. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10744. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10745. {
  10746. // Filter control sequences.
  10747. // When not searching yet, prefer use of the space for toggling file selection
  10748. // (so we cannot incrementally search for a string starting with a space).
  10749. if ((Key > VK_SPACE) ||
  10750. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && !FIncrementalSearch.IsEmpty()))
  10751. {
  10752. IncrementalSearch(FIncrementalSearch + Key, false, false);
  10753. Key = 0;
  10754. }
  10755. }
  10756. }
  10757. //---------------------------------------------------------------------------
  10758. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10759. {
  10760. if (!FIncrementalSearch.IsEmpty())
  10761. {
  10762. FIncrementalSearch = L"";
  10763. DirView(osCurrent)->UpdateStatusBar();
  10764. }
  10765. }
  10766. //---------------------------------------------------------------------------
  10767. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10768. {
  10769. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  10770. if (Item == NULL)
  10771. {
  10772. MessageBeep(MB_ICONHAND);
  10773. }
  10774. else
  10775. {
  10776. TCustomDirView * ADirView = DirView(osCurrent);
  10777. {
  10778. TAutoNestingCounter Guard(FIncrementalSearching);
  10779. ADirView->FocusItem(Item);
  10780. if (ADirView->NortonLike == nlOff)
  10781. {
  10782. if ((ADirView->Selected != Item) ||
  10783. (ADirView->SelCount > 1))
  10784. {
  10785. ADirView->ClearSelection();
  10786. ADirView->Selected = Item;
  10787. }
  10788. }
  10789. }
  10790. FIncrementalSearch = Text;
  10791. Item->MakeVisible(false);
  10792. TListItem * NextItem = SearchFile(Text, true, Reverse);
  10793. FIncrementalSearchHaveNext = (NextItem != NULL) && (NextItem != Item);
  10794. ADirView->UpdateStatusBar();
  10795. }
  10796. }
  10797. //---------------------------------------------------------------------------
  10798. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  10799. {
  10800. int Index = Item->Index;
  10801. if (!Reverse)
  10802. {
  10803. Index++;
  10804. if (Index >= Item->Owner->Count)
  10805. {
  10806. Index = 0;
  10807. }
  10808. }
  10809. else
  10810. {
  10811. Index--;
  10812. if (Index < 0)
  10813. {
  10814. Index = Item->Owner->Count - 1;
  10815. }
  10816. }
  10817. return Item->Owner->Item[Index];
  10818. }
  10819. //---------------------------------------------------------------------------
  10820. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10821. {
  10822. TCustomDirView * ADirView = DirView(osCurrent);
  10823. if (ADirView->Items->Count == 0)
  10824. {
  10825. return NULL;
  10826. }
  10827. else
  10828. {
  10829. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  10830. TListItem * Item = CurrentItem;
  10831. if (SkipCurrent)
  10832. {
  10833. Item = DebugNotNull(GetNextFile(Item, Reverse));
  10834. }
  10835. while (true)
  10836. {
  10837. bool Matches = false;
  10838. switch (WinConfiguration->PanelSearch)
  10839. {
  10840. case isNameStartOnly:
  10841. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  10842. break;
  10843. case isName:
  10844. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  10845. break;
  10846. case isAll:
  10847. int ColCount = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Count : 1;
  10848. int Index = 0;
  10849. while ((Index < ColCount) && !Matches)
  10850. {
  10851. bool Visible = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Visible[Index] : true;
  10852. if (Visible)
  10853. {
  10854. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  10855. }
  10856. Index++;
  10857. }
  10858. break;
  10859. }
  10860. if (Matches)
  10861. {
  10862. return Item;
  10863. }
  10864. Item = GetNextFile(Item, Reverse);
  10865. if (Item == CurrentItem)
  10866. {
  10867. return NULL;
  10868. }
  10869. }
  10870. }
  10871. }
  10872. //---------------------------------------------------------------------------
  10873. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  10874. {
  10875. ResetIncrementalSearch();
  10876. }
  10877. //---------------------------------------------------------------------------
  10878. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  10879. {
  10880. if (Message.CharCode == VK_TAB)
  10881. {
  10882. if (!FIncrementalSearch.IsEmpty())
  10883. {
  10884. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  10885. bool Reverse = Shift.Contains(ssShift);
  10886. IncrementalSearch(FIncrementalSearch, true, Reverse);
  10887. Message.Result = 1;
  10888. return;
  10889. }
  10890. }
  10891. else if (Message.CharCode == VK_ESCAPE)
  10892. {
  10893. if (!FIncrementalSearch.IsEmpty())
  10894. {
  10895. ResetIncrementalSearch();
  10896. Message.Result = 1;
  10897. return;
  10898. }
  10899. }
  10900. TForm::Dispatch(&Message);
  10901. }
  10902. //---------------------------------------------------------------------------
  10903. void __fastcall TCustomScpExplorerForm::Deactivate()
  10904. {
  10905. TForm::Deactivate();
  10906. // E.g. when switching to an internal editor window
  10907. ResetIncrementalSearch();
  10908. }
  10909. //---------------------------------------------------------------------------
  10910. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  10911. {
  10912. // When switching to another application
  10913. ResetIncrementalSearch();
  10914. }
  10915. //---------------------------------------------------------------------------
  10916. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  10917. {
  10918. ResetIncrementalSearch();
  10919. }
  10920. //---------------------------------------------------------------------------
  10921. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  10922. {
  10923. if (FIncrementalSearching <= 0)
  10924. {
  10925. ResetIncrementalSearch();
  10926. }
  10927. }
  10928. //---------------------------------------------------------------------------
  10929. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  10930. {
  10931. CountClicksForWindowPrint(this);
  10932. }
  10933. //---------------------------------------------------------------------------
  10934. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  10935. {
  10936. CenterReconnectToolbar();
  10937. }
  10938. //---------------------------------------------------------------------------
  10939. void __fastcall TCustomScpExplorerForm::BrowseFile()
  10940. {
  10941. if (RemoteDirView->ItemFocused != NULL)
  10942. {
  10943. RemoteDirView->ItemFocused->Selected = true;
  10944. }
  10945. }
  10946. //---------------------------------------------------------------------------
  10947. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  10948. {
  10949. if (!FQueueStatusUpdating)
  10950. {
  10951. bool Refresh;
  10952. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  10953. {
  10954. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  10955. }
  10956. else
  10957. {
  10958. if (FQueueFileList->GetCount() > 0)
  10959. {
  10960. FQueueFileList->Clear();
  10961. Refresh = true;
  10962. }
  10963. }
  10964. int Count = FQueueFileList->GetCount();
  10965. if (QueueFileList->Items->Count != Count)
  10966. {
  10967. DebugAssert(Refresh);
  10968. QueueFileList->Items->Count = Count;
  10969. }
  10970. if (Refresh)
  10971. {
  10972. QueueFileList->Invalidate();
  10973. }
  10974. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  10975. }
  10976. }
  10977. //---------------------------------------------------------------------------
  10978. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  10979. {
  10980. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  10981. }
  10982. //---------------------------------------------------------------------------
  10983. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  10984. {
  10985. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  10986. // See TSynchronizeChecklistDialog::UpdateTimer
  10987. if (QueueFileList->Items->Count > 0)
  10988. {
  10989. QueueFileList->Items->Item[0]->MakeVisible(false);
  10990. }
  10991. UpdateQueueFileList();
  10992. }
  10993. //---------------------------------------------------------------------------
  10994. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  10995. {
  10996. Active = QueueView3->Focused() || QueueFileList->Focused();
  10997. }
  10998. //---------------------------------------------------------------------------
  10999. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11000. {
  11001. QueueLabelUpdateStatus();
  11002. }
  11003. //---------------------------------------------------------------------------
  11004. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11005. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11006. {
  11007. int State = FQueueFileList->GetState(Item->Index);
  11008. if (State == qfsProcessed)
  11009. {
  11010. Sender->Canvas->Font->Color = clGrayText;
  11011. }
  11012. }
  11013. //---------------------------------------------------------------------------
  11014. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11015. {
  11016. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11017. QueueFileList->Column[0]->Width =
  11018. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11019. }
  11020. //---------------------------------------------------------------------------
  11021. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11022. {
  11023. QueueFileListColumnAutoSize();
  11024. }
  11025. //---------------------------------------------------------------------------
  11026. void __fastcall TCustomScpExplorerForm::CloseApp()
  11027. {
  11028. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11029. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11030. // So we clear the flag here.
  11031. DebugAssert(NonVisualDataModule->Busy);
  11032. NonVisualDataModule->EndBusy();
  11033. try
  11034. {
  11035. Close();
  11036. }
  11037. __finally
  11038. {
  11039. NonVisualDataModule->StartBusy();
  11040. }
  11041. }
  11042. //---------------------------------------------------------------------------
  11043. bool __fastcall TCustomScpExplorerForm::IsActiveTerminal(TTerminal * Terminal)
  11044. {
  11045. return (Terminal != NULL) && Terminal->Active;
  11046. }
  11047. //---------------------------------------------------------------------------
  11048. bool __fastcall TCustomScpExplorerForm::HasManagedSession()
  11049. {
  11050. return (ManagedSession != NULL);
  11051. }
  11052. //---------------------------------------------------------------------------
  11053. bool __fastcall TCustomScpExplorerForm::HasActiveTerminal()
  11054. {
  11055. return IsActiveTerminal(Terminal);
  11056. }
  11057. //---------------------------------------------------------------------------
  11058. void TCustomScpExplorerForm::LocalLocalCopy(
  11059. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11060. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11061. {
  11062. DebugFail();
  11063. }
  11064. //---------------------------------------------------------------------------
  11065. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11066. {
  11067. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11068. }
  11069. //---------------------------------------------------------------------------
  11070. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11071. {
  11072. // 1) Changing tab list triggers the OnResize.
  11073. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11074. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11075. {
  11076. // UpdateTabsCaptionTruncation should be enough
  11077. SessionListChanged(true);
  11078. }
  11079. }
  11080. //---------------------------------------------------------------------------
  11081. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11082. {
  11083. if (ASession == ManagedSession)
  11084. {
  11085. UpdateSession(ASession);
  11086. }
  11087. TSessionData * Data = ASession->StateData;
  11088. UnicodeString Result;
  11089. if (Side == osLocal)
  11090. {
  11091. Result = Data->LocalDirectory;
  11092. }
  11093. else if (DebugAlwaysTrue(Side == osOther))
  11094. {
  11095. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11096. }
  11097. return Result;
  11098. }
  11099. //---------------------------------------------------------------------------
  11100. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11101. {
  11102. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11103. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11104. if (Title == Result)
  11105. {
  11106. Result = EmptyStr;
  11107. }
  11108. else
  11109. {
  11110. Result += L"\n";
  11111. }
  11112. return Result;
  11113. }
  11114. //---------------------------------------------------------------------------
  11115. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11116. {
  11117. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11118. if (!ASession->Active)
  11119. {
  11120. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11121. }
  11122. else
  11123. {
  11124. Result += GetSessionPath(ASession, osRemote);
  11125. }
  11126. return Result;
  11127. }
  11128. //---------------------------------------------------------------------------
  11129. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11130. {
  11131. return LoadStr(NEW_REMOTE_TAB_HINT);
  11132. }
  11133. //---------------------------------------------------------------------------
  11134. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11135. {
  11136. if (Index >= 0)
  11137. {
  11138. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11139. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11140. if (TabSession == NULL)
  11141. {
  11142. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11143. if (NewTabTabCaption != TabSheet->Caption)
  11144. {
  11145. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11146. }
  11147. }
  11148. else
  11149. {
  11150. TTerminalManager * Manager = TTerminalManager::Instance();
  11151. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11152. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11153. }
  11154. }
  11155. }
  11156. //---------------------------------------------------------------------------
  11157. typedef std::vector<TListItem *> TListItemsVector;
  11158. struct TCalculateSizeOperation
  11159. {
  11160. TCalculateSizeStats Stats;
  11161. TListItemsVector ListItems;
  11162. size_t Index;
  11163. };
  11164. //---------------------------------------------------------------------------
  11165. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11166. {
  11167. TCalculateSizeOperation CalculateSizeOperation;
  11168. Side = GetSide(Side);
  11169. TCustomDirView * ADirView = DirView(Side);
  11170. bool LocalSide = IsSideLocalBrowser(Side);
  11171. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11172. std::unique_ptr<TStrings> FileList(new TStringList());
  11173. for (int Index = 0; Index < AllFileList->Count; Index++)
  11174. {
  11175. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11176. if (ADirView->ItemIsDirectory(Item))
  11177. {
  11178. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11179. CalculateSizeOperation.ListItems.push_back(Item);
  11180. }
  11181. }
  11182. CalculateSizeOperation.Index = 0;
  11183. __int64 Size = 0;
  11184. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation);
  11185. FCalculateSizeOperation = &CalculateSizeOperation;
  11186. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11187. FOnFileOperationFinished = DirectorySizeCalculated;
  11188. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation);
  11189. FPrimaryOperation = foCalculateSize;
  11190. TCalculatedSizes CalculatedSizes;
  11191. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11192. if (LocalSide)
  11193. {
  11194. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  11195. FProgressSide = Side;
  11196. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11197. }
  11198. else
  11199. {
  11200. TCalculateSizeParams Params;
  11201. Params.Stats = &CalculateSizeOperation.Stats;
  11202. Params.UseCache = true;
  11203. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11204. }
  11205. }
  11206. //---------------------------------------------------------------------------
  11207. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(TOperationSide Side, const UnicodeString & FileName, bool Success)
  11208. {
  11209. DebugAlwaysTrue(FCalculateSizeOperation != NULL);
  11210. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11211. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11212. // optimization
  11213. bool GotExpectedItem =
  11214. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11215. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11216. int Index = -1;
  11217. if (DebugAlwaysTrue(GotExpectedItem))
  11218. {
  11219. Index = FCalculateSizeOperation->Index;
  11220. FCalculateSizeOperation->Index++;
  11221. }
  11222. else
  11223. {
  11224. TListItemsVector::iterator I =
  11225. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11226. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11227. {
  11228. Index = I - FCalculateSizeOperation->ListItems.begin();
  11229. }
  11230. }
  11231. if (DebugAlwaysTrue(Index >= 0) && Success)
  11232. {
  11233. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11234. ADirView->SetItemCalculatedSize(Item, Size);
  11235. }
  11236. }
  11237. //---------------------------------------------------------------------------
  11238. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11239. {
  11240. Accept = false;
  11241. }
  11242. //---------------------------------------------------------------------------