CustomScpExplorer.cpp 345 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include <Common.h>
  6. #include "CustomScpExplorer.h"
  7. #include <Bookmarks.h>
  8. #include <Interface.h>
  9. #include <Exceptions.h>
  10. #include <CoreMain.h>
  11. #include <FileSystems.h>
  12. #include <TextsCore.h>
  13. #include <TextsWin.h>
  14. #include <HelpWin.h>
  15. #include <VCLCommon.h>
  16. #include <Progress.h>
  17. #include <SynchronizeProgress.h>
  18. #include <DragExt.h>
  19. #include <WinApi.h>
  20. #include "GUITools.h"
  21. #include "NonVisual.h"
  22. #include "Glyphs.h"
  23. #include "Tools.h"
  24. #include "WinConfiguration.h"
  25. #include "TerminalManager.h"
  26. #include "EditorManager.h"
  27. #include "ProgParams.h"
  28. #include "Setup.h"
  29. #include <Consts.hpp>
  30. #include <DateUtils.hpp>
  31. #include <TB2Common.hpp>
  32. #include <DirectoryMonitor.hpp>
  33. //---------------------------------------------------------------------------
  34. #pragma package(smart_init)
  35. #pragma link "CustomDirView"
  36. #pragma link "CustomUnixDirView"
  37. #pragma link "IEListView"
  38. #pragma link "NortonLikeListView"
  39. #pragma link "UnixDirView"
  40. #pragma link "CustomDriveView"
  41. #pragma link "UnixDriveView"
  42. #pragma link "CustomDriveView"
  43. #pragma link "TB2Dock"
  44. #pragma link "TBXStatusBars"
  45. #pragma link "TB2Item"
  46. #pragma link "TB2Toolbar"
  47. #pragma link "ThemePageControl"
  48. #pragma link "PathLabel"
  49. #ifndef NO_RESOURCES
  50. #pragma resource "*.dfm"
  51. #endif
  52. //---------------------------------------------------------------------------
  53. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  54. static const int SessionPanelCount = 4;
  55. //---------------------------------------------------------------------------
  56. class TMutexGuard
  57. {
  58. public:
  59. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  60. int Timeout = 5000)
  61. {
  62. FMutex = NULL;
  63. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  64. if (WaitResult == WAIT_TIMEOUT)
  65. {
  66. throw Exception(LoadStr(MUTEX_RELEASE_TIMEOUT));
  67. }
  68. else
  69. {
  70. FMutex = AMutex;
  71. }
  72. }
  73. ~TMutexGuard()
  74. {
  75. if (FMutex != NULL)
  76. {
  77. ReleaseMutex(FMutex);
  78. }
  79. }
  80. private:
  81. HANDLE FMutex;
  82. };
  83. //---------------------------------------------------------------------------
  84. class TWindowLock
  85. {
  86. public:
  87. TWindowLock(TCustomScpExplorerForm * Form) :
  88. FForm(Form)
  89. {
  90. FForm->LockWindow();
  91. }
  92. ~TWindowLock()
  93. {
  94. FForm->UnlockWindow();
  95. }
  96. private:
  97. TCustomScpExplorerForm * FForm;
  98. };
  99. //---------------------------------------------------------------------------
  100. class TAutoBatch
  101. {
  102. public:
  103. TAutoBatch(TCustomScpExplorerForm * Form) :
  104. FForm(Form)
  105. {
  106. FForm->BatchStart(FBatchStorage);
  107. }
  108. ~TAutoBatch()
  109. {
  110. FForm->BatchEnd(FBatchStorage);
  111. }
  112. private:
  113. TCustomScpExplorerForm * FForm;
  114. void * FBatchStorage;
  115. };
  116. //---------------------------------------------------------------------------
  117. struct TTransferOperationParam
  118. {
  119. TTransferOperationParam();
  120. UnicodeString TargetDirectory;
  121. bool Temp;
  122. bool DragDrop;
  123. int Options;
  124. TAutoSwitch Queue;
  125. };
  126. //---------------------------------------------------------------------------
  127. TTransferOperationParam::TTransferOperationParam()
  128. {
  129. Temp = false;
  130. DragDrop = false;
  131. Options = 0;
  132. Queue = asAuto;
  133. }
  134. //---------------------------------------------------------------------------
  135. class TTransferPresetNoteData : public TObject
  136. {
  137. public:
  138. UnicodeString Message;
  139. };
  140. //---------------------------------------------------------------------------
  141. class TTerminalNoteData : public TObject
  142. {
  143. public:
  144. TTerminal * Terminal;
  145. };
  146. //---------------------------------------------------------------------------
  147. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  148. FFormRestored(false),
  149. TForm(Owner)
  150. {
  151. FCurrentSide = osRemote;
  152. FEverShown = false;
  153. FDocks = new TList();
  154. InitControls();
  155. RestoreParams();
  156. ConfigurationChanged();
  157. RemoteDirView->Invalidate();
  158. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  159. NonVisualDataModule->ScpExplorer = this;
  160. FAutoOperation = false;
  161. FOnFileOperationFinished = NULL;
  162. FForceExecution = false;
  163. FIgnoreNextDialogChar = 0;
  164. FErrorList = NULL;
  165. FSynchronizeProgressForm = NULL;
  166. FProgressForm = NULL;
  167. FRefreshLocalDirectory = false;
  168. FRefreshRemoteDirectory = false;
  169. FDDExtMapFile = NULL;
  170. // CreateMutexW keeps failing with ERROR_NOACCESS
  171. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  172. DebugAssert(FDDExtMutex != NULL);
  173. FDDTargetControl = NULL;
  174. FDelayedDeletionTimer = NULL;
  175. FDelayedDeletionList = new TStringList();
  176. FDDFileList = NULL;
  177. FPendingTempSpaceWarn = false;
  178. FCapturedLog = NULL;
  179. FDragDropOperation = false;
  180. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  181. FAllowTransferPresetAutoSelect = true;
  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. FMoveToQueue = false;
  195. FStandaloneEditing = false;
  196. FOnFeedSynchronizeError = NULL;
  197. FNeedSession = false;
  198. FDoNotIdleCurrentTerminal = 0;
  199. FIncrementalSearching = 0;
  200. FIncrementalSearchHaveNext = false;
  201. FEditorManager = new TEditorManager();
  202. FEditorManager->OnFileChange = ExecutedFileChanged;
  203. FEditorManager->OnFileReload = ExecutedFileReload;
  204. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  205. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  206. FLocalEditors = new TList();
  207. FQueueStatus = NULL;
  208. FQueueStatusSection = new TCriticalSection();
  209. FQueueStatusInvalidated = false;
  210. FQueueItemInvalidated = false;
  211. FQueueActedItem = NULL;
  212. FQueueController = new TQueueController(QueueView3);
  213. FUserActionTimer = new TTimer(this);
  214. FUserActionTimer->Enabled = false;
  215. FUserActionTimer->Interval = 10;
  216. FUserActionTimer->OnTimer = UserActionTimer;
  217. FNotes = new TStringList();
  218. FNoteTimer = new TTimer(this);
  219. FNoteTimer->Enabled = false;
  220. FNoteTimer->OnTimer = NoteTimer;
  221. FOnNoteClick = NULL;
  222. FOle32Library = LoadLibrary(L"Ole32.dll");
  223. FDragMoveCursor = FOle32Library != NULL ?
  224. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  225. UseSystemSettings(this);
  226. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  227. static_cast<TObject*>(GetComponent(fcTransferList)));
  228. DebugAssert(TransferList != NULL);
  229. FTransferListHoverIndex = -1;
  230. TransferList->OnChange = TransferListChange;
  231. TransferList->OnDrawItem = TransferListDrawItem;
  232. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))));
  233. SetSubmenu(NonVisualDataModule->ColorMenuItem);
  234. UseDesktopFont(SessionsPageControl);
  235. UpdateSessionsPageControlHeight();
  236. UseDesktopFont(RemoteDirView);
  237. UseDesktopFont(RemoteDriveView);
  238. UseDesktopFont(QueueView3);
  239. UseDesktopFont(QueueLabel);
  240. UseDesktopFont(RemoteStatusBar);
  241. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  242. QueueSplitter->ShowHint = true;
  243. RemotePanelSplitter->ShowHint = true;
  244. UpdateImages();
  245. FCustomCommandMenu = CreateTBXPopupMenu(this);
  246. FCustomCommandLocalFileList = NULL;
  247. FCustomCommandRemoteFileList = NULL;
  248. FSessionColors = new TPngImageList(this);
  249. FSessionColors->ColorDepth = cd32Bit;
  250. AddFixedSessionImages();
  251. SessionsPageControl->Images = FSessionColors;
  252. QueueLabel->FocusControl = QueueView3;
  253. UpdateQueueLabel();
  254. FRemoteDirViewWasFocused = true;
  255. CreateHiddenWindow();
  256. StartUpdates();
  257. }
  258. //---------------------------------------------------------------------------
  259. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  260. {
  261. // this has to be one of the very first things to do
  262. StopUpdateThread();
  263. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  264. TTerminalManager::Instance()->ScpExplorer = NULL;
  265. delete FCustomCommandLocalFileList;
  266. delete FCustomCommandRemoteFileList;
  267. delete FCustomCommandMenu;
  268. delete FTrayIcon;
  269. FTrayIcon = NULL;
  270. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  271. delete FEditorManager;
  272. ForceCloseLocalEditors();
  273. delete FLocalEditors;
  274. HideFileFindDialog();
  275. if (FDelayedDeletionTimer)
  276. {
  277. DoDelayedDeletion(NULL);
  278. SAFE_DESTROY(FDelayedDeletionTimer);
  279. }
  280. SAFE_DESTROY(FDelayedDeletionList);
  281. // sometimes we do not get DDEnd so the list is not released
  282. SAFE_DESTROY(FDDFileList);
  283. DebugAssert(FSynchronizeController == NULL);
  284. CloseHandle(FDDExtMutex);
  285. FDDExtMutex = NULL;
  286. FreeLibrary(FOle32Library);
  287. FOle32Library = NULL;
  288. FDragMoveCursor = NULL;
  289. DebugAssert(!FErrorList);
  290. if (FEverShown)
  291. {
  292. // when window is never shown (like when running command-line operation),
  293. // particularly window site is not restored correctly (BoundsRect value set
  294. // in RestoreForm gets lost during handle allocation), so we do not want
  295. // it to be stored
  296. StoreParams();
  297. }
  298. Terminal = NULL;
  299. Queue = NULL;
  300. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  301. NonVisualDataModule->ScpExplorer = NULL;
  302. delete FQueueController;
  303. FQueueController = NULL;
  304. delete FQueueStatusSection;
  305. FQueueStatusSection = NULL;
  306. delete FQueueStatus;
  307. FQueueStatus = NULL;
  308. delete FUserActionTimer;
  309. FUserActionTimer = NULL;
  310. delete FNoteTimer;
  311. delete FNotes;
  312. delete FNoteData;
  313. SAFE_DESTROY(FDocks);
  314. SessionsPageControl->Images = NULL;
  315. // only after clearing Terminal (after DoTerminalListChanged => ... => AddSessionColor is called)
  316. SAFE_DESTROY(FSessionColors);
  317. SAFE_DESTROY(FSessionsDragDropFilesEx);
  318. SAFE_DESTROY(FHistoryMenu[0][0]);
  319. SAFE_DESTROY(FHistoryMenu[0][1]);
  320. SAFE_DESTROY(FHistoryMenu[1][0]);
  321. SAFE_DESTROY(FHistoryMenu[1][1]);
  322. if (FHiddenWindow != NULL)
  323. {
  324. DestroyWindow(FHiddenWindow);
  325. FHiddenWindow = NULL;
  326. }
  327. }
  328. //---------------------------------------------------------------------------
  329. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  330. {
  331. std::unique_ptr<TSessionData> Data;
  332. if (!Session.IsEmpty())
  333. {
  334. bool DefaultsOnly;
  335. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  336. }
  337. TTerminalManager * Manager = TTerminalManager::Instance();
  338. for (int Index = 0; Index < Manager->Count; Index++)
  339. {
  340. TTerminal * Terminal = Manager->Terminals[Index];
  341. if (Session.IsEmpty() ||
  342. Terminal->SessionData->IsSameSite(Data.get()))
  343. {
  344. if (Path.IsEmpty())
  345. {
  346. Terminal->ClearCaches();
  347. }
  348. else
  349. {
  350. Terminal->DirectoryModified(Path, true);
  351. }
  352. }
  353. }
  354. // We should flag a pending refresh for the background terminals or busy foreground terminals
  355. if ((Terminal != NULL) && Terminal->Active &&
  356. CanCommandLineFromAnotherInstance() &&
  357. (Session.IsEmpty() || Terminal->SessionData->IsSameSite(Data.get())) &&
  358. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  359. {
  360. Terminal->ReloadDirectory();
  361. }
  362. }
  363. //---------------------------------------------------------------------------
  364. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  365. {
  366. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  367. size_t MessageSize = sizeof(TCopyDataMessage);
  368. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  369. if (Result)
  370. {
  371. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  372. Result = (Message.Version == TCopyDataMessage::Version1);
  373. if (Result)
  374. {
  375. switch (Message.Command)
  376. {
  377. case TCopyDataMessage::CommandCanCommandLine:
  378. Result = CanCommandLineFromAnotherInstance();
  379. break;
  380. case TCopyDataMessage::CommandCommandLine:
  381. {
  382. UnicodeString CommandLine(Message.CommandLine);
  383. Result = CommandLineFromAnotherInstance(CommandLine);
  384. }
  385. break;
  386. case TCopyDataMessage::RefreshPanel:
  387. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  388. break;
  389. case TCopyDataMessage::MainWindowCheck:
  390. Result = true;
  391. break;
  392. default:
  393. Result = false;
  394. break;
  395. }
  396. }
  397. }
  398. Message.Result = Result ? 1 : 0;
  399. }
  400. //---------------------------------------------------------------------------
  401. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  402. {
  403. WNDCLASS WindowClass = {0};
  404. WindowClass.lpfnWndProc = DefWindowProc;
  405. WindowClass.hInstance = HInstance;
  406. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  407. FHiddenWindow = NULL;
  408. if (RegisterClass(&WindowClass))
  409. {
  410. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  411. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  412. }
  413. }
  414. //---------------------------------------------------------------------------
  415. bool __fastcall TCustomScpExplorerForm::CanConsole()
  416. {
  417. return
  418. (Terminal != NULL) &&
  419. Terminal->Active &&
  420. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  421. }
  422. //---------------------------------------------------------------------------
  423. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  424. {
  425. bool Result = Visible && !NonVisualDataModule->Busy;
  426. return Result;
  427. }
  428. //---------------------------------------------------------------------------
  429. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  430. const UnicodeString & CommandLine)
  431. {
  432. TProgramParams Params(CommandLine);
  433. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  434. if (Result)
  435. {
  436. NonVisualDataModule->StartBusy();
  437. try
  438. {
  439. // this action is initiated from another process,
  440. // so it's likely that our window is not visible,
  441. // and user won't see what is going on
  442. Application->BringToFront();
  443. // reload sessions as we may be asked to open a session
  444. // just stored by another instance
  445. StoredSessions->Reload();
  446. UnicodeString SessionName = Params.Param[1];
  447. std::unique_ptr<TObjectList> DataList(new TObjectList());
  448. UnicodeString DownloadFile; // unused
  449. try
  450. {
  451. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this);
  452. }
  453. catch (EAbort &)
  454. {
  455. // Happens when opening session in PuTTY and in other situations,
  456. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  457. // to process the command-line on its own (or to pass it to yet another instance)
  458. }
  459. if (DataList->Count > 0)
  460. {
  461. TTerminalManager * Manager = TTerminalManager::Instance();
  462. Manager->ActiveTerminal = Manager->NewTerminals(DataList.get());
  463. }
  464. }
  465. __finally
  466. {
  467. NonVisualDataModule->EndBusy();
  468. }
  469. }
  470. return Result;
  471. }
  472. //---------------------------------------------------------------------------
  473. void __fastcall TCustomScpExplorerForm::SetTerminal(TTerminal * value)
  474. {
  475. if (FTerminal != value)
  476. {
  477. TerminalChanging();
  478. DoSetTerminal(value, false);
  479. }
  480. }
  481. //---------------------------------------------------------------------------
  482. void __fastcall TCustomScpExplorerForm::DoSetTerminal(TTerminal * value, bool Replace)
  483. {
  484. FTerminal = value;
  485. bool PrevAllowTransferPresetAutoSelect = FAllowTransferPresetAutoSelect;
  486. FAllowTransferPresetAutoSelect = false;
  487. try
  488. {
  489. TerminalChanged(Replace);
  490. }
  491. __finally
  492. {
  493. FAllowTransferPresetAutoSelect = PrevAllowTransferPresetAutoSelect;
  494. }
  495. if (Terminal != NULL)
  496. {
  497. TransferPresetAutoSelect();
  498. }
  499. }
  500. //---------------------------------------------------------------------------
  501. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TTerminal * value)
  502. {
  503. DoSetTerminal(value, true);
  504. }
  505. //---------------------------------------------------------------------------
  506. void __fastcall TCustomScpExplorerForm::TerminalChanging()
  507. {
  508. if (FTerminal != NULL)
  509. {
  510. UpdateTerminal(Terminal);
  511. }
  512. }
  513. //---------------------------------------------------------------------------
  514. void __fastcall TCustomScpExplorerForm::TerminalChanged(bool Replaced)
  515. {
  516. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  517. if (ManagedTerminal != NULL)
  518. {
  519. UpdateSessionColor((TColor)ManagedTerminal->StateData->Color);
  520. }
  521. DoTerminalListChanged();
  522. DebugAssert(!IsLocalBrowserMode()); // TODO
  523. if (Replaced)
  524. {
  525. RemoteDirView->ReplaceTerminal(Terminal);
  526. }
  527. else
  528. {
  529. RemoteDirView->Terminal = Terminal;
  530. }
  531. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  532. if (Terminal != NULL)
  533. {
  534. if (Terminal->Active)
  535. {
  536. Terminal->RefreshDirectory();
  537. }
  538. DebugAssert(ManagedTerminal == Terminal);
  539. if (WinConfiguration->PreservePanelState)
  540. {
  541. if (ManagedTerminal->RemoteExplorerState != NULL)
  542. {
  543. DirView(osRemote)->RestoreState(ManagedTerminal->RemoteExplorerState);
  544. }
  545. else
  546. {
  547. DirView(osRemote)->ClearState();
  548. }
  549. }
  550. if (!Replaced)
  551. {
  552. InitStatusBar();
  553. }
  554. }
  555. UpdateTransferList();
  556. // Update panels Enable state before refreshing the labels
  557. UpdateControls();
  558. }
  559. //---------------------------------------------------------------------------
  560. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  561. {
  562. if (Queue != value)
  563. {
  564. if (FQueue != NULL)
  565. {
  566. FQueue->OnListUpdate = NULL;
  567. FQueue->OnQueueItemUpdate = NULL;
  568. }
  569. FQueue = value;
  570. if (FQueue != NULL)
  571. {
  572. DebugAssert(FQueue->OnListUpdate == NULL);
  573. FQueue->OnListUpdate = QueueListUpdate;
  574. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  575. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  576. }
  577. QueueChanged();
  578. }
  579. }
  580. //---------------------------------------------------------------------------
  581. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  582. TListItem * Item)
  583. {
  584. if (FQueueActedItem == Item)
  585. {
  586. FQueueActedItem = NULL;
  587. if ((QueueView3->PopupMenu != NULL) &&
  588. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  589. {
  590. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  591. ReleaseCapture();
  592. }
  593. }
  594. if (Item->Data == FPendingQueueActionItem)
  595. {
  596. FPendingQueueActionItem = NULL;
  597. }
  598. }
  599. //---------------------------------------------------------------------------
  600. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  601. {
  602. {
  603. TGuard Guard(FQueueStatusSection);
  604. FQueueStatusInvalidated = false;
  605. if (FQueue != NULL)
  606. {
  607. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  608. }
  609. }
  610. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  611. {
  612. FMaxQueueLength = FQueueStatus->Count;
  613. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  614. }
  615. FQueueController->UpdateQueueStatus(FQueueStatus);
  616. SetQueueProgress();
  617. UpdateQueueView();
  618. bool IsEmpty = (FQueueStatus == NULL) || (FQueueStatus->Count == 0);
  619. if (IsEmpty && (Terminal != NULL))
  620. {
  621. TOnceDoneOperation OnceDoneOperation =
  622. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  623. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  624. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  625. {
  626. FQueue->Enabled = false;
  627. }
  628. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  629. {
  630. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  631. }
  632. }
  633. }
  634. //---------------------------------------------------------------------------
  635. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  636. {
  637. UnicodeString Result;
  638. if (FQueueStatus != NULL)
  639. {
  640. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  641. {
  642. TFileOperationProgressType * ProgressData =
  643. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  644. if ((ProgressData != NULL) && ProgressData->InProgress)
  645. {
  646. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  647. }
  648. }
  649. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  650. {
  651. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  652. }
  653. }
  654. return Result;
  655. }
  656. //---------------------------------------------------------------------------
  657. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  658. {
  659. ComponentVisible[fcQueueView] =
  660. (WinConfiguration->QueueView.Show == qvShow) ||
  661. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  662. (FQueueStatus != NULL) && (FQueueStatus->Count > 0));
  663. }
  664. //---------------------------------------------------------------------------
  665. void __fastcall TCustomScpExplorerForm::QueueChanged()
  666. {
  667. if (FQueueStatus != NULL)
  668. {
  669. delete FQueueStatus;
  670. FQueueStatus = NULL;
  671. }
  672. UpdateQueueStatus(true);
  673. }
  674. //---------------------------------------------------------------------------
  675. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  676. {
  677. if (FQueue == Queue)
  678. {
  679. FQueueStatusInvalidated = true;
  680. }
  681. }
  682. //---------------------------------------------------------------------------
  683. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  684. TQueueItem * Item)
  685. {
  686. if (FQueue == Queue)
  687. {
  688. TGuard Guard(FQueueStatusSection);
  689. // this may be running in parallel with QueueChanged
  690. if (FQueueStatus != NULL)
  691. {
  692. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  693. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  694. {
  695. FRefreshLocalDirectory = (QueueItem == NULL) ||
  696. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  697. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  698. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  699. }
  700. if (QueueItem != NULL)
  701. {
  702. QueueItem->UserData = (void*)true;
  703. FQueueItemInvalidated = true;
  704. }
  705. }
  706. }
  707. }
  708. //---------------------------------------------------------------------------
  709. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  710. {
  711. // during standalone editing, we have no way to see/control queue,
  712. // so we have to always popup prompts automatically
  713. return FStandaloneEditing || GUIConfiguration->QueueAutoPopup;
  714. }
  715. //---------------------------------------------------------------------------
  716. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  717. {
  718. if (FQueueStatus != NULL)
  719. {
  720. bool QueueAutoPopup = IsQueueAutoPopup();
  721. bool NeedRefresh = FQueueController->NeedRefresh();
  722. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  723. FQueueItemInvalidated = false;
  724. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  725. bool Updated = false;
  726. TQueueItemProxy * QueueItem;
  727. bool WasUserAction;
  728. for (int Index = 0; Index < Limit; Index++)
  729. {
  730. bool Update = false;
  731. QueueItem = FQueueStatus->Items[Index];
  732. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  733. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  734. (FPendingQueueActionItem == NULL))
  735. {
  736. FPendingQueueActionItem = QueueItem;
  737. FUserActionTimer->Enabled = true;
  738. }
  739. if ((bool)QueueItem->UserData)
  740. {
  741. QueueItem->UserData = (void*)false;
  742. QueueItem->Update();
  743. Updated = true;
  744. Update = true;
  745. }
  746. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  747. {
  748. Update = true;
  749. }
  750. if (Update)
  751. {
  752. FQueueController->RefreshQueueItem(QueueItem);
  753. }
  754. }
  755. if (Updated)
  756. {
  757. NonVisualDataModule->UpdateNonVisibleActions();
  758. SetQueueProgress();
  759. }
  760. }
  761. }
  762. //---------------------------------------------------------------------------
  763. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  764. {
  765. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  766. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  767. }
  768. //---------------------------------------------------------------------------
  769. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  770. {
  771. if (ProgressData->Operation != foCalculateSize)
  772. {
  773. int OverallProgress;
  774. // FProgressForm is null when this is called from SetQueueProgress
  775. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  776. {
  777. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  778. }
  779. else
  780. {
  781. OverallProgress = ProgressData->OverallProgress();
  782. }
  783. // implies TBPF_NORMAL
  784. FTaskbarList->SetProgressValue(GetMainForm()->Handle, OverallProgress, 100);
  785. }
  786. else
  787. {
  788. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  789. }
  790. }
  791. //---------------------------------------------------------------------------
  792. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  793. {
  794. TTerminalManager::Instance()->QueueStatusUpdated();
  795. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  796. {
  797. if ((FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0))
  798. {
  799. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  800. {
  801. TFileOperationProgressType * ProgressData = NULL;
  802. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  803. {
  804. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  805. }
  806. if ((ProgressData != NULL) &&
  807. ProgressData->InProgress)
  808. {
  809. SetTaskbarListProgressValue(ProgressData);
  810. }
  811. else
  812. {
  813. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  814. }
  815. }
  816. else
  817. {
  818. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  819. }
  820. }
  821. else
  822. {
  823. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  824. }
  825. }
  826. UpdateQueueLabel();
  827. }
  828. //---------------------------------------------------------------------------
  829. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  830. {
  831. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  832. if (FQueueStatus != NULL)
  833. {
  834. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  835. if (ActiveAndPendingPrimaryCount > 0)
  836. {
  837. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  838. }
  839. }
  840. QueueLabel->Caption = Caption;
  841. }
  842. //---------------------------------------------------------------------------
  843. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  844. {
  845. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  846. static_cast<TComponent*>(GetComponent(fcTransferList)));
  847. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  848. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  849. TransferList->Strings->BeginUpdate();
  850. try
  851. {
  852. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  853. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  854. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  855. if (FTransferDropDownHint.IsEmpty())
  856. {
  857. FTransferDropDownHint = TransferDropDown->Hint;
  858. }
  859. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  860. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  861. TransferDropDown->Text = StripHotkey(Name);
  862. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  863. (FTransferDropDownHint, StripHotkey(Name),
  864. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  865. FLAGMASK(((Terminal != NULL) && Terminal->Active), Terminal->UsableCopyParamAttrs(0).General))));
  866. // update the label, otherwise when it is updated only on the first draw
  867. // of the list, it is drawn "bold" for some reason
  868. FTransferListHoverIndex = TransferList->ItemIndex;
  869. UpdateTransferLabel();
  870. }
  871. __finally
  872. {
  873. TransferList->Strings->EndUpdate();
  874. }
  875. }
  876. //---------------------------------------------------------------------------
  877. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  878. {
  879. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  880. DebugAssert(Toolbar != NULL);
  881. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  882. }
  883. //---------------------------------------------------------------------------
  884. void __fastcall TCustomScpExplorerForm::UpdateActions()
  885. {
  886. TForm::UpdateActions();
  887. if (ComponentVisible[fcCustomCommandsBand])
  888. {
  889. UpdateCustomCommandsToolbar();
  890. }
  891. }
  892. //---------------------------------------------------------------------------
  893. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  894. {
  895. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  896. }
  897. //---------------------------------------------------------------------------
  898. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  899. {
  900. Color = GetBtnFaceColor();
  901. DebugAssert(Configuration && RemoteDirView);
  902. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  903. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  904. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  905. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  906. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  907. if (RemoteDirView->RowSelect != WinConfiguration->FullRowSelect)
  908. {
  909. RemoteDirView->RowSelect = WinConfiguration->FullRowSelect;
  910. // selection is not redrawn automatically when RowSelect changes
  911. RemoteDirView->Invalidate();
  912. }
  913. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  914. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  915. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  916. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  917. UpdateSessionsPageControlHeight();
  918. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  919. UpdateToolbarDisplayMode();
  920. UpdateTransferList();
  921. if (Terminal != NULL)
  922. {
  923. TransferPresetAutoSelect();
  924. }
  925. UpdateQueueView();
  926. UpdateControls();
  927. // this can be called even before constuctor finishes.
  928. if (FEditorManager != NULL)
  929. {
  930. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  931. }
  932. // this can be called even before constuctor finishes.
  933. if (FLocalEditors != NULL)
  934. {
  935. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  936. {
  937. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  938. }
  939. }
  940. if (ComponentVisible[fcCustomCommandsBand])
  941. {
  942. UpdateCustomCommandsToolbar();
  943. }
  944. // show only when keeping queue items forever,
  945. // otherwise, its enough to have in in the context menu
  946. QueueDeleteAllDoneQueueToolbarItem->Visible =
  947. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  948. if (FFileColorsCurrent != WinConfiguration->FileColors)
  949. {
  950. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  951. FFileColorsCurrent = WinConfiguration->FileColors;
  952. FileColorsChanged();
  953. }
  954. }
  955. //---------------------------------------------------------------------------
  956. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  957. {
  958. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  959. DirView->Invalidate();
  960. }
  961. //---------------------------------------------------------------------------
  962. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  963. {
  964. DoFileColorsChanged(RemoteDirView);
  965. }
  966. //---------------------------------------------------------------------------
  967. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  968. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  969. void * /*Arg*/)
  970. {
  971. if (Token != NULL)
  972. {
  973. TForm * Editor = dynamic_cast<TForm*>(Token);
  974. DebugAssert(Editor != NULL);
  975. ReconfigureEditorForm(Editor);
  976. }
  977. }
  978. //---------------------------------------------------------------------------
  979. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  980. {
  981. WinConfiguration->DDTransferConfirmation = asOn;
  982. }
  983. //---------------------------------------------------------------------------
  984. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  985. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  986. {
  987. // noop
  988. }
  989. //---------------------------------------------------------------------------
  990. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  991. TTransferDirection Direction, TTransferType Type, bool Temp,
  992. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  993. bool Confirm, bool DragDrop, int Options)
  994. {
  995. bool Result = true;
  996. DebugAssert(Terminal && Terminal->Active);
  997. // these parameters are known in advance
  998. int Params =
  999. FLAGMASK(Type == ttMove, cpDelete);
  1000. bool ToTemp = (Temp && (Direction == tdToLocal));
  1001. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1002. {
  1003. bool DisableNewerOnly =
  1004. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1005. ToTemp;
  1006. Options |=
  1007. FLAGMASK(ToTemp, coTemp) |
  1008. FLAGMASK(!Terminal->IsCapable[fsBackgroundTransfers], coDisableQueue) |
  1009. coDoNotShowAgain;
  1010. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1011. int CopyParamAttrs = (Direction == tdToRemote ?
  1012. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1013. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1014. int OutputOptions =
  1015. FLAGMASK(DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto),
  1016. cooDoNotShowAgain);
  1017. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1018. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1019. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1020. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions);
  1021. if (Result)
  1022. {
  1023. if (FLAGSET(OutputOptions, cooDoNotShowAgain))
  1024. {
  1025. if (DragDrop)
  1026. {
  1027. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1028. {
  1029. PopupTrayBalloon(NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation,
  1030. NULL, 0, EnableDDTransferConfirmation, NULL);
  1031. }
  1032. WinConfiguration->DDTransferConfirmation = asOff;
  1033. }
  1034. else
  1035. {
  1036. WinConfiguration->ConfirmTransferring = false;
  1037. }
  1038. }
  1039. else
  1040. {
  1041. // User explicitly unchecked "do not show again",
  1042. // so show him the dialog the next time
  1043. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1044. {
  1045. WinConfiguration->DDTransferConfirmation = asOn;
  1046. }
  1047. }
  1048. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1049. }
  1050. }
  1051. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fsBackgroundTransfers])
  1052. {
  1053. Configuration->Usage->Inc(L"TransfersOnBackground");
  1054. // these parameter are known only after transfer dialog
  1055. Params |=
  1056. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1057. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1058. Result = false;
  1059. ClearTransferSourceSelection(Direction);
  1060. }
  1061. return Result;
  1062. }
  1063. //---------------------------------------------------------------------------
  1064. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1065. {
  1066. if (FOnFileOperationFinished != NULL)
  1067. {
  1068. FOnFileOperationFinished(UnicodeString(), true);
  1069. }
  1070. else
  1071. {
  1072. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1073. if (HasDirView[Side])
  1074. {
  1075. DirView(Side)->SelectAll(smNone);
  1076. }
  1077. }
  1078. }
  1079. //---------------------------------------------------------------------------
  1080. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1081. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1082. const UnicodeString TargetDirectory, const TGUICopyParamType & CopyParam,
  1083. int Params)
  1084. {
  1085. DebugAssert(Queue != NULL);
  1086. bool SingleFile = false;
  1087. if (FileList->Count == 1)
  1088. {
  1089. if (Direction == tdToRemote)
  1090. {
  1091. UnicodeString FileName = FileList->Strings[0];
  1092. SingleFile = FileExists(ApiPath(FileName));
  1093. }
  1094. else
  1095. {
  1096. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1097. SingleFile = !File->IsDirectory;
  1098. }
  1099. }
  1100. TQueueItem * QueueItem;
  1101. if (Direction == tdToRemote)
  1102. {
  1103. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1104. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1105. }
  1106. else
  1107. {
  1108. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1109. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1110. }
  1111. AddQueueItem(Queue, QueueItem, Terminal);
  1112. }
  1113. //---------------------------------------------------------------------------
  1114. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TTerminal * Terminal)
  1115. {
  1116. if (Queue->IsEmpty)
  1117. {
  1118. TManagedTerminal * ManagedTerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  1119. ManagedTerminal->QueueOperationStart = Now();
  1120. }
  1121. Queue->AddItem(QueueItem);
  1122. }
  1123. //---------------------------------------------------------------------------
  1124. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1125. {
  1126. }
  1127. //---------------------------------------------------------------------------
  1128. void __fastcall TCustomScpExplorerForm::InitControls()
  1129. {
  1130. DebugAssert(FDocks != NULL);
  1131. for (int Index = 0; Index < ComponentCount; Index++)
  1132. {
  1133. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1134. if ((Dock != NULL) && (Dock->Tag == 0))
  1135. {
  1136. FDocks->Add(Dock);
  1137. }
  1138. }
  1139. CollectItemsWithTextDisplayMode(this);
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1143. {
  1144. ConfigurationChanged();
  1145. QueuePanel->Height =
  1146. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1147. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1148. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1149. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1150. }
  1151. //---------------------------------------------------------------------------
  1152. void __fastcall TCustomScpExplorerForm::StoreParams()
  1153. {
  1154. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1155. WinConfiguration->QueueView.HeightPixelsPerInch = GetControlPixelsPerInch(this);
  1156. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1157. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1158. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1159. }
  1160. //---------------------------------------------------------------------------
  1161. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1162. {
  1163. if (!FFormRestored)
  1164. {
  1165. FFormRestored = true;
  1166. RestoreFormParams();
  1167. }
  1168. TForm::CreateParams(Params);
  1169. }
  1170. //---------------------------------------------------------------------------
  1171. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1172. {
  1173. DebugAssert(FDocks != NULL);
  1174. for (int Index = 0; Index < FDocks->Count; Index++)
  1175. {
  1176. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1177. }
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1181. {
  1182. SetDockAllowDrag(true);
  1183. while (!ButtonsStr.IsEmpty())
  1184. {
  1185. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1186. UnicodeString Name = CutToChar(S, L'=', true);
  1187. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1188. {
  1189. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1190. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1191. {
  1192. while (!S.IsEmpty())
  1193. {
  1194. UnicodeString S2 = CutToChar(S, L',', true);
  1195. UnicodeString Name = CutToChar(S2, L':', true);
  1196. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1197. {
  1198. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1199. if (SameText(GetToolbarItemName(Item), Name))
  1200. {
  1201. // forward compatibility
  1202. UnicodeString S3 = CutToChar(S2, L':', true);
  1203. bool Visible = StrToIntDef(S3, 0);
  1204. Item->Visible = Visible;
  1205. }
  1206. }
  1207. }
  1208. }
  1209. }
  1210. }
  1211. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1212. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1213. }
  1214. //---------------------------------------------------------------------------
  1215. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1216. {
  1217. UnicodeString Result;
  1218. SetDockAllowDrag(true);
  1219. Result = ::GetToolbarsLayoutStr(this);
  1220. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1221. return Result;
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1225. {
  1226. UnicodeString Result;
  1227. if (Item->Action != NULL)
  1228. {
  1229. Result = Item->Action->Name;
  1230. Result = RemoveSuffix(Result, L"Action");
  1231. }
  1232. else
  1233. {
  1234. Result = Item->Name;
  1235. Result = RemoveSuffix(Result, L"SubmenuItem");
  1236. Result = RemoveSuffix(Result, L"Item");
  1237. }
  1238. return Result;
  1239. }
  1240. //---------------------------------------------------------------------------
  1241. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1242. {
  1243. UnicodeString Result;
  1244. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1245. {
  1246. UnicodeString ToolbarStr;
  1247. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1248. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1249. {
  1250. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1251. {
  1252. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1253. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1254. // Once we introduce any buttons that aer hidden by default, we would have to remember their initial state
  1255. // and save the changes here only.
  1256. if (!Item->Visible)
  1257. {
  1258. UnicodeString Name = GetToolbarItemName(Item);
  1259. DebugAssert(Name.Pos(L"TBX") == 0);
  1260. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1261. }
  1262. }
  1263. }
  1264. if (!ToolbarStr.IsEmpty())
  1265. {
  1266. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1267. }
  1268. }
  1269. return Result;
  1270. }
  1271. //---------------------------------------------------------------------------
  1272. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1273. {
  1274. DebugAssert(FProgressForm == NULL);
  1275. bool AllowSkip = (Terminal != NULL) ? Terminal->IsCapable[fsSkipTransfer] : false;
  1276. FProgressForm = new TProgressForm(Application, (FTransferResumeList != NULL), AllowSkip, SynchronizeProgress);
  1277. FProgressForm->DeleteLocalToRecycleBin =
  1278. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1279. FProgressForm->DeleteRemoteToRecycleBin =
  1280. (Terminal != NULL) &&
  1281. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1282. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1283. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1284. LockWindow();
  1285. if (FTaskbarList != NULL)
  1286. {
  1287. // Actually, do not know what hides the progress once the operation finishes
  1288. SetTaskbarListProgressState(TBPF_NORMAL);
  1289. }
  1290. }
  1291. //---------------------------------------------------------------------------
  1292. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1293. {
  1294. UnlockWindow();
  1295. SAFE_DESTROY(FProgressForm);
  1296. SetQueueProgress();
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1300. TFileOperationProgressType & ProgressData)
  1301. {
  1302. // Download to temporary local directory
  1303. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1304. {
  1305. bool Continue = true;
  1306. FPendingTempSpaceWarn = false;
  1307. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1308. if (!Continue)
  1309. {
  1310. Abort();
  1311. }
  1312. }
  1313. // operation is being executed and we still didn't show up progress form
  1314. if (ProgressData.InProgress && !FProgressForm)
  1315. {
  1316. CreateProgressForm(NULL);
  1317. // When main window is hidden, synchronisation form does not exist (we do not get here during synchronization - only comparing),
  1318. // we suppose "/upload" or URL download mode
  1319. if (!Visible && (ProgressData.Operation != foCalculateSize) &&
  1320. (ProgressData.Operation != foCalculateChecksum) &&
  1321. // Hack to prevent renames from DoSynchronizeMove (synchronize checklist) closing the connection
  1322. (ProgressData.Operation != foRemoteMove) &&
  1323. (FSynchronizeProgressForm == NULL) &&
  1324. !FStandaloneEditing)
  1325. {
  1326. FProgressForm->OnceDoneOperation = odoDisconnect;
  1327. }
  1328. }
  1329. // operation is finished (or terminated), so we hide progress form
  1330. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1331. {
  1332. DestroyProgressForm();
  1333. if (ProgressData.Operation == foCalculateSize)
  1334. {
  1335. // When calculating size before transfer, the abort caused by
  1336. // cancel flag set due to "MoveToQueue" below,
  1337. // is not propagated back to us in ExecuteFileOperation,
  1338. // as it is silently swallowed.
  1339. // So we explicitly (re)throw it here.
  1340. if (FMoveToQueue)
  1341. {
  1342. Abort();
  1343. }
  1344. }
  1345. else
  1346. {
  1347. if ((ProgressData.Cancel == csContinue) &&
  1348. !FAutoOperation)
  1349. {
  1350. OperationComplete(ProgressData.StartTime);
  1351. }
  1352. }
  1353. }
  1354. if (FProgressForm &&
  1355. // Can happen only during synchronization, when ending one of the operations
  1356. ProgressData.InProgress)
  1357. {
  1358. FProgressForm->SetProgressData(ProgressData);
  1359. if (FTaskbarList != NULL)
  1360. {
  1361. DebugAssert(ProgressData.InProgress);
  1362. SetTaskbarListProgressValue(&ProgressData);
  1363. }
  1364. if (FProgressForm->Cancel > csContinue)
  1365. {
  1366. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1367. if (FProgressForm->Cancel == csCancelFile)
  1368. {
  1369. FProgressForm->ClearCancel();
  1370. }
  1371. // cancel cancels even the move
  1372. FMoveToQueue = false;
  1373. }
  1374. else if (FProgressForm->MoveToQueue)
  1375. {
  1376. FMoveToQueue = true;
  1377. ProgressData.SetCancelAtLeast(csCancel);
  1378. }
  1379. if ((FTransferResumeList != NULL) &&
  1380. ProgressData.InProgress &&
  1381. ((ProgressData.Operation == foCopy) || (ProgressData.Operation == foMove)) &&
  1382. !ProgressData.FullFileName.IsEmpty())
  1383. {
  1384. if ((FTransferResumeList->Count == 0) ||
  1385. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1386. {
  1387. // note that we do not recognize directories from files here
  1388. FTransferResumeList->Add(ProgressData.FullFileName);
  1389. }
  1390. }
  1391. }
  1392. }
  1393. //---------------------------------------------------------------------------
  1394. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1395. const TDateTime & StartTime)
  1396. {
  1397. if (GUIConfiguration->BeepOnFinish &&
  1398. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1399. {
  1400. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1401. DWORD Sound;
  1402. if (!ExtractFileExt(BeepSound).IsEmpty())
  1403. {
  1404. Sound = SND_FILENAME;
  1405. }
  1406. else
  1407. {
  1408. Sound = SND_ALIAS;
  1409. }
  1410. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1411. }
  1412. }
  1413. //---------------------------------------------------------------------------
  1414. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1415. TFileOperationProgressType & ProgressData)
  1416. {
  1417. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1418. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1419. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1420. FileOperationProgress(ProgressData);
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1424. {
  1425. UnicodeString Result;
  1426. if (FProgressForm != NULL)
  1427. {
  1428. Result = FProgressForm->ProgressStr();
  1429. }
  1430. return Result;
  1431. }
  1432. //---------------------------------------------------------------------------
  1433. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1434. bool DragDrop)
  1435. {
  1436. return (!DragDrop && (DropSourceControl == NULL)) ||
  1437. (DropSourceControl == DirView(osOther));
  1438. }
  1439. //---------------------------------------------------------------------------
  1440. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1441. TFileOperation Operation, TOperationSide Side,
  1442. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1443. TOnceDoneOperation & OnceDoneOperation)
  1444. {
  1445. if (!FAutoOperation)
  1446. {
  1447. // no selection on "/upload", form servers only as event handler
  1448. // (it is not displayed)
  1449. if (PanelOperation(Side, FDragDropOperation) &&
  1450. Visible && (Operation != foCalculateSize) &&
  1451. (Operation != foGetProperties) && (Operation != foCalculateChecksum))
  1452. {
  1453. if (FOnFileOperationFinished != NULL)
  1454. {
  1455. FOnFileOperationFinished(FileName, Success);
  1456. }
  1457. else
  1458. {
  1459. TCustomDirView * DView = DirView(Side);
  1460. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1461. TListItem *Item = DView->FindFileItem(FileNameOnly);
  1462. // this can happen when local drive is unplugged in the middle of the operation
  1463. if (Item != NULL)
  1464. {
  1465. if (Success) Item->Selected = false;
  1466. DView->MakeProgressVisible(Item);
  1467. }
  1468. }
  1469. }
  1470. if ((Operation == foCopy) || (Operation == foMove))
  1471. {
  1472. DebugAssert(!IsLocalBrowserMode()); // TODO
  1473. if (Side == osLocal)
  1474. {
  1475. Configuration->Usage->Inc(L"UploadedFiles");
  1476. }
  1477. else
  1478. {
  1479. Configuration->Usage->Inc(L"DownloadedFiles");
  1480. }
  1481. }
  1482. }
  1483. if (Success && (FSynchronizeController != NULL))
  1484. {
  1485. DebugAssert(!IsSideLocalBrowser(Side));
  1486. if (Operation == foCopy)
  1487. {
  1488. DebugAssert(Side == osLocal);
  1489. FSynchronizeController->LogOperation(soUpload, FileName);
  1490. }
  1491. else if (Operation == foDelete)
  1492. {
  1493. DebugAssert(Side == osRemote);
  1494. FSynchronizeController->LogOperation(soDelete, FileName);
  1495. }
  1496. }
  1497. if (FProgressForm)
  1498. {
  1499. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1500. }
  1501. }
  1502. //---------------------------------------------------------------------------
  1503. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1504. TFileOperation Operation, TOperationSide Side,
  1505. bool Temp, const UnicodeString & FileName, Boolean Success,
  1506. TOnceDoneOperation & OnceDoneOperation)
  1507. {
  1508. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1509. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1510. OnceDoneOperation);
  1511. }
  1512. //---------------------------------------------------------------------------
  1513. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1514. {
  1515. return false;
  1516. }
  1517. //---------------------------------------------------------------------------
  1518. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1519. {
  1520. return false;
  1521. }
  1522. //---------------------------------------------------------------------------
  1523. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1524. {
  1525. return NULL;
  1526. }
  1527. //---------------------------------------------------------------------------
  1528. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1529. {
  1530. DebugAssert(GetSide(Side) == osRemote);
  1531. DebugUsedParam(Side);
  1532. return RemoteDirView;
  1533. }
  1534. //---------------------------------------------------------------------------
  1535. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1536. {
  1537. DebugAssert(GetSide(Side) == osRemote);
  1538. DebugUsedParam(Side);
  1539. return RemoteDriveView;
  1540. }
  1541. //---------------------------------------------------------------------------
  1542. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1543. {
  1544. DebugAssert(GetSide(Side) == osRemote);
  1545. DebugUsedParam(Side);
  1546. return (Terminal != NULL);
  1547. }
  1548. //---------------------------------------------------------------------------
  1549. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1550. TOperationSide Side, int FilesOnly)
  1551. {
  1552. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1553. }
  1554. //---------------------------------------------------------------------------
  1555. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1556. TOperationSide Side, int FilesOnly)
  1557. {
  1558. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1559. }
  1560. //---------------------------------------------------------------------------
  1561. struct THistoryItemData
  1562. {
  1563. short int Side;
  1564. short int Index;
  1565. };
  1566. //---------------------------------------------------------------------------
  1567. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1568. {
  1569. DirView(Side)->HistoryGo(Index);
  1570. }
  1571. //---------------------------------------------------------------------------
  1572. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1573. {
  1574. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1575. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1576. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1577. }
  1578. //---------------------------------------------------------------------------
  1579. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1580. bool Back)
  1581. {
  1582. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1583. {
  1584. TCustomDirView * DView = DirView(Side);
  1585. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1586. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1587. if (ICount > 10)
  1588. {
  1589. ICount = 10;
  1590. }
  1591. Menu->Items->Clear();
  1592. THistoryItemData Data;
  1593. Data.Side = Side;
  1594. for (short int i = 1; i <= ICount; i++)
  1595. {
  1596. TTBCustomItem * Item = new TTBXItem(Menu);
  1597. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1598. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1599. Item->Hint = DView->HistoryPath[Data.Index];
  1600. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1601. Item->Tag = *reinterpret_cast<int*>(&Data);
  1602. Item->OnClick = HistoryItemClick;
  1603. Menu->Items->Add(Item);
  1604. }
  1605. }
  1606. }
  1607. //---------------------------------------------------------------------------
  1608. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1609. TOperationSide Side, bool Back)
  1610. {
  1611. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1612. {
  1613. // workaround
  1614. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1615. // operator new allocates memory in Pascal code, but calls inline
  1616. // contructor in C++, leading in problems, the function does
  1617. // both in Pascal code
  1618. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1619. UpdateHistoryMenu(Side, Back);
  1620. }
  1621. return FHistoryMenu[Side == osLocal][Back];
  1622. }
  1623. //---------------------------------------------------------------------------
  1624. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1625. TCustomDirView *Sender)
  1626. {
  1627. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1628. UpdateHistoryMenu(Side, true);
  1629. UpdateHistoryMenu(Side, false);
  1630. }
  1631. //---------------------------------------------------------------------------
  1632. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1633. {
  1634. // remote custom commands can be executed only if the server supports shell commands
  1635. // or have secondary shell
  1636. return (FTerminal != NULL) && (FTerminal->IsCapable[fcSecondaryShell] || FTerminal->IsCapable[fcShellAnyCommand]);
  1637. }
  1638. //---------------------------------------------------------------------------
  1639. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1640. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1641. {
  1642. int Result;
  1643. TFileCustomCommand RemoteCustomCommand;
  1644. TLocalCustomCommand LocalCustomCommand;
  1645. TFileCustomCommand * NonInteractiveCustomCommand =
  1646. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1647. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1648. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1649. if (FLAGCLEAR(Command.Params, ccLocal))
  1650. {
  1651. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1652. // custom command that does not operate with files can be executed anytime ...
  1653. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1654. {
  1655. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1656. {
  1657. // ... but do not show such command in remote file menu (TODO)
  1658. Result = AllowedState;
  1659. }
  1660. else
  1661. {
  1662. Result = -1;
  1663. }
  1664. }
  1665. else
  1666. {
  1667. if ((ListType == ccltAll) || (ListType == ccltFile))
  1668. {
  1669. Result = (!IsSideLocalBrowser(FCurrentSide) && DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1670. }
  1671. else
  1672. {
  1673. Result = -1;
  1674. }
  1675. }
  1676. }
  1677. else
  1678. {
  1679. // custom command that does not operate with files can be executed anytime
  1680. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1681. {
  1682. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1683. }
  1684. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1685. {
  1686. if ((ListType == ccltAll) || (ListType == ccltFile))
  1687. {
  1688. // special case is "diff"-style command that can be executed over any side,
  1689. // if we have both sides
  1690. Result =
  1691. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1692. // directly (instead of EnableSelectedOperation) to pass
  1693. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1694. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1695. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1696. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1697. }
  1698. else if (ListType == ccltBoth)
  1699. {
  1700. DebugAssert(!IsLocalBrowserMode());
  1701. Result = 1;
  1702. }
  1703. else
  1704. {
  1705. Result = -1;
  1706. }
  1707. }
  1708. else
  1709. {
  1710. if ((ListType == ccltAll) || (ListType == ccltFile))
  1711. {
  1712. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1713. }
  1714. else
  1715. {
  1716. Result = -1;
  1717. }
  1718. }
  1719. }
  1720. return Result;
  1721. }
  1722. //---------------------------------------------------------------------------
  1723. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1724. TStrings * FileList, const TCustomCommandType & ACommand,
  1725. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1726. {
  1727. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1728. {
  1729. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1730. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1731. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1732. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1733. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1734. bool Capture =
  1735. FLAGSET(ACommand.Params, ccShowResults) ||
  1736. FLAGSET(ACommand.Params, ccCopyResults) ||
  1737. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1738. TCaptureOutputEvent OutputEvent = NULL;
  1739. DebugAssert(FCapturedLog == NULL);
  1740. if (Capture)
  1741. {
  1742. FCapturedLog = new TStringList();
  1743. OutputEvent = TerminalCaptureLog;
  1744. }
  1745. try
  1746. {
  1747. if (!RemoteCustomCommand.IsFileCommand(Command))
  1748. {
  1749. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1750. OutputEvent);
  1751. }
  1752. else
  1753. {
  1754. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1755. }
  1756. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1757. {
  1758. if (FLAGSET(ACommand.Params, ccCopyResults))
  1759. {
  1760. CopyToClipboard(FCapturedLog);
  1761. }
  1762. if (FLAGSET(ACommand.Params, ccShowResults))
  1763. {
  1764. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1765. }
  1766. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1767. {
  1768. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1769. }
  1770. }
  1771. }
  1772. __finally
  1773. {
  1774. SAFE_DESTROY(FCapturedLog);
  1775. }
  1776. }
  1777. }
  1778. //---------------------------------------------------------------------------
  1779. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1780. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1781. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1782. {
  1783. DebugAssert(!IsLocalBrowserMode());
  1784. TStrings * LocalFileList = NULL;
  1785. TStrings * RemoteFileList = NULL;
  1786. TStrings * RemoteFileListFull = NULL;
  1787. try
  1788. {
  1789. if (LocalFileCommand)
  1790. {
  1791. if (ALocalFileList == NULL)
  1792. {
  1793. DebugAssert(HasDirView[osLocal]);
  1794. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1795. // directly (instead of EnableSelectedOperation) to pass
  1796. // false to FocusedFileOnlyWhenFocused
  1797. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  1798. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  1799. }
  1800. else
  1801. {
  1802. LocalFileList = ALocalFileList;
  1803. }
  1804. if (FileListCommand)
  1805. {
  1806. if (LocalFileList->Count != 1)
  1807. {
  1808. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  1809. }
  1810. }
  1811. else
  1812. {
  1813. if ((LocalFileList->Count != 1) &&
  1814. (FileList->Count != 1) &&
  1815. (LocalFileList->Count != FileList->Count))
  1816. {
  1817. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  1818. }
  1819. }
  1820. }
  1821. UnicodeString RootTempDir;
  1822. UnicodeString TempDir;
  1823. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  1824. if (!RemoteFiles)
  1825. {
  1826. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  1827. }
  1828. try
  1829. {
  1830. TDateTimes RemoteFileTimes;
  1831. if (RemoteFiles)
  1832. {
  1833. RemoteFileList = FileList;
  1834. }
  1835. else
  1836. {
  1837. RemoteFileList = new TStringList();
  1838. TMakeLocalFileListParams MakeFileListParam;
  1839. MakeFileListParam.FileList = RemoteFileList;
  1840. MakeFileListParam.FileTimes = &RemoteFileTimes;
  1841. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  1842. MakeFileListParam.Recursive =
  1843. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  1844. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  1845. if (!MakeFileListParam.Recursive)
  1846. {
  1847. RemoteFileTimes.clear();
  1848. RemoteFileListFull = new TStringList();
  1849. MakeFileListParam.FileList = RemoteFileListFull;
  1850. MakeFileListParam.Recursive = true;
  1851. MakeFileListParam.IncludeDirs = false;
  1852. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  1853. }
  1854. else
  1855. {
  1856. RemoteFileListFull = RemoteFileList;
  1857. }
  1858. }
  1859. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  1860. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  1861. if (!NonBlocking)
  1862. {
  1863. int Count;
  1864. if (FileListCommand)
  1865. {
  1866. Count = 1;
  1867. }
  1868. else if (LocalFileCommand)
  1869. {
  1870. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  1871. }
  1872. else
  1873. {
  1874. Count = RemoteFileList->Count;
  1875. }
  1876. Progress.Start(foCustomCommand, osRemote, Count);
  1877. DebugAssert(FProgressForm != NULL);
  1878. FProgressForm->ReadOnly = true;
  1879. }
  1880. try
  1881. {
  1882. if (FileListCommand)
  1883. {
  1884. UnicodeString LocalFile;
  1885. // MakeFileList does not delimit filenames
  1886. UnicodeString FileList = MakeFileList(RemoteFileList);
  1887. if (LocalFileCommand)
  1888. {
  1889. DebugAssert(LocalFileList->Count == 1);
  1890. LocalFile = LocalFileList->Strings[0];
  1891. }
  1892. TLocalCustomCommand CustomCommand(Data,
  1893. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  1894. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  1895. if (NonBlocking)
  1896. {
  1897. DebugAssert(!POutput);
  1898. ExecuteShellChecked(ShellCommand);
  1899. }
  1900. else
  1901. {
  1902. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  1903. }
  1904. }
  1905. else if (LocalFileCommand)
  1906. {
  1907. if (LocalFileList->Count == 1)
  1908. {
  1909. UnicodeString LocalFile = LocalFileList->Strings[0];
  1910. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  1911. {
  1912. UnicodeString FileName = RemoteFileList->Strings[Index];
  1913. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  1914. Progress.SetFile(FileNameForProgress);
  1915. TLocalCustomCommand CustomCommand(Data,
  1916. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  1917. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1918. TOnceDoneOperation OnceDoneOperation;
  1919. // Do not unselect anything, as it won't work with two panels anyway
  1920. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  1921. }
  1922. }
  1923. else if (RemoteFileList->Count == 1)
  1924. {
  1925. UnicodeString FileName = RemoteFileList->Strings[0];
  1926. for (int Index = 0; Index < LocalFileList->Count; Index++)
  1927. {
  1928. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  1929. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  1930. Progress.SetFile(LocalFileNameOnly);
  1931. TLocalCustomCommand CustomCommand(
  1932. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  1933. FileName, LocalFileName, L"");
  1934. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1935. TOnceDoneOperation OnceDoneOperation;
  1936. // Do not unselect anything, as it won't work with two panels anyway
  1937. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  1938. }
  1939. }
  1940. else
  1941. {
  1942. if (LocalFileList->Count != RemoteFileList->Count)
  1943. {
  1944. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  1945. }
  1946. for (int Index = 0; Index < LocalFileList->Count; Index++)
  1947. {
  1948. UnicodeString FileName = RemoteFileList->Strings[Index];
  1949. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  1950. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  1951. Progress.SetFile(LocalFileNameOnly); // sic
  1952. TLocalCustomCommand CustomCommand(
  1953. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  1954. FileName, LocalFileName, L"");
  1955. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1956. TOnceDoneOperation OnceDoneOperation;
  1957. // Do not unselect anything, as it won't work with two panels anyway
  1958. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  1959. }
  1960. }
  1961. }
  1962. else
  1963. {
  1964. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  1965. {
  1966. UnicodeString FileName = RemoteFileList->Strings[Index];
  1967. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  1968. Progress.SetFile(FileNameForProgress);
  1969. TLocalCustomCommand CustomCommand(Data,
  1970. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  1971. FileName, L"", L"");
  1972. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1973. TOnceDoneOperation OnceDoneOperation;
  1974. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  1975. }
  1976. }
  1977. }
  1978. __finally
  1979. {
  1980. if (!NonBlocking)
  1981. {
  1982. Progress.Stop();
  1983. }
  1984. }
  1985. DebugAssert(!FAutoOperation);
  1986. if (!RemoteFiles)
  1987. {
  1988. TempDir = IncludeTrailingBackslash(TempDir);
  1989. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  1990. {
  1991. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  1992. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  1993. // Skip directories, process only nested files.
  1994. // The check is redundant as FileAge fails for directories anyway.
  1995. !DirectoryExists(FileName))
  1996. {
  1997. UnicodeString RemoteDir =
  1998. UnixExtractFileDir(
  1999. UnixIncludeTrailingBackslash(FTerminal->CurrentDirectory) +
  2000. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  2001. TDateTime NewTime;
  2002. if (FileAge(FileName, NewTime) &&
  2003. (NewTime != RemoteFileTimes[Index]))
  2004. {
  2005. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2006. TemporaryFileCopyParam(CopyParam);
  2007. CopyParam.FileMask = L"";
  2008. FAutoOperation = true;
  2009. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2010. TemporaryFilesList->Add(FileName);
  2011. FTerminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2012. }
  2013. }
  2014. }
  2015. }
  2016. }
  2017. __finally
  2018. {
  2019. FAutoOperation = false;
  2020. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2021. {
  2022. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  2023. }
  2024. }
  2025. }
  2026. __finally
  2027. {
  2028. if (RemoteFileList != FileList)
  2029. {
  2030. delete RemoteFileList;
  2031. }
  2032. if (LocalFileList != ALocalFileList)
  2033. {
  2034. delete LocalFileList;
  2035. }
  2036. if (RemoteFileListFull != RemoteFileList)
  2037. {
  2038. delete RemoteFileListFull;
  2039. }
  2040. }
  2041. }
  2042. //---------------------------------------------------------------------------
  2043. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2044. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2045. bool FileListCommand, UnicodeString * POutput)
  2046. {
  2047. std::unique_ptr<TStrings> SelectedFileList(DirView(osLocal)->CreateFileList(false, true, NULL));
  2048. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2049. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2050. {
  2051. UnicodeString FileName = SelectedFileList->Strings[Index];
  2052. if (DirectoryExists(FileName))
  2053. {
  2054. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2055. {
  2056. LocalFileList->Add(FileName);
  2057. }
  2058. if (FLAGSET(ACommand.Params, ccRecursive))
  2059. {
  2060. TMakeLocalFileListParams MakeFileListParam;
  2061. MakeFileListParam.FileList = LocalFileList.get();
  2062. MakeFileListParam.FileTimes = NULL;
  2063. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2064. MakeFileListParam.Recursive = true;
  2065. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2066. }
  2067. }
  2068. else
  2069. {
  2070. LocalFileList->Add(FileName);
  2071. }
  2072. }
  2073. UnicodeString RemotePath;
  2074. if (Terminal != NULL)
  2075. {
  2076. RemotePath = Terminal->CurrentDirectory;
  2077. }
  2078. if (FileListCommand)
  2079. {
  2080. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2081. TLocalCustomCommand CustomCommand(
  2082. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2083. L"", L"", FileList);
  2084. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2085. }
  2086. else
  2087. {
  2088. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2089. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2090. DebugAssert(FProgressForm != NULL);
  2091. FProgressForm->ReadOnly = true;
  2092. try
  2093. {
  2094. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2095. {
  2096. UnicodeString FileName = LocalFileList->Strings[Index];
  2097. Progress.SetFile(FileName);
  2098. TLocalCustomCommand CustomCommand(
  2099. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2100. FileName, L"", L"");
  2101. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2102. TOnceDoneOperation OnceDoneOperation;
  2103. Progress.Finish(FileName, true, OnceDoneOperation);
  2104. }
  2105. }
  2106. __finally
  2107. {
  2108. Progress.Stop();
  2109. }
  2110. }
  2111. }
  2112. //---------------------------------------------------------------------------
  2113. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2114. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2115. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2116. {
  2117. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2118. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2119. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2120. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2121. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2122. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2123. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2124. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2125. std::unique_ptr<UnicodeString> POutput;
  2126. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2127. FLAGSET(ACommand.Params, ccCopyResults))
  2128. {
  2129. POutput.reset(new UnicodeString());
  2130. }
  2131. if (!LocalCustomCommand.IsFileCommand(Command))
  2132. {
  2133. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2134. }
  2135. // remote files?
  2136. else if ((FCurrentSide == osRemote) || LocalFileCommand)
  2137. {
  2138. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2139. }
  2140. // local files
  2141. else
  2142. {
  2143. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2144. }
  2145. if (POutput.get() != NULL)
  2146. {
  2147. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2148. int P = POutput->Pos(sLineBreak);
  2149. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2150. {
  2151. POutput->SetLength(P - 1);
  2152. }
  2153. // Copy even empty output to clipboard
  2154. if (FLAGSET(ACommand.Params, ccCopyResults))
  2155. {
  2156. CopyToClipboard(*POutput);
  2157. }
  2158. // But do not show an empty message box.
  2159. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2160. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2161. !POutput->IsEmpty())
  2162. {
  2163. TClipboardHandler ClipboardHandler;
  2164. ClipboardHandler.Text = *POutput;
  2165. TMessageParams Params;
  2166. TQueryButtonAlias Aliases[1];
  2167. Aliases[0].Button = qaRetry;
  2168. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2169. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2170. Params.Aliases = Aliases;
  2171. Params.AliasesCount = LENOF(Aliases);
  2172. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2173. }
  2174. }
  2175. }
  2176. //---------------------------------------------------------------------------
  2177. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2178. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2179. {
  2180. TCustomCommandData Data;
  2181. UnicodeString Site;
  2182. UnicodeString RemotePath;
  2183. if (Terminal != NULL)
  2184. {
  2185. Data = TCustomCommandData(Terminal);
  2186. Site = Terminal->SessionData->SessionKey;
  2187. RemotePath = Terminal->CurrentDirectory;
  2188. }
  2189. UnicodeString HelpKeyword = ACommand.HomePage;
  2190. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2191. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2192. {
  2193. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2194. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2195. {
  2196. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2197. }
  2198. else
  2199. {
  2200. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2201. }
  2202. if (!DoCustomCommandOptionsDialog(
  2203. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2204. {
  2205. Abort();
  2206. }
  2207. }
  2208. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2209. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2210. {
  2211. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2212. }
  2213. else
  2214. {
  2215. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2216. }
  2217. }
  2218. //---------------------------------------------------------------------------
  2219. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2220. const TCustomCommandType & Command)
  2221. {
  2222. DebugAssert(FCustomCommandLocalFileList != NULL);
  2223. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2224. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2225. TStrings * LocalFileList = new TStringList();
  2226. TStrings * RemoteFileList = new TStringList();
  2227. try
  2228. {
  2229. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2230. {
  2231. LocalFileList->Clear();
  2232. LocalFileList->AddObject(
  2233. FCustomCommandLocalFileList->Strings[Index],
  2234. FCustomCommandLocalFileList->Objects[Index]);
  2235. RemoteFileList->Clear();
  2236. RemoteFileList->AddObject(
  2237. FCustomCommandRemoteFileList->Strings[Index],
  2238. FCustomCommandRemoteFileList->Objects[Index]);
  2239. CustomCommand(RemoteFileList, Command, LocalFileList);
  2240. }
  2241. }
  2242. __finally
  2243. {
  2244. delete LocalFileList;
  2245. delete RemoteFileList;
  2246. }
  2247. }
  2248. //---------------------------------------------------------------------------
  2249. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2250. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2251. {
  2252. delete FCustomCommandLocalFileList;
  2253. delete FCustomCommandRemoteFileList;
  2254. // takeover ownership,
  2255. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2256. FCustomCommandLocalFileList = LocalFileList;
  2257. FCustomCommandRemoteFileList = RemoteFileList;
  2258. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2259. if (Button != NULL)
  2260. {
  2261. FCustomCommandMenu->Items->Clear();
  2262. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth);
  2263. MenuPopup(FCustomCommandMenu, Button);
  2264. }
  2265. else
  2266. {
  2267. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2268. }
  2269. }
  2270. //---------------------------------------------------------------------------
  2271. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2272. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2273. {
  2274. DebugAssert(FCapturedLog != NULL);
  2275. if ((OutputType == cotOutput) || (OutputType == cotError))
  2276. {
  2277. FCapturedLog->Add(AddedLine);
  2278. }
  2279. }
  2280. //---------------------------------------------------------------------------
  2281. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2282. TOperationSide Side)
  2283. {
  2284. return
  2285. (Side == osOther) &&
  2286. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2287. }
  2288. //---------------------------------------------------------------------------
  2289. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2290. TOperationSide Side, TTBXCustomItem * Item, TDoubleClickAction DoubleClickAction)
  2291. {
  2292. TTBItemOptions O;
  2293. O = Item->Options;
  2294. TCustomDirView * DView = DirView(Side);
  2295. if ((DView->ItemFocused != NULL) &&
  2296. (WinConfiguration->DoubleClickAction == DoubleClickAction) &&
  2297. // when resolving links is disabled, default action is to enter the directory,
  2298. // no matter what DoubleClickAction is configured to
  2299. (IsSideLocalBrowser(Side) || Terminal->ResolvingSymlinks || Terminal->IsEncryptingFiles()) &&
  2300. // Can only Edit files, but can Open/Copy even directories
  2301. ((DoubleClickAction != dcaEdit) ||
  2302. !DView->ItemIsDirectory(DView->ItemFocused)))
  2303. {
  2304. Item->Options = O << tboDefault;
  2305. }
  2306. else
  2307. {
  2308. Item->Options = O >> tboDefault;
  2309. }
  2310. }
  2311. //---------------------------------------------------------------------------
  2312. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2313. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2314. {
  2315. TCustomDirView * DView = DirView(Side);
  2316. TListItem * Item = DView->ItemFocused;
  2317. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2318. EnableFocusedOperation[Side])
  2319. {
  2320. TPoint ClientPoint;
  2321. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2322. TPoint(0, 0) : MousePos;
  2323. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2324. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2325. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2326. }
  2327. }
  2328. //---------------------------------------------------------------------------
  2329. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2330. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2331. {
  2332. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, dcaOpen);
  2333. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, dcaEdit);
  2334. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, dcaCopy);
  2335. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2336. Handled = true;
  2337. }
  2338. //---------------------------------------------------------------------------
  2339. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2340. {
  2341. }
  2342. //---------------------------------------------------------------------------
  2343. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2344. {
  2345. DebugAssert(FErrorList == NULL);
  2346. if (WinConfiguration->ContinueOnError)
  2347. {
  2348. FErrorList = new TStringList();
  2349. Configuration->Usage->Inc(L"ContinuationsOnError");
  2350. }
  2351. NonVisualDataModule->StartBusy();
  2352. }
  2353. //---------------------------------------------------------------------------
  2354. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2355. {
  2356. NonVisualDataModule->EndBusy();
  2357. if (FErrorList)
  2358. {
  2359. HandleErrorList(FErrorList);
  2360. }
  2361. }
  2362. //---------------------------------------------------------------------------
  2363. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2364. const TCopyParamType & CopyParam)
  2365. {
  2366. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2367. {
  2368. Configuration->Usage->Inc(L"FileMaskUses");
  2369. }
  2370. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2371. {
  2372. Configuration->Usage->Inc(L"OperationMaskUses");
  2373. }
  2374. }
  2375. //---------------------------------------------------------------------------
  2376. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2377. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2378. {
  2379. DebugAssert(!IsLocalBrowserMode());
  2380. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2381. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2382. TTransferOperationParam DefaultParam;
  2383. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2384. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2385. switch (Param.Queue)
  2386. {
  2387. case asOn:
  2388. CopyParam.Queue = true;
  2389. break;
  2390. case asOff:
  2391. CopyParam.Queue = false;
  2392. break;
  2393. case asAuto:
  2394. default:
  2395. // keep default
  2396. break;
  2397. }
  2398. bool Result =
  2399. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2400. if (Result)
  2401. {
  2402. DebugAssert(Terminal);
  2403. bool SelectionRestored = false;
  2404. TCustomDirView * DView = NULL;
  2405. if (HasDirView[Side])
  2406. {
  2407. DView = DirView(Side);
  2408. DView->SaveSelection();
  2409. DView->SaveSelectedNames();
  2410. }
  2411. UpdateCopyParamCounters(CopyParam);
  2412. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2413. DebugAssert(FTransferResumeList == NULL);
  2414. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2415. FMoveToQueue = false;
  2416. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2417. try
  2418. {
  2419. TStrings * PermanentFileList;
  2420. std::unique_ptr<TStrings> PermanentFileListOwner;
  2421. try
  2422. {
  2423. if (Side == osLocal)
  2424. {
  2425. PermanentFileList = FileList;
  2426. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2427. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2428. if (Operation == foMove)
  2429. {
  2430. ReloadLocalDirectory();
  2431. if (DView != NULL)
  2432. {
  2433. DView->RestoreSelection();
  2434. }
  2435. SelectionRestored = true;
  2436. }
  2437. }
  2438. else
  2439. {
  2440. // Clone the file list as it may refer to current directory files,
  2441. // which get destroyed, when the source directory is reloaded after foMove operation.
  2442. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2443. // But for a hotfix, we are not going to do such a big change.
  2444. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2445. PermanentFileList = PermanentFileListOwner.get();
  2446. try
  2447. {
  2448. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2449. }
  2450. __finally
  2451. {
  2452. if (Operation == foMove)
  2453. {
  2454. if (DView != NULL)
  2455. {
  2456. DView->RestoreSelection();
  2457. }
  2458. SelectionRestored = true;
  2459. }
  2460. ReloadLocalDirectory(Param.TargetDirectory);
  2461. }
  2462. }
  2463. }
  2464. catch (EAbort &)
  2465. {
  2466. if (FMoveToQueue)
  2467. {
  2468. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2469. DebugAssert(CopyParam.TransferSkipList == NULL);
  2470. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2471. if (TransferResumeList->Count > 0)
  2472. {
  2473. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2474. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2475. }
  2476. CopyParam.TransferSkipList = TransferResumeList.release();
  2477. // not really needed, just to keep it consistent with TransferResumeList
  2478. FTransferResumeList = NULL;
  2479. FMoveToQueue = false;
  2480. Configuration->Usage->Inc("MovesToBackground");
  2481. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2482. ClearTransferSourceSelection(Direction);
  2483. }
  2484. throw;
  2485. }
  2486. }
  2487. __finally
  2488. {
  2489. if (!SelectionRestored && (DView != NULL))
  2490. {
  2491. DView->DiscardSavedSelection();
  2492. }
  2493. FTransferResumeList = NULL;
  2494. }
  2495. }
  2496. return Result;
  2497. }
  2498. //---------------------------------------------------------------------------
  2499. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2500. TOperationSide Side, TStrings * FileList, void * Param)
  2501. {
  2502. DebugAssert(FileList->Count);
  2503. // We deliberately do not toggle alternative flag (Param), but use OR,
  2504. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2505. // shortcut of CurrentDeleteAlternativeAction
  2506. bool Alternative =
  2507. bool(Param) || UseAlternativeFunction();
  2508. bool Recycle;
  2509. if (IsSideLocalBrowser(Side))
  2510. {
  2511. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2512. }
  2513. else
  2514. {
  2515. Recycle =
  2516. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2517. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2518. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2519. }
  2520. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2521. if (!Result)
  2522. {
  2523. UnicodeString Query;
  2524. if (FileList->Count == 1)
  2525. {
  2526. if (IsSideLocalBrowser(Side))
  2527. {
  2528. Query = ExtractFileName(FileList->Strings[0]);
  2529. }
  2530. else
  2531. {
  2532. Query = UnixExtractFileName(FileList->Strings[0]);
  2533. }
  2534. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2535. }
  2536. else
  2537. {
  2538. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2539. }
  2540. TMessageParams Params(mpNeverAskAgainCheck);
  2541. Params.ImageName = L"Delete file";
  2542. unsigned int Answer =
  2543. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2544. if (Answer == qaNeverAskAgain)
  2545. {
  2546. Result = true;
  2547. if (Recycle)
  2548. {
  2549. WinConfiguration->ConfirmRecycling = false;
  2550. }
  2551. else
  2552. {
  2553. WinConfiguration->ConfirmDeleting = false;
  2554. }
  2555. }
  2556. else
  2557. {
  2558. Result = (Answer == qaOK);
  2559. }
  2560. }
  2561. if (Result)
  2562. {
  2563. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2564. }
  2565. return Result;
  2566. }
  2567. //---------------------------------------------------------------------------
  2568. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2569. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2570. {
  2571. TAutoBatch AutoBatch(this);
  2572. bool Result;
  2573. if ((Operation == foCopy) || (Operation == foMove))
  2574. {
  2575. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2576. }
  2577. else if (Operation == foRename)
  2578. {
  2579. DebugAssert(DirView(Side)->ItemFocused);
  2580. DirView(Side)->ItemFocused->EditCaption();
  2581. Result = true;
  2582. }
  2583. else if (Operation == foDelete)
  2584. {
  2585. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2586. }
  2587. else if (Operation == foSetProperties)
  2588. {
  2589. DirView(osRemote)->SaveSelectedNames();
  2590. Result = SetProperties(Side, FileList);
  2591. }
  2592. else if (Operation == foCustomCommand)
  2593. {
  2594. DebugAssert(Param);
  2595. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2596. DirView(osRemote)->SaveSelectedNames();
  2597. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2598. CustomCommand(FileList, *Command, NULL);
  2599. Result = true;
  2600. }
  2601. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2602. {
  2603. DebugAssert(!IsSideLocalBrowser(Side));
  2604. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2605. (Operation == foRemoteMove), reinterpret_cast<TTerminal *>(Param));
  2606. }
  2607. else if (Operation == foLock)
  2608. {
  2609. DebugAssert(!IsSideLocalBrowser(Side));
  2610. LockFiles(FileList, true);
  2611. Result = true;
  2612. }
  2613. else if (Operation == foUnlock)
  2614. {
  2615. DebugAssert(!IsSideLocalBrowser(Side));
  2616. LockFiles(FileList, false);
  2617. Result = true;
  2618. }
  2619. else
  2620. {
  2621. DebugFail();
  2622. }
  2623. return Result;
  2624. }
  2625. //---------------------------------------------------------------------------
  2626. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2627. {
  2628. if (Side == osCurrent)
  2629. {
  2630. Side = FCurrentSide;
  2631. }
  2632. return Side;
  2633. }
  2634. //---------------------------------------------------------------------------
  2635. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2636. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2637. {
  2638. Side = GetSide(Side);
  2639. bool Result;
  2640. TStrings * FileList = DirView(Side)->CreateFileList(OnFocused, IsSideLocalBrowser(Side), NULL);
  2641. try
  2642. {
  2643. Result = ExecuteFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2644. }
  2645. __finally
  2646. {
  2647. delete FileList;
  2648. }
  2649. return Result;
  2650. }
  2651. //---------------------------------------------------------------------------
  2652. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2653. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2654. bool NoConfirmation, void * Param)
  2655. {
  2656. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2657. {
  2658. if ((Operation == foCopy) || (Operation == foMove))
  2659. {
  2660. DebugAssert(!IsLocalBrowserMode());
  2661. if (GetSide(Side) == osLocal)
  2662. {
  2663. Configuration->Usage->Inc(L"UploadsCommand");
  2664. }
  2665. else
  2666. {
  2667. Configuration->Usage->Inc(L"DownloadsCommand");
  2668. }
  2669. }
  2670. }
  2671. }
  2672. //---------------------------------------------------------------------------
  2673. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2674. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2675. {
  2676. TTransferOperationParam Param;
  2677. if ((WinConfiguration->Interface != ifCommander) ||
  2678. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2679. {
  2680. Flags &= ~cocShortCutHint;
  2681. }
  2682. TCustomDirView * DView = DirView(Side);
  2683. Param.Options =
  2684. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2685. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2686. if (FLAGSET(Flags, cocQueue))
  2687. {
  2688. Param.Queue = asOn;
  2689. }
  2690. else if (FLAGSET(Flags, cocNonQueue))
  2691. {
  2692. Param.Queue = asOff;
  2693. }
  2694. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2695. }
  2696. //---------------------------------------------------------------------------
  2697. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2698. {
  2699. try
  2700. {
  2701. if (ErrorList->Count)
  2702. {
  2703. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2704. if (MessageDialog(Message, qtError,
  2705. qaOK | qaCancel, HELP_NONE) == qaOK)
  2706. {
  2707. unsigned int Answer;
  2708. int Index = 0;
  2709. do
  2710. {
  2711. DebugAssert(Index >= 0 && Index < ErrorList->Count);
  2712. TQueryButtonAlias Aliases[2];
  2713. Aliases[0].Button = qaYes;
  2714. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2715. Aliases[1].Button = qaNo;
  2716. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2717. TMessageParams Params;
  2718. Params.Aliases = Aliases;
  2719. Params.AliasesCount = LENOF(Aliases);
  2720. Answer = MoreMessageDialog(
  2721. FMTLOAD(ERROR_LIST_NUMBER, (Index+1, ErrorList->Count, ErrorList->Strings[Index])),
  2722. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2723. (Index ? qaYes : 0) | (Index < ErrorList->Count - 1 ? qaNo : 0) |
  2724. qaOK, HELP_NONE, &Params);
  2725. if (Answer == qaNo)
  2726. {
  2727. Index++;
  2728. }
  2729. if (Answer == qaYes)
  2730. {
  2731. Index--;
  2732. }
  2733. }
  2734. while (Answer != qaOK);
  2735. }
  2736. }
  2737. }
  2738. __finally
  2739. {
  2740. TStrings * List = ErrorList;
  2741. ErrorList = NULL;
  2742. for (int i = 0; i < List->Count; i++)
  2743. {
  2744. delete List->Objects[i];
  2745. }
  2746. delete List;
  2747. }
  2748. }
  2749. //---------------------------------------------------------------------------
  2750. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  2751. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  2752. {
  2753. // needed for checking filemasks, as there's no directory object
  2754. // associated with the file object
  2755. File->FullFileName = FullFileName;
  2756. TFileMasks::TParams MaskParams;
  2757. MaskParams.Size = File->Size;
  2758. MaskParams.Modification = File->Modification;
  2759. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  2760. }
  2761. //---------------------------------------------------------------------------
  2762. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  2763. {
  2764. DebugAssert(!WinConfiguration->DisableOpenEdit);
  2765. Side = GetSide(Side);
  2766. TCustomDirView * DView = DirView(Side);
  2767. TListItem * FocusedItem = DView->ItemFocused;
  2768. UnicodeString Name;
  2769. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  2770. {
  2771. Name = DView->ItemFileName(FocusedItem);
  2772. }
  2773. else
  2774. {
  2775. Name = LoadStr(NEW_FILE);
  2776. }
  2777. UnicodeString Names = Name;
  2778. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  2779. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  2780. HELP_EDIT_NEW, History.get(), true))
  2781. {
  2782. while (!Names.IsEmpty())
  2783. {
  2784. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  2785. CustomWinConfiguration->History[L"EditFile"] = History.get();
  2786. UnicodeString TargetFileName;
  2787. UnicodeString LocalFileName;
  2788. UnicodeString RootTempDir;
  2789. UnicodeString TempDir;
  2790. UnicodeString RemoteDirectory;
  2791. bool ExistingFile = false;
  2792. if (!IsSideLocalBrowser(Side))
  2793. {
  2794. Name = AbsolutePath(FTerminal->CurrentDirectory, Name);
  2795. TRemoteFile * File = NULL;
  2796. if (FTerminal->FileExists(Name, &File) &&
  2797. !File->IsDirectory)
  2798. {
  2799. try
  2800. {
  2801. ExecuteRemoteFile(Name, File, efDefaultEditor);
  2802. ExistingFile = true;
  2803. }
  2804. __finally
  2805. {
  2806. delete File;
  2807. }
  2808. }
  2809. if (!ExistingFile)
  2810. {
  2811. RemoteDirectory = UnixExtractFilePath(Name);
  2812. TemporaryDirectoryForRemoteFiles(
  2813. RemoteDirectory, GUIConfiguration->CurrentCopyParam, TempDir, RootTempDir);
  2814. TargetFileName = UnixExtractFileName(Name);
  2815. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2816. LocalFileName = TempDir +
  2817. // We probably do not want to trim the VMS version here
  2818. FTerminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  2819. }
  2820. }
  2821. else
  2822. {
  2823. if (ExtractFilePath(Name).IsEmpty())
  2824. {
  2825. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  2826. }
  2827. else
  2828. {
  2829. LocalFileName = ExpandFileName(Name);
  2830. }
  2831. TargetFileName = ExtractFileName(Name);
  2832. }
  2833. if (!ExistingFile)
  2834. {
  2835. bool NewFile = !FileExists(ApiPath(LocalFileName));
  2836. if (NewFile)
  2837. {
  2838. int File = FileCreate(ApiPath(LocalFileName));
  2839. if (File < 0)
  2840. {
  2841. if (!RootTempDir.IsEmpty())
  2842. {
  2843. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  2844. }
  2845. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  2846. }
  2847. else
  2848. {
  2849. FileClose(File);
  2850. }
  2851. }
  2852. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  2853. const TEditorData * ExternalEditor = NULL;
  2854. TFileMasks::TParams MaskParams; // size not known
  2855. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  2856. false, MaskParams);
  2857. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  2858. ExternalEditor, RootTempDir, RemoteDirectory, NewFile);
  2859. }
  2860. }
  2861. }
  2862. }
  2863. //---------------------------------------------------------------------------
  2864. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  2865. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  2866. {
  2867. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  2868. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  2869. DebugAssert(ExecuteFileBy != efDefaultEditor);
  2870. return
  2871. ((ExecuteFileBy == efInternalEditor)) ||
  2872. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  2873. }
  2874. //---------------------------------------------------------------------------
  2875. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  2876. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  2877. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  2878. UnicodeString RemoteDirectory, bool NewFile)
  2879. {
  2880. DebugAssert(!WinConfiguration->DisableOpenEdit);
  2881. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  2882. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  2883. DebugAssert(ExecuteFileBy != efDefaultEditor);
  2884. Side = GetSide(Side);
  2885. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  2886. if (!IsSideLocalBrowser(Side))
  2887. {
  2888. Data->Terminal = Terminal;
  2889. Data->Queue = Queue;
  2890. Data->SessionData = CloneCurrentSessionData();
  2891. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  2892. Data->RemoteDirectory = RemoteDirectory;
  2893. Data->SessionName = Terminal->SessionData->SessionName;
  2894. Data->LocalRootDirectory = LocalRootDirectory;
  2895. Data->OriginalFileName = OriginalFileName;
  2896. Data->Command = L""; // will be changed later for external editor
  2897. }
  2898. if (ExecuteFileBy == efInternalEditor)
  2899. {
  2900. if (!IsSideLocalBrowser(Side))
  2901. {
  2902. UnicodeString Caption = UnixIncludeTrailingBackslash(RemoteDirectory) + OriginalFileName +
  2903. L" - " + Terminal->SessionData->SessionName;
  2904. TForm * Editor;
  2905. try
  2906. {
  2907. TNotifyEvent OnFileChanged = NULL;
  2908. TNotifyEvent OnSaveAll = NULL;
  2909. TAnyModifiedEvent OnAnyModified = NULL;
  2910. // Edited files are uploaded in background queue, what we do not support with encrypted files
  2911. if (Terminal->IsCapable[fsBackgroundTransfers])
  2912. {
  2913. OnFileChanged = FEditorManager->FileChanged;
  2914. OnSaveAll = SaveAllInternalEditors;
  2915. OnAnyModified = AnyInternalEditorModified;
  2916. }
  2917. Editor = ShowEditorForm(FileName, this, OnFileChanged,
  2918. FEditorManager->FileReload, FEditorManager->FileClosed,
  2919. OnSaveAll, OnAnyModified,
  2920. Caption, FStandaloneEditing, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  2921. }
  2922. catch(...)
  2923. {
  2924. if (!LocalRootDirectory.IsEmpty())
  2925. {
  2926. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory), false);
  2927. }
  2928. throw;
  2929. }
  2930. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  2931. }
  2932. else
  2933. {
  2934. DebugAssert(!FStandaloneEditing);
  2935. TForm * Editor =
  2936. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  2937. SaveAllInternalEditors, AnyInternalEditorModified,
  2938. L"", false, SessionColor, -1, NewFile);
  2939. FLocalEditors->Add(Editor);
  2940. }
  2941. }
  2942. else
  2943. {
  2944. HANDLE Process;
  2945. if (ExecuteFileBy == efExternalEditor)
  2946. {
  2947. UnicodeString Program, Params, Dir;
  2948. Data->Command = ExternalEditor->ExternalEditor;
  2949. ReformatFileNameCommand(Data->Command);
  2950. SplitCommand(Data->Command, Program, Params, Dir);
  2951. Params = ExpandFileNameCommand(Params, FileName);
  2952. Program = ExpandEnvironmentVariables(Program);
  2953. if (!ExecuteShell(Program, Params, Process))
  2954. {
  2955. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  2956. }
  2957. }
  2958. else
  2959. {
  2960. DebugAssert(IsSideLocalBrowser(Side));
  2961. if (!ExecuteShell(FileName, L"", Process))
  2962. {
  2963. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  2964. }
  2965. }
  2966. if (IsSideLocalBrowser(Side) ||
  2967. ((ExecuteFileBy == efShell) &&
  2968. !WinConfiguration->Editor.SDIShellEditor) ||
  2969. ((ExecuteFileBy == efExternalEditor) &&
  2970. !ExternalEditor->SDIExternalEditor))
  2971. {
  2972. // no need for handle
  2973. if (Process != NULL)
  2974. {
  2975. DebugCheck(CloseHandle(Process));
  2976. }
  2977. Process = INVALID_HANDLE_VALUE;
  2978. }
  2979. else
  2980. {
  2981. if (Process == NULL)
  2982. {
  2983. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  2984. }
  2985. }
  2986. if (!IsSideLocalBrowser(Side))
  2987. {
  2988. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  2989. }
  2990. }
  2991. }
  2992. //---------------------------------------------------------------------------
  2993. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  2994. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  2995. void * /*Arg*/)
  2996. {
  2997. if (Token != NULL)
  2998. {
  2999. EditorFormFileSave(static_cast<TForm *>(Token));
  3000. }
  3001. }
  3002. //---------------------------------------------------------------------------
  3003. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3004. {
  3005. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3006. {
  3007. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3008. }
  3009. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3010. }
  3011. //---------------------------------------------------------------------------
  3012. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3013. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3014. void * Arg)
  3015. {
  3016. if ((Token != NULL) &&
  3017. IsEditorFormModified(static_cast<TForm *>(Token)))
  3018. {
  3019. *static_cast<bool *>(Arg) = true;
  3020. }
  3021. }
  3022. //---------------------------------------------------------------------------
  3023. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3024. TObject * /*Sender*/, bool & Modified)
  3025. {
  3026. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3027. {
  3028. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3029. {
  3030. Modified = true;
  3031. }
  3032. }
  3033. if (!Modified)
  3034. {
  3035. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3036. }
  3037. }
  3038. //---------------------------------------------------------------------------
  3039. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3040. {
  3041. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3042. }
  3043. //---------------------------------------------------------------------------
  3044. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3045. UnicodeString RemoteDirectory, TCopyParamType CopyParam,
  3046. UnicodeString & Result, UnicodeString & RootDirectory)
  3047. {
  3048. if (!WinConfiguration->TemporaryDirectoryDeterministic)
  3049. {
  3050. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3051. Result = RootDirectory;
  3052. }
  3053. else
  3054. {
  3055. RootDirectory = L"";
  3056. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3057. Result = IncludeTrailingBackslash(Result);
  3058. }
  3059. if (WinConfiguration->TemporaryDirectoryAppendSession)
  3060. {
  3061. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3062. }
  3063. if (WinConfiguration->TemporaryDirectoryAppendPath)
  3064. {
  3065. if (!RemoteDirectory.IsEmpty() && (RemoteDirectory[1] == L'/'))
  3066. {
  3067. RemoteDirectory.Delete(1, 1);
  3068. }
  3069. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(RemoteDirectory)));
  3070. }
  3071. if (!ForceDirectories(ApiPath(Result)))
  3072. {
  3073. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3074. }
  3075. }
  3076. //---------------------------------------------------------------------------
  3077. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3078. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3079. bool AllFiles, bool GetTargetNames, bool AutoOperation)
  3080. {
  3081. DebugAssert(!IsLocalBrowserMode());
  3082. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3083. if (ForceText)
  3084. {
  3085. CopyParam.TransferMode = tmAscii;
  3086. }
  3087. TemporaryFileCopyParam(CopyParam);
  3088. if (AllFiles)
  3089. {
  3090. CopyParam.IncludeFileMask = TFileMasks();
  3091. }
  3092. if (TempDir.IsEmpty())
  3093. {
  3094. TemporaryDirectoryForRemoteFiles(FTerminal->CurrentDirectory, CopyParam, TempDir, RootTempDir);
  3095. }
  3096. DebugAssert(!FAutoOperation);
  3097. FAutoOperation = AutoOperation;
  3098. Terminal->ExceptionOnFail = true;
  3099. try
  3100. {
  3101. try
  3102. {
  3103. // turn off confirmations, as for MDI editors we may possibly download
  3104. // the same file over
  3105. Terminal->CopyToLocal(
  3106. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3107. if (GetTargetNames)
  3108. {
  3109. for (int i = 0; i < FileList->Count; i++)
  3110. {
  3111. FileList->Strings[i] =
  3112. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3113. }
  3114. }
  3115. }
  3116. catch(...)
  3117. {
  3118. if (!RootTempDir.IsEmpty())
  3119. {
  3120. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  3121. }
  3122. throw;
  3123. }
  3124. }
  3125. __finally
  3126. {
  3127. FAutoOperation = false;
  3128. Terminal->ExceptionOnFail = false;
  3129. }
  3130. }
  3131. //---------------------------------------------------------------------------
  3132. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3133. {
  3134. // Do not waste time checking for default editor list the next time,
  3135. // or testing if default editor is not notepad.
  3136. bool TryNextTime = false;
  3137. UnicodeString UsageState;
  3138. if (!WinConfiguration->EditorList->IsDefaultList())
  3139. {
  3140. UsageState = "H";
  3141. }
  3142. else
  3143. {
  3144. UnicodeString Executable;
  3145. UnicodeString ExecutableDescription;
  3146. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3147. {
  3148. UnicodeString Message =
  3149. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3150. unsigned int Answer =
  3151. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3152. if (Answer != qaOK)
  3153. {
  3154. UsageState = "R";
  3155. }
  3156. else
  3157. {
  3158. UsageState = "A";
  3159. TEditorData EditorData;
  3160. EditorData.Editor = edExternal;
  3161. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3162. EditorData.DecideExternalEditorText();
  3163. TEditorList EditorList;
  3164. EditorList = *WinConfiguration->EditorList;
  3165. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3166. WinConfiguration->EditorList = &EditorList;
  3167. }
  3168. }
  3169. }
  3170. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3171. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3172. }
  3173. //---------------------------------------------------------------------------
  3174. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3175. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3176. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3177. {
  3178. if (ExecuteFileBy == efDefaultEditor)
  3179. {
  3180. if (!WinConfiguration->OfferedEditorAutoConfig)
  3181. {
  3182. EditorAutoConfig();
  3183. }
  3184. const TEditorPreferences * Editor =
  3185. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3186. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3187. {
  3188. ExecuteFileBy = efInternalEditor;
  3189. ExternalEditor = NULL;
  3190. }
  3191. else if (Editor->Data->Editor == edOpen)
  3192. {
  3193. ExecuteFileBy = efShell;
  3194. ExternalEditor = NULL;
  3195. }
  3196. else
  3197. {
  3198. ExecuteFileBy = efExternalEditor;
  3199. ExternalEditor = Editor->Data;
  3200. }
  3201. }
  3202. }
  3203. //---------------------------------------------------------------------------
  3204. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3205. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3206. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3207. {
  3208. UnicodeString OriginalFileName;
  3209. UnicodeString LocalRootDirectory;
  3210. UnicodeString RemoteDirectory;
  3211. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3212. IsSideLocalBrowser(Side), MaskParams);
  3213. UnicodeString Counter;
  3214. UnicodeString LocalFileName;
  3215. bool Handled = false;
  3216. if (!IsSideLocalBrowser(Side))
  3217. {
  3218. // We need to trim VMS version here, so that we use name without version
  3219. // when uploading back to create a new version of the file
  3220. OriginalFileName = FTerminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3221. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3222. TObject * Token = NULL;
  3223. UnicodeString LocalDirectory;
  3224. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3225. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3226. LocalDirectory))
  3227. {
  3228. if (Token != NULL)
  3229. {
  3230. TForm * Form = dynamic_cast<TForm *>(Token);
  3231. if (Form->WindowState == wsMinimized)
  3232. {
  3233. ShowWindow(Form->Handle, SW_RESTORE);
  3234. }
  3235. else
  3236. {
  3237. Form->SetFocus();
  3238. }
  3239. Handled = true;
  3240. }
  3241. else
  3242. {
  3243. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3244. }
  3245. }
  3246. if (!Handled)
  3247. {
  3248. TStringList * FileList1 = new TStringList();
  3249. try
  3250. {
  3251. FileList1->AddObject(FullFileName, Object);
  3252. TemporarilyDownloadFiles(FileList1,
  3253. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3254. LocalRootDirectory, LocalDirectory, true, true, true);
  3255. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3256. }
  3257. __finally
  3258. {
  3259. delete FileList1;
  3260. }
  3261. switch (ExecuteFileBy)
  3262. {
  3263. case efShell:
  3264. Counter = "RemoteFilesExecuted";
  3265. break;
  3266. case efInternalEditor:
  3267. Counter = "RemoteFilesOpenedInInternalEditor";
  3268. break;
  3269. case efExternalEditor:
  3270. Counter = "RemoteFilesOpenedInExternalEditor";
  3271. break;
  3272. default:
  3273. DebugFail();
  3274. }
  3275. }
  3276. }
  3277. else
  3278. {
  3279. LocalFileName = FullFileName;
  3280. OriginalFileName = ExtractFileName(FullFileName);
  3281. switch (ExecuteFileBy)
  3282. {
  3283. case efShell:
  3284. Counter = "LocalFilesExecuted";
  3285. break;
  3286. case efInternalEditor:
  3287. Counter = "LocalFilesOpenedInInternalEditor";
  3288. break;
  3289. case efExternalEditor:
  3290. Counter = "LocalFilesOpenedInExternalEditor";
  3291. break;
  3292. default:
  3293. DebugFail();
  3294. }
  3295. }
  3296. if (!Handled)
  3297. {
  3298. Configuration->Usage->Inc(Counter);
  3299. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3300. ExternalEditor, LocalRootDirectory, RemoteDirectory, false);
  3301. }
  3302. }
  3303. //---------------------------------------------------------------------------
  3304. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3305. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3306. bool AllSelected, bool OnFocused)
  3307. {
  3308. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3309. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3310. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3311. Side = GetSide(Side);
  3312. TCustomDirView * DView = DirView(Side);
  3313. TStrings * FileList =
  3314. AllSelected ?
  3315. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3316. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3317. try
  3318. {
  3319. DebugAssert(AllSelected || (FileList->Count == 1));
  3320. for (int i = 0; i < FileList->Count; i++)
  3321. {
  3322. UnicodeString ListFileName = FileList->Strings[i];
  3323. UnicodeString FileNameOnly =
  3324. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3325. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3326. if (!DView->ItemIsDirectory(Item))
  3327. {
  3328. UnicodeString FullFileName;
  3329. if (!IsSideLocalBrowser(Side))
  3330. {
  3331. FullFileName = DirView(Side)->Path + ListFileName;
  3332. }
  3333. else
  3334. {
  3335. FullFileName = ListFileName;
  3336. }
  3337. TFileMasks::TParams MaskParams;
  3338. MaskParams.Size = DView->ItemFileSize(Item);
  3339. TDateTimePrecision Precision;
  3340. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3341. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName,
  3342. FileList->Objects[i], MaskParams);
  3343. }
  3344. }
  3345. }
  3346. __finally
  3347. {
  3348. delete FileList;
  3349. }
  3350. }
  3351. //---------------------------------------------------------------------------
  3352. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3353. {
  3354. // do not forget to add additional options to TemporarilyDownloadFiles, and AS
  3355. CopyParam.FileNameCase = ncNoChange;
  3356. CopyParam.PreserveRights = false;
  3357. CopyParam.PreserveReadOnly = false;
  3358. CopyParam.ReplaceInvalidChars = true;
  3359. CopyParam.IncludeFileMask = TFileMasks();
  3360. CopyParam.NewerOnly = false;
  3361. CopyParam.FileMask = L"";
  3362. }
  3363. //---------------------------------------------------------------------------
  3364. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(const UnicodeString FileName,
  3365. TEditedFileData * Data, HANDLE UploadCompleteEvent)
  3366. {
  3367. TTerminalManager * Manager = TTerminalManager::Instance();
  3368. if ((Data->Terminal == NULL) || !Data->Terminal->Active)
  3369. {
  3370. if (!NonVisualDataModule->Busy)
  3371. {
  3372. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3373. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3374. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3375. if (Data->Terminal == NULL)
  3376. {
  3377. TTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3378. if (SameSiteTerminal != NULL)
  3379. {
  3380. UnicodeString Message =
  3381. FMTLOAD(EDIT_SESSION_REATTACH,
  3382. (FileNameOnly, Data->SessionName, FileNameOnly));
  3383. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3384. {
  3385. Data->Terminal = Terminal;
  3386. Data->Queue = Manager->FindQueueForTerminal(Terminal);
  3387. Data->SessionName = Terminal->SessionData->SessionName;
  3388. // We might also overwrite session data
  3389. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3390. }
  3391. else
  3392. {
  3393. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3394. Abort();
  3395. }
  3396. }
  3397. }
  3398. // foreground session should reconnect itself
  3399. else if (Terminal != Data->Terminal)
  3400. {
  3401. UnicodeString Message =
  3402. MainInstructions(
  3403. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3404. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3405. {
  3406. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3407. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3408. }
  3409. else
  3410. {
  3411. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3412. Abort();
  3413. }
  3414. }
  3415. }
  3416. if ((Data->Terminal == NULL) || !Data->Terminal->Active)
  3417. {
  3418. Configuration->Usage->Inc(L"EditInactiveSession");
  3419. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3420. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3421. (ExtractFileName(FileName), Data->SessionName)));
  3422. }
  3423. }
  3424. TStrings * FileList = new TStringList();
  3425. try
  3426. {
  3427. FileList->Add(FileName);
  3428. // consider using the same settings (preset) as when the file was downloaded
  3429. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3430. TemporaryFileCopyParam(CopyParam);
  3431. if (Data->ForceText)
  3432. {
  3433. CopyParam.TransferMode = tmAscii;
  3434. }
  3435. // so i do not need to worry if masking algorithm works in all cases
  3436. // ("" means "copy file name", no masking is actually done)
  3437. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3438. {
  3439. CopyParam.FileMask = L"";
  3440. }
  3441. else
  3442. {
  3443. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3444. }
  3445. DebugAssert(Data->Queue != NULL);
  3446. int Params = cpNoConfirmation | cpTemporary;
  3447. TQueueItem * QueueItem = new TUploadQueueItem(Data->Terminal, FileList,
  3448. Data->RemoteDirectory, &CopyParam, Params, true, false);
  3449. QueueItem->CompleteEvent = UploadCompleteEvent;
  3450. AddQueueItem(Data->Queue, QueueItem, Data->Terminal);
  3451. }
  3452. __finally
  3453. {
  3454. delete FileList;
  3455. }
  3456. }
  3457. //---------------------------------------------------------------------------
  3458. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3459. const UnicodeString FileName, const TEditedFileData * Data)
  3460. {
  3461. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3462. DebugAssert(!NonVisualDataModule->Busy);
  3463. if ((Data->Terminal == NULL) || !Data->Terminal->Active)
  3464. {
  3465. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3466. (ExtractFileName(FileName), Data->SessionName)));
  3467. }
  3468. TTerminal * PrevTerminal = TTerminalManager::Instance()->ActiveTerminal;
  3469. TTerminalManager::Instance()->ActiveTerminal = Data->Terminal;
  3470. NonVisualDataModule->StartBusy();
  3471. try
  3472. {
  3473. std::unique_ptr<TRemoteFile> File;
  3474. UnicodeString RemoteFileName =
  3475. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3476. FTerminal->ExceptionOnFail = true;
  3477. try
  3478. {
  3479. TRemoteFile * AFile = NULL;
  3480. FTerminal->ReadFile(RemoteFileName, AFile);
  3481. File.reset(AFile);
  3482. if (!File->HaveFullFileName)
  3483. {
  3484. File->FullFileName = RemoteFileName;
  3485. }
  3486. }
  3487. __finally
  3488. {
  3489. FTerminal->ExceptionOnFail = false;
  3490. }
  3491. std::unique_ptr<TStrings> FileList(new TStringList());
  3492. FileList->AddObject(RemoteFileName, File.get());
  3493. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3494. UnicodeString TempDir = ExtractFilePath(FileName);
  3495. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir,
  3496. TempDir, true, true, true);
  3497. // sanity check, the target file name should be still the same
  3498. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3499. }
  3500. __finally
  3501. {
  3502. NonVisualDataModule->EndBusy();
  3503. // it actually may not exist anymore...
  3504. TTerminalManager::Instance()->ActiveTerminal = PrevTerminal;
  3505. }
  3506. }
  3507. //---------------------------------------------------------------------------
  3508. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3509. const TEditedFileData * Data, bool & KeepOpen)
  3510. {
  3511. // Command is set for external editors only (not for "shell" open).
  3512. if (!Data->Command.IsEmpty())
  3513. {
  3514. bool AnyFound = false;
  3515. bool AnyMDI = false;
  3516. bool AnyNonMDI = false;
  3517. bool AnyDetect = false;
  3518. TEditorList * EditorList = new TEditorList();
  3519. try
  3520. {
  3521. *EditorList = *WinConfiguration->EditorList;
  3522. for (int i = 0; i < EditorList->Count; i++)
  3523. {
  3524. const TEditorPreferences * Editor = EditorList->Editors[i];
  3525. if ((Editor->Data->Editor == edExternal) &&
  3526. (Editor->Data->ExternalEditor == Data->Command))
  3527. {
  3528. AnyFound = true;
  3529. if (Editor->Data->SDIExternalEditor)
  3530. {
  3531. AnyNonMDI = true;
  3532. if (Editor->Data->DetectMDIExternalEditor)
  3533. {
  3534. AnyDetect = true;
  3535. }
  3536. }
  3537. else
  3538. {
  3539. AnyMDI = true;
  3540. }
  3541. }
  3542. }
  3543. bool EnableMDI = false;
  3544. bool DisableDetect = false;
  3545. if (AnyMDI)
  3546. {
  3547. KeepOpen = true;
  3548. if (AnyNonMDI)
  3549. {
  3550. // there is at least one instance of the editor with MDI support enabled,
  3551. // and one with disabled, enable it for all instances
  3552. EnableMDI = true;
  3553. }
  3554. }
  3555. else if (AnyFound && !AnyDetect)
  3556. {
  3557. // at least once instance found but all have MDI autodetection disabled
  3558. // => close the file (default action)
  3559. }
  3560. else
  3561. {
  3562. // no instance of the editor has MDI support enabled
  3563. TMessageParams Params;
  3564. if (AnyFound)
  3565. {
  3566. // there is at least one instance of the editor
  3567. Params.Params |= mpNeverAskAgainCheck;
  3568. }
  3569. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3570. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3571. switch (Answer)
  3572. {
  3573. case qaNeverAskAgain:
  3574. DisableDetect = true;
  3575. break;
  3576. case qaNo:
  3577. EnableMDI = true;
  3578. KeepOpen = true;
  3579. break;
  3580. }
  3581. }
  3582. if (AnyFound && (EnableMDI || DisableDetect))
  3583. {
  3584. bool Changed = false;
  3585. for (int i = 0; i < EditorList->Count; i++)
  3586. {
  3587. const TEditorPreferences * Editor = EditorList->Editors[i];
  3588. if ((Editor->Data->Editor == edExternal) &&
  3589. (Editor->Data->ExternalEditor == Data->Command) &&
  3590. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3591. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3592. {
  3593. Changed = true;
  3594. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3595. if (EnableMDI)
  3596. {
  3597. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3598. }
  3599. if (DisableDetect)
  3600. {
  3601. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3602. }
  3603. EditorList->Change(i, UpdatedEditor);
  3604. }
  3605. }
  3606. if (Changed)
  3607. {
  3608. WinConfiguration->EditorList = EditorList;
  3609. }
  3610. }
  3611. }
  3612. __finally
  3613. {
  3614. delete EditorList;
  3615. }
  3616. }
  3617. else
  3618. {
  3619. // "open" case
  3620. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  3621. qaOK, HELP_APP_EARLY_CLOSED);
  3622. }
  3623. }
  3624. //---------------------------------------------------------------------------
  3625. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  3626. {
  3627. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  3628. }
  3629. //---------------------------------------------------------------------------
  3630. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  3631. {
  3632. SideEnter(osRemote);
  3633. }
  3634. //---------------------------------------------------------------------------
  3635. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  3636. {
  3637. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  3638. SideEnter(osRemote);
  3639. }
  3640. //---------------------------------------------------------------------------
  3641. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  3642. {
  3643. FCurrentSide = Side;
  3644. if (Visible)
  3645. {
  3646. UpdateControls();
  3647. }
  3648. }
  3649. //---------------------------------------------------------------------------
  3650. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  3651. TStrings * FileList, bool Alternative)
  3652. {
  3653. TCustomDirView * DView = DirView(Side);
  3654. DView->SaveSelection();
  3655. DView->SaveSelectedNames();
  3656. DebugAssert(!FAlternativeDelete);
  3657. FAlternativeDelete = Alternative;
  3658. try
  3659. {
  3660. if (!IsSideLocalBrowser(Side))
  3661. {
  3662. DebugAssert(Terminal != NULL);
  3663. Terminal->DeleteFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  3664. }
  3665. else
  3666. {
  3667. try
  3668. {
  3669. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  3670. }
  3671. __finally
  3672. {
  3673. ReloadLocalDirectory();
  3674. }
  3675. }
  3676. FAlternativeDelete = false;
  3677. }
  3678. catch(...)
  3679. {
  3680. FAlternativeDelete = false;
  3681. DView->DiscardSavedSelection();
  3682. throw;
  3683. }
  3684. DView->RestoreSelection();
  3685. }
  3686. //---------------------------------------------------------------------------
  3687. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  3688. {
  3689. DebugAssert(Terminal);
  3690. DebugAssert(!IsLocalBrowserMode());
  3691. RemoteDirView->SaveSelection();
  3692. RemoteDirView->SaveSelectedNames();
  3693. try
  3694. {
  3695. if (Lock)
  3696. {
  3697. Terminal->LockFiles(FileList);
  3698. }
  3699. else
  3700. {
  3701. Terminal->UnlockFiles(FileList);
  3702. }
  3703. }
  3704. catch(...)
  3705. {
  3706. RemoteDirView->DiscardSavedSelection();
  3707. throw;
  3708. }
  3709. RemoteDirView->RestoreSelection();
  3710. }
  3711. //---------------------------------------------------------------------------
  3712. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TTerminal *& Session,
  3713. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  3714. bool NoConfirmation, bool Move)
  3715. {
  3716. DebugAssert(Terminal != NULL);
  3717. DebugAssert(!IsLocalBrowserMode());
  3718. // update Terminal->StateData->RemoteDirectory
  3719. UpdateTerminal(Terminal);
  3720. if (Session == NULL)
  3721. {
  3722. Session = TTerminalManager::Instance()->ActiveTerminal;
  3723. }
  3724. if (Session == TTerminalManager::Instance()->ActiveTerminal)
  3725. {
  3726. if (RemoteDriveView->DropTarget != NULL)
  3727. {
  3728. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  3729. }
  3730. else if (RemoteDirView->DropTarget != NULL)
  3731. {
  3732. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  3733. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  3734. }
  3735. else
  3736. {
  3737. Target = RemoteDirView->Path;
  3738. }
  3739. }
  3740. else
  3741. {
  3742. TManagedTerminal * ManagedTerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(Session));
  3743. Target = ManagedTerminal->StateData->RemoteDirectory;
  3744. }
  3745. Target = UnixIncludeTrailingBackslash(Target);
  3746. if (FileList->Count == 1)
  3747. {
  3748. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  3749. }
  3750. else
  3751. {
  3752. FileMask = AnyMask;
  3753. }
  3754. DirectCopy = FTerminal->IsCapable[fcRemoteCopy] || FTerminal->IsCapable[fcSecondaryShell];
  3755. bool Result = true;
  3756. if (!NoConfirmation)
  3757. {
  3758. bool Multi = (FileList->Count > 1);
  3759. if (Move)
  3760. {
  3761. Result = DoRemoteMoveDialog(Multi, Target, FileMask);
  3762. }
  3763. else
  3764. {
  3765. TStrings * Sessions = TTerminalManager::Instance()->TerminalList;
  3766. TStrings * Directories = new TStringList;
  3767. try
  3768. {
  3769. for (int Index = 0; Index < Sessions->Count; Index++)
  3770. {
  3771. TManagedTerminal * Terminal =
  3772. dynamic_cast<TManagedTerminal *>(Sessions->Objects[Index]);
  3773. Directories->Add(Terminal->StateData->RemoteDirectory);
  3774. }
  3775. TDirectRemoteCopy AllowDirectCopy;
  3776. if (FTerminal->IsCapable[fcRemoteCopy] || FTerminal->CommandSessionOpened)
  3777. {
  3778. DebugAssert(DirectCopy);
  3779. AllowDirectCopy = drcAllow;
  3780. }
  3781. else if (FTerminal->IsCapable[fcSecondaryShell])
  3782. {
  3783. DebugAssert(DirectCopy);
  3784. AllowDirectCopy = drcConfirmCommandSession;
  3785. }
  3786. else
  3787. {
  3788. DebugAssert(!DirectCopy);
  3789. AllowDirectCopy = drcDisallow;
  3790. }
  3791. void * ASession = Session;
  3792. Result = DoRemoteCopyDialog(Sessions, Directories, AllowDirectCopy,
  3793. Multi, ASession, Target, FileMask, DirectCopy, TTerminalManager::Instance()->ActiveTerminal);
  3794. Session = static_cast<TTerminal *>(ASession);
  3795. }
  3796. __finally
  3797. {
  3798. delete Directories;
  3799. }
  3800. }
  3801. }
  3802. return Result;
  3803. }
  3804. //---------------------------------------------------------------------------
  3805. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  3806. TStrings * FileList, bool NoConfirmation, bool Move, TTerminal * Session)
  3807. {
  3808. DebugAssert(!IsLocalBrowserMode());
  3809. bool DirectCopy;
  3810. UnicodeString Target, FileMask;
  3811. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  3812. if (Result)
  3813. {
  3814. if (!Move && !DirectCopy)
  3815. {
  3816. Configuration->Usage->Inc("RemoteCopyTemp");
  3817. UnicodeString RootTempDir;
  3818. UnicodeString TempDir;
  3819. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, false);
  3820. TStrings * TemporaryFilesList = new TStringList();
  3821. try
  3822. {
  3823. TMakeLocalFileListParams MakeFileListParam;
  3824. MakeFileListParam.FileList = TemporaryFilesList;
  3825. MakeFileListParam.FileTimes = NULL;
  3826. MakeFileListParam.IncludeDirs = true;
  3827. MakeFileListParam.Recursive = false;
  3828. ProcessLocalDirectory(TempDir, FTerminal->MakeLocalFileList, &MakeFileListParam);
  3829. TTerminalManager::Instance()->ActiveTerminal = Session;
  3830. if (TemporaryFilesList->Count > 0)
  3831. {
  3832. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3833. CopyParam.FileMask = FileMask;
  3834. DebugAssert(!FAutoOperation);
  3835. FAutoOperation = true;
  3836. FTerminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  3837. }
  3838. }
  3839. __finally
  3840. {
  3841. delete TemporaryFilesList;
  3842. FAutoOperation = false;
  3843. if (!RootTempDir.IsEmpty())
  3844. {
  3845. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  3846. }
  3847. }
  3848. }
  3849. else
  3850. {
  3851. RemoteDirView->SaveSelection();
  3852. RemoteDirView->SaveSelectedNames();
  3853. try
  3854. {
  3855. if (Move)
  3856. {
  3857. Configuration->Usage->Inc("RemoteMove");
  3858. Terminal->MoveFiles(FileList, Target, FileMask);
  3859. }
  3860. else
  3861. {
  3862. Configuration->Usage->Inc("RemoteCopyDirect");
  3863. DebugAssert(DirectCopy);
  3864. DebugAssert(Session == FTerminal);
  3865. if (FTerminal->IsCapable[fcRemoteCopy] ||
  3866. FTerminal->CommandSessionOpened ||
  3867. CommandSessionFallback())
  3868. {
  3869. Terminal->CopyFiles(FileList, Target, FileMask);
  3870. }
  3871. }
  3872. }
  3873. catch(...)
  3874. {
  3875. RemoteDirView->DiscardSavedSelection();
  3876. throw;
  3877. }
  3878. RemoteDirView->RestoreSelection();
  3879. }
  3880. }
  3881. return Result;
  3882. }
  3883. //---------------------------------------------------------------------------
  3884. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  3885. const UnicodeString & Path, TRemoteProperties & Properties)
  3886. {
  3887. DebugAssert(!IsLocalBrowserMode());
  3888. Properties.Valid = Properties.Valid << vpEncrypt;
  3889. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  3890. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  3891. }
  3892. //---------------------------------------------------------------------------
  3893. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  3894. {
  3895. Side = GetSide(Side);
  3896. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  3897. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  3898. UnicodeString Name = LoadStr(NEW_FOLDER);
  3899. int AllowedChanges =
  3900. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  3901. bool SaveSettings = false;
  3902. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  3903. {
  3904. TWindowLock Lock(this);
  3905. if (!IsSideLocalBrowser(Side))
  3906. {
  3907. if (SaveSettings)
  3908. {
  3909. GUIConfiguration->NewDirectoryProperties = Properties;
  3910. }
  3911. CreateRemoteDirectory(Name, Properties);
  3912. }
  3913. else
  3914. {
  3915. DirView(Side)->CreateDirectory(Name);
  3916. }
  3917. }
  3918. }
  3919. //---------------------------------------------------------------------------
  3920. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  3921. {
  3922. TWindowLock Lock(this);
  3923. DirView(Side)->ExecuteHomeDirectory();
  3924. }
  3925. //---------------------------------------------------------------------------
  3926. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  3927. {
  3928. DoOpenDirectoryDialog(odBrowse, Side);
  3929. }
  3930. //---------------------------------------------------------------------------
  3931. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  3932. {
  3933. UnicodeString Path = Bookmark->GetSideDirectory(Side);
  3934. bool Result = !Path.IsEmpty();
  3935. if (Result)
  3936. {
  3937. // While we might get here when the session is closed (from location profiles),
  3938. // it's not a problem as the Path setter is noop then
  3939. DirView(Side)->Path = Path;
  3940. }
  3941. return Result;
  3942. }
  3943. //---------------------------------------------------------------------------
  3944. void __fastcall TCustomScpExplorerForm::CalculateSize(
  3945. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  3946. bool & Close)
  3947. {
  3948. // terminal can be already closed (e.g. dropped connection)
  3949. if (Terminal != NULL)
  3950. {
  3951. try
  3952. {
  3953. Terminal->CalculateFilesSize(FileList, Size, 0, NULL, true, Stats);
  3954. }
  3955. catch(...)
  3956. {
  3957. if (!Terminal->Active)
  3958. {
  3959. Close = true;
  3960. }
  3961. throw;
  3962. }
  3963. }
  3964. }
  3965. //---------------------------------------------------------------------------
  3966. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  3967. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  3968. bool & Close)
  3969. {
  3970. // terminal can be already closed (e.g. dropped connection)
  3971. if (Terminal != NULL)
  3972. {
  3973. Configuration->Usage->Inc(L"ChecksumCalculated");
  3974. try
  3975. {
  3976. Terminal->CalculateFilesChecksum(Alg, FileList, NULL, OnCalculatedChecksum);
  3977. }
  3978. catch(...)
  3979. {
  3980. if (!Terminal->Active)
  3981. {
  3982. Close = true;
  3983. }
  3984. throw;
  3985. }
  3986. }
  3987. }
  3988. //---------------------------------------------------------------------------
  3989. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  3990. {
  3991. bool Result;
  3992. if (!IsSideLocalBrowser(Side))
  3993. {
  3994. TRemoteTokenList * GroupList = NULL;
  3995. TRemoteTokenList * UserList = NULL;
  3996. try
  3997. {
  3998. TRemoteProperties CurrentProperties;
  3999. if (Terminal->LoadFilesProperties(FileList))
  4000. {
  4001. RemoteDirView->Invalidate();
  4002. }
  4003. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4004. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4005. if (CapableGroupChanging || CapableOwnerChanging)
  4006. {
  4007. if (CapableGroupChanging)
  4008. {
  4009. GroupList = Terminal->Groups->Duplicate();
  4010. }
  4011. if (CapableOwnerChanging)
  4012. {
  4013. UserList = Terminal->Users->Duplicate();
  4014. }
  4015. TRemoteDirectory * Files = Terminal->Files;
  4016. int Count = Files->Count;
  4017. if (Count > 100)
  4018. {
  4019. Count = 100;
  4020. }
  4021. for (int Index = 0; Index < Count; Index++)
  4022. {
  4023. TRemoteFile * File = Files->Files[Index];
  4024. if (CapableGroupChanging)
  4025. {
  4026. GroupList->AddUnique(File->Group);
  4027. }
  4028. if (CapableOwnerChanging)
  4029. {
  4030. UserList->AddUnique(File->Owner);
  4031. }
  4032. }
  4033. // if we haven't collected tokens for all files in current directory,
  4034. // make sure we collect them at least for all selected files.
  4035. // (note that so far the files in FileList has to be from current direcotry)
  4036. if (Count < Files->Count)
  4037. {
  4038. for (int Index = 0; Index < FileList->Count; Index++)
  4039. {
  4040. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4041. if (CapableGroupChanging)
  4042. {
  4043. GroupList->AddUnique(File->Group);
  4044. }
  4045. if (CapableOwnerChanging)
  4046. {
  4047. UserList->AddUnique(File->Owner);
  4048. }
  4049. }
  4050. }
  4051. }
  4052. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4053. int Flags = 0;
  4054. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4055. if (CapableOwnerChanging) Flags |= cpOwner;
  4056. if (CapableGroupChanging) Flags |= cpGroup;
  4057. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4058. if (Terminal->IsCapable[fcCalculatingChecksum])
  4059. {
  4060. CalculateChecksumEvent = CalculateChecksum;
  4061. }
  4062. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4063. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4064. TRemoteProperties NewProperties = CurrentProperties;
  4065. Result =
  4066. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4067. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4068. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4069. CalculateSize, CalculateChecksumEvent);
  4070. if (Result)
  4071. {
  4072. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4073. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4074. }
  4075. }
  4076. __finally
  4077. {
  4078. delete GroupList;
  4079. delete UserList;
  4080. }
  4081. }
  4082. else
  4083. {
  4084. DirView(Side)->DisplayPropertiesMenu();
  4085. Result = true;
  4086. }
  4087. return Result;
  4088. }
  4089. //---------------------------------------------------------------------------
  4090. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4091. {
  4092. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4093. {
  4094. FIgnoreNextDialogChar = Key;
  4095. }
  4096. Key = 0;
  4097. }
  4098. //---------------------------------------------------------------------------
  4099. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4100. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4101. {
  4102. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4103. if (Command != NULL)
  4104. {
  4105. KeyProcessed(Key, Shift);
  4106. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4107. {
  4108. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4109. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4110. false, false, const_cast<TCustomCommandType *>(Command));
  4111. }
  4112. }
  4113. }
  4114. //---------------------------------------------------------------------------
  4115. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4116. {
  4117. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4118. {
  4119. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4120. }
  4121. if (!DirView(osCurrent)->IsEditing())
  4122. {
  4123. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4124. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4125. {
  4126. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4127. if (((Action->ShortCut == KeyShortCut) ||
  4128. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4129. AllowedAction(Action, aaShortCut))
  4130. {
  4131. // Has to be called before the action as the dialog char is already in queue.
  4132. // So when the action consumes message queue, we already need to have the
  4133. // FIgnoreNextDialogChar set
  4134. KeyProcessed(Key, Shift);
  4135. // Reset reference to previous component (when menu/toolbar was clicked).
  4136. // Needed to detect that action was invoked by keyboard shortcut
  4137. // in TNonVisualDataModule::ExplorerActionsExecute
  4138. Action->ActionComponent = NULL;
  4139. Action->Execute();
  4140. return;
  4141. }
  4142. }
  4143. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4144. {
  4145. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4146. {
  4147. KeyProcessed(Key, Shift);
  4148. TTerminalManager::Instance()->ActiveTerminalIndex = i;
  4149. return;
  4150. }
  4151. }
  4152. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4153. {
  4154. KeyProcessed(Key, Shift);
  4155. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4156. }
  4157. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4158. if (IsCustomShortCut(CustomShortCut))
  4159. {
  4160. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4161. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4162. if (WinConfiguration->SharedBookmarks != NULL)
  4163. {
  4164. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4165. if ((Bookmark != NULL) &&
  4166. OpenBookmark(FCurrentSide, Bookmark))
  4167. {
  4168. KeyProcessed(Key, Shift);
  4169. }
  4170. }
  4171. }
  4172. }
  4173. TForm::KeyDown(Key, Shift);
  4174. }
  4175. //---------------------------------------------------------------------------
  4176. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4177. {
  4178. DebugAssert(Terminal != NULL);
  4179. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  4180. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  4181. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4182. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4183. bool SecurityEnabled = !SessionInfo.SecurityProtocolName.IsEmpty();
  4184. SessionStatusBar->Panels->Items[Offset + 0]->Enabled = SecurityEnabled;
  4185. // expanded from ?: to avoid memory leaks
  4186. if (SecurityEnabled)
  4187. {
  4188. SessionStatusBar->Panels->Items[Offset + 0]->Hint =
  4189. FMTLOAD(STATUS_SECURE, (SessionInfo.SecurityProtocolName));
  4190. }
  4191. else
  4192. {
  4193. SessionStatusBar->Panels->Items[Offset + 0]->Hint = LoadStr(STATUS_INSECURE);
  4194. }
  4195. if (FileSystemInfo.ProtocolName.IsEmpty())
  4196. {
  4197. SessionStatusBar->Panels->Items[Offset + 1]->Caption = SessionInfo.ProtocolName;
  4198. }
  4199. else
  4200. {
  4201. SessionStatusBar->Panels->Items[Offset + 1]->Caption = FileSystemInfo.ProtocolName;
  4202. }
  4203. SessionStatusBar->Panels->Items[Offset + 1]->Hint = LoadStr(STATUS_PROTOCOL_HINT);
  4204. SessionStatusBar->Panels->Items[Offset + 2]->Enabled =
  4205. (!SessionInfo.CSCompression.IsEmpty() || !SessionInfo.SCCompression.IsEmpty());
  4206. UnicodeString CSCompressionStr = DefaultStr(SessionInfo.CSCompression, LoadStr(NO_STR));
  4207. UnicodeString SCCompressionStr = DefaultStr(SessionInfo.SCCompression, LoadStr(NO_STR));
  4208. UnicodeString CompressionStr = CSCompressionStr;
  4209. if (CSCompressionStr != SCCompressionStr)
  4210. {
  4211. CompressionStr += UnicodeString(L"/") + SCCompressionStr;
  4212. }
  4213. SessionStatusBar->Panels->Items[Offset + 2]->Hint = FMTLOAD(STATUS_COMPRESSION_HINT, (CompressionStr));
  4214. SessionStatusBar->Panels->Items[Offset + 3]->Hint = LoadStr(STATUS_DURATION_HINT);
  4215. UpdateStatusBar();
  4216. }
  4217. //---------------------------------------------------------------------------
  4218. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4219. {
  4220. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4221. DebugAssert(SessionStatusBar != NULL);
  4222. if (!Terminal || !Terminal->Active || Terminal->Status < ssOpened)
  4223. {
  4224. // note: (Terminal->Status < sshReady) currently never happens here,
  4225. // so STATUS_CONNECTING is never used
  4226. SessionStatusBar->SimplePanel = true;
  4227. SessionStatusBar->SimpleText = LoadStr(
  4228. !Terminal || !Terminal->Active ? STATUS_NOT_CONNECTED : STATUS_CONNECTING);
  4229. }
  4230. else
  4231. {
  4232. DebugAssert(Terminal);
  4233. SessionStatusBar->SimplePanel = false;
  4234. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  4235. if (!FNote.IsEmpty())
  4236. {
  4237. SessionStatusBar->Panels->Items[0]->Caption = FNote;
  4238. }
  4239. else
  4240. {
  4241. UpdateStatusPanelText(SessionStatusBar->Panels->Items[0]);
  4242. }
  4243. SessionStatusBar->Panels->Items[0]->Hint = FNoteHints;
  4244. SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1]->Caption =
  4245. FormatDateTimeSpan(Configuration->TimeFormat, Now() - SessionInfo.LoginTime);
  4246. }
  4247. }
  4248. //---------------------------------------------------------------------------
  4249. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4250. {
  4251. Panel->Caption = L"";
  4252. }
  4253. //---------------------------------------------------------------------------
  4254. void __fastcall TCustomScpExplorerForm::Idle()
  4255. {
  4256. if (FShowing || FStandaloneEditing)
  4257. {
  4258. FEditorManager->Check();
  4259. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4260. // that needs to know if queue view is visible (and it may be closed after queue update)
  4261. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4262. }
  4263. if (FShowing)
  4264. {
  4265. if (!NonVisualDataModule->Busy &&
  4266. // Menu is opened or drag&drop is going on
  4267. (Mouse->Capture == NULL))
  4268. {
  4269. if (FRefreshRemoteDirectory)
  4270. {
  4271. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4272. {
  4273. Terminal->RefreshDirectory();
  4274. }
  4275. FRefreshRemoteDirectory = false;
  4276. }
  4277. if (FRefreshLocalDirectory)
  4278. {
  4279. ReloadLocalDirectory();
  4280. FRefreshLocalDirectory = false;
  4281. }
  4282. if (WinConfiguration->RefreshRemotePanel)
  4283. {
  4284. TManagedTerminal * ManagedTerminal =
  4285. dynamic_cast<TManagedTerminal *>(Terminal);
  4286. if ((ManagedTerminal != NULL) && (Terminal->Status == ssOpened) &&
  4287. (Now() - ManagedTerminal->DirectoryLoaded >
  4288. WinConfiguration->RefreshRemotePanelInterval))
  4289. {
  4290. RemoteDirView->ReloadDirectory();
  4291. }
  4292. }
  4293. }
  4294. }
  4295. if (FShowing || FStandaloneEditing)
  4296. {
  4297. if (FQueueStatusInvalidated)
  4298. {
  4299. UpdateQueueStatus(false);
  4300. }
  4301. RefreshQueueItems();
  4302. }
  4303. if (FShowing)
  4304. {
  4305. UpdateStatusBar();
  4306. }
  4307. FIgnoreNextDialogChar = 0;
  4308. }
  4309. //---------------------------------------------------------------------------
  4310. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4311. {
  4312. try
  4313. {
  4314. FUserActionTimer->Enabled = false;
  4315. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4316. {
  4317. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4318. {
  4319. FPendingQueueActionItem->ProcessUserAction();
  4320. }
  4321. }
  4322. }
  4323. __finally
  4324. {
  4325. FPendingQueueActionItem = NULL;
  4326. }
  4327. }
  4328. //---------------------------------------------------------------------------
  4329. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4330. {
  4331. if (WinConfiguration->MinimizeToTray)
  4332. {
  4333. UpdateTrayIcon();
  4334. FTrayIcon->Visible = true;
  4335. if (Visible)
  4336. {
  4337. ShowWindow(Handle, SW_HIDE);
  4338. }
  4339. }
  4340. }
  4341. //---------------------------------------------------------------------------
  4342. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4343. {
  4344. // WORKAROUND
  4345. // When restoring maximized window from minimization,
  4346. // rarely some controls do not align properly.
  4347. // Two instances seen (both for Commander):
  4348. // - When restoring, window is temporarily narrower (not maximized),
  4349. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4350. // Once maximized already, top dock shinks back, but the session PageControl,
  4351. // do not align up, leaving space between TopDock and PageControl.
  4352. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4353. for (int Index = 0; Index < ControlCount; Index++)
  4354. {
  4355. RealignControl(Controls[Index]);
  4356. }
  4357. if (FTrayIcon->Visible)
  4358. {
  4359. FTrayIcon->Visible = false;
  4360. if (Visible)
  4361. {
  4362. ShowWindow(Handle, SW_SHOW);
  4363. }
  4364. }
  4365. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4366. {
  4367. FNeedSession = false;
  4368. NonVisualDataModule->StartBusy();
  4369. try
  4370. {
  4371. NeedSession(false);
  4372. }
  4373. __finally
  4374. {
  4375. NonVisualDataModule->EndBusy();
  4376. }
  4377. }
  4378. }
  4379. //---------------------------------------------------------------------------
  4380. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4381. {
  4382. FTrayIcon->Hint = GetMainForm()->Caption;
  4383. }
  4384. //---------------------------------------------------------------------------
  4385. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4386. {
  4387. UpdateTrayIcon();
  4388. }
  4389. //---------------------------------------------------------------------------
  4390. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4391. {
  4392. // workaround
  4393. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4394. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4395. // But WM_ACTIVATEAPP message can be received even when
  4396. // the main window is minimized to the tray and internal editor window is focused
  4397. // (after another application was previously active)
  4398. if (::IsIconic(Handle))
  4399. {
  4400. if (!IsAppIconic())
  4401. {
  4402. SetAppIconic(true);
  4403. }
  4404. }
  4405. ::ApplicationRestore();
  4406. Application->BringToFront();
  4407. }
  4408. //---------------------------------------------------------------------------
  4409. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4410. {
  4411. RestoreApp();
  4412. }
  4413. //---------------------------------------------------------------------------
  4414. void __fastcall TCustomScpExplorerForm::NewSession(bool FromSite, const UnicodeString & SessionUrl)
  4415. {
  4416. if (OpenInNewWindow())
  4417. {
  4418. // todo: Pass FromSite
  4419. ExecuteNewInstance(SessionUrl);
  4420. }
  4421. else
  4422. {
  4423. TTerminalManager::Instance()->NewSession(FromSite, SessionUrl);
  4424. }
  4425. }
  4426. //---------------------------------------------------------------------------
  4427. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4428. {
  4429. UnicodeString SessionName = StoredSessions->HiddenPrefix + Terminal->SessionData->SessionName;
  4430. // current working directories become defaults here, what is not right
  4431. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4432. StoredSessions->NewSession(SessionName, SessionData.get());
  4433. // modified only, explicit
  4434. StoredSessions->Save(false, true);
  4435. // encode session name because of slashes in hierarchical sessions
  4436. return EncodeUrlString(SessionName);
  4437. }
  4438. //---------------------------------------------------------------------------
  4439. void __fastcall TCustomScpExplorerForm::DuplicateSession()
  4440. {
  4441. if (OpenInNewWindow())
  4442. {
  4443. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4444. }
  4445. else
  4446. {
  4447. // current working directories become defaults here, what is not right
  4448. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4449. TTerminalManager * Manager = TTerminalManager::Instance();
  4450. TTerminal * Terminal = Manager->NewTerminal(SessionData.get());
  4451. Manager->ActiveTerminal = Terminal;
  4452. }
  4453. }
  4454. //---------------------------------------------------------------------------
  4455. void __fastcall TCustomScpExplorerForm::RenameSession()
  4456. {
  4457. UnicodeString Name = Terminal->SessionData->SessionName;
  4458. if (InputDialog(LoadStr(RENAME_SESSION_TITLE), LoadStr(RENAME_SESSION_PROMPT), Name, HELP_SESSION_RENAME))
  4459. {
  4460. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  4461. TSessionData::ValidateName(Name);
  4462. // This is inconsistent with how color (for example) is handled.
  4463. Terminal->SessionData->Name = Name;
  4464. UpdateControls();
  4465. // Add/Remove distinguishing paths from sessions of the same name.
  4466. DoTerminalListChanged();
  4467. }
  4468. }
  4469. //---------------------------------------------------------------------------
  4470. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  4471. {
  4472. DebugAssert(Queue != NULL);
  4473. bool Result = Queue->IsEmpty;
  4474. if (!Result)
  4475. {
  4476. SetFocus();
  4477. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  4478. }
  4479. return Result;
  4480. }
  4481. //---------------------------------------------------------------------------
  4482. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  4483. {
  4484. return CanCloseQueue(FQueue);
  4485. }
  4486. //---------------------------------------------------------------------------
  4487. void __fastcall TCustomScpExplorerForm::CloseSession()
  4488. {
  4489. if (CanCloseQueue())
  4490. {
  4491. TTerminalManager::Instance()->FreeActiveTerminal();
  4492. }
  4493. }
  4494. //---------------------------------------------------------------------------
  4495. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  4496. {
  4497. if (OpenInNewWindow())
  4498. {
  4499. // encode session name because of slashes in hierarchical sessions
  4500. ExecuteNewInstance(EncodeUrlString(Data->Name));
  4501. }
  4502. else
  4503. {
  4504. TTerminalManager * Manager = TTerminalManager::Instance();
  4505. TTerminal * Terminal = Manager->NewTerminal(Data);
  4506. Manager->ActiveTerminal = Terminal;
  4507. }
  4508. }
  4509. //---------------------------------------------------------------------------
  4510. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  4511. {
  4512. if (OpenInNewWindow())
  4513. {
  4514. ExecuteNewInstance(Name);
  4515. }
  4516. else
  4517. {
  4518. TTerminalManager * Manager = TTerminalManager::Instance();
  4519. std::unique_ptr<TObjectList> DataList(new TObjectList());
  4520. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  4521. Manager->ActiveTerminal = Manager->NewTerminals(DataList.get());
  4522. }
  4523. }
  4524. //---------------------------------------------------------------------------
  4525. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  4526. bool &CanClose)
  4527. {
  4528. if (Terminal != NULL)
  4529. {
  4530. if (Terminal->Active && WinConfiguration->ConfirmClosingSession)
  4531. {
  4532. unsigned int Result;
  4533. TMessageParams Params(mpNeverAskAgainCheck);
  4534. UnicodeString Message;
  4535. int Answers = qaOK | qaCancel;
  4536. if (TTerminalManager::Instance()->Count > 1)
  4537. {
  4538. if (!WinConfiguration->AutoSaveWorkspace)
  4539. {
  4540. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE2);
  4541. Answers = qaYes | qaNo | qaCancel;
  4542. }
  4543. else
  4544. {
  4545. Message = MainInstructions(LoadStr(CLOSE_SESSIONS));
  4546. }
  4547. }
  4548. else
  4549. {
  4550. Message = MainInstructions(FMTLOAD(CLOSE_SESSION, (Terminal->SessionData->SessionName)));
  4551. }
  4552. if (WinConfiguration->AutoSaveWorkspace)
  4553. {
  4554. Message =
  4555. FORMAT("%s\n\n%s", (Message,
  4556. FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()))));
  4557. }
  4558. SetFocus();
  4559. Result = MessageDialog(Message, qtConfirmation,
  4560. Answers, HELP_NONE, &Params);
  4561. if (Result == qaNeverAskAgain)
  4562. {
  4563. WinConfiguration->ConfirmClosingSession = false;
  4564. }
  4565. if (Result == qaNo)
  4566. {
  4567. CanClose = SaveWorkspace(true);
  4568. // note that the workspace will be saved redundatly again from FormClose
  4569. }
  4570. else
  4571. {
  4572. CanClose =
  4573. (Result == qaOK) ||
  4574. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  4575. (Result == qaNeverAskAgain);
  4576. }
  4577. }
  4578. if (CanClose)
  4579. {
  4580. CanClose = CanCloseQueue();
  4581. }
  4582. }
  4583. if (CanClose)
  4584. {
  4585. CanClose =
  4586. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  4587. FEditorManager->CloseExternalFilesWithoutProcess();
  4588. if (CanClose)
  4589. {
  4590. while (CanClose && (FLocalEditors->Count > 0))
  4591. {
  4592. int PrevCount = FLocalEditors->Count;
  4593. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  4594. CanClose = (FLocalEditors->Count < PrevCount);
  4595. }
  4596. if (CanClose)
  4597. {
  4598. CanClose = FEditorManager->Empty(true);
  4599. if (!CanClose)
  4600. {
  4601. SetFocus();
  4602. CanClose =
  4603. (MessageDialog(
  4604. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  4605. }
  4606. }
  4607. }
  4608. }
  4609. }
  4610. //---------------------------------------------------------------------------
  4611. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  4612. {
  4613. TForm * Form = dynamic_cast<TForm *>(Sender);
  4614. DebugAssert(Form != NULL);
  4615. Form->Close();
  4616. }
  4617. //---------------------------------------------------------------------------
  4618. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  4619. {
  4620. TForm * Form = dynamic_cast<TForm *>(Sender);
  4621. delete Form;
  4622. }
  4623. //---------------------------------------------------------------------------
  4624. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  4625. {
  4626. while (FLocalEditors->Count > 0)
  4627. {
  4628. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  4629. }
  4630. }
  4631. //---------------------------------------------------------------------------
  4632. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  4633. TObject *Sender)
  4634. {
  4635. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  4636. try
  4637. {
  4638. SetProperties(osRemote, FileList);
  4639. }
  4640. __finally
  4641. {
  4642. delete FileList;
  4643. }
  4644. }
  4645. //---------------------------------------------------------------------------
  4646. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  4647. {
  4648. if (value)
  4649. {
  4650. if (Component == fcCustomCommandsBand)
  4651. {
  4652. UpdateCustomCommandsToolbar();
  4653. }
  4654. }
  4655. }
  4656. //---------------------------------------------------------------------------
  4657. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  4658. {
  4659. TControl * Control = GetComponent(Component);
  4660. DebugAssert(Control);
  4661. bool Changed = (Control->Visible != value);
  4662. if (Changed)
  4663. {
  4664. ComponentShowing(Component, value);
  4665. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  4666. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  4667. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  4668. if (value)
  4669. {
  4670. int RemainingHeight = Control->Parent->ClientHeight;
  4671. int RemainingWidth = Control->Parent->ClientWidth;
  4672. for (int i = 0; i < Control->Parent->ControlCount; i++)
  4673. {
  4674. TControl * ChildControl = Control->Parent->Controls[i];
  4675. if (ChildControl->Visible)
  4676. {
  4677. switch (ChildControl->Align)
  4678. {
  4679. case alTop:
  4680. case alBottom:
  4681. RemainingHeight -= ChildControl->Height;
  4682. break;
  4683. case alLeft:
  4684. case alRight:
  4685. RemainingWidth -= ChildControl->Width;
  4686. break;
  4687. }
  4688. }
  4689. }
  4690. int Reserve = ScaleByTextHeight(this, 32);
  4691. // queue in explorer, trees in commander
  4692. if (Control->Height > RemainingHeight - Reserve)
  4693. {
  4694. Control->Height = RemainingHeight / 2;
  4695. }
  4696. if (Control->Width > RemainingWidth - Reserve)
  4697. {
  4698. Control->Width = RemainingWidth / 2;
  4699. }
  4700. }
  4701. Control->Visible = value;
  4702. if (WasFocused && Visible)
  4703. {
  4704. DirView(osCurrent)->SetFocus();
  4705. }
  4706. FixControlsPlacement();
  4707. }
  4708. }
  4709. //---------------------------------------------------------------------------
  4710. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  4711. {
  4712. TControl * Control = GetComponent(Component);
  4713. if (Control == NULL)
  4714. {
  4715. return false;
  4716. }
  4717. else
  4718. {
  4719. return Control->Visible;
  4720. }
  4721. }
  4722. //---------------------------------------------------------------------------
  4723. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  4724. {
  4725. bool Result;
  4726. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  4727. {
  4728. Result = !IsUWP();
  4729. }
  4730. else
  4731. {
  4732. Result = true;
  4733. }
  4734. return Result;
  4735. }
  4736. //---------------------------------------------------------------------------
  4737. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  4738. {
  4739. if (DirView(osOther)->ItemFocused != NULL)
  4740. {
  4741. DirView(osOther)->ItemFocused->MakeVisible(false);
  4742. }
  4743. QueueSplitter->Visible = QueuePanel->Visible;
  4744. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  4745. }
  4746. //---------------------------------------------------------------------------
  4747. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  4748. {
  4749. switch (Component) {
  4750. case fcStatusBar: return RemoteStatusBar;
  4751. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  4752. case fcQueueView: return QueuePanel;
  4753. case fcQueueToolbar: return QueueDock;
  4754. case fcRemoteTree: return RemoteDrivePanel;
  4755. case fcSessionsTabs: return SessionsPageControl;
  4756. default: return NULL;
  4757. }
  4758. }
  4759. //---------------------------------------------------------------------------
  4760. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  4761. TObject *Sender, TListColumn *Column, TPoint &Point)
  4762. {
  4763. DebugAssert(NonVisualDataModule && Column && Sender);
  4764. NonVisualDataModule->ListColumn = Column;
  4765. TPopupMenu * DirViewColumnMenu;
  4766. if (dynamic_cast<TUnixDirView *>(Sender) != NULL)
  4767. {
  4768. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  4769. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible =
  4770. (Column->Index == uvName);
  4771. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible =
  4772. (Column->Index == uvSize);
  4773. }
  4774. else
  4775. {
  4776. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  4777. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible =
  4778. (Column->Index == dvName);
  4779. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible =
  4780. (Column->Index == dvSize);
  4781. }
  4782. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  4783. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  4784. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  4785. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  4786. }
  4787. //---------------------------------------------------------------------------
  4788. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  4789. TObject *Sender, TListItem *Item, bool &AllowExec)
  4790. {
  4791. DoDirViewExecFile(Sender, Item, AllowExec);
  4792. }
  4793. //---------------------------------------------------------------------------
  4794. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  4795. TListItem * Item, bool & AllowExec)
  4796. {
  4797. DebugAssert(Sender && Item && Configuration);
  4798. DebugAssert(AllowExec);
  4799. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  4800. bool Remote = (ADirView == DirView(osRemote)) && !IsSideLocalBrowser(osRemote);
  4801. bool ResolvedSymlinks = !Remote || Terminal->ResolvingSymlinks;
  4802. TOperationSide Side = (Remote ? osRemote : osLocal); // TODO
  4803. // Anything special is done on double click only (not on "open" indicated by FForceExecution),
  4804. // on files only (not directories)
  4805. // and only when symlinks are resolved (apply to remote panel only)
  4806. if (!ADirView->ItemIsDirectory(Item) &&
  4807. (ResolvedSymlinks || FForceExecution || Terminal->IsEncryptingFiles()))
  4808. {
  4809. if ((WinConfiguration->DoubleClickAction != dcaOpen) &&
  4810. !FForceExecution &&
  4811. (ResolvedSymlinks || Terminal->IsEncryptingFiles()))
  4812. {
  4813. if (WinConfiguration->DoubleClickAction == dcaCopy)
  4814. {
  4815. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  4816. UnlockWindow();
  4817. try
  4818. {
  4819. ExecuteFileOperation(
  4820. foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  4821. }
  4822. __finally
  4823. {
  4824. LockWindow();
  4825. }
  4826. AllowExec = false;
  4827. }
  4828. else if (WinConfiguration->DoubleClickAction == dcaEdit)
  4829. {
  4830. if (!Remote || !WinConfiguration->DisableOpenEdit)
  4831. {
  4832. ExecuteFile(Side, efDefaultEditor);
  4833. AllowExec = false;
  4834. }
  4835. }
  4836. else
  4837. {
  4838. DebugFail();
  4839. }
  4840. }
  4841. // if we have not done anything special, fall back to default behavior
  4842. if (AllowExec)
  4843. {
  4844. if (Remote && !WinConfiguration->DisableOpenEdit)
  4845. {
  4846. ExecuteFile(osRemote, efShell);
  4847. AllowExec = false;
  4848. }
  4849. }
  4850. }
  4851. }
  4852. //---------------------------------------------------------------------------
  4853. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  4854. {
  4855. return ((Side == osRemote) || (Side == osCurrent));
  4856. }
  4857. //---------------------------------------------------------------------------
  4858. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  4859. {
  4860. DebugFail();
  4861. }
  4862. //---------------------------------------------------------------------------
  4863. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  4864. {
  4865. DebugFail();
  4866. }
  4867. //---------------------------------------------------------------------------
  4868. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  4869. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, bool UseDefaults)
  4870. {
  4871. TSynchronizeParamType Params;
  4872. Params.LocalDirectory = LocalDirectory;
  4873. Params.RemoteDirectory = RemoteDirectory;
  4874. int UnusedParams =
  4875. (GUIConfiguration->SynchronizeParams &
  4876. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize));
  4877. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  4878. Params.Options = GUIConfiguration->SynchronizeOptions;
  4879. bool SaveSettings = false;
  4880. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  4881. &DoSynchronizeTooManyDirectories);
  4882. DebugAssert(FSynchronizeController == NULL);
  4883. FSynchronizeController = &Controller;
  4884. bool Result;
  4885. try
  4886. {
  4887. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4888. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  4889. int Options =
  4890. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  4891. DebugAssert(FOnFeedSynchronizeError == NULL);
  4892. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  4893. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  4894. FOnFeedSynchronizeError, SynchronizeInNewWindow, UseDefaults);
  4895. if (Result)
  4896. {
  4897. if (SaveSettings)
  4898. {
  4899. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  4900. GUIConfiguration->SynchronizeOptions = Params.Options;
  4901. }
  4902. else
  4903. {
  4904. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  4905. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  4906. FLAGSET(Params.Options, soSynchronize))
  4907. {
  4908. GUIConfiguration->SynchronizeOptions =
  4909. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  4910. soSynchronize;
  4911. }
  4912. }
  4913. LocalDirectory = Params.LocalDirectory;
  4914. RemoteDirectory = Params.RemoteDirectory;
  4915. }
  4916. }
  4917. __finally
  4918. {
  4919. FSynchronizeController = NULL;
  4920. DebugAssert(FOnFeedSynchronizeError == NULL);
  4921. FOnFeedSynchronizeError = NULL;
  4922. }
  4923. return Result;
  4924. }
  4925. //---------------------------------------------------------------------------
  4926. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  4927. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  4928. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  4929. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  4930. TSynchronizeOptions * Options, bool Full)
  4931. {
  4932. // Keep-up-to-date mode
  4933. if (Terminal->Status == ssOpened)
  4934. {
  4935. try
  4936. {
  4937. int PParams = Params.Params;
  4938. if (!Full)
  4939. {
  4940. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  4941. if (FLAGSET(Params.Options, soRecurse))
  4942. {
  4943. PParams |= TTerminal::spSubDirs;
  4944. }
  4945. }
  4946. else
  4947. {
  4948. // if keepuptodate is non-recursive,
  4949. // full sync before has to be non-recursive as well
  4950. if (FLAGCLEAR(Params.Options, soRecurse))
  4951. {
  4952. PParams |= TTerminal::spNoRecurse;
  4953. }
  4954. }
  4955. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  4956. PParams, Checklist, Options);
  4957. }
  4958. catch (Exception & E)
  4959. {
  4960. if (FLAGSET(Params.Options, soContinueOnError) && Terminal->Active &&
  4961. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  4962. {
  4963. // noop, already logged in MoreMessageDialog
  4964. }
  4965. else
  4966. {
  4967. ShowExtendedExceptionEx(Terminal, &E);
  4968. throw;
  4969. }
  4970. }
  4971. }
  4972. }
  4973. //---------------------------------------------------------------------------
  4974. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  4975. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  4976. const UnicodeString ErrorStr)
  4977. {
  4978. if (!Directory.IsEmpty())
  4979. {
  4980. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  4981. }
  4982. else
  4983. {
  4984. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  4985. }
  4986. }
  4987. //---------------------------------------------------------------------------
  4988. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  4989. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  4990. {
  4991. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  4992. {
  4993. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  4994. }
  4995. else
  4996. {
  4997. TMessageParams Params(mpNeverAskAgainCheck);
  4998. unsigned int Result = MessageDialog(
  4999. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5000. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5001. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5002. {
  5003. MaxDirectories *= 2;
  5004. if (Result == qaNeverAskAgain)
  5005. {
  5006. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5007. }
  5008. }
  5009. else
  5010. {
  5011. Abort();
  5012. }
  5013. }
  5014. }
  5015. //---------------------------------------------------------------------------
  5016. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5017. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5018. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5019. TSynchronizeOptions * Options)
  5020. {
  5021. // Keep-up-to-date mode
  5022. DebugAssert(!FAutoOperation);
  5023. void * BatchStorage;
  5024. BatchStart(BatchStorage);
  5025. FAutoOperation = true;
  5026. bool AnyOperation = false;
  5027. TDateTime StartTime = Now();
  5028. TSynchronizeChecklist * AChecklist = NULL;
  5029. try
  5030. {
  5031. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, true);
  5032. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5033. {
  5034. FSynchronizeProgressForm->Start();
  5035. }
  5036. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5037. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5038. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5039. Options);
  5040. SAFE_DESTROY(FSynchronizeProgressForm);
  5041. AnyOperation = (AChecklist->CheckedCount > 0);
  5042. if (AnyOperation)
  5043. {
  5044. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5045. CreateProgressForm(&SynchronizeProgress);
  5046. try
  5047. {
  5048. Terminal->SynchronizeApply(
  5049. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5050. SynchronizeProcessedItem, NULL, NULL, NULL);
  5051. }
  5052. __finally
  5053. {
  5054. DestroyProgressForm();
  5055. }
  5056. }
  5057. }
  5058. __finally
  5059. {
  5060. if (Checklist == NULL)
  5061. {
  5062. delete AChecklist;
  5063. }
  5064. else
  5065. {
  5066. *Checklist = AChecklist;
  5067. }
  5068. FAutoOperation = false;
  5069. SAFE_DESTROY(FSynchronizeProgressForm);
  5070. BatchEnd(BatchStorage);
  5071. ReloadLocalDirectory();
  5072. if (AnyOperation)
  5073. {
  5074. OperationComplete(StartTime);
  5075. }
  5076. }
  5077. }
  5078. //---------------------------------------------------------------------------
  5079. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5080. {
  5081. // can be called from command line
  5082. return Visible &&
  5083. ((DirView(osOther)->SelCount > 0) ||
  5084. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5085. }
  5086. //---------------------------------------------------------------------------
  5087. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5088. {
  5089. LogSynchronizeEvent(Terminal, Message);
  5090. }
  5091. //---------------------------------------------------------------------------
  5092. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5093. int Params, TSynchronizeOptions & Options)
  5094. {
  5095. DebugAssert(!IsLocalBrowserMode());
  5096. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5097. {
  5098. Options.Filter = new TStringList();
  5099. Options.Filter->CaseSensitive = false;
  5100. Options.Filter->Duplicates = Types::dupAccept;
  5101. if (DirView(osRemote)->SelCount > 0)
  5102. {
  5103. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5104. }
  5105. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5106. {
  5107. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5108. }
  5109. Options.Filter->Sort();
  5110. }
  5111. }
  5112. //---------------------------------------------------------------------------
  5113. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5114. {
  5115. TCopyParamType Defaults;
  5116. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5117. ConfigStorage->AccessMode = smRead;
  5118. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false, false))
  5119. {
  5120. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5121. }
  5122. ConfigStorage.reset(NULL);
  5123. std::unique_ptr<TStringList> Options(new TStringList());
  5124. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5125. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5126. UnicodeString Result;
  5127. if (Options->Count > 0)
  5128. {
  5129. Result =
  5130. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5131. }
  5132. return Result;
  5133. }
  5134. //---------------------------------------------------------------------------
  5135. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5136. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5137. {
  5138. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5139. UnicodeString AdditionalParams =
  5140. FORMAT(L"%s \"%s\" \"%s\" %d %d %s%s", (
  5141. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5142. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options,
  5143. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5144. SerializeCopyParamForCommandLine(CopyParams)));
  5145. ExecuteNewInstance(SessionName, AdditionalParams);
  5146. }
  5147. //---------------------------------------------------------------------------
  5148. struct TSynchronizeParams
  5149. {
  5150. UnicodeString LocalDirectory;
  5151. UnicodeString RemoteDirectory;
  5152. TSynchronizeMode Mode;
  5153. TSynchronizeChecklist * Checklist;
  5154. int Params;
  5155. TCopyParamType * CopyParam;
  5156. TDateTime CollectElapsed;
  5157. TDateTime * StartTime;
  5158. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5159. };
  5160. //---------------------------------------------------------------------------
  5161. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5162. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5163. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5164. {
  5165. DebugAssert(!FAutoOperation);
  5166. void * BatchStorage;
  5167. BatchStart(BatchStorage);
  5168. FAutoOperation = true;
  5169. TFileOperationStatistics Statistics;
  5170. TDateTime Start = Now();
  5171. try
  5172. {
  5173. Params.OnProcessedItem = OnProcessedItem;
  5174. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5175. CreateProgressForm(&SynchronizeProgress);
  5176. Terminal->SynchronizeApply(
  5177. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5178. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5179. &Statistics);
  5180. }
  5181. __finally
  5182. {
  5183. Params.OnProcessedItem = NULL;
  5184. FAutoOperation = false;
  5185. DestroyProgressForm();
  5186. BatchEnd(BatchStorage);
  5187. ReloadLocalDirectory();
  5188. }
  5189. if (WinConfiguration->SynchronizeSummary)
  5190. {
  5191. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5192. // The statistics should be 0 anyway in this case
  5193. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5194. {
  5195. Message += L"\n";
  5196. if (Statistics.FilesUploaded > 0)
  5197. {
  5198. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5199. }
  5200. if (Statistics.FilesDownloaded > 0)
  5201. {
  5202. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5203. }
  5204. if (Statistics.FilesDeletedLocal > 0)
  5205. {
  5206. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5207. }
  5208. if (Statistics.FilesDeletedRemote > 0)
  5209. {
  5210. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5211. }
  5212. }
  5213. TDateTime Elapsed = (Now() - Start);
  5214. Message +=
  5215. L"\n" +
  5216. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Configuration->TimeFormat, Params.CollectElapsed))) + L"\n" +
  5217. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Configuration->TimeFormat, Elapsed)));
  5218. TMessageParams Params(mpNeverAskAgainCheck);
  5219. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5220. if (Result == qaNeverAskAgain)
  5221. {
  5222. WinConfiguration->SynchronizeSummary = false;
  5223. }
  5224. }
  5225. }
  5226. //---------------------------------------------------------------------------
  5227. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5228. {
  5229. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5230. {
  5231. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5232. }
  5233. // Not set in keep-up-to-date mode - Synchronize() method
  5234. if (Token != NULL)
  5235. {
  5236. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5237. if (Params.OnProcessedItem != NULL)
  5238. {
  5239. Params.OnProcessedItem(NULL, ChecklistItem);
  5240. }
  5241. }
  5242. }
  5243. //---------------------------------------------------------------------------
  5244. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5245. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5246. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5247. {
  5248. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5249. *Params.StartTime = Now();
  5250. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5251. }
  5252. //---------------------------------------------------------------------------
  5253. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5254. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5255. {
  5256. // terminal can be already closed (e.g. dropped connection)
  5257. if (Terminal != NULL)
  5258. {
  5259. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5260. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5261. }
  5262. }
  5263. //---------------------------------------------------------------------------
  5264. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5265. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5266. {
  5267. DebugAssert(!IsLocalBrowserMode());
  5268. TAutoBatch AutoBatch(this);
  5269. TAutoFlag AutoOperationFlag(FAutoOperation);
  5270. if (Side == osRemote)
  5271. {
  5272. std::unique_ptr<TStrings> FileList(new TStringList());
  5273. FileList->AddObject(FileName, RemoteFile);
  5274. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5275. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5276. RemoteDirView->SaveSelection();
  5277. RemoteDirView->SaveSelectedNames();
  5278. try
  5279. {
  5280. Terminal->MoveFiles(FileList.get(), Target, FileMask);
  5281. }
  5282. catch(...)
  5283. {
  5284. RemoteDirView->DiscardSavedSelection();
  5285. throw;
  5286. }
  5287. RemoteDirView->RestoreSelection();
  5288. }
  5289. else if (DebugAlwaysTrue(Side == osLocal))
  5290. {
  5291. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5292. {
  5293. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5294. }
  5295. UnicodeString Directory = ExtractFileDir(FileName);
  5296. ReloadLocalDirectory(Directory);
  5297. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5298. if (!SamePaths(Directory, NewDirectory))
  5299. {
  5300. ReloadLocalDirectory(NewDirectory);
  5301. }
  5302. }
  5303. }
  5304. //---------------------------------------------------------------------------
  5305. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  5306. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  5307. const TCopyParamType * CopyParams)
  5308. {
  5309. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5310. UnicodeString AdditionalParams =
  5311. FORMAT(L"%s \"%s\" \"%s\" %d %d %s%s", (
  5312. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  5313. LocalDirectory, RemoteDirectory, Mode, Params,
  5314. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5315. SerializeCopyParamForCommandLine(CopyParams)));
  5316. ExecuteNewInstance(SessionName, AdditionalParams);
  5317. }
  5318. //---------------------------------------------------------------------------
  5319. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  5320. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  5321. TSynchronizeMode & Mode, int Params, bool & SaveMode, bool UseDefaults)
  5322. {
  5323. int Result;
  5324. bool SaveSettings = false;
  5325. int Options =
  5326. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  5327. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  5328. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5329. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  5330. bool Continue =
  5331. UseDefaults ||
  5332. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  5333. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow);
  5334. if (Continue)
  5335. {
  5336. Configuration->Usage->Inc(L"Synchronizations");
  5337. UpdateCopyParamCounters(CopyParam);
  5338. TSynchronizeOptions SynchronizeOptions;
  5339. GetSynchronizeOptions(Params, SynchronizeOptions);
  5340. if (SaveSettings)
  5341. {
  5342. GUIConfiguration->SynchronizeParams = Params;
  5343. }
  5344. else
  5345. {
  5346. SaveMode = false;
  5347. }
  5348. TDateTime StartTime = Now();
  5349. TSynchronizeChecklist * Checklist = NULL;
  5350. try
  5351. {
  5352. DebugAssert(!FAutoOperation);
  5353. FAutoOperation = true;
  5354. try
  5355. {
  5356. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, true);
  5357. FSynchronizeProgressForm->Start();
  5358. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5359. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5360. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5361. &SynchronizeOptions);
  5362. }
  5363. __finally
  5364. {
  5365. FAutoOperation = false;
  5366. SAFE_DESTROY(FSynchronizeProgressForm);
  5367. }
  5368. TSynchronizeParams SynchronizeParams;
  5369. SynchronizeParams.LocalDirectory = LocalDirectory;
  5370. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  5371. SynchronizeParams.Mode = Mode;
  5372. SynchronizeParams.CopyParam = &CopyParam;
  5373. SynchronizeParams.Params = Params;
  5374. SynchronizeParams.Checklist = Checklist;
  5375. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  5376. SynchronizeParams.StartTime = &StartTime;
  5377. SynchronizeParams.OnProcessedItem = NULL;
  5378. Result = Checklist->Count;
  5379. if (Checklist->Count > 0)
  5380. {
  5381. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  5382. {
  5383. if (!DoSynchronizeChecklistDialog(
  5384. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  5385. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, &SynchronizeParams))
  5386. {
  5387. Result = -1;
  5388. }
  5389. }
  5390. else
  5391. {
  5392. FullSynchronize(SynchronizeParams, NULL, NULL);
  5393. }
  5394. }
  5395. else
  5396. {
  5397. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  5398. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  5399. }
  5400. }
  5401. __finally
  5402. {
  5403. delete Checklist;
  5404. }
  5405. OperationComplete(StartTime);
  5406. }
  5407. else
  5408. {
  5409. Result = -1;
  5410. }
  5411. return Result;
  5412. }
  5413. //---------------------------------------------------------------------------
  5414. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  5415. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  5416. bool & Continue, bool Collect)
  5417. {
  5418. if (Collect)
  5419. {
  5420. DebugAssert(FSynchronizeProgressForm != NULL);
  5421. if (!FSynchronizeProgressForm->Started)
  5422. {
  5423. FSynchronizeProgressForm->Start();
  5424. }
  5425. FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Continue);
  5426. }
  5427. else
  5428. {
  5429. DebugAssert(FSynchronizeProgressForm == NULL);
  5430. DebugAssert(FProgressForm != NULL);
  5431. }
  5432. }
  5433. //---------------------------------------------------------------------------
  5434. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  5435. {
  5436. UnicodeString FullFileName = AbsolutePath(FTerminal->CurrentDirectory, FileName);
  5437. TRemoteFile * File = NULL;
  5438. Terminal->ReadFile(FullFileName, File);
  5439. if (File != NULL)
  5440. {
  5441. std::unique_ptr<TRemoteFile> FileOwner(File);
  5442. TAutoFlag Flag(FStandaloneEditing);
  5443. ExecuteRemoteFile(FullFileName, File, efInternalEditor);
  5444. Application->ShowMainForm = false;
  5445. Application->Run();
  5446. }
  5447. }
  5448. //---------------------------------------------------------------------------
  5449. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory()
  5450. {
  5451. DebugFail();
  5452. }
  5453. //---------------------------------------------------------------------------
  5454. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  5455. {
  5456. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  5457. SessionData->Assign(Terminal->SessionData);
  5458. UpdateSessionData(SessionData.get());
  5459. Terminal->UpdateSessionCredentials(SessionData.get());
  5460. if (!Terminal->SessionData->HasSessionName())
  5461. {
  5462. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  5463. // once IsWorkspace is cleared
  5464. SessionData->Name = UnicodeString();
  5465. SessionData->IsWorkspace = false;
  5466. }
  5467. return SessionData.release();
  5468. }
  5469. //---------------------------------------------------------------------------
  5470. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  5471. {
  5472. TSessionData * SessionData = CloneCurrentSessionData();
  5473. try
  5474. {
  5475. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  5476. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  5477. }
  5478. __finally
  5479. {
  5480. delete SessionData;
  5481. }
  5482. }
  5483. //---------------------------------------------------------------------------
  5484. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  5485. {
  5486. TTerminalManager * Manager = TTerminalManager::Instance();
  5487. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5488. if (DebugAlwaysTrue(Terminal != NULL))
  5489. {
  5490. // Update (Managed)Terminal->StateData
  5491. UpdateTerminal(Terminal);
  5492. }
  5493. Manager->SaveWorkspace(DataList.get());
  5494. return DataList.release();
  5495. }
  5496. //---------------------------------------------------------------------------
  5497. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  5498. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  5499. {
  5500. WinConfiguration->LastWorkspace = Name;
  5501. if (!SavePasswords)
  5502. {
  5503. for (int Index = 0; Index < DataList->Count; Index++)
  5504. {
  5505. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  5506. if (SessionData->Link.IsEmpty())
  5507. {
  5508. SessionData->ClearSessionPasswords();
  5509. }
  5510. }
  5511. }
  5512. StoredSessions->NewWorkspace(Name, DataList);
  5513. // modified only
  5514. StoredSessions->Save(false, Explicit);
  5515. }
  5516. //---------------------------------------------------------------------------
  5517. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  5518. {
  5519. return
  5520. DefaultStr(WinConfiguration->LastWorkspace,
  5521. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  5522. }
  5523. //---------------------------------------------------------------------------
  5524. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  5525. {
  5526. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  5527. bool AnyNonStoredSessionWithPassword = false;
  5528. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  5529. bool AllNonStoredSessionsAnonymous = true;
  5530. TTerminalManager * Manager = TTerminalManager::Instance();
  5531. for (int Index = 0; Index < DataList->Count; Index++)
  5532. {
  5533. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  5534. if (SessionData->Link.IsEmpty())
  5535. {
  5536. if (SessionData->HasAnySessionPassword())
  5537. {
  5538. AnyNonStoredSessionWithPassword = true;
  5539. if (!Manager->Terminals[Index]->SessionData->IsWorkspace)
  5540. {
  5541. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  5542. }
  5543. }
  5544. if (!SameText(SessionData->UserName, AnonymousUserName))
  5545. {
  5546. AllNonStoredSessionsAnonymous = false;
  5547. }
  5548. }
  5549. }
  5550. bool SavePasswords;
  5551. bool * PSavePasswords;
  5552. bool NotRecommendedSavingPasswords =
  5553. !CustomWinConfiguration->UseMasterPassword &&
  5554. !AllNonStoredSessionsAnonymous;
  5555. if (Configuration->DisablePasswordStoring ||
  5556. !AnyNonStoredSessionWithPassword)
  5557. {
  5558. PSavePasswords = NULL;
  5559. SavePasswords = false;
  5560. }
  5561. else
  5562. {
  5563. PSavePasswords = &SavePasswords;
  5564. SavePasswords =
  5565. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  5566. !NotRecommendedSavingPasswords;
  5567. }
  5568. UnicodeString Name = WorkspaceName();
  5569. bool CreateShortcut = false;
  5570. bool Result =
  5571. DoSaveWorkspaceDialog(
  5572. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  5573. EnableAutoSave);
  5574. if (Result)
  5575. {
  5576. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  5577. if (CreateShortcut)
  5578. {
  5579. TOperationVisualizer Visualizer;
  5580. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  5581. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  5582. }
  5583. if (EnableAutoSave)
  5584. {
  5585. WinConfiguration->AutoSaveWorkspace = true;
  5586. WinConfiguration->AutoWorkspace = Name;
  5587. if (PSavePasswords != NULL)
  5588. {
  5589. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  5590. }
  5591. }
  5592. }
  5593. return Result;
  5594. }
  5595. //---------------------------------------------------------------------------
  5596. void __fastcall TCustomScpExplorerForm::UpdateTerminal(TTerminal * Terminal)
  5597. {
  5598. DebugAssert(!IsLocalBrowserMode());
  5599. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  5600. DebugAssert(ManagedTerminal != NULL);
  5601. SAFE_DESTROY(ManagedTerminal->RemoteExplorerState);
  5602. if (WinConfiguration->PreservePanelState)
  5603. {
  5604. ManagedTerminal->RemoteExplorerState = RemoteDirView->SaveState();
  5605. }
  5606. UpdateSessionData(ManagedTerminal->StateData);
  5607. }
  5608. //---------------------------------------------------------------------------
  5609. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  5610. {
  5611. // Keep in sync with TSessionData::CopyStateData
  5612. DebugAssert(!IsLocalBrowserMode());
  5613. DebugAssert(Data != NULL);
  5614. // This is inconsistent with how color (for example) is handled.
  5615. Data->Name = Terminal->SessionData->Name;
  5616. // cannot use RemoteDirView->Path, because it is empty if connection
  5617. // was already closed
  5618. // also only peek, we may not be connected at all atm
  5619. // so make sure we do not try retrieving current directory from the server
  5620. // (particularly with FTP)
  5621. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  5622. if (!ACurrentDirectory.IsEmpty())
  5623. {
  5624. Data->RemoteDirectory = ACurrentDirectory;
  5625. }
  5626. Data->Color = SessionColor;
  5627. }
  5628. //---------------------------------------------------------------------------
  5629. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  5630. {
  5631. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  5632. DebugAssert(Toolbar != NULL);
  5633. for (int i = 0; i < Toolbar->Items->Count; i++)
  5634. {
  5635. TTBXCustomDropDownItem * DropDownItem;
  5636. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  5637. if (DropDownItem != NULL)
  5638. {
  5639. ToolbarItemResize(DropDownItem,
  5640. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  5641. Toolbar->NonClientWidth);
  5642. break;
  5643. }
  5644. }
  5645. }
  5646. //---------------------------------------------------------------------------
  5647. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  5648. {
  5649. Item->EditWidth = Width;
  5650. }
  5651. //---------------------------------------------------------------------------
  5652. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  5653. TTBCustomToolbar * Toolbar, TPoint & ASize)
  5654. {
  5655. for (int i = 0; i < Toolbar->Items->Count; i++)
  5656. {
  5657. TTBXCustomDropDownItem * DropDownItem;
  5658. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  5659. if (DropDownItem != NULL)
  5660. {
  5661. ASize.x -= DropDownItem->EditWidth;
  5662. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  5663. }
  5664. }
  5665. }
  5666. //---------------------------------------------------------------------------
  5667. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  5668. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  5669. {
  5670. if (WinConfiguration->DDWarnLackOfTempSpace)
  5671. {
  5672. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  5673. if (!ADrive.IsEmpty())
  5674. {
  5675. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  5676. DebugAssert(RequiredSpace >= 0);
  5677. __int64 RequiredWithReserve;
  5678. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  5679. if (FreeSpace < RequiredWithReserve)
  5680. {
  5681. unsigned int Result;
  5682. TMessageParams Params(mpNeverAskAgainCheck);
  5683. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  5684. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  5685. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  5686. if (Result == qaNeverAskAgain)
  5687. {
  5688. WinConfiguration->DDWarnLackOfTempSpace = false;
  5689. }
  5690. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  5691. }
  5692. }
  5693. }
  5694. }
  5695. //---------------------------------------------------------------------------
  5696. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  5697. {
  5698. DoOpenDirectoryDialog(odAddBookmark, Side);
  5699. }
  5700. //---------------------------------------------------------------------------
  5701. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  5702. {
  5703. // we should better use TCustomDirView::FCaseSensitive, but it is private
  5704. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  5705. try
  5706. {
  5707. TCustomDirView * DView = DirView(Side);
  5708. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  5709. {
  5710. VisitedDirectories->Add(DView->HistoryPath[Index]);
  5711. }
  5712. }
  5713. catch (...)
  5714. {
  5715. delete VisitedDirectories;
  5716. throw;
  5717. }
  5718. return VisitedDirectories;
  5719. }
  5720. //---------------------------------------------------------------------------
  5721. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  5722. TOpenDirectoryMode Mode, TOperationSide Side)
  5723. {
  5724. bool Continue = true;
  5725. if (Mode == odAddBookmark)
  5726. {
  5727. TMessageParams Params(mpNeverAskAgainCheck);
  5728. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  5729. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  5730. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  5731. unsigned int Answer =
  5732. MessageDialog(Message,
  5733. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  5734. if (Answer == qaNeverAskAgain)
  5735. {
  5736. Continue = true;
  5737. WinConfiguration->UseSharedBookmarks = true;
  5738. }
  5739. else if (Answer == qaOK)
  5740. {
  5741. Continue = true;
  5742. WinConfiguration->UseSharedBookmarks = false;
  5743. }
  5744. else
  5745. {
  5746. Continue = false;
  5747. }
  5748. }
  5749. if (Continue)
  5750. {
  5751. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  5752. try
  5753. {
  5754. UnicodeString Name = DirView(Side)->PathName;
  5755. bool Repeat;
  5756. do
  5757. {
  5758. Repeat = false;
  5759. if (::DoOpenDirectoryDialog(Mode, Side, Name, VisitedDirectories, Terminal,
  5760. // do not allow switching to location profiles,
  5761. // if we are not connected
  5762. HasDirView[osLocal] && (Terminal != NULL)))
  5763. {
  5764. TWindowLock Lock(this);
  5765. if (!TryOpenDirectory(Side, Name))
  5766. {
  5767. Repeat = true;
  5768. Mode = odBrowse;
  5769. }
  5770. }
  5771. }
  5772. while (Repeat);
  5773. }
  5774. __finally
  5775. {
  5776. delete VisitedDirectories;
  5777. }
  5778. }
  5779. }
  5780. //---------------------------------------------------------------------------
  5781. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  5782. {
  5783. DebugAssert(!FTerminal->CommandSessionOpened);
  5784. return TTerminalManager::Instance()->ConnectTerminal(FTerminal->CommandSession);
  5785. }
  5786. //---------------------------------------------------------------------------
  5787. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  5788. {
  5789. bool Result = FTerminal->IsCapable[Capability] ||
  5790. FTerminal->CommandSessionOpened;
  5791. if (!Result)
  5792. {
  5793. DebugAssert(FTerminal->IsCapable[fcSecondaryShell]);
  5794. if (!GUIConfiguration->ConfirmCommandSession)
  5795. {
  5796. Result = true;
  5797. }
  5798. else
  5799. {
  5800. TMessageParams Params(mpNeverAskAgainCheck);
  5801. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  5802. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  5803. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  5804. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  5805. if (Answer == qaNeverAskAgain)
  5806. {
  5807. GUIConfiguration->ConfirmCommandSession = false;
  5808. Result = true;
  5809. }
  5810. else if (Answer == qaOK)
  5811. {
  5812. Result = true;
  5813. }
  5814. }
  5815. if (Result)
  5816. {
  5817. Result = CommandSessionFallback();
  5818. }
  5819. }
  5820. return Result;
  5821. }
  5822. //---------------------------------------------------------------------------
  5823. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  5824. {
  5825. if (EnsureCommandSessionFallback(fcAnyCommand))
  5826. {
  5827. DoConsoleDialog(Terminal, Command);
  5828. }
  5829. }
  5830. //---------------------------------------------------------------------------
  5831. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  5832. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  5833. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  5834. {
  5835. if (!IsSideLocalBrowser(osRemote) &&
  5836. IsFileControl(DropSourceControl, osRemote) &&
  5837. (FDDExtMapFile != NULL))
  5838. {
  5839. Accept = true;
  5840. }
  5841. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  5842. DebugAssert(FDDTargetControl != NULL);
  5843. }
  5844. //---------------------------------------------------------------------------
  5845. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  5846. _di_IDataObject DataObj, int KeyState,
  5847. const TPoint & Point, int & Effect, bool & Accept)
  5848. {
  5849. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  5850. }
  5851. //---------------------------------------------------------------------------
  5852. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  5853. _di_IDataObject DataObj, int KeyState,
  5854. const TPoint & Point, int & Effect, bool & Accept)
  5855. {
  5856. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  5857. }
  5858. //---------------------------------------------------------------------------
  5859. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  5860. TObject * Sender)
  5861. {
  5862. DebugUsedParam(Sender);
  5863. DebugAssert(FDDTargetControl == Sender);
  5864. FDDTargetControl = NULL;
  5865. }
  5866. //---------------------------------------------------------------------------
  5867. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  5868. {
  5869. FileControlDDDragLeave(SessionsPageControl);
  5870. }
  5871. //---------------------------------------------------------------------------
  5872. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  5873. {
  5874. FileControlDDDragLeave(QueueView3);
  5875. }
  5876. //---------------------------------------------------------------------------
  5877. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  5878. {
  5879. DebugAssert(!IsSideLocalBrowser(Side));
  5880. DebugUsedParam(Side);
  5881. bool Edit = false;
  5882. TRemoteFile * File = NULL;
  5883. UnicodeString FileName;
  5884. UnicodeString PointTo;
  5885. bool SymbolicLink = true;
  5886. if (RemoteDirView->ItemFocused)
  5887. {
  5888. DebugAssert(RemoteDirView->ItemFocused->Data);
  5889. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  5890. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  5891. if (Edit)
  5892. {
  5893. FileName = File->FileName;
  5894. PointTo = File->LinkTo;
  5895. }
  5896. else
  5897. {
  5898. PointTo = File->FileName;
  5899. }
  5900. }
  5901. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  5902. Terminal->IsCapable[fcHardLink]))
  5903. {
  5904. Configuration->Usage->Inc(L"RemoteLinksCreated");
  5905. if (Edit)
  5906. {
  5907. DebugAssert(File->FileName == FileName);
  5908. int Params = dfNoRecursive;
  5909. Terminal->ExceptionOnFail = true;
  5910. try
  5911. {
  5912. Terminal->DeleteFile(L"", File, &Params);
  5913. }
  5914. __finally
  5915. {
  5916. Terminal->ExceptionOnFail = false;
  5917. }
  5918. }
  5919. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  5920. }
  5921. }
  5922. //---------------------------------------------------------------------------
  5923. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  5924. {
  5925. return
  5926. (IsSideLocalBrowser(Side) ||
  5927. ((Terminal != NULL) &&
  5928. Terminal->ResolvingSymlinks &&
  5929. Terminal->IsCapable[fcSymbolicLink]));
  5930. }
  5931. //---------------------------------------------------------------------------
  5932. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  5933. {
  5934. return
  5935. !IsSideLocalBrowser(FCurrentSide) &&
  5936. (RemoteDirView->ItemFocused != NULL) &&
  5937. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  5938. Terminal->SessionData->ResolveSymlinks;
  5939. }
  5940. //---------------------------------------------------------------------------
  5941. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  5942. {
  5943. DebugAssert(!WinConfiguration->DisableOpenEdit);
  5944. FForceExecution = true;
  5945. try
  5946. {
  5947. DirView(osCurrent)->ExecuteCurrentFile();
  5948. }
  5949. __finally
  5950. {
  5951. FForceExecution = false;
  5952. }
  5953. }
  5954. //---------------------------------------------------------------------------
  5955. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  5956. {
  5957. TEditorData ExternalEditor;
  5958. ExternalEditor.Editor = edExternal;
  5959. bool Remember = false;
  5960. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  5961. {
  5962. if (Remember)
  5963. {
  5964. TEditorList * EditorList = new TEditorList;
  5965. try
  5966. {
  5967. *EditorList = *WinConfiguration->EditorList;
  5968. bool Found = false;
  5969. int i = 0;
  5970. while (!Found && (i < EditorList->Count))
  5971. {
  5972. const TEditorPreferences * Editor = EditorList->Editors[i];
  5973. if ((Editor->Data->Editor == edExternal) &&
  5974. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  5975. {
  5976. Found = true;
  5977. }
  5978. i++;
  5979. }
  5980. if (!Found)
  5981. {
  5982. EditorList->Add(new TEditorPreferences(ExternalEditor));
  5983. WinConfiguration->EditorList = EditorList;
  5984. }
  5985. }
  5986. __finally
  5987. {
  5988. delete EditorList;
  5989. }
  5990. }
  5991. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  5992. }
  5993. }
  5994. //---------------------------------------------------------------------------
  5995. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  5996. {
  5997. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  5998. if (FFileFindTerminal == Sender)
  5999. {
  6000. FFileFindTerminal = NULL;
  6001. HideFileFindDialog();
  6002. }
  6003. if (FClipboardTerminal == Sender)
  6004. {
  6005. ClipboardClear(); // implies ClipboardStop
  6006. }
  6007. }
  6008. //---------------------------------------------------------------------------
  6009. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6010. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6011. {
  6012. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6013. DebugAssert(Terminal != NULL);
  6014. if (Data->Terminal == Terminal)
  6015. {
  6016. Data->Terminal = NULL;
  6017. }
  6018. }
  6019. //---------------------------------------------------------------------------
  6020. void __fastcall TCustomScpExplorerForm::LastTerminalClosed(TObject * /*Sender*/)
  6021. {
  6022. UpdateControls();
  6023. SessionColor = TColor(0);
  6024. UpdateRemotePathComboBox(false);
  6025. NeedSession(true);
  6026. }
  6027. //---------------------------------------------------------------------------
  6028. void __fastcall TCustomScpExplorerForm::NeedSession(bool ReloadSessions)
  6029. {
  6030. try
  6031. {
  6032. try
  6033. {
  6034. TTerminalManager::Instance()->NewSession(false, L"", ReloadSessions, this);
  6035. }
  6036. __finally
  6037. {
  6038. if (!WinConfiguration->KeepOpenWhenNoSession &&
  6039. (!Terminal || !Terminal->Active))
  6040. {
  6041. TerminateApplication();
  6042. }
  6043. }
  6044. }
  6045. catch (EAbort &)
  6046. {
  6047. // swallow
  6048. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6049. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6050. }
  6051. }
  6052. //---------------------------------------------------------------------------
  6053. void __fastcall TCustomScpExplorerForm::DoTerminalListChanged()
  6054. {
  6055. TStrings * TerminalList = TTerminalManager::Instance()->TerminalList;
  6056. int ActiveTerminalIndex = TTerminalManager::Instance()->ActiveTerminalIndex;
  6057. Configuration->Usage->SetMax(L"MaxOpenedSessions", TerminalList->Count);
  6058. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6059. try
  6060. {
  6061. while ((SessionsPageControl->PageCount > TerminalList->Count + 1) ||
  6062. // Clear the design time unthemed tab
  6063. ((SessionsPageControl->PageCount > 0) &&
  6064. (dynamic_cast<TThemeTabSheet *>(SessionsPageControl->Pages[SessionsPageControl->PageCount - 1]) == NULL)))
  6065. {
  6066. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6067. }
  6068. for (int Index = 0; Index <= TerminalList->Count; Index++)
  6069. {
  6070. TThemeTabSheet * TabSheet;
  6071. if (Index >= SessionsPageControl->PageCount)
  6072. {
  6073. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6074. TabSheet->PageControl = SessionsPageControl;
  6075. }
  6076. else
  6077. {
  6078. TabSheet = DebugNotNull(dynamic_cast<TThemeTabSheet *>(SessionsPageControl->Pages[Index]));
  6079. }
  6080. bool IsSessionTab = (Index < TerminalList->Count);
  6081. if (IsSessionTab)
  6082. {
  6083. TTerminal * Terminal = dynamic_cast<TTerminal *>(TerminalList->Objects[Index]);
  6084. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6085. UpdateSessionTab(TabSheet);
  6086. }
  6087. else
  6088. {
  6089. TabSheet->ImageIndex = FNewSessionTabImageIndex;
  6090. TabSheet->Tag = 0; // not really needed
  6091. // We know that we are at the last page, sotherwise we could not call this (it assumes that new session tab is the last one)
  6092. UpdateNewSessionTab();
  6093. }
  6094. TabSheet->ShowCloseButton = IsSessionTab;
  6095. }
  6096. }
  6097. __finally
  6098. {
  6099. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6100. }
  6101. SessionsPageControl->ActivePageIndex = ActiveTerminalIndex;
  6102. }
  6103. //---------------------------------------------------------------------------
  6104. void __fastcall TCustomScpExplorerForm::TerminalListChanged(TObject * /*Sender*/)
  6105. {
  6106. DoTerminalListChanged();
  6107. }
  6108. //---------------------------------------------------------------------------
  6109. void __fastcall TCustomScpExplorerForm::UpdateNewSessionTab()
  6110. {
  6111. TTabSheet * TabSheet = SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6112. DebugAssert(TabSheet->ImageIndex == 0);
  6113. TabSheet->Caption =
  6114. WinConfiguration->SelectiveToolbarText ?
  6115. StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewSessionAction->Caption)) :
  6116. UnicodeString();
  6117. }
  6118. //---------------------------------------------------------------------------
  6119. TTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabTerminal(TTabSheet * TabSheet)
  6120. {
  6121. return reinterpret_cast<TTerminal *>(TabSheet->Tag);
  6122. }
  6123. //---------------------------------------------------------------------------
  6124. void __fastcall TCustomScpExplorerForm::UpdateSessionTab(TTabSheet * TabSheet)
  6125. {
  6126. if (DebugAlwaysTrue(TabSheet != NULL))
  6127. {
  6128. TManagedTerminal * ManagedTerminal =
  6129. dynamic_cast<TManagedTerminal *>(GetSessionTabTerminal(TabSheet));
  6130. if (DebugAlwaysTrue(ManagedTerminal != NULL))
  6131. {
  6132. TColor Color = (ManagedTerminal == FTerminal) ? FSessionColor : ManagedTerminal->StateData->Color;
  6133. TabSheet->ImageIndex = AddSessionColor(Color);
  6134. UnicodeString TabCaption = TTerminalManager::Instance()->GetTerminalTitle(ManagedTerminal, true);
  6135. TabSheet->Caption = SessionsPageControl->FormatCaptionWithCloseButton(TabCaption);
  6136. TThemeTabSheet * ThemeTabSheet = dynamic_cast<TThemeTabSheet *>(TabSheet);
  6137. if (DebugAlwaysTrue(ThemeTabSheet != NULL))
  6138. {
  6139. ThemeTabSheet->Shadowed = !ManagedTerminal->Active;
  6140. }
  6141. }
  6142. }
  6143. }
  6144. //---------------------------------------------------------------------------
  6145. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6146. {
  6147. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6148. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->ActivePage);
  6149. bool Result = (Terminal != NULL);
  6150. if (Result)
  6151. {
  6152. TTerminalManager::Instance()->ActiveTerminal = Terminal;
  6153. }
  6154. else
  6155. {
  6156. try
  6157. {
  6158. NewSession(false);
  6159. }
  6160. __finally
  6161. {
  6162. DoTerminalListChanged();
  6163. }
  6164. FSessionsPageControlNewSessionTime = Now();
  6165. }
  6166. return Result;
  6167. }
  6168. //---------------------------------------------------------------------------
  6169. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  6170. {
  6171. SessionTabSwitched();
  6172. }
  6173. //---------------------------------------------------------------------------
  6174. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  6175. {
  6176. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  6177. DebugAssert(TransferList != NULL);
  6178. UnicodeString Name;
  6179. if (TransferList->ItemIndex <= 0)
  6180. {
  6181. Name = L"";
  6182. }
  6183. else
  6184. {
  6185. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  6186. }
  6187. if (FCopyParamAutoSelected.IsEmpty())
  6188. {
  6189. // if previous preset was not autoselected, make new preset the "default"
  6190. FCopyParamDefault = Name;
  6191. }
  6192. GUIConfiguration->CopyParamCurrent = Name;
  6193. }
  6194. //---------------------------------------------------------------------------
  6195. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  6196. {
  6197. // sanity check
  6198. bool ExistingPreset =
  6199. (FTransferListHoverIndex >= 0) &&
  6200. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  6201. DebugAssert(ExistingPreset);
  6202. if (ExistingPreset)
  6203. {
  6204. HDC DC = GetDC(0);
  6205. TCanvas * Canvas = new TCanvas();
  6206. try
  6207. {
  6208. Canvas->Handle = DC;
  6209. Canvas->Font = GetToolbarFont(this);
  6210. UnicodeString Name;
  6211. if (FTransferListHoverIndex == 0)
  6212. {
  6213. Name = L"";
  6214. }
  6215. else
  6216. {
  6217. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  6218. }
  6219. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  6220. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  6221. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  6222. static_cast<TObject*>(GetComponent(fcTransferList)));
  6223. UnicodeString InfoStr =
  6224. GUIConfiguration->CopyParamPreset[Name].
  6225. GetInfoStr(L"; ",
  6226. FLAGMASK(((Terminal != NULL) && Terminal->Active), Terminal->UsableCopyParamAttrs(0).General));
  6227. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  6228. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  6229. {
  6230. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  6231. {
  6232. InfoStr.SetLength(InfoStr.Length() - 1);
  6233. }
  6234. InfoStr += Ellipsis;
  6235. }
  6236. // UpdateCaption does not cause invalidation of whole submenu, while
  6237. // setting Caption property does.
  6238. // also it probably does not resize the label, even if necessary
  6239. // (we do not want that anyway)
  6240. TransferLabel->UpdateCaption(InfoStr);
  6241. }
  6242. __finally
  6243. {
  6244. Canvas->Handle = NULL;
  6245. ReleaseDC(0, DC);
  6246. delete Canvas;
  6247. }
  6248. }
  6249. }
  6250. //---------------------------------------------------------------------------
  6251. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  6252. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  6253. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  6254. {
  6255. if (FTransferListHoverIndex != AHoverIndex)
  6256. {
  6257. FTransferListHoverIndex = AHoverIndex;
  6258. UpdateTransferLabel();
  6259. }
  6260. }
  6261. //---------------------------------------------------------------------------
  6262. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  6263. {
  6264. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  6265. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  6266. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  6267. {
  6268. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  6269. {
  6270. OpenDirectory(GetSide(osCurrent));
  6271. Message.Result = 1;
  6272. }
  6273. else
  6274. {
  6275. TForm::Dispatch(&Message);
  6276. }
  6277. }
  6278. else
  6279. {
  6280. TForm::Dispatch(&Message);
  6281. }
  6282. }
  6283. //---------------------------------------------------------------------------
  6284. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  6285. {
  6286. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  6287. if ((FIgnoreNextDialogChar != 0) &&
  6288. (toupper(Message.CharCode) == toupper(FIgnoreNextDialogChar)))
  6289. {
  6290. Message.Result = 1;
  6291. }
  6292. else
  6293. {
  6294. TForm::Dispatch(&Message);
  6295. }
  6296. FIgnoreNextDialogChar = 0;
  6297. }
  6298. //---------------------------------------------------------------------------
  6299. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  6300. {
  6301. // The four low-order bits are used internally by Windows
  6302. unsigned int Cmd = (Message.WParam & 0xFFF0);
  6303. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  6304. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  6305. // 61730 - restore thru double click - undocumented
  6306. // 61490 - maximize thru double click - undocumented
  6307. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  6308. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  6309. {
  6310. SysResizing(Cmd);
  6311. }
  6312. TForm::Dispatch(&Message);
  6313. }
  6314. //---------------------------------------------------------------------------
  6315. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  6316. {
  6317. // We were actually never able to make ENDSESSION_CRITICAL happen.
  6318. // Also there no point returning TRUE as we are not able to
  6319. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  6320. // Hence the process termination might be safer :)
  6321. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  6322. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  6323. {
  6324. Message.Result = FALSE;
  6325. }
  6326. else
  6327. {
  6328. Message.Result = TRUE;
  6329. }
  6330. // Do not call default handling as that triggers OnCloseQuery,
  6331. // where our implementation will popup confirmation dialogs, what we do not want,
  6332. // as per Vista guidelines:
  6333. // https://docs.microsoft.com/en-us/windows/desktop/shutdown/shutting-down
  6334. }
  6335. //---------------------------------------------------------------------------
  6336. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  6337. {
  6338. if (Message.EndSession && IsApplicationMinimized())
  6339. {
  6340. // WORKAROUND
  6341. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  6342. // when it receives WM_ENDSESSION,
  6343. // but that sometimes (particularly when application is minimized) cause crashes.
  6344. // Crash popups message that blocks log off.
  6345. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  6346. // so we call ExitProcess() immediately, not even trying to cleanup.
  6347. // It still causes beep, so there's likely some popup, but it does not block
  6348. // log off.
  6349. ExitProcess(0);
  6350. }
  6351. TForm::Dispatch(&Message);
  6352. }
  6353. #ifdef _DEBUG
  6354. //---------------------------------------------------------------------------
  6355. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  6356. {
  6357. TForm::Dispatch(&Message);
  6358. }
  6359. #endif
  6360. //---------------------------------------------------------------------------
  6361. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  6362. {
  6363. }
  6364. //---------------------------------------------------------------------------
  6365. void __fastcall TCustomScpExplorerForm::DoShow()
  6366. {
  6367. // only now are the controls resized finally, so the size constraints
  6368. // will not conflict with possibly very small window size
  6369. RestoreFormParams();
  6370. // This indicates that the form was rescaled after parameters were loaded and
  6371. // as most probably the parameters were actually saved with the current form scaling
  6372. // (windows was the last time likely closed on the same monitor, where it is starting now),
  6373. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  6374. // and no rounding problems will occur.
  6375. // See also RestoreForm.
  6376. // (we should be safe to call RestoreParams unconditionally)
  6377. if (PixelsPerInch != Screen->PixelsPerInch)
  6378. {
  6379. RestoreParams();
  6380. }
  6381. FixControlsPlacement();
  6382. if (Position == poDefaultPosOnly)
  6383. {
  6384. CutFormToDesktop(this);
  6385. }
  6386. TForm::DoShow();
  6387. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  6388. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  6389. if (Terminal == NULL)
  6390. {
  6391. StartingDisconnected();
  6392. }
  6393. UpdatePixelsPerInchMainWindowCounter();
  6394. FShowing = true;
  6395. }
  6396. //---------------------------------------------------------------------------
  6397. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  6398. {
  6399. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  6400. }
  6401. //---------------------------------------------------------------------------
  6402. void __fastcall TCustomScpExplorerForm::StartingDisconnected()
  6403. {
  6404. DoTerminalListChanged();
  6405. }
  6406. //---------------------------------------------------------------------------
  6407. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  6408. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  6409. TNotifyEvent OnBalloonClick, TObject * UserData)
  6410. {
  6411. bool Do;
  6412. UnicodeString Message;
  6413. if (E == NULL)
  6414. {
  6415. Message = Str;
  6416. Do = true;
  6417. }
  6418. else
  6419. {
  6420. Do = ExceptionMessage(E, Message);
  6421. }
  6422. if (Do && WinConfiguration->BalloonNotifications)
  6423. {
  6424. UnicodeString Title;
  6425. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  6426. {
  6427. Message = TrimLeft(Message);
  6428. }
  6429. else
  6430. {
  6431. Message = UnformatMessage(Message);
  6432. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  6433. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  6434. Title = LoadResourceString(Captions[Type]);
  6435. if (Terminal != NULL)
  6436. {
  6437. Title = FORMAT(L"%s - %s",
  6438. (TTerminalManager::Instance()->GetTerminalTitle(Terminal, true), Title));
  6439. }
  6440. }
  6441. if (Seconds == 0)
  6442. {
  6443. Seconds = WinConfiguration->NotificationsTimeout;
  6444. }
  6445. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  6446. }
  6447. }
  6448. //---------------------------------------------------------------------------
  6449. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  6450. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  6451. UnicodeString HelpKeyword, const TMessageParams * Params,
  6452. TTerminal * Terminal)
  6453. {
  6454. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  6455. (FOnFeedSynchronizeError != NULL)) &&
  6456. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  6457. {
  6458. if (FOnFeedSynchronizeError != NULL)
  6459. {
  6460. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  6461. }
  6462. else
  6463. {
  6464. DebugAssert(FErrorList != NULL);
  6465. TStringList * MoreMessagesCopy = NULL;
  6466. if (MoreMessages)
  6467. {
  6468. MoreMessagesCopy = new TStringList();
  6469. MoreMessagesCopy->Assign(MoreMessages);
  6470. }
  6471. FErrorList->AddObject(Message, MoreMessagesCopy);
  6472. }
  6473. PopupTrayBalloon(Terminal, Message, Type);
  6474. return ContinueAnswer(Answers);
  6475. }
  6476. else
  6477. {
  6478. bool UseBalloon = FTrayIcon->Visible;
  6479. if (UseBalloon)
  6480. {
  6481. PopupTrayBalloon(Terminal, Message, Type);
  6482. }
  6483. unsigned int Result;
  6484. try
  6485. {
  6486. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  6487. }
  6488. __finally
  6489. {
  6490. // cancel only balloon we popped up, otherwise we may cancel notification
  6491. // balloon that was there before the message dialog
  6492. // (such as "dd confirmation opt in balloon)
  6493. if (UseBalloon)
  6494. {
  6495. FTrayIcon->CancelBalloon();
  6496. }
  6497. }
  6498. return Result;
  6499. }
  6500. }
  6501. //---------------------------------------------------------------------------
  6502. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  6503. TTerminal * Terminal, Exception * E)
  6504. {
  6505. if (FTrayIcon->Visible)
  6506. {
  6507. PopupTrayBalloon(Terminal, L"", qtError, E);
  6508. }
  6509. // particularly prevent opening new session from jump list,
  6510. // while exception is shown
  6511. NonVisualDataModule->StartBusy();
  6512. try
  6513. {
  6514. ShowExtendedExceptionEx(Terminal, E);
  6515. }
  6516. __finally
  6517. {
  6518. NonVisualDataModule->EndBusy();
  6519. FTrayIcon->CancelBalloon();
  6520. }
  6521. }
  6522. //---------------------------------------------------------------------------
  6523. void __fastcall TCustomScpExplorerForm::TerminalReady()
  6524. {
  6525. // cannot rely on active page being page for active terminal,
  6526. // as it can happen that active page is the "new session" page
  6527. // (e.g. when reconnecting active terminal, while login dialog
  6528. // invoked from "new session" page is modal)
  6529. int ActiveTerminalIndex = TTerminalManager::Instance()->ActiveTerminalIndex;
  6530. UpdateSessionTab(SessionsPageControl->Pages[ActiveTerminalIndex]);
  6531. }
  6532. //---------------------------------------------------------------------------
  6533. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  6534. TTerminal * Terminal, Exception * E)
  6535. {
  6536. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  6537. if (!Terminal->Active)
  6538. {
  6539. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  6540. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  6541. {
  6542. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  6543. }
  6544. }
  6545. }
  6546. //---------------------------------------------------------------------------
  6547. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  6548. UnicodeString Message, TQueryType Type,
  6549. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  6550. {
  6551. if ((E == NULL) ||
  6552. ExceptionMessage(E, Message))
  6553. {
  6554. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  6555. if (Important)
  6556. {
  6557. Seconds *= 5;
  6558. }
  6559. UnicodeString NoteMessage(UnformatMessage(Message));
  6560. if (Terminal != NULL)
  6561. {
  6562. NoteMessage = FORMAT(L"%s: %s",
  6563. (TTerminalManager::Instance()->GetTerminalTitle(Terminal, true), NoteMessage));
  6564. }
  6565. if (WinConfiguration->BalloonNotifications)
  6566. {
  6567. AddNote(NoteMessage);
  6568. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  6569. }
  6570. else
  6571. {
  6572. FlashOnBackground();
  6573. PostNote(NoteMessage, Seconds, OnClick, UserData);
  6574. }
  6575. }
  6576. }
  6577. //---------------------------------------------------------------------------
  6578. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  6579. {
  6580. RestoreApp();
  6581. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  6582. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  6583. !NonVisualDataModule->Busy)
  6584. {
  6585. TTerminal * Terminal = TerminalNoteData->Terminal;
  6586. TTerminalManager::Instance()->ActiveTerminal = Terminal;
  6587. if (!ComponentVisible[fcQueueView])
  6588. {
  6589. ToggleQueueVisibility();
  6590. GoToQueue();
  6591. }
  6592. }
  6593. }
  6594. //---------------------------------------------------------------------------
  6595. void __fastcall TCustomScpExplorerForm::QueueEvent(TTerminal * ATerminal,
  6596. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  6597. {
  6598. TManagedTerminal * ManagedTerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  6599. UnicodeString Message;
  6600. TNotifyEvent OnClick = NULL;
  6601. TObject * UserData = NULL;
  6602. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  6603. switch (Event)
  6604. {
  6605. case qeEmptyButMonitored:
  6606. if ((ATerminal != Terminal) || QueueInvisible)
  6607. {
  6608. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  6609. OnClick = QueueEmptyNoteClicked;
  6610. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  6611. TerminalNoteData->Terminal = ATerminal;
  6612. UserData = TerminalNoteData;
  6613. }
  6614. break;
  6615. case qeEmpty:
  6616. OperationComplete(ManagedTerminal->QueueOperationStart);
  6617. break;
  6618. case qePendingUserAction:
  6619. if ((ATerminal != Terminal) ||
  6620. (QueueInvisible && !IsQueueAutoPopup()))
  6621. {
  6622. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  6623. }
  6624. break;
  6625. default:
  6626. DebugFail();
  6627. }
  6628. if (!Message.IsEmpty())
  6629. {
  6630. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  6631. }
  6632. }
  6633. //---------------------------------------------------------------------------
  6634. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  6635. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  6636. {
  6637. if (FDDExtMapFile != NULL)
  6638. {
  6639. CloseHandle(FDDExtMapFile);
  6640. FDDExtMapFile = NULL;
  6641. }
  6642. if (WinConfiguration->DDFakeFile)
  6643. {
  6644. DDFakeFileInitDrag(FileList, Created);
  6645. }
  6646. }
  6647. //---------------------------------------------------------------------------
  6648. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  6649. {
  6650. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  6651. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  6652. {
  6653. FFakeFileDropTarget = FileName;
  6654. }
  6655. }
  6656. //---------------------------------------------------------------------------
  6657. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  6658. {
  6659. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  6660. if (!ForceDirectories(ApiPath(Result)))
  6661. {
  6662. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  6663. }
  6664. FileSetAttr(ApiPath(Result), faHidden);
  6665. return Result;
  6666. }
  6667. //---------------------------------------------------------------------------
  6668. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  6669. bool & Created)
  6670. {
  6671. FFakeFileDropTarget = UnicodeString();
  6672. FDragFakeDirectory = CreateFakeTransferDirectory();
  6673. FileList->AddItem(NULL, FDragFakeDirectory);
  6674. Created = true;
  6675. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  6676. {
  6677. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  6678. }
  6679. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  6680. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  6681. {
  6682. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  6683. TDragExtCommStruct* CommStruct;
  6684. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  6685. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  6686. DebugAssert(CommStruct != NULL);
  6687. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  6688. CommStruct->Dragging = true;
  6689. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  6690. LENOF(CommStruct->DropDest));
  6691. NULL_TERMINATE(CommStruct->DropDest);
  6692. UnmapViewOfFile(CommStruct);
  6693. }
  6694. }
  6695. //---------------------------------------------------------------------------
  6696. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  6697. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  6698. {
  6699. bool Result;
  6700. DebugAssert(!IsLocalBrowserMode());
  6701. if (Sender == RemoteDirView)
  6702. {
  6703. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  6704. }
  6705. else
  6706. {
  6707. DebugAssert(Sender == RemoteDriveView);
  6708. TStrings * FileList = RemoteDriveView->DragFileList();
  6709. try
  6710. {
  6711. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  6712. }
  6713. __finally
  6714. {
  6715. delete FileList;
  6716. }
  6717. }
  6718. if (FDDTargetControl == RemoteDriveView)
  6719. {
  6720. RemoteDriveView->UpdateDropTarget();
  6721. }
  6722. // foRemoteMove happens when file/dir is dragged within the remote tree view
  6723. // or from tree view to dir view.
  6724. // foMove happens when file/dir is dragged from remote tree view outside of
  6725. // application via dragex
  6726. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  6727. (DropSourceControl == RemoteDriveView))
  6728. {
  6729. RemoteDriveView->UpdateDropSource();
  6730. }
  6731. return Result;
  6732. }
  6733. //---------------------------------------------------------------------------
  6734. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  6735. {
  6736. DebugAssert(!IsLocalBrowserMode());
  6737. // This also handles drops of remote files to queue.
  6738. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  6739. SAFE_DESTROY(FDDFileList);
  6740. if (!FFakeFileDropTarget.IsEmpty())
  6741. {
  6742. RemoveDir(ApiPath(FFakeFileDropTarget));
  6743. }
  6744. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  6745. {
  6746. try
  6747. {
  6748. TDragResult DDResult = (Sender == RemoteDirView) ?
  6749. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  6750. // Focus is moved to the target application,
  6751. // but as we are going to present the UI, we need to steal the focus back.
  6752. // This most likely won't work though (windows does not allow application
  6753. // to steal focus most of the time)
  6754. Application->BringToFront();
  6755. // On older version of Windows we never got drMove here, see also comment below.
  6756. // On Windows 10, we get the "move".
  6757. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  6758. {
  6759. UnicodeString TargetDirectory;
  6760. TFileOperation Operation;
  6761. // drInvalid may mean drMove, see comment below
  6762. switch (DDResult)
  6763. {
  6764. case drCopy:
  6765. Operation = foCopy;
  6766. break;
  6767. case drMove:
  6768. Operation = foMove;
  6769. break;
  6770. default:
  6771. DebugFail();
  6772. case drInvalid:
  6773. // prefer "copy" for safety
  6774. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  6775. break;
  6776. }
  6777. TTransferOperationParam Param;
  6778. UnicodeString CounterName;
  6779. bool ForceQueue;
  6780. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  6781. {
  6782. // we get drInvalid both if d&d was intercepted by ddext,
  6783. // and when users drops on no-drop location.
  6784. // we tell the difference by existence of response from ddext,
  6785. // so we ignore absence of response in this case
  6786. if (DDResult != drInvalid)
  6787. {
  6788. // here we know that the extension is installed,
  6789. // as it is checked as soon as drag&drop starts from
  6790. // RemoteFileControlDDCreateDragFileList
  6791. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  6792. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  6793. {
  6794. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  6795. }
  6796. else
  6797. {
  6798. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  6799. }
  6800. }
  6801. }
  6802. else
  6803. {
  6804. // download using fake file
  6805. Param.Temp = false;
  6806. Param.DragDrop = true;
  6807. if (ForceQueue)
  6808. {
  6809. Param.Queue = asOn;
  6810. }
  6811. if (Sender == RemoteDirView)
  6812. {
  6813. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  6814. }
  6815. if (RemoteFileControlFileOperation(Sender, Operation,
  6816. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  6817. {
  6818. Configuration->Usage->Inc(CounterName);
  6819. }
  6820. }
  6821. }
  6822. }
  6823. __finally
  6824. {
  6825. CloseHandle(FDDExtMapFile);
  6826. FDDExtMapFile = NULL;
  6827. delete FDragFakeMonitors;
  6828. FDragFakeMonitors = NULL;
  6829. RemoveDir(ApiPath(FDragFakeDirectory));
  6830. FDragFakeDirectory = L"";
  6831. FFakeFileDropTarget = UnicodeString();
  6832. }
  6833. }
  6834. if (FDragDropSshTerminate.get() != NULL)
  6835. {
  6836. FDragDropSshTerminate->Rethrow();
  6837. }
  6838. }
  6839. //---------------------------------------------------------------------------
  6840. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  6841. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  6842. {
  6843. // Remember drop effect so we know (when user drops files), if we copy or move
  6844. FLastDropEffect = dwEffect;
  6845. }
  6846. //---------------------------------------------------------------------------
  6847. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  6848. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  6849. {
  6850. bool Result;
  6851. if (FDDTargetControl == QueueView3)
  6852. {
  6853. Directory = DefaultDownloadTargetDirectory();
  6854. Result = true;
  6855. CounterName = L"DownloadsDragDropQueue";
  6856. ForceQueue = true;
  6857. }
  6858. else if (!FFakeFileDropTarget.IsEmpty())
  6859. {
  6860. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  6861. Result = true;
  6862. ForceQueue = false;
  6863. CounterName = L"DownloadsDragDropFakeFile";
  6864. }
  6865. else
  6866. {
  6867. ForceQueue = false;
  6868. Enabled = false;
  6869. try
  6870. {
  6871. int Timer = 0;
  6872. Result = false;
  6873. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  6874. {
  6875. {
  6876. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  6877. TDragExtCommStruct* CommStruct;
  6878. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  6879. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  6880. DebugAssert(CommStruct != NULL);
  6881. Result = !CommStruct->Dragging;
  6882. if (Result)
  6883. {
  6884. Directory = ExtractFilePath(CommStruct->DropDest);
  6885. CounterName = L"DownloadsDragDropExternalExt";
  6886. }
  6887. UnmapViewOfFile(CommStruct);
  6888. }
  6889. if (!Result)
  6890. {
  6891. Sleep(50);
  6892. Timer += 50;
  6893. Application->ProcessMessages();
  6894. }
  6895. }
  6896. }
  6897. __finally
  6898. {
  6899. Enabled = true;
  6900. }
  6901. }
  6902. return Result;
  6903. }
  6904. //---------------------------------------------------------------------------
  6905. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  6906. const UnicodeString TempDir, int SecDelay)
  6907. {
  6908. TDateTime Alarm = Now() + (double)((double)SecDelay*OneMillisecond);
  6909. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  6910. if (FDelayedDeletionTimer == NULL)
  6911. {
  6912. DebugAssert(HandleAllocated());
  6913. FDelayedDeletionTimer = new TTimer(this);
  6914. FDelayedDeletionTimer->Interval = 10000;
  6915. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  6916. }
  6917. else
  6918. {
  6919. FDelayedDeletionTimer->Enabled = true;
  6920. }
  6921. }
  6922. //---------------------------------------------------------------------------
  6923. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  6924. {
  6925. DebugAssert(FDelayedDeletionList != NULL);
  6926. TDateTime N = Now();
  6927. TDateTime Alert;
  6928. UnicodeString Directory;
  6929. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  6930. {
  6931. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  6932. if ((N >= Alert) || (Sender == NULL))
  6933. {
  6934. Directory = FDelayedDeletionList->Strings[Index];
  6935. if (DeleteDirectory(ExcludeTrailingBackslash(Directory)))
  6936. {
  6937. FDelayedDeletionList->Delete(Index);
  6938. }
  6939. }
  6940. }
  6941. if (FDelayedDeletionList->Count == 0)
  6942. {
  6943. FDelayedDeletionTimer->Enabled = false;
  6944. }
  6945. }
  6946. //---------------------------------------------------------------------------
  6947. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  6948. {
  6949. DebugAssert(!IsLocalBrowserMode());
  6950. if (IsFileControl(FDDTargetControl, osRemote) ||
  6951. (FDDTargetControl == SessionsPageControl))
  6952. {
  6953. TTerminal * TargetTerminal = NULL;
  6954. TFileOperation Operation = foNone;
  6955. if (FDDTargetControl == SessionsPageControl)
  6956. {
  6957. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  6958. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  6959. // do not allow dropping on the "+" tab
  6960. TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  6961. if (TargetTerminal != NULL)
  6962. {
  6963. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  6964. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  6965. {
  6966. Operation = foRemoteMove;
  6967. }
  6968. else
  6969. {
  6970. Operation = foRemoteCopy;
  6971. }
  6972. }
  6973. }
  6974. else
  6975. {
  6976. if (FLastDropEffect == DROPEFFECT_MOVE)
  6977. {
  6978. Operation = foRemoteMove;
  6979. }
  6980. else if (FLastDropEffect == DROPEFFECT_COPY)
  6981. {
  6982. Operation = foRemoteCopy;
  6983. }
  6984. }
  6985. if (Operation != foNone)
  6986. {
  6987. RemoteFileControlFileOperation(DropSourceControl,
  6988. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  6989. }
  6990. // abort drag&drop
  6991. Abort();
  6992. }
  6993. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  6994. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  6995. (FDDTargetControl != QueueView3))
  6996. {
  6997. DebugAssert(!FDragTempDir.IsEmpty());
  6998. TTransferType Type;
  6999. UnicodeString TempDir = FDragTempDir;
  7000. // We clear FDragTempDir before calling
  7001. // just in case it fail (raises exception)
  7002. FDragTempDir = L"";
  7003. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7004. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7005. // empty directory parameter means temp directory -> don't display it!
  7006. UnicodeString TargetDir = L"";
  7007. int Options = 0;
  7008. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7009. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7010. {
  7011. Abort();
  7012. }
  7013. // TargetDir is set when dropped on local file control
  7014. // (this was workaround for legacy dirview event handling, now it should be
  7015. // made prettier)
  7016. if (TargetDir.IsEmpty())
  7017. {
  7018. TargetDir = TempDir;
  7019. if (ForceDirectories(ApiPath(TargetDir)))
  7020. {
  7021. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7022. FPendingTempSpaceWarn = true;
  7023. try
  7024. {
  7025. FDragDropOperation = true;
  7026. int Params = cpTemporary |
  7027. (Type == ttMove ? cpDelete : 0);
  7028. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7029. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7030. }
  7031. __finally
  7032. {
  7033. FDragDropOperation = false;
  7034. FPendingTempSpaceWarn = false;
  7035. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7036. }
  7037. }
  7038. else
  7039. {
  7040. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7041. }
  7042. }
  7043. }
  7044. }
  7045. //---------------------------------------------------------------------------
  7046. void __fastcall TCustomScpExplorerForm::DDDownload(
  7047. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params)
  7048. {
  7049. DebugAssert(!IsLocalBrowserMode());
  7050. TAutoBatch AutoBatch(this);
  7051. UpdateCopyParamCounters(*CopyParam);
  7052. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7053. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7054. {
  7055. RemoteDriveView->UpdateDropSource();
  7056. }
  7057. }
  7058. //---------------------------------------------------------------------------
  7059. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7060. {
  7061. public:
  7062. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7063. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7064. {
  7065. }
  7066. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7067. {
  7068. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7069. TDataObjectFilesEx::AllowData(FormatEtc);
  7070. }
  7071. };
  7072. //---------------------------------------------------------------------------
  7073. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7074. TObject * Sender, TDataObject *& DataObject)
  7075. {
  7076. if (FDDExtMapFile != NULL)
  7077. {
  7078. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7079. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7080. {
  7081. Abort();
  7082. }
  7083. if (FileList->Count > 0)
  7084. {
  7085. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7086. if (!FilesObject->IsValid(true, true))
  7087. {
  7088. FilesObject->_Release();
  7089. }
  7090. else
  7091. {
  7092. DataObject = FilesObject;
  7093. }
  7094. }
  7095. }
  7096. }
  7097. //---------------------------------------------------------------------------
  7098. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7099. {
  7100. DebugFail();
  7101. }
  7102. //---------------------------------------------------------------------------
  7103. void __fastcall TCustomScpExplorerForm::GoToTree()
  7104. {
  7105. ComponentVisible[fcRemoteTree] = true;
  7106. DriveView(osRemote)->SetFocus();
  7107. }
  7108. //---------------------------------------------------------------------------
  7109. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7110. TPanelExport Export)
  7111. {
  7112. TCustomDirView * DirView = this->DirView(Side);
  7113. std::unique_ptr<TStrings> ExportData(new TStringList());
  7114. switch (Export)
  7115. {
  7116. case pePath:
  7117. ExportData->Add(DirView->PathName);
  7118. break;
  7119. case peFileList:
  7120. case peFullFileList:
  7121. {
  7122. bool FullPath = (Export == peFullFileList);
  7123. DirView->CreateFileList(false, FullPath, ExportData.get());
  7124. for (int Index = 0; Index < ExportData->Count; Index++)
  7125. {
  7126. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7127. {
  7128. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7129. }
  7130. }
  7131. }
  7132. break;
  7133. default:
  7134. DebugFail();
  7135. }
  7136. return ExportData.release();
  7137. }
  7138. //---------------------------------------------------------------------------
  7139. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7140. TPanelExport Export, TPanelExportDestination Destination)
  7141. {
  7142. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7143. PanelExportStore(Side, Export, Destination, ExportData.get());
  7144. }
  7145. //---------------------------------------------------------------------------
  7146. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  7147. TPanelExport /*Export*/, TPanelExportDestination Destination,
  7148. TStrings * ExportData)
  7149. {
  7150. if (Destination == pedClipboard)
  7151. {
  7152. TInstantOperationVisualizer Visualizer;
  7153. CopyToClipboard(ExportData);
  7154. }
  7155. else
  7156. {
  7157. DebugFail();
  7158. }
  7159. }
  7160. //---------------------------------------------------------------------------
  7161. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  7162. {
  7163. TCustomDirView * DirView = this->DirView(Side);
  7164. UnicodeString Mask = DirView->Mask;
  7165. if (DoFilterMaskDialog(DirView, Mask))
  7166. {
  7167. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  7168. Configuration->Usage->Inc(L"Filters");
  7169. }
  7170. }
  7171. //---------------------------------------------------------------------------
  7172. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  7173. {
  7174. return FQueueController->DefaultOperation();
  7175. }
  7176. //---------------------------------------------------------------------------
  7177. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  7178. TQueueOperation Operation, void ** Param)
  7179. {
  7180. switch (Operation)
  7181. {
  7182. case qoPreferences:
  7183. return true;
  7184. case qoGoTo:
  7185. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  7186. case qoOnceEmpty:
  7187. return !FQueueController->Empty;
  7188. default:
  7189. return FQueueController->AllowOperation(Operation, Param);
  7190. }
  7191. }
  7192. //---------------------------------------------------------------------------
  7193. void __fastcall TCustomScpExplorerForm::GoToQueue()
  7194. {
  7195. if (DebugAlwaysTrue(QueueView3->Visible))
  7196. {
  7197. QueueView3->SetFocus();
  7198. }
  7199. }
  7200. //---------------------------------------------------------------------------
  7201. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  7202. TQueueOperation Operation, void * Param)
  7203. {
  7204. if (Operation == qoGoTo)
  7205. {
  7206. GoToQueue();
  7207. }
  7208. else if (Operation == qoPreferences)
  7209. {
  7210. PreferencesDialog(pmQueue);
  7211. }
  7212. else
  7213. {
  7214. FQueueController->ExecuteOperation(Operation, Param);
  7215. }
  7216. }
  7217. //---------------------------------------------------------------------------
  7218. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  7219. {
  7220. return (Queue != NULL) && Queue->Enabled;
  7221. }
  7222. //---------------------------------------------------------------------------
  7223. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  7224. {
  7225. DebugAssert(Queue != NULL);
  7226. if (Queue != NULL)
  7227. {
  7228. Queue->Enabled = !Queue->Enabled;
  7229. }
  7230. }
  7231. //---------------------------------------------------------------------------
  7232. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  7233. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  7234. {
  7235. FQueueActedItem = QueueView3->ItemFocused;
  7236. }
  7237. //---------------------------------------------------------------------------
  7238. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  7239. {
  7240. return TopDock->Height + QueueSplitter->Height;
  7241. }
  7242. //---------------------------------------------------------------------------
  7243. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  7244. TObject * /*Sender*/, int & NewSize, bool & Accept)
  7245. {
  7246. // when queue is hidden by double-clicking splitter, stray attempt to
  7247. // resize the panel with strange value arrives, make sure it is ignored
  7248. if (ComponentVisible[fcQueueView])
  7249. {
  7250. int HeightLimit = ClientHeight - GetStaticComponentsHeight() -
  7251. RemotePanel->Constraints->MinHeight;
  7252. if (NewSize > HeightLimit)
  7253. {
  7254. NewSize = HeightLimit;
  7255. }
  7256. }
  7257. else
  7258. {
  7259. Accept = false;
  7260. }
  7261. }
  7262. //---------------------------------------------------------------------------
  7263. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  7264. TDragObject *& /*DragObject*/)
  7265. {
  7266. FQueueActedItem = QueueView3->ItemFocused;
  7267. }
  7268. //---------------------------------------------------------------------------
  7269. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  7270. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  7271. {
  7272. Accept = true;
  7273. if (Source == QueueView3)
  7274. {
  7275. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  7276. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  7277. if (Accept)
  7278. {
  7279. TQueueItemProxy * QueueItem;
  7280. TQueueItemProxy * DestQueueItem;
  7281. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  7282. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  7283. Accept = (QueueItem != DestQueueItem) &&
  7284. (QueueItem->Status == TQueueItem::qsPending) &&
  7285. (DestQueueItem->Status == TQueueItem::qsPending);
  7286. }
  7287. }
  7288. }
  7289. //---------------------------------------------------------------------------
  7290. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  7291. TObject * /*Source*/, int /*X*/, int /*Y*/)
  7292. {
  7293. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  7294. {
  7295. TQueueItemProxy * QueueItem;
  7296. TQueueItemProxy * DestQueueItem;
  7297. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  7298. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  7299. QueueItem->Move(DestQueueItem);
  7300. }
  7301. }
  7302. //---------------------------------------------------------------------------
  7303. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  7304. {
  7305. if ((QueueView3->ItemFocused == NULL) &&
  7306. (QueueView3->Items->Count > 0))
  7307. {
  7308. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  7309. }
  7310. QueueLabelUpdateStatus();
  7311. }
  7312. //---------------------------------------------------------------------------
  7313. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  7314. {
  7315. QueueLabelUpdateStatus();
  7316. }
  7317. //---------------------------------------------------------------------------
  7318. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  7319. {
  7320. QueueLabel->UpdateStatus();
  7321. }
  7322. //---------------------------------------------------------------------------
  7323. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  7324. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  7325. {
  7326. if (Selected)
  7327. {
  7328. NonVisualDataModule->UpdateNonVisibleActions();
  7329. }
  7330. }
  7331. //---------------------------------------------------------------------------
  7332. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  7333. {
  7334. TDragDropFilesEx * Result = NULL;
  7335. if (Sender == SessionsPageControl)
  7336. {
  7337. Result = FSessionsDragDropFilesEx;
  7338. }
  7339. else if (Sender == QueueView3)
  7340. {
  7341. Result = FQueueDragDropFilesEx;
  7342. }
  7343. else
  7344. {
  7345. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  7346. if (DirView != NULL)
  7347. {
  7348. Result = DirView->DragDropFilesEx;
  7349. }
  7350. else
  7351. {
  7352. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  7353. if (DriveView != NULL)
  7354. {
  7355. Result = DriveView->DragDropFilesEx;
  7356. }
  7357. }
  7358. }
  7359. DebugAssert(Result != NULL);
  7360. return Result;
  7361. }
  7362. //---------------------------------------------------------------------------
  7363. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  7364. {
  7365. return (DView->SelCount == DView->FilesCount);
  7366. }
  7367. //---------------------------------------------------------------------------
  7368. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  7369. {
  7370. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  7371. }
  7372. //---------------------------------------------------------------------------
  7373. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  7374. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  7375. {
  7376. DebugAssert(!IsLocalBrowserMode());
  7377. TFileOperation Operation;
  7378. switch (Effect)
  7379. {
  7380. case DROPEFFECT_MOVE:
  7381. Operation = foMove;
  7382. break;
  7383. case DROPEFFECT_COPY:
  7384. // occures on WinXP (reported by user)
  7385. default:
  7386. Operation = foCopy;
  7387. break;
  7388. };
  7389. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  7390. // see a comment in TUnixDirView::PerformItemDragDropOperation
  7391. if (DragDropFilesEx->FileList->Count > 0)
  7392. {
  7393. TStrings * FileList = new TStringList();
  7394. try
  7395. {
  7396. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  7397. {
  7398. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  7399. }
  7400. FDragDropOperation = true;
  7401. TTransferOperationParam Param;
  7402. Param.TargetDirectory = TargetPath;
  7403. // upload, no temp dirs
  7404. Param.Temp = false;
  7405. Param.DragDrop = DragDrop;
  7406. Param.Options =
  7407. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  7408. if (ForceQueue)
  7409. {
  7410. Param.Queue = asOn;
  7411. }
  7412. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  7413. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  7414. {
  7415. if (IsFileControl(DropSourceControl, osLocal))
  7416. {
  7417. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  7418. }
  7419. else
  7420. {
  7421. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  7422. }
  7423. }
  7424. }
  7425. __finally
  7426. {
  7427. FDragDropOperation = false;
  7428. delete FileList;
  7429. }
  7430. }
  7431. }
  7432. //---------------------------------------------------------------------------
  7433. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  7434. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  7435. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  7436. {
  7437. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  7438. }
  7439. //---------------------------------------------------------------------------
  7440. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  7441. TObject * Sender, int grfKeyState, int & dwEffect)
  7442. {
  7443. DebugAssert(!IsLocalBrowserMode());
  7444. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  7445. if ((dwEffect != DROPEFFECT_NONE) &&
  7446. IsFileControl(DropSourceControl, osRemote))
  7447. {
  7448. // do not allow drop on remote panel (on free space, still allow drop on directories)
  7449. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  7450. (RemoteDirView->DropTarget == NULL))
  7451. {
  7452. dwEffect = DROPEFFECT_NONE;
  7453. }
  7454. else
  7455. {
  7456. if (dwEffect == DROPEFFECT_COPY)
  7457. {
  7458. bool MoveCapable = FTerminal->IsCapable[fcRemoteMove];
  7459. // currently we support copying always (at least via temporary directory);
  7460. // remove associated checks once this all proves stable and working
  7461. bool CopyCapable = true;
  7462. // if we do not support neither of operations, there's no discussion
  7463. if (!MoveCapable && !CopyCapable)
  7464. {
  7465. dwEffect = DROPEFFECT_NONE;
  7466. }
  7467. else
  7468. {
  7469. // The default effect inside remote panel is move,
  7470. // unless we do not support it, but support copy
  7471. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  7472. {
  7473. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  7474. }
  7475. else
  7476. {
  7477. // with ctrl-down, we want copy unless it is not supported
  7478. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  7479. }
  7480. }
  7481. }
  7482. }
  7483. }
  7484. }
  7485. //---------------------------------------------------------------------------
  7486. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  7487. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  7488. {
  7489. DebugAssert(!IsLocalBrowserMode());
  7490. if (FDDTotalSize >= 0)
  7491. {
  7492. if (File->IsDirectory)
  7493. {
  7494. FDDTotalSize = -1;
  7495. }
  7496. else
  7497. {
  7498. FDDTotalSize += File->Size;
  7499. }
  7500. }
  7501. DebugAssert(!FDragTempDir.IsEmpty());
  7502. // TODO: this is quite ineffective
  7503. // TODO: what if invalid character replacement is disabled?
  7504. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  7505. UnicodeString TransferFileName;
  7506. if (Sender == RemoteDriveView)
  7507. {
  7508. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  7509. }
  7510. else
  7511. {
  7512. TransferFileName = File->FileName;
  7513. }
  7514. FDDFileList->AddObject(TransferFileName, File);
  7515. }
  7516. //---------------------------------------------------------------------------
  7517. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  7518. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  7519. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  7520. {
  7521. // sometimes we do not get DDEnd so the list is not released
  7522. SAFE_DESTROY(FDDFileList);
  7523. FDDFileList = new TStringList();
  7524. FDragTempDir = WinConfiguration->TemporaryDir();
  7525. FDDTotalSize = 0;
  7526. FDragDropSshTerminate.reset(NULL);
  7527. }
  7528. //---------------------------------------------------------------------------
  7529. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  7530. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  7531. HRESULT & Result)
  7532. {
  7533. if (Result == DRAGDROP_S_DROP)
  7534. {
  7535. try
  7536. {
  7537. GlobalDragImageList->HideDragImage();
  7538. try
  7539. {
  7540. RemoteFileControlDDTargetDrop();
  7541. }
  7542. catch(ESshTerminate & E)
  7543. {
  7544. FDragDropSshTerminate.reset(E.Clone());
  7545. }
  7546. }
  7547. catch (Exception &E)
  7548. {
  7549. // If downloading fails we need to cancel drag&drop, otherwise
  7550. // Explorer shows error
  7551. // But by the way exception probably never reach this point as
  7552. // it's catched on way.
  7553. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  7554. Result = DRAGDROP_S_CANCEL;
  7555. ShowExtendedException(Terminal, &E);
  7556. }
  7557. }
  7558. }
  7559. //---------------------------------------------------------------------------
  7560. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  7561. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  7562. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  7563. {
  7564. TFileMasks::TParams MaskParams;
  7565. MaskParams.Size = Size;
  7566. MaskParams.Modification = Modification;
  7567. // this does not re-parse the mask if it is the same as the last time
  7568. FDirViewMatchMask = Masks;
  7569. bool ImplicitMatch;
  7570. Matches =
  7571. // RecurseInclude parameter has no effect as the Path is empty
  7572. FDirViewMatchMask.Matches(FileName, Directory, UnicodeString(L""), &MaskParams, true, ImplicitMatch) &&
  7573. (AllowImplicitMatches || !ImplicitMatch);
  7574. }
  7575. //---------------------------------------------------------------------------
  7576. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  7577. TObject * Sender, TListItem * Item, WORD & Indexes)
  7578. {
  7579. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  7580. UnicodeString Ext;
  7581. if (dynamic_cast<TUnixDirView *>(DirView) != NULL)
  7582. {
  7583. Ext = UnixExtractFileExt(DirView->ItemFileName(Item));
  7584. }
  7585. else
  7586. {
  7587. Ext = ExtractFileExt(DirView->ItemFileName(Item));
  7588. }
  7589. if (SameText(Ext, Configuration->PartialExt))
  7590. {
  7591. Indexes |= oiPartial;
  7592. }
  7593. }
  7594. //---------------------------------------------------------------------------
  7595. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  7596. {
  7597. return
  7598. DirViewEnabled(osCurrent) &&
  7599. DirView(osCurrent)->CanPasteFromClipBoard();
  7600. }
  7601. //---------------------------------------------------------------------------
  7602. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  7603. {
  7604. bool Result = false;
  7605. if (CanPasteToDirViewFromClipBoard())
  7606. {
  7607. Result = true;
  7608. }
  7609. else
  7610. {
  7611. UnicodeString ClipboardText;
  7612. if (NonEmptyTextFromClipboard(ClipboardText))
  7613. {
  7614. if (StoredSessions->IsUrl(ClipboardText))
  7615. {
  7616. Result = true;
  7617. }
  7618. else
  7619. {
  7620. Result = DirViewEnabled(osCurrent);
  7621. }
  7622. }
  7623. }
  7624. return Result;
  7625. }
  7626. //---------------------------------------------------------------------------
  7627. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  7628. {
  7629. if (DoesClipboardContainOurFiles())
  7630. {
  7631. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  7632. {
  7633. DebugAssert(!IsLocalBrowserMode());
  7634. TTerminalManager * Manager = TTerminalManager::Instance();
  7635. TTerminal * TergetTerminal = Manager->ActiveTerminal;
  7636. Manager->ActiveTerminal = FClipboardTerminal;
  7637. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TergetTerminal);
  7638. }
  7639. }
  7640. else if (CanPasteToDirViewFromClipBoard())
  7641. {
  7642. DirView(osCurrent)->PasteFromClipBoard();
  7643. }
  7644. else
  7645. {
  7646. UnicodeString ClipboardText;
  7647. if (NonEmptyTextFromClipboard(ClipboardText))
  7648. {
  7649. if (StoredSessions->IsUrl(ClipboardText))
  7650. {
  7651. NewSession(false, ClipboardText);
  7652. }
  7653. else
  7654. {
  7655. DirView(osCurrent)->Path = ClipboardText;
  7656. }
  7657. }
  7658. }
  7659. }
  7660. //---------------------------------------------------------------------------
  7661. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  7662. {
  7663. // TBD
  7664. }
  7665. //---------------------------------------------------------------------------
  7666. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  7667. {
  7668. TCustomDirView * ADirView = DirView(Side);
  7669. ADirView->SelectAll(Mode);
  7670. ADirView->SetFocus();
  7671. }
  7672. //---------------------------------------------------------------------------
  7673. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  7674. {
  7675. TCustomDirView * ADirView = DirView(Side);
  7676. TFileFilter Filter;
  7677. DefaultFileFilter(Filter);
  7678. if (DoSelectMaskDialog(ADirView, Select, Filter))
  7679. {
  7680. Configuration->Usage->Inc(L"MaskSelections");
  7681. ADirView->SelectFiles(Filter, Select);
  7682. ADirView->SetFocus();
  7683. }
  7684. }
  7685. //---------------------------------------------------------------------------
  7686. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  7687. {
  7688. TCustomDirView * ADirView = DirView(Side);
  7689. ADirView->RestoreSelectedNames();
  7690. ADirView->SetFocus();
  7691. }
  7692. //---------------------------------------------------------------------------
  7693. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  7694. {
  7695. TCustomDirView * CurrentDirView = DirView(osCurrent);
  7696. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  7697. {
  7698. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  7699. UnicodeString Ext;
  7700. if (!IsSideLocalBrowser(osCurrent))
  7701. {
  7702. Ext = UnixExtractFileExt(FileName);
  7703. }
  7704. else
  7705. {
  7706. Ext = ExtractFileExt(FileName);
  7707. }
  7708. if (Ext.IsEmpty())
  7709. {
  7710. Ext = L".";
  7711. }
  7712. TFileFilter Filter;
  7713. Filter.Masks = FORMAT(L"*%s", (Ext));
  7714. Filter.Directories = false;
  7715. CurrentDirView->SelectFiles(Filter, Select);
  7716. }
  7717. }
  7718. //---------------------------------------------------------------------------
  7719. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  7720. const TStatusFileInfo & FileInfo, TOperationSide Side)
  7721. {
  7722. UnicodeString Result;
  7723. if (!FIncrementalSearch.IsEmpty() && (Side == GetSide(osCurrent)))
  7724. {
  7725. Result = FormatIncrementalSearchStatus(FIncrementalSearch, FIncrementalSearchHaveNext);
  7726. }
  7727. else if (!IsSideLocalBrowser(Side) && (Terminal == NULL))
  7728. {
  7729. // noop
  7730. }
  7731. else
  7732. {
  7733. Result =
  7734. FMTLOAD(FILE_INFO_FORMAT,
  7735. (FormatBytes(FileInfo.SelectedSize),
  7736. FormatBytes(FileInfo.FilesSize),
  7737. FormatNumber(FileInfo.SelectedCount),
  7738. FormatNumber(FileInfo.FilesCount)));
  7739. }
  7740. return Result;
  7741. }
  7742. //---------------------------------------------------------------------------
  7743. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  7744. TTBXStatusPanel * Panel, TOperationSide Side)
  7745. {
  7746. if (Panel->Index == 1)
  7747. {
  7748. ToggleShowHiddenFiles();
  7749. }
  7750. else if (Panel->Index == 2)
  7751. {
  7752. Filter(Side);
  7753. }
  7754. }
  7755. //---------------------------------------------------------------------------
  7756. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  7757. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  7758. {
  7759. DebugAssert(!StatusBar->SimplePanel);
  7760. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  7761. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  7762. }
  7763. //---------------------------------------------------------------------------
  7764. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  7765. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  7766. {
  7767. DebugAssert(StatusBar->Panels->Count >= 3);
  7768. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  7769. if (FileInfo.HiddenCount > 0)
  7770. {
  7771. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  7772. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  7773. }
  7774. else
  7775. {
  7776. HiddenFilesPanel->ViewPriority = 0;
  7777. // not really necessary, just to cleanup no-longer-valid data
  7778. HiddenFilesPanel->Caption = L"";
  7779. }
  7780. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  7781. if (FileInfo.FilteredCount > 0)
  7782. {
  7783. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  7784. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  7785. }
  7786. else
  7787. {
  7788. FilteredFilesPanel->ViewPriority = 0;
  7789. // not really necessary, just to cleanup no-longer-valid data
  7790. FilteredFilesPanel->Caption = L"";
  7791. }
  7792. }
  7793. //---------------------------------------------------------------------------
  7794. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  7795. TObject * /*Sender*/)
  7796. {
  7797. if (DirView(osRemote)->Enabled)
  7798. {
  7799. DirView(osRemote)->SetFocus();
  7800. }
  7801. }
  7802. //---------------------------------------------------------------------------
  7803. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  7804. {
  7805. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  7806. switch (Config.Show)
  7807. {
  7808. case qvShow:
  7809. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  7810. {
  7811. Config.Show = qvHide;
  7812. }
  7813. else
  7814. {
  7815. Config.Show = Config.LastHideShow;
  7816. }
  7817. break;
  7818. case qvHideWhenEmpty:
  7819. if (ComponentVisible[fcQueueView])
  7820. {
  7821. Config.Show = qvHide;
  7822. }
  7823. else
  7824. {
  7825. Config.LastHideShow = Config.Show;
  7826. Config.Show = qvShow;
  7827. }
  7828. break;
  7829. case qvHide:
  7830. Config.LastHideShow = Config.Show;
  7831. Config.Show = qvShow;
  7832. break;
  7833. }
  7834. WinConfiguration->QueueView = Config;
  7835. }
  7836. //---------------------------------------------------------------------------
  7837. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  7838. {
  7839. UnicodeString Result;
  7840. if (FTerminal != NULL)
  7841. {
  7842. switch (WinConfiguration->PathInCaption)
  7843. {
  7844. case picShort:
  7845. Result = TTerminalManager::Instance()->GetTerminalShortPath(FTerminal);
  7846. break;
  7847. case picFull:
  7848. Result = FTerminal->CurrentDirectory;
  7849. break;
  7850. }
  7851. }
  7852. return Result;
  7853. }
  7854. //---------------------------------------------------------------------------
  7855. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  7856. {
  7857. TColor Result = GetWindowColor(FSessionColor);
  7858. return Result;
  7859. }
  7860. //---------------------------------------------------------------------------
  7861. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  7862. {
  7863. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  7864. return Result;
  7865. }
  7866. //---------------------------------------------------------------------------
  7867. void __fastcall TCustomScpExplorerForm::UpdateControls()
  7868. {
  7869. TTerminalManager::Instance()->UpdateAppTitle();
  7870. // WORAKRDOUND: Disabling list view when it is not showing yet does not set its
  7871. // background to gray on Windows 7 (works on Windows 10).
  7872. // See also EnableControl
  7873. if (Showing)
  7874. {
  7875. bool HasTerminal = (Terminal != NULL) && Terminal->Active;
  7876. if (HasTerminal)
  7877. {
  7878. // Update path when it changes
  7879. if ((SessionsPageControl->ActivePage != NULL) && (GetSessionTabTerminal(SessionsPageControl->ActivePage) == Terminal))
  7880. {
  7881. UpdateSessionTab(SessionsPageControl->ActivePage);
  7882. }
  7883. // TODO needed yet with second local browser?
  7884. if (!RemoteDirView->Enabled)
  7885. {
  7886. RemoteDirView->Enabled = true;
  7887. if (FRemoteDirViewWasFocused)
  7888. {
  7889. ActiveControl = RemoteDirView;
  7890. }
  7891. }
  7892. RemoteDirView->Color = PanelColor();
  7893. }
  7894. else
  7895. {
  7896. if (RemoteDirView->Enabled)
  7897. {
  7898. // This is first called when the form is being constructed
  7899. // (not anymore due to Showing test above)
  7900. // but the false is overriden in the constructor later.
  7901. // An even later in TScpCommanderForm::DoShow()
  7902. FRemoteDirViewWasFocused = (ActiveControl == RemoteDirView);
  7903. RemoteDirView->Enabled = false;
  7904. RemoteDirView->Color = DisabledPanelColor();
  7905. }
  7906. }
  7907. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  7908. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  7909. RemoteDriveView->Color = RemoteDirView->Color;
  7910. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  7911. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fsBackgroundTransfers];
  7912. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  7913. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  7914. QueueLabelUpdateStatus();
  7915. RemoteDirView->DarkMode = WinConfiguration->UseDarkTheme();
  7916. RemoteDriveView->DarkMode = RemoteDirView->DarkMode;
  7917. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal;
  7918. }
  7919. }
  7920. //---------------------------------------------------------------------------
  7921. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  7922. {
  7923. UpdateControls();
  7924. }
  7925. //---------------------------------------------------------------------------
  7926. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  7927. TObject * Sender)
  7928. {
  7929. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  7930. DebugAssert(DirView != NULL);
  7931. DoDirViewLoaded(DirView);
  7932. TransferPresetAutoSelect();
  7933. }
  7934. //---------------------------------------------------------------------------
  7935. void __fastcall TCustomScpExplorerForm::StartUpdates()
  7936. {
  7937. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  7938. // first run after installation
  7939. if (double(Updates.LastCheck) == 0)
  7940. {
  7941. // make sure next time there will be an update (if enabled)
  7942. Updates.LastCheck = TDateTime(1);
  7943. WinConfiguration->Updates = Updates;
  7944. }
  7945. else if ((double(Updates.Period) > 0) &&
  7946. (Now() - Updates.LastCheck >= Updates.Period))
  7947. {
  7948. TThreadMethod OnUpdatesChecked = NULL;
  7949. if (!IsUWP())
  7950. {
  7951. OnUpdatesChecked = UpdatesChecked;
  7952. }
  7953. StartUpdateThread(OnUpdatesChecked);
  7954. }
  7955. }
  7956. //---------------------------------------------------------------------------
  7957. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  7958. {
  7959. UnicodeString Message;
  7960. bool New;
  7961. TQueryType Type;
  7962. GetUpdatesMessage(Message, New, Type, false);
  7963. if (!Message.IsEmpty())
  7964. {
  7965. if (New)
  7966. {
  7967. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  7968. }
  7969. if (!New && (Type != qtWarning))
  7970. {
  7971. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  7972. }
  7973. else
  7974. {
  7975. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  7976. }
  7977. if (New)
  7978. {
  7979. Configuration->Usage->Inc(L"UpdateNotifications");
  7980. }
  7981. }
  7982. }
  7983. //---------------------------------------------------------------------------
  7984. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  7985. {
  7986. RestoreApp();
  7987. bool CanDisplay = !NonVisualDataModule->Busy;
  7988. if (!CanDisplay && (Screen->ActiveForm != NULL))
  7989. {
  7990. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  7991. }
  7992. if (CanDisplay)
  7993. {
  7994. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  7995. CheckForUpdates(true);
  7996. }
  7997. else
  7998. {
  7999. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  8000. }
  8001. }
  8002. //---------------------------------------------------------------------------
  8003. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  8004. TCopyParamRuleData & Data)
  8005. {
  8006. DebugAssert(Terminal != NULL);
  8007. Data.HostName = Terminal->SessionData->HostNameExpanded;
  8008. Data.UserName = Terminal->SessionData->UserNameExpanded;
  8009. Data.RemoteDirectory = RemoteDirView->PathName;
  8010. }
  8011. //---------------------------------------------------------------------------
  8012. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  8013. {
  8014. // Terminal can be null when we are changing local directory implicitly,
  8015. // because it has been deleted, while no session is connected
  8016. // (Login dialog is open)
  8017. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  8018. {
  8019. DebugAssert(!IsLocalBrowserMode());
  8020. TCopyParamRuleData Data;
  8021. GetTransferPresetAutoSelectData(Data);
  8022. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  8023. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  8024. if (CopyParamIndex < 0)
  8025. {
  8026. // there is no preset that matches autoselection
  8027. // set preset that we consider "default"
  8028. FCopyParamAutoSelected = L""; // forget last autoselected preset
  8029. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  8030. }
  8031. else
  8032. {
  8033. // there is preset matching autoselection
  8034. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  8035. if (CopyParamName == FCopyParamAutoSelected)
  8036. {
  8037. // autoselected the same preset as the last time
  8038. // make no change (i.e. preserve custom user preset, if any)
  8039. }
  8040. else
  8041. {
  8042. // autoselected the different preset then the last time (or there
  8043. // was default preset set)
  8044. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  8045. GUIConfiguration->CopyParamCurrent = CopyParamName;
  8046. }
  8047. }
  8048. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  8049. {
  8050. if (CopyParamIndex >= 0)
  8051. {
  8052. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  8053. }
  8054. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  8055. try
  8056. {
  8057. int Fmt =
  8058. (CopyParamIndex < 0) ?
  8059. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8060. COPY_PARAM_AUTOSELECTED;
  8061. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  8062. Data->Message = MainInstructions(Message);
  8063. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  8064. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  8065. CopyParamAttrs);
  8066. if (CopyParamIndex >= 0)
  8067. {
  8068. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  8069. Info = FORMAT(L"%s\n \n%s", (Info,
  8070. FMTLOAD(COPY_PARAM_RULE,
  8071. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  8072. }
  8073. Data->Message += L"\n\n" + Info;
  8074. if (WinConfiguration->CopyParamAutoSelectNotice)
  8075. {
  8076. TransferPresetNoteMessage(Data, true);
  8077. }
  8078. else
  8079. {
  8080. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  8081. Data = NULL; // ownership passed
  8082. }
  8083. }
  8084. __finally
  8085. {
  8086. delete Data;
  8087. }
  8088. }
  8089. }
  8090. }
  8091. //---------------------------------------------------------------------------
  8092. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  8093. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  8094. {
  8095. DebugAssert(NoteData != NULL);
  8096. DebugAssert(!IsLocalBrowserMode());
  8097. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  8098. TQueryButtonAlias Aliases[1];
  8099. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  8100. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  8101. Params.Aliases = Aliases;
  8102. Params.AliasesCount = LENOF(Aliases);
  8103. unsigned int Result =
  8104. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  8105. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  8106. switch (Result)
  8107. {
  8108. case qaNeverAskAgain:
  8109. DebugAssert(AllowNeverAskAgain);
  8110. WinConfiguration->CopyParamAutoSelectNotice = false;
  8111. break;
  8112. case qaIgnore:
  8113. PreferencesDialog(pmPresets);
  8114. break;
  8115. }
  8116. }
  8117. //---------------------------------------------------------------------------
  8118. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  8119. {
  8120. // as of now useless, as this is used for notes only, never for balloons, ...
  8121. RestoreApp();
  8122. // .. and we should never be busy here
  8123. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  8124. {
  8125. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  8126. }
  8127. }
  8128. //---------------------------------------------------------------------------
  8129. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  8130. TPreferencesMode APreferencesMode)
  8131. {
  8132. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  8133. TCopyParamRuleData Data;
  8134. if (Terminal != NULL)
  8135. {
  8136. PreferencesData.reset(new TPreferencesDialogData());
  8137. GetTransferPresetAutoSelectData(Data);
  8138. PreferencesData->CopyParamRuleData = &Data;
  8139. }
  8140. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  8141. }
  8142. //---------------------------------------------------------------------------
  8143. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  8144. const TCustomCommandType & Command)
  8145. {
  8146. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  8147. {
  8148. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE, (Command.Command)));
  8149. }
  8150. }
  8151. //---------------------------------------------------------------------------
  8152. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  8153. {
  8154. bool RemoteAllowed = CustomCommandRemoteAllowed();
  8155. TCustomCommandType Command;
  8156. // make sure we use local custom command when remote are not supported
  8157. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  8158. {
  8159. Command = FLastCustomCommand;
  8160. }
  8161. else
  8162. {
  8163. Command.Params = Command.Params | ccLocal;
  8164. }
  8165. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  8166. FEditingFocusedAdHocCommand = OnFocused;
  8167. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  8168. int Options =
  8169. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  8170. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  8171. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  8172. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  8173. {
  8174. FLastCustomCommand = Command;
  8175. UpdateCustomCommandsToolbar();
  8176. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  8177. }
  8178. }
  8179. //---------------------------------------------------------------------------
  8180. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  8181. {
  8182. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  8183. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  8184. DebugAssert(State > 0);
  8185. if (State <= 0)
  8186. {
  8187. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE, (FLastCustomCommand.Command)));
  8188. }
  8189. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  8190. }
  8191. //---------------------------------------------------------------------------
  8192. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  8193. TCustomCommandType & Command, int & State)
  8194. {
  8195. bool Result = !FLastCustomCommand.Command.IsEmpty();
  8196. if (Result)
  8197. {
  8198. Command = FLastCustomCommand;
  8199. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  8200. }
  8201. return Result;
  8202. }
  8203. //---------------------------------------------------------------------------
  8204. void __fastcall TCustomScpExplorerForm::BeforeAction()
  8205. {
  8206. ResetIncrementalSearch();
  8207. }
  8208. //---------------------------------------------------------------------------
  8209. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  8210. {
  8211. DebugAssert(ComponentVisible[Component]);
  8212. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  8213. }
  8214. //---------------------------------------------------------------------------
  8215. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  8216. {
  8217. // when queue panel is resized here directly, the status bar is stretched
  8218. // over whole space the panel occupied
  8219. PostComponentHide(fcQueueView);
  8220. }
  8221. //---------------------------------------------------------------------------
  8222. void __fastcall TCustomScpExplorerForm::WMWinIniChange(TMessage & Message)
  8223. {
  8224. WinConfiguration->ResetSysDarkTheme();
  8225. ConfigurationChanged();
  8226. ConfigureInterface();
  8227. TForm::Dispatch(&Message);
  8228. }
  8229. //---------------------------------------------------------------------------
  8230. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  8231. {
  8232. TMessage * M = static_cast<TMessage*>(Message);
  8233. switch (M->Msg)
  8234. {
  8235. case CM_DIALOGCHAR:
  8236. CMDialogChar(*M);
  8237. break;
  8238. case WM_APPCOMMAND:
  8239. WMAppCommand(*M);
  8240. break;
  8241. case WM_SYSCOMMAND:
  8242. WMSysCommand(*M);
  8243. break;
  8244. case WM_QUERYENDSESSION:
  8245. WMQueryEndSession(*M);
  8246. break;
  8247. case WM_ENDSESSION:
  8248. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  8249. break;
  8250. #ifdef _DEBUG
  8251. case WM_WINDOWPOSCHANGED:
  8252. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  8253. break;
  8254. case CM_CUSTOMSTYLECHANGED:
  8255. TForm::Dispatch(Message);
  8256. break;
  8257. #endif
  8258. case WM_COMPONENT_HIDE:
  8259. {
  8260. Byte Component = static_cast<Byte>(M->WParam);
  8261. // sanity check
  8262. if (ComponentVisible[Component])
  8263. {
  8264. // special treatment
  8265. if (Component == fcQueueView)
  8266. {
  8267. ToggleQueueVisibility();
  8268. DebugAssert(!ComponentVisible[fcQueueView]);
  8269. }
  8270. else
  8271. {
  8272. ComponentVisible[Component] = false;
  8273. }
  8274. }
  8275. }
  8276. break;
  8277. case WM_COPYDATA:
  8278. WMCopyData(*M);
  8279. break;
  8280. case WM_MANAGES_CAPTION:
  8281. // caption managed in TTerminalManager::UpdateAppTitle()
  8282. M->Result = 1;
  8283. break;
  8284. case WM_WANTS_MOUSEWHEEL:
  8285. M->Result = 1;
  8286. break;
  8287. case CM_SHOWINGCHANGED:
  8288. CMShowingChanged(*M);
  8289. break;
  8290. case WM_CLOSE:
  8291. WMClose(*M);
  8292. break;
  8293. case WM_DPICHANGED:
  8294. WMDpiChanged(*M);
  8295. break;
  8296. case CM_DPICHANGED:
  8297. CMDpiChanged(*M);
  8298. break;
  8299. case WM_WININICHANGE:
  8300. WMWinIniChange(*M);
  8301. break;
  8302. case CM_DIALOGKEY:
  8303. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  8304. break;
  8305. default:
  8306. TForm::Dispatch(Message);
  8307. break;
  8308. }
  8309. }
  8310. //---------------------------------------------------------------------------
  8311. void __fastcall TCustomScpExplorerForm::UpdateImages()
  8312. {
  8313. // noop
  8314. }
  8315. //---------------------------------------------------------------------------
  8316. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  8317. {
  8318. TForm::Dispatch(&Message);
  8319. FSessionColors->Clear();
  8320. AddFixedSessionImages();
  8321. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  8322. UpdateImages();
  8323. }
  8324. //---------------------------------------------------------------------------
  8325. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  8326. {
  8327. TForm::Dispatch(&Message);
  8328. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  8329. UpdatePixelsPerInchMainWindowCounter();
  8330. }
  8331. //---------------------------------------------------------------------------
  8332. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  8333. {
  8334. // Cannot close window while we are busy.
  8335. // We cannot test this in FormCloseQuery as that is called also from
  8336. // Close(), which is called by CloseApplicationAction. So we can be busy
  8337. // there already even, when it is legitimate to close the application.
  8338. // Possibly a better place to handle this would be WMSysCommand.
  8339. if (NonVisualDataModule->Busy)
  8340. {
  8341. Message.Result = 1;
  8342. }
  8343. else
  8344. {
  8345. TForm::Dispatch(&Message);
  8346. }
  8347. }
  8348. //---------------------------------------------------------------------------
  8349. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  8350. {
  8351. TForm::Dispatch(&Message);
  8352. if (Showing && (Terminal == NULL))
  8353. {
  8354. // When we are starting minimized (i.e. from an installer),
  8355. // postpone showing Login dialog until we get restored.
  8356. // Otherwise the Login dialog (and Authentication window) show restored
  8357. // over invidible (minimized) main window.
  8358. if (WindowState == wsMinimized)
  8359. {
  8360. FNeedSession = true;
  8361. }
  8362. else
  8363. {
  8364. // This happens before application ever goes idle, so the toolbars would
  8365. // stay enabled (initial state) until the Login dialog is dismissed.
  8366. UpdateActions();
  8367. NonVisualDataModule->StartBusy();
  8368. try
  8369. {
  8370. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  8371. // otherwise the dialog does not receive focus.
  8372. // With Commander interface the ProcessMessages is called already
  8373. // by TDriveView, but with Explorer interface, we need to call it explicily
  8374. Application->ProcessMessages();
  8375. // do not reload sessions, they have been loaded just now (optimization)
  8376. NeedSession(false);
  8377. }
  8378. __finally
  8379. {
  8380. NonVisualDataModule->EndBusy();
  8381. }
  8382. }
  8383. }
  8384. }
  8385. //---------------------------------------------------------------------------
  8386. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  8387. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  8388. int & MaxHeight)
  8389. {
  8390. // workaround for bug in TWinControl.CalcConstraints
  8391. // Check for empty rect (restore from iconic state) is done there only after
  8392. // call to AdjustClientRect, which enlarges the rect (for forms).
  8393. TRect R = GetClientRect();
  8394. // when restoring from iconic state, place no restrictions
  8395. if (IsRectEmpty(R))
  8396. {
  8397. MinWidth = 0;
  8398. MinHeight = 0;
  8399. MaxWidth = 32000;
  8400. MaxHeight = 32000;
  8401. }
  8402. }
  8403. //---------------------------------------------------------------------------
  8404. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  8405. TSpaceAvailable & ASpaceAvailable, bool & Close)
  8406. {
  8407. // terminal can be already closed (e.g. dropped connection)
  8408. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  8409. {
  8410. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  8411. try
  8412. {
  8413. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  8414. }
  8415. catch(...)
  8416. {
  8417. if (!Terminal->Active)
  8418. {
  8419. Close = true;
  8420. }
  8421. throw;
  8422. }
  8423. }
  8424. }
  8425. //---------------------------------------------------------------------------
  8426. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  8427. {
  8428. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  8429. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  8430. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  8431. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  8432. {
  8433. OnGetSpaceAvailable = GetSpaceAvailable;
  8434. }
  8435. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  8436. OnGetSpaceAvailable);
  8437. }
  8438. //---------------------------------------------------------------------------
  8439. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  8440. {
  8441. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  8442. Terminal->FillSessionDataForCode(Data.get());
  8443. return Data.release();
  8444. }
  8445. //---------------------------------------------------------------------------
  8446. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  8447. {
  8448. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  8449. DoGenerateUrlDialog(Data.get(), Paths);
  8450. }
  8451. //---------------------------------------------------------------------------
  8452. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  8453. {
  8454. GenerateUrl(NULL);
  8455. }
  8456. //---------------------------------------------------------------------------
  8457. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  8458. {
  8459. std::unique_ptr<TStrings> Paths(new TStringList());
  8460. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  8461. GenerateUrl(Paths.get());
  8462. }
  8463. //---------------------------------------------------------------------------
  8464. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  8465. {
  8466. FSessionColor = value;
  8467. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  8468. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  8469. static_cast<TObject *>(GetComponent(fcColorMenu)));
  8470. DebugAssert(ColorItem != NULL);
  8471. ColorItem->Color = C;
  8472. NonVisualDataModule->ColorMenuItem->Color = C;
  8473. UpdateControls();
  8474. }
  8475. //---------------------------------------------------------------------------
  8476. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  8477. {
  8478. if (value != FSessionColor)
  8479. {
  8480. UpdateSessionColor(value);
  8481. // Is null when called from LastTerminalClosed
  8482. if (Terminal != NULL)
  8483. {
  8484. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  8485. }
  8486. }
  8487. }
  8488. //---------------------------------------------------------------------------
  8489. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  8490. {
  8491. bool Result = FNoteTimer->Enabled;
  8492. if (Result)
  8493. {
  8494. // cannot cancel note too early
  8495. bool NotEarly =
  8496. (Now() - FNoteShown >
  8497. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  8498. if (Force || NotEarly)
  8499. {
  8500. FNoteTimer->Enabled = false;
  8501. FNote = L"";
  8502. SAFE_DESTROY(FNoteData);
  8503. FOnNoteClick = NULL;
  8504. FNoteHints = FNotes->Text;
  8505. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  8506. UpdateStatusBar();
  8507. }
  8508. }
  8509. return Result;
  8510. }
  8511. //---------------------------------------------------------------------------
  8512. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  8513. {
  8514. DebugAssert(FNoteTimer->Enabled);
  8515. CancelNote(true);
  8516. }
  8517. //---------------------------------------------------------------------------
  8518. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  8519. {
  8520. int P = Note.Pos(L"\n");
  8521. if (P > 0)
  8522. {
  8523. Note.SetLength(P - 1);
  8524. }
  8525. FNotes->Add(FORMAT(L"[%s] %s",
  8526. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  8527. while (FNotes->Count > 10)
  8528. {
  8529. FNotes->Delete(0);
  8530. }
  8531. if (UpdateNow)
  8532. {
  8533. FNoteHints = FNotes->Text;
  8534. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  8535. UpdateStatusBar();
  8536. }
  8537. }
  8538. //---------------------------------------------------------------------------
  8539. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  8540. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  8541. {
  8542. int P = Note.Pos(L"\n");
  8543. if (P > 0)
  8544. {
  8545. Note.SetLength(P - 1);
  8546. }
  8547. FNoteHints = FNotes->Text;
  8548. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  8549. FNote = Note;
  8550. SAFE_DESTROY(FNoteData);
  8551. FNoteData = NoteData;
  8552. FOnNoteClick = OnNoteClick;
  8553. AddNote(Note, false);
  8554. UpdateStatusBar();
  8555. FNoteShown = Now();
  8556. FNoteTimer->Enabled = false;
  8557. if (Seconds == 0)
  8558. {
  8559. Seconds = WinConfiguration->NotificationsTimeout;
  8560. }
  8561. FNoteTimer->Interval = Seconds * MSecsPerSec;
  8562. FNoteTimer->Enabled = true;
  8563. }
  8564. //---------------------------------------------------------------------------
  8565. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  8566. {
  8567. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  8568. }
  8569. //---------------------------------------------------------------------------
  8570. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  8571. {
  8572. if (NonVisualDataModule->SynchronizeBrowsingAction->Checked)
  8573. {
  8574. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  8575. }
  8576. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  8577. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  8578. (NonVisualDataModule->SynchronizeBrowsingAction->Checked ? 2 : 3)))),
  8579. 0, NULL, NULL);
  8580. }
  8581. //---------------------------------------------------------------------------
  8582. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  8583. {
  8584. WinConfiguration->ShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  8585. PostNote(FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1),
  8586. (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE,
  8587. (WinConfiguration->ShowHiddenFiles ? 2 : 3)))), 0, NULL, NULL);
  8588. }
  8589. //---------------------------------------------------------------------------
  8590. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  8591. {
  8592. WinConfiguration->FormatSizeBytes = Style;
  8593. }
  8594. //---------------------------------------------------------------------------
  8595. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  8596. {
  8597. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  8598. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  8599. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  8600. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  8601. }
  8602. //---------------------------------------------------------------------------
  8603. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  8604. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  8605. {
  8606. if (Panel->Index == 0)
  8607. {
  8608. if (FOnNoteClick != NULL)
  8609. {
  8610. // prevent the user data from being freed by possible call
  8611. // to CancelNote or PostNote during call to OnNoteClick
  8612. std::unique_ptr<TObject> NoteData(FNoteData);
  8613. TNotifyEvent OnNoteClick = FOnNoteClick;
  8614. FNoteData = NULL;
  8615. // need to cancel the note as we are going to delete its user data
  8616. CancelNote(true);
  8617. OnNoteClick(NoteData.get());
  8618. }
  8619. }
  8620. if (Panel->Index >= Sender->Panels->Count - SessionPanelCount)
  8621. {
  8622. FileSystemInfo();
  8623. }
  8624. }
  8625. //---------------------------------------------------------------------------
  8626. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  8627. {
  8628. // workaround:
  8629. // 1) for unknown reason, disabling window, while minimized,
  8630. // prevents it from restoring, even if it was enabled again meanwhile
  8631. // 2) when disabling the main window, while another has focus
  8632. // minimize is no longer possible
  8633. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  8634. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  8635. // Shouldn't we use IsApplicationMinimized() here?
  8636. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  8637. {
  8638. Enabled = false;
  8639. }
  8640. FLockLevel++;
  8641. }
  8642. //---------------------------------------------------------------------------
  8643. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  8644. {
  8645. DebugAssert(FLockLevel > 0);
  8646. FLockLevel--;
  8647. if (FLockLevel == 0)
  8648. {
  8649. DebugAssert(FLockSuspendLevel == 0);
  8650. Enabled = true;
  8651. }
  8652. }
  8653. //---------------------------------------------------------------------------
  8654. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  8655. {
  8656. // We need to make sure that window is enabled when the last modal window closes
  8657. // otherwise focus is not restored correctly.
  8658. // So we re-enable the window when modal window opens and
  8659. // disable it back after is closes
  8660. if (FLockLevel > 0)
  8661. {
  8662. // while we have nesting counter, we know that we never be called
  8663. // recursivelly as Application->OnModalBegin is called only
  8664. // for the top-level modal window
  8665. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  8666. {
  8667. // won't be disabled when conditions in LockWindow() were not satisfied
  8668. FDisabledOnLockSuspend = !Enabled;
  8669. // When minimized to tray (or actually when set to SW_HIDE),
  8670. // setting Enabled makes the window focusable even when there's
  8671. // modal window over it
  8672. if (!FTrayIcon->Visible)
  8673. {
  8674. Enabled = true;
  8675. }
  8676. }
  8677. FLockSuspendLevel++;
  8678. }
  8679. }
  8680. //---------------------------------------------------------------------------
  8681. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  8682. {
  8683. if (FLockSuspendLevel > 0)
  8684. {
  8685. DebugAssert(FLockLevel > 0);
  8686. FLockSuspendLevel--;
  8687. // see comment in SuspendWindowLock
  8688. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  8689. {
  8690. // Note that window can be enabled here, when we were minized to tray when
  8691. // was SuspendWindowLock() called.
  8692. // We should possibly do the same check as in LockWindow(),
  8693. // if it is ever possible that the consitions change between
  8694. // SuspendWindowLock() and ResumeWindowLock()
  8695. Enabled = !FDisabledOnLockSuspend;
  8696. }
  8697. }
  8698. }
  8699. //---------------------------------------------------------------------------
  8700. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  8701. {
  8702. if (!TextOnly)
  8703. {
  8704. TTBXComboBoxItem * RemotePathComboBox =
  8705. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  8706. TStrings * Items = RemotePathComboBox->Strings;
  8707. Items->BeginUpdate();
  8708. try
  8709. {
  8710. Items->Clear();
  8711. if (Terminal != NULL)
  8712. {
  8713. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  8714. while (!IsUnixRootPath(APath))
  8715. {
  8716. int P = APath.LastDelimiter(L'/');
  8717. DebugAssert(P >= 0);
  8718. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  8719. APath.SetLength(P - 1);
  8720. }
  8721. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  8722. }
  8723. }
  8724. __finally
  8725. {
  8726. RemotePathComboBox->ItemIndex = Items->Count - 1;
  8727. // Setting ItemIndex to -1 does not reset its text
  8728. if (Items->Count == 0)
  8729. {
  8730. RemotePathComboBox->Text = L"";
  8731. }
  8732. Items->EndUpdate();
  8733. }
  8734. }
  8735. }
  8736. //---------------------------------------------------------------------------
  8737. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  8738. TTBXComboBoxItem * Sender, const UnicodeString /*AText*/, int AIndex,
  8739. int & ImageIndex)
  8740. {
  8741. if (AIndex < 0)
  8742. {
  8743. AIndex = Sender->ItemIndex;
  8744. }
  8745. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  8746. }
  8747. //---------------------------------------------------------------------------
  8748. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  8749. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  8750. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  8751. {
  8752. ARect.Left += (10 * AIndex);
  8753. }
  8754. //---------------------------------------------------------------------------
  8755. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  8756. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  8757. {
  8758. AWidth += (10 * AIndex);
  8759. }
  8760. //---------------------------------------------------------------------------
  8761. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(
  8762. TObject * Sender)
  8763. {
  8764. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  8765. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  8766. int Index = RemotePathComboBox->ItemIndex;
  8767. while (Index < RemotePathComboBox->Strings->Count - 1)
  8768. {
  8769. APath = UnixExtractFileDir(APath);
  8770. Index++;
  8771. }
  8772. // VanDyke style paths
  8773. if (APath.IsEmpty())
  8774. {
  8775. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  8776. APath = ROOTDIRECTORY;
  8777. }
  8778. if (RemoteDirView->Path != APath)
  8779. {
  8780. RemoteDirView->Path = APath;
  8781. }
  8782. }
  8783. //---------------------------------------------------------------------------
  8784. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  8785. {
  8786. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  8787. DebugUsedParam(Sender);
  8788. UpdateRemotePathComboBox(true);
  8789. }
  8790. //---------------------------------------------------------------------------
  8791. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  8792. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  8793. {
  8794. ResetIncrementalSearch();
  8795. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8796. DebugAssert(DirView != NULL);
  8797. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  8798. {
  8799. HWND Edit = ListView_GetEditControl(DirView->Handle);
  8800. // OnEditing is called also from TCustomListView::CanEdit
  8801. if (Edit != NULL)
  8802. {
  8803. EditSelectBaseName(Edit);
  8804. }
  8805. }
  8806. }
  8807. //---------------------------------------------------------------------------
  8808. //---------------------------------------------------------------------------
  8809. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  8810. {
  8811. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  8812. Result->AutoDetectDnD = false;
  8813. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  8814. Result->RenderDataOn = rdoEnterAndDropSync;
  8815. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  8816. return Result;
  8817. }
  8818. //---------------------------------------------------------------------------
  8819. void __fastcall TCustomScpExplorerForm::CreateWnd()
  8820. {
  8821. TForm::CreateWnd();
  8822. if (FSessionsDragDropFilesEx == NULL)
  8823. {
  8824. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  8825. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  8826. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  8827. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  8828. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  8829. }
  8830. if (FQueueDragDropFilesEx == NULL)
  8831. {
  8832. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  8833. // No need to set OnDragOver as we do not have any restrictions
  8834. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  8835. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  8836. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  8837. }
  8838. }
  8839. //---------------------------------------------------------------------------
  8840. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  8841. {
  8842. TForm::DestroyWnd();
  8843. FSessionsDragDropFilesEx->DragDropControl = NULL;
  8844. FQueueDragDropFilesEx->DragDropControl = NULL;
  8845. }
  8846. //---------------------------------------------------------------------------
  8847. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  8848. {
  8849. SideEnter(FCurrentSide);
  8850. FEverShown = true;
  8851. }
  8852. //---------------------------------------------------------------------------
  8853. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  8854. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  8855. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  8856. {
  8857. if (!NonVisualDataModule->Busy)
  8858. {
  8859. TTerminalManager::Instance()->ActiveTerminal = ATerminal;
  8860. Configuration->Usage->Inc(L"FileFinds");
  8861. LockWindow(true);
  8862. NonVisualDataModule->StartBusy();
  8863. WinConfiguration->LockedInterface = true;
  8864. try
  8865. {
  8866. FTerminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  8867. }
  8868. __finally
  8869. {
  8870. WinConfiguration->LockedInterface = false;
  8871. NonVisualDataModule->EndBusy();
  8872. UnlockWindow();
  8873. }
  8874. }
  8875. }
  8876. //---------------------------------------------------------------------------
  8877. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  8878. {
  8879. if (!NonVisualDataModule->Busy)
  8880. {
  8881. TTerminalManager::Instance()->ActiveTerminal = ATerminal;
  8882. SetFocus();
  8883. RemoteDirView->Path = UnixExtractFilePath(Path);
  8884. UnicodeString FileName = UnixExtractFileName(Path);
  8885. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  8886. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  8887. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  8888. if (Item == NULL)
  8889. {
  8890. ReloadDirectory(osRemote);
  8891. Item = RemoteDirView->FindFileItem(FileName);
  8892. }
  8893. if (Item != NULL)
  8894. {
  8895. RemoteDirView->ItemFocused = Item;
  8896. RemoteDirView->ItemFocused->MakeVisible(false);
  8897. RemoteDirView->SetFocus();
  8898. }
  8899. }
  8900. }
  8901. //---------------------------------------------------------------------------
  8902. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  8903. {
  8904. bool Result = !NonVisualDataModule->Busy;
  8905. if (Result)
  8906. {
  8907. TTerminalManager::Instance()->ActiveTerminal = ATerminal;
  8908. }
  8909. return Result;
  8910. }
  8911. //---------------------------------------------------------------------------
  8912. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  8913. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8914. {
  8915. if (CanOperateOnFoundFiles(ATerminal))
  8916. {
  8917. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  8918. FOnFileOperationFinished = OnFileOperationFinished;
  8919. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  8920. }
  8921. }
  8922. //---------------------------------------------------------------------------
  8923. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  8924. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8925. {
  8926. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  8927. }
  8928. //---------------------------------------------------------------------------
  8929. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  8930. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8931. {
  8932. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  8933. }
  8934. //---------------------------------------------------------------------------
  8935. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  8936. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8937. {
  8938. if (CanOperateOnFoundFiles(ATerminal))
  8939. {
  8940. for (int Index = 0; Index < FileList->Count; Index++)
  8941. {
  8942. UnicodeString FileName = FileList->Strings[Index];
  8943. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  8944. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  8945. OnFileOperationFinished(FileName, true);
  8946. }
  8947. }
  8948. }
  8949. //---------------------------------------------------------------------------
  8950. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  8951. {
  8952. FFileFindTerminal = Terminal;
  8953. ShowFileFindDialog(
  8954. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  8955. DoDownloadFoundFiles, DoEditFoundFiles);
  8956. }
  8957. //---------------------------------------------------------------------------
  8958. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  8959. {
  8960. FTaskbarList = TaskbarList;
  8961. }
  8962. //---------------------------------------------------------------------------
  8963. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  8964. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  8965. {
  8966. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  8967. if (Index >= 0)
  8968. {
  8969. if (Button == mbLeft)
  8970. {
  8971. // "Mouse down" is raised only after tab is switched.
  8972. // If switching tab (switching session) takes long enough for user
  8973. // to actually release the button, "mouse down" is still raised,
  8974. // but we do not get "mouse up" event, so dragging is not cancelled,
  8975. // prevent that by not beginning dragging in the first place.
  8976. if (IsKeyPressed(VK_LBUTTON))
  8977. {
  8978. // when user clicks the "+", we get mouse down only after the session
  8979. // is closed, when new session tab is already on X:Y, so dragging
  8980. // starts, prevent that
  8981. if (MilliSecondsBetween(Now(), FSessionsPageControlNewSessionTime) > 500)
  8982. {
  8983. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8984. if (Terminal != NULL)
  8985. {
  8986. SessionsPageControl->BeginDrag(false);
  8987. }
  8988. }
  8989. }
  8990. }
  8991. else if (Button == mbMiddle)
  8992. {
  8993. // ignore middle-click for "New session tab"
  8994. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8995. if (Terminal != NULL)
  8996. {
  8997. CloseSessionTab(Index);
  8998. }
  8999. }
  9000. }
  9001. }
  9002. //---------------------------------------------------------------------------
  9003. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  9004. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  9005. {
  9006. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9007. // do not allow dropping on the "+" tab
  9008. TTerminal * TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  9009. if ((TargetTerminal != NULL) &&
  9010. (SessionsPageControl->ActivePage->PageIndex != Index))
  9011. {
  9012. Configuration->Usage->Inc(L"SessionTabMoves");
  9013. // this is almost redundant as we would recreate tabs in DoTerminalListChanged,
  9014. // but we want to actually prevent that to avoid flicker
  9015. SessionsPageControl->ActivePage->PageIndex = Index;
  9016. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->ActivePage);
  9017. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  9018. }
  9019. }
  9020. //---------------------------------------------------------------------------
  9021. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  9022. TObject * Sender, TObject * Source, int X, int Y,
  9023. TDragState /*State*/, bool & Accept)
  9024. {
  9025. Accept = (Sender == Source);
  9026. if (Accept)
  9027. {
  9028. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9029. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  9030. // do not allow dragging to the "+" tab
  9031. Accept = (Terminal != NULL);
  9032. }
  9033. }
  9034. //---------------------------------------------------------------------------
  9035. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(int /*KeyState*/,
  9036. const TPoint & Point, int & Effect)
  9037. {
  9038. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  9039. if (Index < 0)
  9040. {
  9041. Effect = DROPEFFECT_NONE;
  9042. }
  9043. else
  9044. {
  9045. TTerminal * TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  9046. // do not allow dropping on the "+" tab
  9047. if (TargetTerminal == NULL)
  9048. {
  9049. Effect = DROPEFFECT_NONE;
  9050. }
  9051. else if ((TargetTerminal != Terminal) && (Effect == DROPEFFECT_MOVE))
  9052. {
  9053. Effect = DROPEFFECT_COPY;
  9054. }
  9055. }
  9056. }
  9057. //---------------------------------------------------------------------------
  9058. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  9059. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  9060. {
  9061. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  9062. // do not allow dropping on the "+" tab
  9063. TTerminal * TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  9064. if (TargetTerminal != NULL)
  9065. {
  9066. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  9067. if (!IsFileControl(DropSourceControl, osRemote))
  9068. {
  9069. TTerminalManager::Instance()->ActiveTerminal = TargetTerminal;
  9070. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  9071. // Why don't we use Terminal->CurrentDirectory directly?
  9072. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  9073. // do not force queue, drag drop
  9074. false, true);
  9075. }
  9076. }
  9077. }
  9078. //---------------------------------------------------------------------------
  9079. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  9080. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  9081. {
  9082. // Downloads are handled in RemoteFileControlDDEnd
  9083. if (!IsFileControl(DropSourceControl, osRemote))
  9084. {
  9085. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  9086. Terminal->CurrentDirectory,
  9087. // force queue, drag drop
  9088. true, true);
  9089. }
  9090. }
  9091. //---------------------------------------------------------------------------
  9092. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  9093. {
  9094. FShowing = false;
  9095. // Do not save empty workspace
  9096. if (WinConfiguration->AutoSaveWorkspace && (Terminal != NULL))
  9097. {
  9098. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  9099. UnicodeString Name = WorkspaceName();
  9100. DoSaveWorkspace(
  9101. Name, DataList.get(),
  9102. !Configuration->DisablePasswordStoring &&
  9103. WinConfiguration->AutoSaveWorkspacePasswords, false);
  9104. WinConfiguration->LastStoredSession = Name;
  9105. }
  9106. }
  9107. //---------------------------------------------------------------------------
  9108. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  9109. {
  9110. TManagedTerminal * ManagedTerminal =
  9111. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  9112. if (ManagedTerminal != NULL)
  9113. {
  9114. ManagedTerminal->DirectoryLoaded = Now();
  9115. }
  9116. }
  9117. //---------------------------------------------------------------------------
  9118. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  9119. TListItem * /*Item*/, bool /*Selected*/)
  9120. {
  9121. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  9122. switch (DirView->LastSelectMethod)
  9123. {
  9124. case smKeyboard:
  9125. Configuration->Usage->Inc(L"KeyboardSelections");
  9126. break;
  9127. case smMouse:
  9128. Configuration->Usage->Inc(L"MouseSelections");
  9129. break;
  9130. }
  9131. }
  9132. //---------------------------------------------------------------------------
  9133. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  9134. {
  9135. if (Color != 0)
  9136. {
  9137. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  9138. }
  9139. else
  9140. {
  9141. return FSessionTabImageIndex;
  9142. }
  9143. }
  9144. //---------------------------------------------------------------------------
  9145. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  9146. {
  9147. TPngImageCollectionItem * Item =
  9148. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  9149. FSessionColors->AddPng(Item->PngImage);
  9150. return FSessionColors->Count - 1;
  9151. }
  9152. //---------------------------------------------------------------------------
  9153. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  9154. {
  9155. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  9156. FNewSessionTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewSessionAction->ImageIndex);
  9157. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  9158. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  9159. }
  9160. //---------------------------------------------------------------------------
  9161. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  9162. {
  9163. for (int Index = 0; Index < Control->ControlCount; Index++)
  9164. {
  9165. TControl * AControl = Control->Controls[Index];
  9166. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  9167. if (WinControl != NULL)
  9168. {
  9169. CollectItemsWithTextDisplayMode(WinControl);
  9170. }
  9171. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  9172. if (Toolbar != NULL)
  9173. {
  9174. // we care for top-level items only
  9175. TTBCustomItem * Items = Toolbar->Items;
  9176. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  9177. {
  9178. TTBCustomItem * Item = Items->Items[ItemIndex];
  9179. if (((Item->DisplayMode == nbdmImageAndText) ||
  9180. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  9181. EligibleForImageDisplayMode(Item))
  9182. {
  9183. FItemsWithTextDisplayMode.insert(Item);
  9184. }
  9185. }
  9186. }
  9187. }
  9188. }
  9189. //---------------------------------------------------------------------------
  9190. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  9191. {
  9192. return true;
  9193. }
  9194. //---------------------------------------------------------------------------
  9195. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  9196. {
  9197. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  9198. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  9199. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  9200. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  9201. bool Result = true;
  9202. while (Result && (i != FItemsWithTextDisplayMode.end()))
  9203. {
  9204. TTBCustomItem * Item = *i;
  9205. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  9206. if (Label != NULL)
  9207. {
  9208. // optimization
  9209. if (Label->Visible == SelectiveToolbarText)
  9210. {
  9211. Result = false;
  9212. }
  9213. else
  9214. {
  9215. Label->Visible = SelectiveToolbarText;
  9216. }
  9217. }
  9218. else
  9219. {
  9220. // optimization
  9221. if (Item->DisplayMode == DisplayMode)
  9222. {
  9223. Result = false;
  9224. }
  9225. else
  9226. {
  9227. Item->DisplayMode = DisplayMode;
  9228. }
  9229. }
  9230. ++i;
  9231. }
  9232. if (Result)
  9233. {
  9234. UpdateNewSessionTab();
  9235. }
  9236. return Result;
  9237. }
  9238. //---------------------------------------------------------------------------
  9239. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  9240. {
  9241. DebugFail();
  9242. }
  9243. //---------------------------------------------------------------------------
  9244. bool __fastcall TCustomScpExplorerForm::IsBusy()
  9245. {
  9246. // Among other, a lock level is non zero, while directory is being loaded,
  9247. // even when it happens as a result of dirview navigation,
  9248. // i.e. when TNonVisualDataModule is NOT FBusy.
  9249. // That's why the TNonVisualDataModule::GetBusy calls this method.
  9250. // Among other this prevents a panel auto update to occur while
  9251. // directory is changing.
  9252. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  9253. }
  9254. //---------------------------------------------------------------------------
  9255. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * /*Action*/, TActionAllowed Allowed)
  9256. {
  9257. // While the window is disabled, we still seem to process menu shortcuts at least,
  9258. // so stop it at least here.
  9259. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  9260. return
  9261. (Allowed == aaUpdate) ||
  9262. !NonVisualDataModule->Busy;
  9263. }
  9264. //---------------------------------------------------------------------------
  9265. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  9266. {
  9267. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  9268. }
  9269. //---------------------------------------------------------------------------
  9270. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  9271. {
  9272. // This is somewhat redundant to LockWindow() call from
  9273. // TTerminalManager::TerminalReadDirectoryProgress.
  9274. // But disabling window is known not to block keyboard shorcuts
  9275. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  9276. if (Busy > 0)
  9277. {
  9278. if (NonVisualDataModule->Busy)
  9279. {
  9280. State = false;
  9281. }
  9282. else
  9283. {
  9284. NonVisualDataModule->StartBusy();
  9285. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  9286. LockWindow();
  9287. }
  9288. }
  9289. else if (Busy < 0)
  9290. {
  9291. UnlockWindow();
  9292. NonVisualDataModule->EndBusy();
  9293. }
  9294. else
  9295. {
  9296. State = NonVisualDataModule->Busy;
  9297. }
  9298. }
  9299. //---------------------------------------------------------------------------
  9300. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  9301. {
  9302. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  9303. // no context menu for "New session tab"
  9304. if ((Index >= 0) && (GetSessionTabTerminal(SessionsPageControl->Pages[Index]) != NULL))
  9305. {
  9306. SessionsPageControl->ActivePageIndex = Index;
  9307. if (DebugAlwaysTrue(SessionTabSwitched()))
  9308. {
  9309. // copied from TControl.WMContextMenu
  9310. SendCancelMode(SessionsPageControl);
  9311. // explicit popup instead of using PopupMenu property
  9312. // to avoid menu to popup somewhere within SessionTabSwitched above,
  9313. // while connecting yet not-connected session and hence
  9314. // allowing an access to commands over not-completelly connected session
  9315. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  9316. TPopupMenu * PopupMenu = NonVisualDataModule->SessionsPopup;
  9317. PopupMenu->PopupComponent = SessionsPageControl;
  9318. PopupMenu->Popup(Point.x, Point.y);
  9319. }
  9320. }
  9321. Handled = true;
  9322. }
  9323. //---------------------------------------------------------------------------
  9324. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  9325. {
  9326. return (Terminal != NULL) && Terminal->Active && Terminal->IsCapable[fcChangePassword];
  9327. }
  9328. //---------------------------------------------------------------------------
  9329. void __fastcall TCustomScpExplorerForm::ChangePassword()
  9330. {
  9331. Configuration->Usage->Inc(L"PasswordChanges");
  9332. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  9333. ChangePasswordData->DisableAuthentationsExceptPassword();
  9334. ChangePasswordData->ChangePassword = true;
  9335. std::unique_ptr<TTerminal> ChangePasswordSession(
  9336. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  9337. ChangePasswordSession->AutoReadDirectory = false;
  9338. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  9339. {
  9340. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  9341. }
  9342. else
  9343. {
  9344. Configuration->Usage->Inc(L"PasswordChangesFailed");
  9345. }
  9346. }
  9347. //---------------------------------------------------------------------------
  9348. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  9349. {
  9350. // No nice way to assert SSH2
  9351. return (Terminal != NULL) && Terminal->Active && (Terminal->FSProtocol == cfsSFTP);
  9352. }
  9353. //---------------------------------------------------------------------------
  9354. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  9355. {
  9356. TOperationVisualizer OperationVisualizer;
  9357. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  9358. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  9359. }
  9360. //---------------------------------------------------------------------------
  9361. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  9362. {
  9363. TForm::ChangeScale(M, D);
  9364. int APixelsPerInch = GetControlPixelsPerInch(this);
  9365. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  9366. try
  9367. {
  9368. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  9369. }
  9370. __finally
  9371. {
  9372. GUIConfiguration->ChangeResourceModule(ResourceModule);
  9373. }
  9374. }
  9375. //---------------------------------------------------------------------------
  9376. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  9377. {
  9378. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  9379. }
  9380. //---------------------------------------------------------------------
  9381. class TPublicControl : public TControl
  9382. {
  9383. friend class TCustomScpExplorerForm;
  9384. };
  9385. //---------------------------------------------------------------------------
  9386. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  9387. {
  9388. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  9389. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  9390. }
  9391. //---------------------------------------------------------------------------
  9392. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  9393. {
  9394. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  9395. OpenBookmark(Side, Bookmark);
  9396. }
  9397. //---------------------------------------------------------------------------
  9398. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  9399. {
  9400. DoBookmarkClick(osLocal, Sender);
  9401. }
  9402. //---------------------------------------------------------------------------
  9403. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  9404. {
  9405. DoBookmarkClick(osRemote, Sender);
  9406. }
  9407. //---------------------------------------------------------------------------
  9408. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  9409. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  9410. {
  9411. // TODO
  9412. if (BookmarkList != NULL)
  9413. {
  9414. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  9415. if (!WinConfiguration->UseLocationProfiles)
  9416. {
  9417. std::unique_ptr<TStringList> Directories(new TStringList());
  9418. Directories->CaseSensitive = (Side == osRemote);
  9419. for (int Index = 0; Index < BookmarkList->Count; Index++)
  9420. {
  9421. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  9422. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  9423. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  9424. {
  9425. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  9426. Item->Caption = EscapeHotkey(Directory);
  9427. Item->ShortCut = Bookmark->ShortCut;
  9428. Item->OnClick = OnBookmarkClick;
  9429. Item->Tag = reinterpret_cast<int>(Bookmark);
  9430. Directories->Add(Directory);
  9431. Menu->Add(Item.release());
  9432. }
  9433. }
  9434. }
  9435. else
  9436. {
  9437. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  9438. for (int Index = 0; Index < BookmarkList->Count; Index++)
  9439. {
  9440. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  9441. if (!Bookmark->Node.IsEmpty())
  9442. {
  9443. Folders->Add(Bookmark->Node);
  9444. }
  9445. }
  9446. for (int Index = 0; Index < Folders->Count; Index++)
  9447. {
  9448. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  9449. Item->Caption = Folders->Strings[Index];
  9450. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction->ImageIndex;
  9451. Folders->Objects[Index] = Item.get();
  9452. Menu->Add(Item.release());
  9453. }
  9454. for (int Index = 0; Index < BookmarkList->Count; Index++)
  9455. {
  9456. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  9457. TTBCustomItem * Parent;
  9458. if (!Bookmark->Node.IsEmpty())
  9459. {
  9460. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  9461. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  9462. }
  9463. else
  9464. {
  9465. Parent = Menu;
  9466. }
  9467. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  9468. Item->Caption = Bookmark->Name;
  9469. Item->ShortCut = Bookmark->ShortCut;
  9470. Item->OnClick = OnBookmarkClick;
  9471. Item->Tag = reinterpret_cast<int>(Bookmark);
  9472. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  9473. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  9474. {
  9475. // No hint for location profiles that are actually mere "bookmarks"
  9476. }
  9477. else
  9478. {
  9479. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  9480. UnicodeString LongHint;
  9481. if (!Bookmark->Local.IsEmpty())
  9482. {
  9483. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  9484. }
  9485. if (!Bookmark->Remote.IsEmpty())
  9486. {
  9487. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  9488. }
  9489. AddToList(Hint, LongHint, L"|");
  9490. Item->Hint = Hint;
  9491. }
  9492. Parent->Add(Item.release());
  9493. }
  9494. }
  9495. AddMenuSeparator(Menu);
  9496. }
  9497. }
  9498. //---------------------------------------------------------------------------
  9499. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  9500. {
  9501. Menu->Clear();
  9502. std::unique_ptr<TTBCustomItem> Item;
  9503. Item.reset(new TTBXItem(Owner));
  9504. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  9505. Item->Options = Item->Options << tboDefault;
  9506. Menu->Add(Item.release());
  9507. AddMenuSeparator(Menu);
  9508. if (Terminal != NULL)
  9509. {
  9510. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  9511. }
  9512. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  9513. Item.reset(new TTBXItem(Owner));
  9514. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction : NonVisualDataModule->RemoteAddBookmarkAction;
  9515. Menu->Add(Item.release());
  9516. }
  9517. //---------------------------------------------------------------------------
  9518. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  9519. {
  9520. bool Result = true;
  9521. try
  9522. {
  9523. if (Side == osRemote)
  9524. {
  9525. Terminal->ExceptionOnFail = true;
  9526. }
  9527. try
  9528. {
  9529. DirView(Side)->Path = Path;
  9530. }
  9531. __finally
  9532. {
  9533. if (Side == osRemote)
  9534. {
  9535. Terminal->ExceptionOnFail = false;
  9536. }
  9537. }
  9538. }
  9539. catch (Exception & E)
  9540. {
  9541. if ((Side != osRemote) || Terminal->Active)
  9542. {
  9543. ShowExtendedExceptionEx(Terminal, &E);
  9544. Result = false;
  9545. }
  9546. else
  9547. {
  9548. throw;
  9549. }
  9550. }
  9551. return Result;
  9552. }
  9553. //---------------------------------------------------------------------------
  9554. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  9555. {
  9556. // Make sure there some feedback even when loading tiny local folders
  9557. TInstantOperationVisualizer Visualizer;
  9558. DirView(Side)->ReloadDirectory();
  9559. }
  9560. //---------------------------------------------------------------------------
  9561. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  9562. {
  9563. if (Index == SessionsPageControl->TabIndex)
  9564. {
  9565. CloseSession();
  9566. }
  9567. else
  9568. {
  9569. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  9570. TTerminal * Terminal = GetSessionTabTerminal(TabSheet);
  9571. TTerminalManager * Manager = TTerminalManager::Instance();
  9572. if (!Terminal->Active)
  9573. {
  9574. Manager->FreeTerminal(Terminal);
  9575. }
  9576. else
  9577. {
  9578. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  9579. if (CanCloseQueue(Queue))
  9580. {
  9581. Manager->FreeTerminal(Terminal);
  9582. }
  9583. }
  9584. }
  9585. }
  9586. //---------------------------------------------------------------------------
  9587. void __fastcall TCustomScpExplorerForm::SessionsPageControlCloseButtonClick(TPageControl * /*Sender*/, int Index)
  9588. {
  9589. CloseSessionTab(Index);
  9590. }
  9591. //---------------------------------------------------------------------------
  9592. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side)
  9593. {
  9594. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  9595. {
  9596. TInstantOperationVisualizer Visualizer;
  9597. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  9598. // before we create a new data object
  9599. ClipboardClear();
  9600. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  9601. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  9602. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  9603. FClipboardFakeMonitors.reset(StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated));
  9604. if (FClipboardDragDropFilesEx.get() == NULL)
  9605. {
  9606. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  9607. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  9608. }
  9609. FClipboardDragDropFilesEx->FileList->Clear();
  9610. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  9611. FClipboardDragDropFilesEx->CopyToClipboard();
  9612. FClipboardTerminal = FTerminal;
  9613. // Need full paths, as cwd can be different once files are pasted
  9614. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(false, true)));
  9615. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  9616. {
  9617. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  9618. }
  9619. }
  9620. }
  9621. //---------------------------------------------------------------------------
  9622. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  9623. {
  9624. if (OpenClipboard(0))
  9625. {
  9626. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  9627. CloseClipboard();
  9628. }
  9629. }
  9630. //---------------------------------------------------------------------------
  9631. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  9632. {
  9633. return !FClipboardFakeDirectory.IsEmpty();
  9634. }
  9635. //---------------------------------------------------------------------------
  9636. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  9637. {
  9638. RemoveDir(ApiPath(FClipboardFakeDirectory));
  9639. FClipboardFakeDirectory = UnicodeString();
  9640. FClipboardTerminal = NULL;
  9641. // Also called in Idle()
  9642. FClipboardFakeMonitors.reset(NULL);
  9643. }
  9644. //---------------------------------------------------------------------------
  9645. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  9646. {
  9647. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  9648. {
  9649. ClipboardStop();
  9650. }
  9651. }
  9652. //---------------------------------------------------------------------------
  9653. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  9654. {
  9655. TTerminalManager * Manager = TTerminalManager::Instance();
  9656. Manager->ActiveTerminal = FClipboardTerminal;
  9657. TTransferOperationParam Params;
  9658. Params.TargetDirectory = TargetDirectory;
  9659. Params.DragDrop = DragDrop;
  9660. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  9661. }
  9662. //---------------------------------------------------------------------------
  9663. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  9664. {
  9665. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  9666. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  9667. {
  9668. RemoveDir(ApiPath(FileName));
  9669. if (!NonVisualDataModule->Busy)
  9670. {
  9671. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  9672. ClipboardDownload(ExtractFilePath(FileName), NoConfirmation, true);
  9673. }
  9674. }
  9675. }
  9676. //---------------------------------------------------------------------------
  9677. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  9678. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  9679. {
  9680. TFileMasks::TParams MaskParams;
  9681. MaskParams.Size = Size;
  9682. MaskParams.Modification = Modification;
  9683. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  9684. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  9685. {
  9686. bool ImplicitMatch;
  9687. if (Iter->FileMask.Matches(FileName, Directory, DirView->PathName, &MaskParams, false, ImplicitMatch) &&
  9688. !ImplicitMatch)
  9689. {
  9690. Color = Iter->Color;
  9691. break;
  9692. }
  9693. }
  9694. }
  9695. //---------------------------------------------------------------------------
  9696. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  9697. {
  9698. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9699. if (!DirView->IsEditing())
  9700. {
  9701. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  9702. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  9703. // while searching
  9704. if (Key == VK_BACK)
  9705. {
  9706. if (!FIncrementalSearch.IsEmpty())
  9707. {
  9708. if (FIncrementalSearch.Length() == 1)
  9709. {
  9710. ResetIncrementalSearch();
  9711. }
  9712. else
  9713. {
  9714. UnicodeString NewText = FIncrementalSearch.SubString(1, FIncrementalSearch.Length() - 1);
  9715. IncrementalSearch(NewText, false, false);
  9716. }
  9717. Key = 0;
  9718. }
  9719. }
  9720. }
  9721. }
  9722. //---------------------------------------------------------------------------
  9723. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  9724. {
  9725. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9726. if (!DirView->IsEditing())
  9727. {
  9728. // Filter control sequences.
  9729. // When not searching yet, prefer use of the space for toggling file selection
  9730. // (so we cannot incrementally search for a string starting with a space).
  9731. if ((Key > VK_SPACE) ||
  9732. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && !FIncrementalSearch.IsEmpty()))
  9733. {
  9734. IncrementalSearch(FIncrementalSearch + Key, false, false);
  9735. Key = 0;
  9736. }
  9737. }
  9738. }
  9739. //---------------------------------------------------------------------------
  9740. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  9741. {
  9742. if (!FIncrementalSearch.IsEmpty())
  9743. {
  9744. FIncrementalSearch = L"";
  9745. DirView(osCurrent)->UpdateStatusBar();
  9746. }
  9747. }
  9748. //---------------------------------------------------------------------------
  9749. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  9750. {
  9751. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  9752. if (Item == NULL)
  9753. {
  9754. MessageBeep(MB_ICONHAND);
  9755. }
  9756. else
  9757. {
  9758. TCustomDirView * ADirView = DirView(osCurrent);
  9759. {
  9760. TAutoNestingCounter Guard(FIncrementalSearching);
  9761. ADirView->FocusItem(Item);
  9762. if (ADirView->NortonLike == nlOff)
  9763. {
  9764. if ((ADirView->Selected != Item) ||
  9765. (ADirView->SelCount > 1))
  9766. {
  9767. ADirView->ClearSelection();
  9768. ADirView->Selected = Item;
  9769. }
  9770. }
  9771. }
  9772. FIncrementalSearch = Text;
  9773. Item->MakeVisible(false);
  9774. TListItem * NextItem = SearchFile(Text, true, Reverse);
  9775. FIncrementalSearchHaveNext = (NextItem != NULL) && (NextItem != Item);
  9776. ADirView->UpdateStatusBar();
  9777. }
  9778. }
  9779. //---------------------------------------------------------------------------
  9780. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  9781. {
  9782. int Index = Item->Index;
  9783. if (!Reverse)
  9784. {
  9785. Index++;
  9786. if (Index >= Item->Owner->Count)
  9787. {
  9788. Index = 0;
  9789. }
  9790. }
  9791. else
  9792. {
  9793. Index--;
  9794. if (Index < 0)
  9795. {
  9796. Index = Item->Owner->Count - 1;
  9797. }
  9798. }
  9799. return Item->Owner->Item[Index];
  9800. }
  9801. //---------------------------------------------------------------------------
  9802. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  9803. {
  9804. TCustomDirView * ADirView = DirView(osCurrent);
  9805. if (ADirView->Items->Count == 0)
  9806. {
  9807. return NULL;
  9808. }
  9809. else
  9810. {
  9811. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  9812. TListItem * Item = CurrentItem;
  9813. if (SkipCurrent)
  9814. {
  9815. Item = DebugNotNull(GetNextFile(Item, Reverse));
  9816. }
  9817. while (true)
  9818. {
  9819. bool Matches = false;
  9820. switch (WinConfiguration->PanelSearch)
  9821. {
  9822. case isNameStartOnly:
  9823. Matches = ContainsTextSemiCaseSensitive(Item->Caption.SubString(1, Text.Length()), Text);
  9824. break;
  9825. case isName:
  9826. Matches = ContainsTextSemiCaseSensitive(Item->Caption, Text);
  9827. break;
  9828. case isAll:
  9829. int ColCount = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Count : 1;
  9830. int Index = 0;
  9831. while ((Index < ColCount) && !Matches)
  9832. {
  9833. bool Visible = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Visible[Index] : true;
  9834. if (Visible)
  9835. {
  9836. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  9837. }
  9838. Index++;
  9839. }
  9840. break;
  9841. }
  9842. if (Matches)
  9843. {
  9844. return Item;
  9845. }
  9846. Item = GetNextFile(Item, Reverse);
  9847. if (Item == CurrentItem)
  9848. {
  9849. return NULL;
  9850. }
  9851. }
  9852. }
  9853. }
  9854. //---------------------------------------------------------------------------
  9855. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  9856. {
  9857. ResetIncrementalSearch();
  9858. }
  9859. //---------------------------------------------------------------------------
  9860. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  9861. {
  9862. if (Message.CharCode == VK_TAB)
  9863. {
  9864. if (!FIncrementalSearch.IsEmpty())
  9865. {
  9866. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  9867. bool Reverse = Shift.Contains(ssShift);
  9868. IncrementalSearch(FIncrementalSearch, true, Reverse);
  9869. Message.Result = 1;
  9870. return;
  9871. }
  9872. }
  9873. else if (Message.CharCode == VK_ESCAPE)
  9874. {
  9875. if (!FIncrementalSearch.IsEmpty())
  9876. {
  9877. ResetIncrementalSearch();
  9878. Message.Result = 1;
  9879. return;
  9880. }
  9881. }
  9882. TForm::Dispatch(&Message);
  9883. }
  9884. //---------------------------------------------------------------------------
  9885. void __fastcall TCustomScpExplorerForm::Deactivate()
  9886. {
  9887. TForm::Deactivate();
  9888. // E.g. when switching to an internal editor window
  9889. ResetIncrementalSearch();
  9890. }
  9891. //---------------------------------------------------------------------------
  9892. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  9893. {
  9894. // When switching to another application
  9895. ResetIncrementalSearch();
  9896. }
  9897. //---------------------------------------------------------------------------
  9898. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  9899. {
  9900. ResetIncrementalSearch();
  9901. }
  9902. //---------------------------------------------------------------------------
  9903. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  9904. {
  9905. if (FIncrementalSearching <= 0)
  9906. {
  9907. ResetIncrementalSearch();
  9908. }
  9909. }
  9910. //---------------------------------------------------------------------------
  9911. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  9912. {
  9913. CountClicksForWindowPrint(this);
  9914. }
  9915. //---------------------------------------------------------------------------