CustomScpExplorer.cpp 405 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include <Common.h>
  6. #include "CustomScpExplorer.h"
  7. #include <algorithm>
  8. #include <Bookmarks.h>
  9. #include <Interface.h>
  10. #include <Exceptions.h>
  11. #include <CoreMain.h>
  12. #include <FileSystems.h>
  13. #include <TextsCore.h>
  14. #include <TextsWin.h>
  15. #include <HelpWin.h>
  16. #include <VCLCommon.h>
  17. #include <Progress.h>
  18. #include <SynchronizeProgress.h>
  19. #include <DragExt.h>
  20. #include <WinApi.h>
  21. #include "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. #include <System.IOUtils.hpp>
  34. #include <System.StrUtils.hpp>
  35. //---------------------------------------------------------------------------
  36. #pragma package(smart_init)
  37. #pragma link "CustomDirView"
  38. #pragma link "CustomUnixDirView"
  39. #pragma link "IEListView"
  40. #pragma link "NortonLikeListView"
  41. #pragma link "UnixDirView"
  42. #pragma link "CustomDriveView"
  43. #pragma link "UnixDriveView"
  44. #pragma link "CustomDriveView"
  45. #pragma link "TB2Dock"
  46. #pragma link "TBXStatusBars"
  47. #pragma link "TB2Item"
  48. #pragma link "TB2Toolbar"
  49. #pragma link "ThemePageControl"
  50. #pragma link "PathLabel"
  51. #pragma resource "*.dfm"
  52. //---------------------------------------------------------------------------
  53. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  54. #define WM_PASTE_FILES (WM_WINSCP_USER + 14)
  55. static const int SessionPanelCount = 3;
  56. //---------------------------------------------------------------------------
  57. class TMutexGuard
  58. {
  59. public:
  60. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  61. int Timeout = 5000)
  62. {
  63. FMutex = NULL;
  64. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  65. if (WaitResult == WAIT_TIMEOUT)
  66. {
  67. throw Exception(LoadStr(MUTEX_RELEASE_TIMEOUT));
  68. }
  69. else
  70. {
  71. FMutex = AMutex;
  72. }
  73. }
  74. ~TMutexGuard()
  75. {
  76. if (FMutex != NULL)
  77. {
  78. ReleaseMutex(FMutex);
  79. }
  80. }
  81. private:
  82. HANDLE FMutex;
  83. };
  84. //---------------------------------------------------------------------------
  85. class TWindowLock
  86. {
  87. public:
  88. TWindowLock(TCustomScpExplorerForm * Form) :
  89. FForm(Form)
  90. {
  91. FForm->LockWindow();
  92. }
  93. ~TWindowLock()
  94. {
  95. FForm->UnlockWindow();
  96. }
  97. private:
  98. TCustomScpExplorerForm * FForm;
  99. };
  100. //---------------------------------------------------------------------------
  101. TAutoBatch::TAutoBatch(TCustomScpExplorerForm * Form) :
  102. FForm(Form)
  103. {
  104. FForm->BatchStart(FBatchStorage);
  105. }
  106. //---------------------------------------------------------------------------
  107. TAutoBatch::~TAutoBatch()
  108. {
  109. FForm->BatchEnd(FBatchStorage);
  110. }
  111. //---------------------------------------------------------------------------
  112. struct TTransferOperationParam
  113. {
  114. TTransferOperationParam();
  115. UnicodeString TargetDirectory;
  116. bool Temp;
  117. bool DragDrop;
  118. int Options;
  119. TAutoSwitch Queue;
  120. };
  121. //---------------------------------------------------------------------------
  122. TTransferOperationParam::TTransferOperationParam()
  123. {
  124. Temp = false;
  125. DragDrop = false;
  126. Options = 0;
  127. Queue = asAuto;
  128. }
  129. //---------------------------------------------------------------------------
  130. class TTransferPresetNoteData : public TObject
  131. {
  132. public:
  133. UnicodeString Message;
  134. };
  135. //---------------------------------------------------------------------------
  136. class TTerminalNoteData : public TObject
  137. {
  138. public:
  139. TManagedTerminal * Terminal;
  140. };
  141. //---------------------------------------------------------------------------
  142. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  143. FFormRestored(false),
  144. TForm(Owner)
  145. {
  146. AddStartupSequence(L"F");
  147. FInvalid = false;
  148. FCurrentSide = osRemote;
  149. FEverShown = false;
  150. FDocks = new TList();
  151. InitControls();
  152. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  153. // So that UpdateCustomCommandsToolbar called from RestoreParams works
  154. NonVisualDataModule->ScpExplorer = this;
  155. RestoreParams();
  156. ConfigurationChanged();
  157. RemoteDirView->Invalidate();
  158. FAutoOperation = false;
  159. FOnFileOperationFinished = NULL;
  160. FPrimaryOperation = foNone;
  161. FForceExecution = false;
  162. FIgnoreNextDialogChar = 0;
  163. FErrorList = NULL;
  164. FSynchronizeProgressForm = NULL;
  165. FProgressForm = NULL;
  166. FRefreshLocalDirectory = false;
  167. FRefreshRemoteDirectory = false;
  168. FDDExtMapFile = NULL;
  169. // CreateMutexW keeps failing with ERROR_NOACCESS
  170. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  171. DebugAssert(FDDExtMutex != NULL);
  172. FDDTargetControl = NULL;
  173. FDelayedDeletionTimer = NULL;
  174. FDelayedDeletionList = new TStringList();
  175. FDDFileList = NULL;
  176. FPendingTempSpaceWarn = false;
  177. FCapturedLog = NULL;
  178. FDragDropOperation = false;
  179. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  180. FAllowTransferPresetAutoSelect = true;
  181. FSessionChanging = false;
  182. FCopyParamDefault = L"";
  183. FSynchronizeController = NULL;
  184. FPendingQueueActionItem = NULL;
  185. FLockLevel = 0;
  186. FLockSuspendLevel = 0;
  187. FDisabledOnLockSuspend = false;
  188. FAlternativeDelete = false;
  189. FTrayIcon = new ::TTrayIcon(0);
  190. FTrayIcon->OnClick = TrayIconClick;
  191. FMaxQueueLength = 0;
  192. FLastContextPopupScreenPoint = TPoint(-1, -1);
  193. FTransferResumeList = NULL;
  194. FDeletedFiles = NULL;
  195. FMoveToQueue = false;
  196. StandaloneOperation = false;
  197. FOnFeedSynchronizeError = NULL;
  198. FOnSynchronizeAbort = NULL;
  199. FSynchronizeTerminal = NULL;
  200. FNeedSession = false;
  201. FDoNotIdleCurrentTerminal = 0;
  202. FIncrementalSearching = 0;
  203. FQueueFileList.reset(new TQueueFileList());
  204. FProgressSide = osCurrent;
  205. FCalculateSizeOperation = NULL;
  206. FDownloadingFromClipboard = false;
  207. FClipboardFakeMonitorsPendingReset = false;
  208. FHiContrastTheme = NULL;
  209. FEditorManager = new TEditorManager();
  210. FEditorManager->OnFileChange = ExecutedFileChanged;
  211. FEditorManager->OnFileReload = ExecutedFileReload;
  212. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  213. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  214. FLocalEditors = new TList();
  215. FQueueStatus = NULL;
  216. FQueueStatusSection = new TCriticalSection();
  217. FQueueStatusInvalidated = false;
  218. FQueueItemInvalidated = false;
  219. FQueueStatusUpdating = false;
  220. FQueueActedItem = NULL;
  221. FQueueController = new TQueueController(QueueView3);
  222. FQueueScrollOnDragOver = new TListViewScrollOnDragOver(QueueView3, true);
  223. FUserActionTimer = new TTimer(this);
  224. FUserActionTimer->Enabled = false;
  225. FUserActionTimer->Interval = 10;
  226. FUserActionTimer->OnTimer = UserActionTimer;
  227. FNotes = new TStringList();
  228. FNoteTimer = new TTimer(this);
  229. FNoteTimer->Enabled = false;
  230. FNoteTimer->OnTimer = NoteTimer;
  231. FOnNoteClick = NULL;
  232. FOle32Library = LoadLibrary(L"Ole32.dll");
  233. FDragMoveCursor = FOle32Library != NULL ?
  234. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  235. UseSystemSettings(this);
  236. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  237. static_cast<TObject*>(GetComponent(fcTransferList)));
  238. DebugAssert(TransferList != NULL);
  239. FTransferListHoverIndex = -1;
  240. TransferList->OnChange = TransferListChange;
  241. TransferList->OnDrawItem = TransferListDrawItem;
  242. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))), true);
  243. SetSubmenu(NonVisualDataModule->ColorMenuItem, true);
  244. UseDesktopFont(SessionsPageControl);
  245. UpdateSessionsPageControlHeight();
  246. UseDesktopFont(RemoteDirView);
  247. UseDesktopFont(RemoteDriveView);
  248. UseDesktopFont(QueueView3);
  249. UseDesktopFont(QueueFileList);
  250. UseDesktopFont(QueueLabel);
  251. UseDesktopFont(RemoteStatusBar);
  252. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  253. QueueSplitter->ShowHint = true;
  254. reinterpret_cast<TLabel*>(QueueFileListSplitter)->OnDblClick = QueueFileListSplitterDblClick;
  255. QueueFileListSplitter->ShowHint = true;
  256. RemotePanelSplitter->ShowHint = true;
  257. UpdateImages();
  258. FCustomCommandMenu = CreateTBXPopupMenu(this);
  259. FCustomCommandLocalFileList = NULL;
  260. FCustomCommandRemoteFileList = NULL;
  261. FSessionColors = new TPngImageList(this);
  262. FSessionColors->ColorDepth = cd32Bit;
  263. AddFixedSessionImages();
  264. SessionsPageControl->Images = FSessionColors;
  265. UpdateQueueLabel();
  266. CheckStoreTransition();
  267. CreateHiddenWindow();
  268. StartUpdates();
  269. // Start loading drive data, so that they are ready once we need them for StartCreationDirectoryMonitorsOnEachDrive
  270. // (necessary for "explorer" only, as "commander" loads it for its drive menu)
  271. DriveInfo->NeedData();
  272. }
  273. //---------------------------------------------------------------------------
  274. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  275. {
  276. FInvalid = true;
  277. ReleaseHiContrastTheme();
  278. if (FClipboardTerminal != NULL)
  279. {
  280. ClipboardClear(); // implies ClipboardStop
  281. }
  282. // this has to be one of the very first things to do
  283. StopUpdateThread();
  284. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  285. TTerminalManager::Instance()->ScpExplorer = NULL;
  286. delete FCustomCommandLocalFileList;
  287. delete FCustomCommandRemoteFileList;
  288. delete FCustomCommandMenu;
  289. delete FTrayIcon;
  290. FTrayIcon = NULL;
  291. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  292. delete FEditorManager;
  293. ForceCloseLocalEditors();
  294. delete FLocalEditors;
  295. HideFileFindDialog();
  296. if (FDelayedDeletionTimer)
  297. {
  298. DoDelayedDeletion(NULL);
  299. SAFE_DESTROY(FDelayedDeletionTimer);
  300. }
  301. SAFE_DESTROY(FDelayedDeletionList);
  302. // sometimes we do not get DDEnd so the list is not released
  303. SAFE_DESTROY(FDDFileList);
  304. DebugAssert(FSynchronizeController == NULL);
  305. CloseHandle(FDDExtMutex);
  306. FDDExtMutex = NULL;
  307. FreeLibrary(FOle32Library);
  308. FOle32Library = NULL;
  309. FDragMoveCursor = NULL;
  310. DebugAssert(!FErrorList);
  311. if (FEverShown)
  312. {
  313. // when window is never shown (like when running command-line operation),
  314. // particularly window site is not restored correctly (BoundsRect value set
  315. // in RestoreForm gets lost during handle allocation), so we do not want
  316. // it to be stored
  317. StoreParams();
  318. }
  319. ManagedSession = NULL;
  320. Queue = NULL;
  321. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  322. NonVisualDataModule->ScpExplorer = NULL;
  323. delete FQueueScrollOnDragOver;
  324. FQueueScrollOnDragOver = NULL;
  325. delete FQueueController;
  326. FQueueController = NULL;
  327. delete FQueueStatusSection;
  328. FQueueStatusSection = NULL;
  329. delete FQueueStatus;
  330. FQueueStatus = NULL;
  331. delete FUserActionTimer;
  332. FUserActionTimer = NULL;
  333. delete FNoteTimer;
  334. delete FNotes;
  335. delete FNoteData;
  336. SAFE_DESTROY(FDocks);
  337. SessionsPageControl->Images = NULL;
  338. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  339. SAFE_DESTROY(FSessionColors);
  340. SAFE_DESTROY(FSessionsDragDropFilesEx);
  341. SAFE_DESTROY(FHistoryMenu[0][0]);
  342. SAFE_DESTROY(FHistoryMenu[0][1]);
  343. SAFE_DESTROY(FHistoryMenu[1][0]);
  344. SAFE_DESTROY(FHistoryMenu[1][1]);
  345. if (FHiddenWindow != NULL)
  346. {
  347. DestroyWindow(FHiddenWindow);
  348. FHiddenWindow = NULL;
  349. }
  350. }
  351. //---------------------------------------------------------------------------
  352. void TCustomScpExplorerForm::ReleaseHiContrastTheme()
  353. {
  354. if (FHiContrastTheme != NULL)
  355. {
  356. ReleaseTBXTheme(FHiContrastTheme);
  357. FHiContrastTheme = NULL;
  358. }
  359. }
  360. //---------------------------------------------------------------------------
  361. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  362. {
  363. std::unique_ptr<TSessionData> Data;
  364. if (!Session.IsEmpty())
  365. {
  366. bool DefaultsOnly;
  367. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  368. }
  369. TTerminalManager * Manager = TTerminalManager::Instance();
  370. for (int Index = 0; Index < Manager->Count; Index++)
  371. {
  372. TTerminal * Terminal = Manager->Sessions[Index];
  373. if (Session.IsEmpty() ||
  374. Manager->IsActiveTerminalForSite(Terminal, Data.get()))
  375. {
  376. if (Path.IsEmpty())
  377. {
  378. Terminal->ClearCaches();
  379. }
  380. else
  381. {
  382. Terminal->DirectoryModified(Path, true);
  383. }
  384. }
  385. }
  386. // We should flag a pending refresh for the background terminals or busy foreground terminals
  387. if (HasActiveTerminal() &&
  388. CanCommandLineFromAnotherInstance() &&
  389. (Session.IsEmpty() || Manager->IsActiveTerminalForSite(Terminal, Data.get())) &&
  390. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  391. {
  392. Terminal->ReloadDirectory();
  393. }
  394. }
  395. //---------------------------------------------------------------------------
  396. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  397. {
  398. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  399. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  400. size_t MessageSize = sizeof(TCopyDataMessage);
  401. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  402. if (Result)
  403. {
  404. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  405. Result = (Message.Version == TCopyDataMessage::Version1);
  406. if (Result)
  407. {
  408. switch (Message.Command)
  409. {
  410. case TCopyDataMessage::CommandCanCommandLine:
  411. Result = CanCommandLineFromAnotherInstance();
  412. if (Result)
  413. {
  414. AppLog(L"Can process command-line from other instance");
  415. }
  416. else
  417. {
  418. AppLog(L"Cannot process command-line from other instance");
  419. }
  420. break;
  421. case TCopyDataMessage::CommandCommandLine:
  422. {
  423. UnicodeString CommandLine(Message.CommandLine);
  424. Result = CommandLineFromAnotherInstance(CommandLine);
  425. }
  426. break;
  427. case TCopyDataMessage::RefreshPanel:
  428. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  429. break;
  430. case TCopyDataMessage::MainWindowCheck:
  431. Result = true;
  432. break;
  433. default:
  434. Result = false;
  435. break;
  436. }
  437. }
  438. }
  439. Message.Result = Result ? 1 : 0;
  440. }
  441. //---------------------------------------------------------------------------
  442. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  443. {
  444. WNDCLASS WindowClass = {0};
  445. WindowClass.lpfnWndProc = DefWindowProc;
  446. WindowClass.hInstance = HInstance;
  447. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  448. FHiddenWindow = NULL;
  449. if (RegisterClass(&WindowClass))
  450. {
  451. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  452. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  453. }
  454. }
  455. //---------------------------------------------------------------------------
  456. bool __fastcall TCustomScpExplorerForm::CanConsole()
  457. {
  458. return
  459. HasActiveTerminal() &&
  460. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  461. }
  462. //---------------------------------------------------------------------------
  463. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  464. {
  465. bool Result = Visible && !NonVisualDataModule->Busy;
  466. return Result;
  467. }
  468. //---------------------------------------------------------------------------
  469. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  470. const UnicodeString & CommandLine)
  471. {
  472. TProgramParams Params(CommandLine);
  473. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  474. if (Result)
  475. {
  476. NonVisualDataModule->StartBusy();
  477. try
  478. {
  479. // this action is initiated from another process,
  480. // so it's likely that our window is not visible,
  481. // and user won't see what is going on
  482. Application->BringToFront();
  483. // reload sessions as we may be asked to open a session
  484. // just stored by another instance
  485. StoredSessions->Reload();
  486. UnicodeString SessionName = Params.Param[1];
  487. std::unique_ptr<TObjectList> DataList(new TObjectList());
  488. try
  489. {
  490. UnicodeString DownloadFile; // unused
  491. int Flags = GetCommandLineParseUrlFlags(&Params);
  492. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  493. }
  494. catch (EAbort &)
  495. {
  496. // Happens when opening session in PuTTY and in other situations,
  497. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  498. // to process the command-line on its own (or to pass it to yet another instance)
  499. }
  500. if (DataList->Count > 0)
  501. {
  502. TTerminalManager * Manager = TTerminalManager::Instance();
  503. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  504. }
  505. }
  506. __finally
  507. {
  508. NonVisualDataModule->EndBusy();
  509. }
  510. }
  511. return Result;
  512. }
  513. //---------------------------------------------------------------------------
  514. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  515. {
  516. TManagedTerminal * Result;
  517. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  518. {
  519. Result = FManagedSession;
  520. }
  521. else
  522. {
  523. Result = NULL;
  524. }
  525. return Result;
  526. }
  527. //---------------------------------------------------------------------------
  528. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  529. {
  530. if (FManagedSession != value)
  531. {
  532. TWindowLock Lock(this);
  533. SessionChanging();
  534. DoSetManagedSession(value, false);
  535. }
  536. }
  537. //---------------------------------------------------------------------------
  538. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  539. {
  540. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  541. FManagedSession = value;
  542. {
  543. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect, false);
  544. TAutoFlag SessionChangingFlag(FSessionChanging);
  545. SessionChanged(Replace);
  546. }
  547. if (Terminal != NULL)
  548. {
  549. TransferPresetAutoSelect();
  550. }
  551. // Update app and tab titles, prevented above by FSessionChanging.
  552. UpdateControls();
  553. }
  554. //---------------------------------------------------------------------------
  555. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  556. {
  557. FEditorManager->ProcessFiles(FileTerminalReplaced, value);
  558. DoSetManagedSession(value, true);
  559. }
  560. //---------------------------------------------------------------------------
  561. void __fastcall TCustomScpExplorerForm::SessionChanging()
  562. {
  563. if (ManagedSession != NULL)
  564. {
  565. UpdateSession(ManagedSession);
  566. }
  567. }
  568. //---------------------------------------------------------------------------
  569. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  570. {
  571. if (ManagedSession != NULL)
  572. {
  573. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  574. }
  575. if (!TTerminalManager::Instance()->Updating)
  576. {
  577. SessionListChanged();
  578. }
  579. if (Terminal != NULL)
  580. {
  581. TObject * State = NULL;
  582. if (WinConfiguration->PreservePanelState)
  583. {
  584. State = Terminal->RemoteExplorerState;
  585. DirView(osRemote)->AnnounceState(State);
  586. }
  587. try
  588. {
  589. if (Replaced)
  590. {
  591. RemoteDirView->ReplaceTerminal(Terminal);
  592. }
  593. else
  594. {
  595. RemoteDirView->Terminal = Terminal;
  596. }
  597. if (Terminal->Active)
  598. {
  599. Terminal->RefreshDirectory();
  600. }
  601. if (State != NULL)
  602. {
  603. DirView(osRemote)->RestoreState(State);
  604. }
  605. }
  606. __finally
  607. {
  608. DirView(osRemote)->AnnounceState(NULL);
  609. }
  610. }
  611. else
  612. {
  613. RemoteDirView->Terminal = NULL;
  614. }
  615. InitStatusBar();
  616. UpdateTransferList();
  617. // Update panels Enable state before refreshing the labels
  618. UpdateControls();
  619. }
  620. //---------------------------------------------------------------------------
  621. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  622. {
  623. if (Queue != value)
  624. {
  625. if (FQueue != NULL)
  626. {
  627. FQueue->OnListUpdate = NULL;
  628. FQueue->OnQueueItemUpdate = NULL;
  629. }
  630. FQueue = value;
  631. if (FQueue != NULL)
  632. {
  633. DebugAssert(FQueue->OnListUpdate == NULL);
  634. FQueue->OnListUpdate = QueueListUpdate;
  635. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  636. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  637. }
  638. QueueChanged();
  639. }
  640. }
  641. //---------------------------------------------------------------------------
  642. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  643. TListItem * Item)
  644. {
  645. if (FQueueActedItem == Item)
  646. {
  647. FQueueActedItem = NULL;
  648. if ((QueueView3->PopupMenu != NULL) &&
  649. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  650. {
  651. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  652. ReleaseCapture();
  653. }
  654. }
  655. if (Item->Data == FPendingQueueActionItem)
  656. {
  657. FPendingQueueActionItem = NULL;
  658. }
  659. }
  660. //---------------------------------------------------------------------------
  661. bool TCustomScpExplorerForm::IsAnythingQueued()
  662. {
  663. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  664. }
  665. //---------------------------------------------------------------------------
  666. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  667. {
  668. {
  669. TGuard Guard(FQueueStatusSection);
  670. FQueueStatusInvalidated = false;
  671. if (FQueue != NULL)
  672. {
  673. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  674. }
  675. }
  676. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  677. {
  678. FMaxQueueLength = FQueueStatus->Count;
  679. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  680. }
  681. {
  682. TAutoFlag Flag(FQueueStatusUpdating);
  683. FQueueController->UpdateQueueStatus(FQueueStatus);
  684. }
  685. UpdateQueueFileList();
  686. SetQueueProgress();
  687. UpdateQueueView();
  688. bool IsEmpty = !IsAnythingQueued();
  689. if (IsEmpty && (Terminal != NULL))
  690. {
  691. TOnceDoneOperation OnceDoneOperation =
  692. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  693. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  694. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  695. {
  696. FQueue->Enabled = false;
  697. }
  698. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  699. {
  700. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  701. }
  702. }
  703. }
  704. //---------------------------------------------------------------------------
  705. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  706. {
  707. UnicodeString Result;
  708. if (FQueueStatus != NULL)
  709. {
  710. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  711. {
  712. TFileOperationProgressType * ProgressData =
  713. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  714. if ((ProgressData != NULL) && ProgressData->InProgress)
  715. {
  716. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  717. }
  718. }
  719. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  720. {
  721. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  722. }
  723. }
  724. return Result;
  725. }
  726. //---------------------------------------------------------------------------
  727. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  728. {
  729. ComponentVisible[fcQueueView] =
  730. !IsLocalBrowserMode() &&
  731. ((WinConfiguration->QueueView.Show == qvShow) ||
  732. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  733. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  734. }
  735. //---------------------------------------------------------------------------
  736. void __fastcall TCustomScpExplorerForm::QueueChanged()
  737. {
  738. if (FQueueStatus != NULL)
  739. {
  740. // UpdateFileList implementation relies on the status being recreated when session changes
  741. delete FQueueStatus;
  742. FQueueStatus = NULL;
  743. }
  744. UpdateQueueStatus(true);
  745. }
  746. //---------------------------------------------------------------------------
  747. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  748. {
  749. if (FQueue == Queue)
  750. {
  751. FQueueStatusInvalidated = true;
  752. }
  753. }
  754. //---------------------------------------------------------------------------
  755. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  756. TQueueItem * Item)
  757. {
  758. if (FQueue == Queue)
  759. {
  760. TGuard Guard(FQueueStatusSection);
  761. // this may be running in parallel with QueueChanged
  762. if (FQueueStatus != NULL)
  763. {
  764. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  765. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  766. {
  767. FRefreshLocalDirectory = (QueueItem == NULL) ||
  768. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  769. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  770. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  771. }
  772. if (QueueItem != NULL)
  773. {
  774. QueueItem->UserData = (void*)true;
  775. FQueueItemInvalidated = true;
  776. }
  777. }
  778. }
  779. }
  780. //---------------------------------------------------------------------------
  781. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  782. {
  783. // during standalone editing, we have no way to see/control queue,
  784. // so we have to always popup prompts automatically
  785. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  786. }
  787. //---------------------------------------------------------------------------
  788. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  789. {
  790. if (FQueueStatus != NULL)
  791. {
  792. bool QueueAutoPopup = IsQueueAutoPopup();
  793. bool NeedRefresh = FQueueController->NeedRefresh();
  794. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  795. FQueueItemInvalidated = false;
  796. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  797. bool Updated = false;
  798. TQueueItemProxy * QueueItem;
  799. bool WasUserAction;
  800. for (int Index = 0; Index < Limit; Index++)
  801. {
  802. bool Update = false;
  803. QueueItem = FQueueStatus->Items[Index];
  804. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  805. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  806. (FPendingQueueActionItem == NULL))
  807. {
  808. FPendingQueueActionItem = QueueItem;
  809. FUserActionTimer->Enabled = true;
  810. }
  811. if ((bool)QueueItem->UserData)
  812. {
  813. QueueItem->UserData = (void*)false;
  814. QueueItem->Update();
  815. Updated = true;
  816. Update = true;
  817. }
  818. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  819. {
  820. Update = true;
  821. }
  822. if (Update)
  823. {
  824. FQueueController->RefreshQueueItem(QueueItem);
  825. }
  826. }
  827. if (Updated)
  828. {
  829. NonVisualDataModule->UpdateNonVisibleActions();
  830. SetQueueProgress();
  831. UpdateQueueFileList();
  832. }
  833. }
  834. }
  835. //---------------------------------------------------------------------------
  836. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  837. {
  838. if (FTaskbarList != NULL)
  839. {
  840. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  841. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  842. }
  843. }
  844. //---------------------------------------------------------------------------
  845. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  846. {
  847. if (Progress >= 0)
  848. {
  849. if (FTaskbarList != NULL)
  850. {
  851. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  852. }
  853. }
  854. else
  855. {
  856. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  857. }
  858. }
  859. //---------------------------------------------------------------------------
  860. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  861. {
  862. int OverallProgress;
  863. // FProgressForm is null when this is called from SetQueueProgress
  864. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  865. {
  866. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  867. }
  868. else if (!ProgressData->IsIndeterminate())
  869. {
  870. OverallProgress = ProgressData->OverallProgress();
  871. }
  872. else
  873. {
  874. OverallProgress = -1;
  875. }
  876. SetTaskbarListProgressValue(OverallProgress);
  877. }
  878. //---------------------------------------------------------------------------
  879. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  880. {
  881. TTerminalManager::Instance()->QueueStatusUpdated();
  882. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  883. {
  884. // Do not animate task bar button, when items are queued, but processing is disabled
  885. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  886. {
  887. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  888. {
  889. TFileOperationProgressType * ProgressData = NULL;
  890. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  891. {
  892. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  893. }
  894. if ((ProgressData != NULL) &&
  895. ProgressData->InProgress)
  896. {
  897. SetTaskbarListProgressValue(ProgressData);
  898. }
  899. else
  900. {
  901. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  902. }
  903. }
  904. else
  905. {
  906. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  907. }
  908. }
  909. else
  910. {
  911. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  912. }
  913. }
  914. UpdateQueueLabel();
  915. }
  916. //---------------------------------------------------------------------------
  917. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  918. {
  919. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  920. if (FQueueStatus != NULL)
  921. {
  922. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  923. if (ActiveAndPendingPrimaryCount > 0)
  924. {
  925. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  926. }
  927. }
  928. QueueLabel->Caption = Caption;
  929. }
  930. //---------------------------------------------------------------------------
  931. void TCustomScpExplorerForm::CheckStoreTransition()
  932. {
  933. if (WinConfiguration->StoreTransition == stInit)
  934. {
  935. if (IsUWP())
  936. {
  937. WinConfiguration->StoreTransition = stStoreFresh;
  938. AppLog(L"Fresh UWP/store installation");
  939. }
  940. else
  941. {
  942. WinConfiguration->StoreTransition = stStandard;
  943. AppLog(L"Fresh standard installation");
  944. }
  945. }
  946. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  947. {
  948. WinConfiguration->StoreTransition = stStoreMigrated;
  949. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  950. AppLog(L"Standard installation migrated to store installation");
  951. }
  952. if (WinConfiguration->StoreTransition == stStoreMigrated)
  953. {
  954. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  955. Toolbar->Parent = MessageDock;
  956. Toolbar->FullSize = true;
  957. Toolbar->Color = Application->HintColor;
  958. TTBXLabelItem * LabelItem;
  959. LabelItem = new TTBXLabelItem(Toolbar);
  960. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  961. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  962. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  963. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  964. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  965. Toolbar->Items->Add(LabelItem);
  966. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  967. LinkItem->FontSettings->Color = LinkColor;
  968. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  969. LinkItem->OnClick = StoreTransitionLinkClick;
  970. Toolbar->Items->Add(LinkItem);
  971. AddMenuSeparator(Toolbar->Items);
  972. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  973. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  974. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  975. CloseItem->OnClick = StoreTransitionCloseClick;
  976. Toolbar->Items->Add(CloseItem);
  977. GiveTBItemPriority(CloseItem);
  978. }
  979. }
  980. //---------------------------------------------------------------------------
  981. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  982. {
  983. ShowHelp(HELP_STORE_TRANSITION);
  984. }
  985. //---------------------------------------------------------------------------
  986. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  987. {
  988. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  989. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  990. delete Toolbar;
  991. WinConfiguration->StoreTransition = stStoreAcknowledged;
  992. UpdateControls();
  993. }
  994. //---------------------------------------------------------------------------
  995. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  996. {
  997. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  998. static_cast<TComponent*>(GetComponent(fcTransferList)));
  999. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  1000. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  1001. TransferList->Strings->BeginUpdate();
  1002. try
  1003. {
  1004. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  1005. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  1006. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  1007. if (FTransferDropDownHint.IsEmpty())
  1008. {
  1009. FTransferDropDownHint = TransferDropDown->Hint;
  1010. }
  1011. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1012. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1013. TransferDropDown->Text = StripHotkey(Name);
  1014. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1015. (FTransferDropDownHint, StripHotkey(Name),
  1016. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1017. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1018. // update the label, otherwise when it is updated only on the first draw
  1019. // of the list, it is drawn "bold" for some reason
  1020. FTransferListHoverIndex = TransferList->ItemIndex;
  1021. UpdateTransferLabel();
  1022. }
  1023. __finally
  1024. {
  1025. TransferList->Strings->EndUpdate();
  1026. }
  1027. }
  1028. //---------------------------------------------------------------------------
  1029. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1030. {
  1031. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1032. DebugAssert(Toolbar != NULL);
  1033. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1034. }
  1035. //---------------------------------------------------------------------------
  1036. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1037. {
  1038. TForm::UpdateActions();
  1039. if (ComponentVisible[fcCustomCommandsBand])
  1040. {
  1041. UpdateCustomCommandsToolbar();
  1042. }
  1043. }
  1044. //---------------------------------------------------------------------------
  1045. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1046. {
  1047. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1048. }
  1049. //---------------------------------------------------------------------------
  1050. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1051. {
  1052. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1053. {
  1054. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1055. // Without this, the panel turns gray and unused part of header turns black
  1056. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1057. }
  1058. }
  1059. //---------------------------------------------------------------------------
  1060. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1061. {
  1062. Color = GetBtnFaceColor();
  1063. DebugAssert(Configuration && RemoteDirView);
  1064. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1065. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1066. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1067. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1068. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1069. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1070. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1071. UpdateRowSelect(RemoteDirView);
  1072. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1073. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1074. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1075. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1076. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1077. UpdateSessionsPageControlHeight();
  1078. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1079. UpdateToolbarDisplayMode();
  1080. UpdateTransferList();
  1081. if (Terminal != NULL)
  1082. {
  1083. TransferPresetAutoSelect();
  1084. }
  1085. UpdateQueueView();
  1086. UpdateControls();
  1087. // this can be called even before constuctor finishes.
  1088. if (FEditorManager != NULL)
  1089. {
  1090. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1091. }
  1092. // this can be called even before constuctor finishes.
  1093. if (FLocalEditors != NULL)
  1094. {
  1095. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1096. {
  1097. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1098. }
  1099. }
  1100. if (ComponentVisible[fcCustomCommandsBand])
  1101. {
  1102. UpdateCustomCommandsToolbar();
  1103. }
  1104. // show only when keeping queue items forever,
  1105. // otherwise, it's enough to have it in the context menu
  1106. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1107. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1108. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1109. {
  1110. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1111. FFileColorsCurrent = WinConfiguration->FileColors;
  1112. FileColorsChanged();
  1113. }
  1114. if ((GetNewTabTab()->CaptionTruncation != GetNewTabTabCaptionTruncation()) &&
  1115. (FSessionColors != NULL))
  1116. {
  1117. SessionListChanged();
  1118. }
  1119. }
  1120. //---------------------------------------------------------------------------
  1121. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1122. {
  1123. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1124. DirView->Invalidate();
  1125. }
  1126. //---------------------------------------------------------------------------
  1127. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1128. {
  1129. DoFileColorsChanged(RemoteDirView);
  1130. }
  1131. //---------------------------------------------------------------------------
  1132. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1133. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  1134. void * /*Arg*/)
  1135. {
  1136. if (Token != NULL)
  1137. {
  1138. TForm * Editor = dynamic_cast<TForm*>(Token);
  1139. DebugAssert(Editor != NULL);
  1140. ReconfigureEditorForm(Editor);
  1141. }
  1142. }
  1143. //---------------------------------------------------------------------------
  1144. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1145. {
  1146. WinConfiguration->DDTransferConfirmation = asOn;
  1147. }
  1148. //---------------------------------------------------------------------------
  1149. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1150. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1151. {
  1152. // noop
  1153. }
  1154. //---------------------------------------------------------------------------
  1155. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1156. {
  1157. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1158. }
  1159. //---------------------------------------------------------------------------
  1160. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1161. {
  1162. if (DoNotShowAgain)
  1163. {
  1164. if (DragDrop)
  1165. {
  1166. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1167. {
  1168. PopupTrayBalloon(
  1169. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1170. }
  1171. WinConfiguration->DDTransferConfirmation = asOff;
  1172. }
  1173. else
  1174. {
  1175. WinConfiguration->ConfirmTransferring = false;
  1176. }
  1177. }
  1178. else
  1179. {
  1180. // User explicitly unchecked "do not show again",
  1181. // so show him the dialog the next time
  1182. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1183. {
  1184. WinConfiguration->DDTransferConfirmation = asOn;
  1185. }
  1186. }
  1187. }
  1188. //---------------------------------------------------------------------------
  1189. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1190. TTransferDirection Direction, TTransferType Type, bool Temp,
  1191. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1192. bool Confirm, bool DragDrop, int Options)
  1193. {
  1194. bool Result = true;
  1195. DebugAssert(HasActiveTerminal());
  1196. // these parameters are known in advance
  1197. int Params =
  1198. FLAGMASK(Type == ttMove, cpDelete);
  1199. bool ToTemp = (Temp && (Direction == tdToLocal));
  1200. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1201. {
  1202. bool DisableNewerOnly =
  1203. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1204. ToTemp;
  1205. Options |=
  1206. FLAGMASK(ToTemp, coTemp) |
  1207. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1208. coDoNotShowAgain;
  1209. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1210. int CopyParamAttrs = (Direction == tdToRemote ?
  1211. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1212. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1213. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1214. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1215. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1216. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1217. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1218. if (Result)
  1219. {
  1220. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1221. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1222. }
  1223. }
  1224. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1225. {
  1226. Configuration->Usage->Inc(L"TransfersOnBackground");
  1227. // these parameter are known only after transfer dialog
  1228. Params |=
  1229. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1230. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1231. Result = false;
  1232. ClearTransferSourceSelection(Direction);
  1233. }
  1234. return Result;
  1235. }
  1236. //---------------------------------------------------------------------------
  1237. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1238. {
  1239. if (FOnFileOperationFinished != NULL)
  1240. {
  1241. FOnFileOperationFinished(Side, UnicodeString(), true);
  1242. }
  1243. else
  1244. {
  1245. if (HasDirView[Side])
  1246. {
  1247. DirView(Side)->SelectAll(smNone);
  1248. }
  1249. }
  1250. }
  1251. //---------------------------------------------------------------------------
  1252. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1253. {
  1254. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1255. ClearOperationSelection(Side);
  1256. }
  1257. //---------------------------------------------------------------------------
  1258. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1259. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1260. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1261. int Params)
  1262. {
  1263. DebugAssert(Queue != NULL);
  1264. bool SingleFile = false;
  1265. if (FileList->Count == 1)
  1266. {
  1267. if (Direction == tdToRemote)
  1268. {
  1269. UnicodeString FileName = FileList->Strings[0];
  1270. SingleFile = FileExists(ApiPath(FileName));
  1271. }
  1272. else
  1273. {
  1274. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1275. SingleFile = !File->IsDirectory;
  1276. }
  1277. }
  1278. TQueueItem * QueueItem;
  1279. if (Direction == tdToRemote)
  1280. {
  1281. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1282. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1283. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1284. }
  1285. else
  1286. {
  1287. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1288. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1289. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1290. }
  1291. AddQueueItem(Queue, QueueItem, Terminal);
  1292. }
  1293. //---------------------------------------------------------------------------
  1294. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1295. {
  1296. if (Queue->IsEmpty)
  1297. {
  1298. Terminal->QueueOperationStart = Now();
  1299. }
  1300. Queue->AddItem(QueueItem);
  1301. }
  1302. //---------------------------------------------------------------------------
  1303. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1304. {
  1305. }
  1306. //---------------------------------------------------------------------------
  1307. void __fastcall TCustomScpExplorerForm::InitControls()
  1308. {
  1309. DebugAssert(FDocks != NULL);
  1310. for (int Index = 0; Index < ComponentCount; Index++)
  1311. {
  1312. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1313. if ((Dock != NULL) && (Dock->Tag == 0))
  1314. {
  1315. FDocks->Add(Dock);
  1316. }
  1317. }
  1318. CollectItemsWithTextDisplayMode(this);
  1319. }
  1320. //---------------------------------------------------------------------------
  1321. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1322. {
  1323. ConfigurationChanged();
  1324. QueuePanel->Height =
  1325. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1326. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1327. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1328. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1329. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1330. QueueFileList->Height =
  1331. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1332. if (QueueFileList->Visible)
  1333. {
  1334. AdjustQueueLayout();
  1335. }
  1336. UpdateCustomCommandsToolbar();
  1337. }
  1338. //---------------------------------------------------------------------------
  1339. void __fastcall TCustomScpExplorerForm::StoreParams()
  1340. {
  1341. int APixelsPerInch = GetControlPixelsPerInch(this);
  1342. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1343. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1344. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1345. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1346. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1347. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1348. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1349. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1350. }
  1351. //---------------------------------------------------------------------------
  1352. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1353. {
  1354. if (!FFormRestored)
  1355. {
  1356. FFormRestored = true;
  1357. RestoreFormParams();
  1358. }
  1359. TForm::CreateParams(Params);
  1360. }
  1361. //---------------------------------------------------------------------------
  1362. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1363. {
  1364. DebugAssert(FDocks != NULL);
  1365. for (int Index = 0; Index < FDocks->Count; Index++)
  1366. {
  1367. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1368. }
  1369. }
  1370. //---------------------------------------------------------------------------
  1371. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1372. {
  1373. SetDockAllowDrag(true);
  1374. while (!ButtonsStr.IsEmpty())
  1375. {
  1376. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1377. UnicodeString Name = CutToChar(S, L'=', true);
  1378. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1379. {
  1380. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1381. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1382. {
  1383. while (!S.IsEmpty())
  1384. {
  1385. UnicodeString S2 = CutToChar(S, L',', true);
  1386. UnicodeString Name = CutToChar(S2, L':', true);
  1387. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1388. {
  1389. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1390. if (SameText(GetToolbarItemName(Item), Name))
  1391. {
  1392. // forward compatibility
  1393. UnicodeString S3 = CutToChar(S2, L':', true);
  1394. bool Visible = StrToIntDef(S3, 0);
  1395. Item->Visible = Visible;
  1396. }
  1397. }
  1398. }
  1399. }
  1400. }
  1401. }
  1402. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1403. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1404. }
  1405. //---------------------------------------------------------------------------
  1406. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1407. {
  1408. UnicodeString Result;
  1409. SetDockAllowDrag(true);
  1410. Result = ::GetToolbarsLayoutStr(this);
  1411. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1412. return Result;
  1413. }
  1414. //---------------------------------------------------------------------------
  1415. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1416. {
  1417. UnicodeString Result;
  1418. if (Item->Action != NULL)
  1419. {
  1420. Result = Item->Action->Name;
  1421. Result = RemoveSuffix(Result, L"Action", true);
  1422. }
  1423. else
  1424. {
  1425. Result = Item->Name;
  1426. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1427. Result = RemoveSuffix(Result, L"Item", true);
  1428. }
  1429. return Result;
  1430. }
  1431. //---------------------------------------------------------------------------
  1432. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1433. {
  1434. UnicodeString Result;
  1435. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1436. {
  1437. UnicodeString ToolbarStr;
  1438. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1439. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1440. {
  1441. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1442. {
  1443. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1444. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1445. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1446. // and save the changes here only.
  1447. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1448. {
  1449. UnicodeString Name = GetToolbarItemName(Item);
  1450. DebugAssert(Name.Pos(L"TBX") == 0);
  1451. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1452. }
  1453. }
  1454. }
  1455. if (!ToolbarStr.IsEmpty())
  1456. {
  1457. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1458. }
  1459. }
  1460. return Result;
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1464. {
  1465. DebugAssert(FProgressForm == NULL);
  1466. bool AllowSkip = HasActiveTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1467. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1468. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1469. FProgressForm->DeleteLocalToRecycleBin =
  1470. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1471. FProgressForm->DeleteRemoteToRecycleBin =
  1472. HasActiveTerminal() &&
  1473. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1474. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1475. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1476. LockWindow();
  1477. // Actually, do not know what hides the progress once the operation finishes
  1478. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1479. SetTaskbarListProgressState(TBPF_NORMAL);
  1480. }
  1481. //---------------------------------------------------------------------------
  1482. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1483. {
  1484. UnlockWindow();
  1485. SAFE_DESTROY(FProgressForm);
  1486. SetQueueProgress();
  1487. }
  1488. //---------------------------------------------------------------------------
  1489. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1490. TFileOperationProgressType & ProgressData)
  1491. {
  1492. // Download to temporary local directory
  1493. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1494. {
  1495. bool Continue = true;
  1496. FPendingTempSpaceWarn = false;
  1497. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1498. if (!Continue)
  1499. {
  1500. Abort();
  1501. }
  1502. }
  1503. // operation is being executed and we still didn't show up progress form
  1504. if (ProgressData.InProgress && !FProgressForm)
  1505. {
  1506. CreateProgressForm(NULL);
  1507. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1508. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1509. }
  1510. // operation is finished (or terminated), so we hide progress form
  1511. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1512. {
  1513. DestroyProgressForm();
  1514. if (ProgressData.Operation == foCalculateSize)
  1515. {
  1516. // When calculating size before transfer, the abort caused by
  1517. // cancel flag set due to "MoveToQueue" below,
  1518. // is not propagated back to us in ExecuteFileOperation,
  1519. // as it is silently swallowed.
  1520. // So we explicitly (re)throw it here.
  1521. if (FMoveToQueue)
  1522. {
  1523. Abort();
  1524. }
  1525. }
  1526. else
  1527. {
  1528. if ((ProgressData.Cancel == csContinue) &&
  1529. !FAutoOperation)
  1530. {
  1531. OperationComplete(ProgressData.StartTime);
  1532. }
  1533. }
  1534. }
  1535. if (FProgressForm &&
  1536. // Can happen only during synchronization, when ending one of the operations
  1537. ProgressData.InProgress)
  1538. {
  1539. FProgressForm->SetProgressData(ProgressData);
  1540. DebugAssert(ProgressData.InProgress);
  1541. SetTaskbarListProgressValue(&ProgressData);
  1542. if (FProgressForm->Cancel > csContinue)
  1543. {
  1544. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1545. if (FProgressForm->Cancel == csCancelFile)
  1546. {
  1547. FProgressForm->ClearCancel();
  1548. }
  1549. // cancel cancels even the move
  1550. FMoveToQueue = false;
  1551. }
  1552. else if (FProgressForm->MoveToQueue)
  1553. {
  1554. FMoveToQueue = true;
  1555. ProgressData.SetCancelAtLeast(csCancel);
  1556. }
  1557. if ((FTransferResumeList != NULL) &&
  1558. ProgressData.InProgress &&
  1559. ProgressData.IsTransfer() &&
  1560. !ProgressData.FullFileName.IsEmpty())
  1561. {
  1562. if ((FTransferResumeList->Count == 0) ||
  1563. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1564. {
  1565. // note that we do not recognize directories from files here
  1566. FTransferResumeList->Add(ProgressData.FullFileName);
  1567. }
  1568. }
  1569. }
  1570. }
  1571. //---------------------------------------------------------------------------
  1572. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1573. const TDateTime & StartTime)
  1574. {
  1575. if (GUIConfiguration->BeepOnFinish &&
  1576. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1577. {
  1578. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1579. DWORD Sound;
  1580. if (!ExtractFileExt(BeepSound).IsEmpty())
  1581. {
  1582. Sound = SND_FILENAME;
  1583. }
  1584. else
  1585. {
  1586. Sound = SND_ALIAS;
  1587. }
  1588. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1589. }
  1590. }
  1591. //---------------------------------------------------------------------------
  1592. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1593. TFileOperationProgressType & ProgressData)
  1594. {
  1595. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1596. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1597. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1598. FileOperationProgress(ProgressData);
  1599. }
  1600. //---------------------------------------------------------------------------
  1601. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1602. {
  1603. UnicodeString Result;
  1604. if (FProgressForm != NULL)
  1605. {
  1606. Result = FProgressForm->ProgressStr();
  1607. }
  1608. return Result;
  1609. }
  1610. //---------------------------------------------------------------------------
  1611. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1612. bool DragDrop)
  1613. {
  1614. return (!DragDrop && (DropSourceControl == NULL)) ||
  1615. (DropSourceControl == DirView(osOther));
  1616. }
  1617. //---------------------------------------------------------------------------
  1618. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1619. {
  1620. TCustomDirView * ADirView = DirView(Side);
  1621. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1622. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1623. // this can happen when local drive is unplugged in the middle of the operation
  1624. if (Item != NULL)
  1625. {
  1626. if (Unselect)
  1627. {
  1628. Item->Selected = false;
  1629. }
  1630. ADirView->MakeProgressVisible(Item);
  1631. }
  1632. return Item;
  1633. }
  1634. //---------------------------------------------------------------------------
  1635. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1636. TFileOperation Operation, TOperationSide Side,
  1637. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1638. TOnceDoneOperation & OnceDoneOperation)
  1639. {
  1640. if (!FAutoOperation)
  1641. {
  1642. // no selection on "/upload", form serves only as event handler
  1643. // (it is not displayed)
  1644. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1645. ((Operation == FPrimaryOperation) ||
  1646. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1647. {
  1648. TOperationSide DViewSide;
  1649. if ((FProgressSide != osCurrent) &&
  1650. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1651. {
  1652. // assume the operation is over the focused panel
  1653. DViewSide = FProgressSide;
  1654. }
  1655. else
  1656. {
  1657. DViewSide = Side;
  1658. }
  1659. if (FOnFileOperationFinished != NULL)
  1660. {
  1661. FOnFileOperationFinished(DViewSide, FileName, Success);
  1662. }
  1663. else
  1664. {
  1665. VisualiseOperationFinished(DViewSide, FileName, Success);
  1666. }
  1667. }
  1668. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1669. {
  1670. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1671. {
  1672. if (Side == osLocal)
  1673. {
  1674. Configuration->Usage->Inc(L"UploadedFiles");
  1675. }
  1676. else
  1677. {
  1678. Configuration->Usage->Inc(L"DownloadedFiles");
  1679. }
  1680. }
  1681. }
  1682. }
  1683. if (Success && (FSynchronizeController != NULL))
  1684. {
  1685. DebugAssert(!IsSideLocalBrowser(osRemote));
  1686. if (Operation == foCopy)
  1687. {
  1688. DebugAssert(Side == osLocal);
  1689. FSynchronizeController->LogOperation(soUpload, FileName);
  1690. }
  1691. else if (Operation == foDelete)
  1692. {
  1693. DebugAssert(Side == osRemote);
  1694. FSynchronizeController->LogOperation(soDelete, FileName);
  1695. }
  1696. }
  1697. if (FProgressForm)
  1698. {
  1699. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1700. }
  1701. }
  1702. //---------------------------------------------------------------------------
  1703. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1704. TFileOperation Operation, TOperationSide Side,
  1705. bool Temp, const UnicodeString & FileName, Boolean Success,
  1706. TOnceDoneOperation & OnceDoneOperation)
  1707. {
  1708. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1709. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1710. OnceDoneOperation);
  1711. }
  1712. //---------------------------------------------------------------------------
  1713. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1714. {
  1715. return false;
  1716. }
  1717. //---------------------------------------------------------------------------
  1718. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1719. {
  1720. return false;
  1721. }
  1722. //---------------------------------------------------------------------------
  1723. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1724. {
  1725. return false;
  1726. }
  1727. //---------------------------------------------------------------------------
  1728. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1729. {
  1730. return NULL;
  1731. }
  1732. //---------------------------------------------------------------------------
  1733. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1734. {
  1735. DebugAssert(GetSide(Side) == osRemote);
  1736. DebugUsedParam(Side);
  1737. return RemoteDirView;
  1738. }
  1739. //---------------------------------------------------------------------------
  1740. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1741. {
  1742. DebugAssert(GetSide(Side) == osRemote);
  1743. DebugUsedParam(Side);
  1744. return RemoteDriveView;
  1745. }
  1746. //---------------------------------------------------------------------------
  1747. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1748. {
  1749. DebugAssert(GetSide(Side) == osRemote);
  1750. DebugUsedParam(Side);
  1751. return HasActiveTerminal();
  1752. }
  1753. //---------------------------------------------------------------------------
  1754. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1755. TOperationSide Side, int FilesOnly)
  1756. {
  1757. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1758. }
  1759. //---------------------------------------------------------------------------
  1760. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1761. TOperationSide Side, int FilesOnly)
  1762. {
  1763. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1764. }
  1765. //---------------------------------------------------------------------------
  1766. struct THistoryItemData
  1767. {
  1768. short int Side;
  1769. short int Index;
  1770. };
  1771. //---------------------------------------------------------------------------
  1772. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1773. {
  1774. DirView(Side)->HistoryGo(Index);
  1775. }
  1776. //---------------------------------------------------------------------------
  1777. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1778. {
  1779. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1780. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1781. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1782. }
  1783. //---------------------------------------------------------------------------
  1784. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1785. bool Back)
  1786. {
  1787. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1788. {
  1789. TCustomDirView * DView = DirView(Side);
  1790. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1791. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1792. if (ICount > 10)
  1793. {
  1794. ICount = 10;
  1795. }
  1796. Menu->Items->Clear();
  1797. THistoryItemData Data;
  1798. Data.Side = Side;
  1799. for (short int i = 1; i <= ICount; i++)
  1800. {
  1801. TTBCustomItem * Item = new TTBXItem(Menu);
  1802. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1803. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1804. Item->Hint = DView->HistoryPath[Data.Index];
  1805. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1806. Item->Tag = *reinterpret_cast<int*>(&Data);
  1807. Item->OnClick = HistoryItemClick;
  1808. Menu->Items->Add(Item);
  1809. }
  1810. }
  1811. }
  1812. //---------------------------------------------------------------------------
  1813. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1814. TOperationSide Side, bool Back)
  1815. {
  1816. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1817. {
  1818. // workaround
  1819. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1820. // operator new allocates memory in Pascal code, but calls inline
  1821. // constructor in C++, leading in problems, the function does
  1822. // both in Pascal code
  1823. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1824. UpdateHistoryMenu(Side, Back);
  1825. }
  1826. return FHistoryMenu[Side == osLocal][Back];
  1827. }
  1828. //---------------------------------------------------------------------------
  1829. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1830. TCustomDirView *Sender)
  1831. {
  1832. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1833. UpdateHistoryMenu(Side, true);
  1834. UpdateHistoryMenu(Side, false);
  1835. }
  1836. //---------------------------------------------------------------------------
  1837. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1838. {
  1839. // remote custom commands can be executed only if the server supports shell commands
  1840. // or have secondary shell
  1841. return HasActiveTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1842. }
  1843. //---------------------------------------------------------------------------
  1844. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1845. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1846. {
  1847. // -1 = hidden, 0 = disabled, 1 = enabled
  1848. int Result;
  1849. TFileCustomCommand RemoteCustomCommand;
  1850. TLocalCustomCommand LocalCustomCommand;
  1851. TFileCustomCommand * NonInteractiveCustomCommand =
  1852. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1853. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1854. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1855. if (FLAGCLEAR(Command.Params, ccLocal))
  1856. {
  1857. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1858. // custom command that does not operate with files can be executed anytime ...
  1859. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1860. {
  1861. // ... but do not show such command in remote file menu
  1862. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1863. {
  1864. Result = AllowedState;
  1865. }
  1866. else
  1867. {
  1868. Result = -1;
  1869. }
  1870. }
  1871. else
  1872. {
  1873. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1874. {
  1875. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1876. }
  1877. else
  1878. {
  1879. Result = -1;
  1880. }
  1881. }
  1882. }
  1883. else
  1884. {
  1885. // custom command that does not operate with files can be executed anytime
  1886. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1887. {
  1888. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1889. }
  1890. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1891. {
  1892. if ((ListType == ccltAll) || (ListType == ccltFile))
  1893. {
  1894. // special case is "diff"-style command that can be executed over any side,
  1895. // if we have both sides
  1896. Result =
  1897. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1898. // directly (instead of EnableSelectedOperation) to pass
  1899. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1900. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1901. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1902. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1903. }
  1904. else if (ListType == ccltBoth)
  1905. {
  1906. DebugAssert(!IsLocalBrowserMode());
  1907. Result = 1;
  1908. }
  1909. else
  1910. {
  1911. Result = -1;
  1912. }
  1913. }
  1914. else
  1915. {
  1916. if ((ListType == ccltAll) ||
  1917. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1918. {
  1919. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1920. }
  1921. else
  1922. {
  1923. Result = -1;
  1924. }
  1925. }
  1926. if ((Result > 0) &&
  1927. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1928. !HasActiveTerminal())
  1929. {
  1930. Result = 0;
  1931. }
  1932. }
  1933. return Result;
  1934. }
  1935. //---------------------------------------------------------------------------
  1936. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1937. TStrings * FileList, const TCustomCommandType & ACommand,
  1938. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1939. {
  1940. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1941. {
  1942. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1943. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1944. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1945. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1946. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1947. bool Capture =
  1948. FLAGSET(ACommand.Params, ccShowResults) ||
  1949. FLAGSET(ACommand.Params, ccCopyResults) ||
  1950. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1951. TCaptureOutputEvent OutputEvent = NULL;
  1952. DebugAssert(FCapturedLog == NULL);
  1953. if (Capture)
  1954. {
  1955. FCapturedLog = new TStringList();
  1956. OutputEvent = TerminalCaptureLog;
  1957. }
  1958. try
  1959. {
  1960. if (!RemoteCustomCommand.IsFileCommand(Command))
  1961. {
  1962. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1963. OutputEvent);
  1964. }
  1965. else
  1966. {
  1967. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1968. }
  1969. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1970. {
  1971. if (FLAGSET(ACommand.Params, ccCopyResults))
  1972. {
  1973. CopyToClipboard(FCapturedLog);
  1974. }
  1975. if (FLAGSET(ACommand.Params, ccShowResults))
  1976. {
  1977. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1978. }
  1979. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1980. {
  1981. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1982. }
  1983. }
  1984. }
  1985. __finally
  1986. {
  1987. SAFE_DESTROY(FCapturedLog);
  1988. }
  1989. }
  1990. }
  1991. //---------------------------------------------------------------------------
  1992. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1993. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1994. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1995. {
  1996. DebugAssert(!IsLocalBrowserMode());
  1997. TStrings * LocalFileList = NULL;
  1998. TStrings * RemoteFileList = NULL;
  1999. TStrings * RemoteFileListFull = NULL;
  2000. try
  2001. {
  2002. if (LocalFileCommand)
  2003. {
  2004. if (ALocalFileList == NULL)
  2005. {
  2006. DebugAssert(HasDirView[osLocal]);
  2007. // Cannot have focus on both panels, so we have to call AnyFileSelected
  2008. // directly (instead of EnableSelectedOperation) to pass
  2009. // false to FocusedFileOnlyWhenFocused
  2010. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  2011. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  2012. }
  2013. else
  2014. {
  2015. LocalFileList = ALocalFileList;
  2016. }
  2017. if (FileListCommand)
  2018. {
  2019. if (LocalFileList->Count != 1)
  2020. {
  2021. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2022. }
  2023. }
  2024. else
  2025. {
  2026. if ((LocalFileList->Count != 1) &&
  2027. (FileList->Count != 1) &&
  2028. (LocalFileList->Count != FileList->Count))
  2029. {
  2030. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2031. }
  2032. }
  2033. }
  2034. UnicodeString RootTempDir;
  2035. UnicodeString TempDir;
  2036. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2037. if (!RemoteFiles)
  2038. {
  2039. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true, true);
  2040. }
  2041. try
  2042. {
  2043. TDateTimes RemoteFileTimes;
  2044. if (RemoteFiles)
  2045. {
  2046. RemoteFileList = FileList;
  2047. }
  2048. else
  2049. {
  2050. RemoteFileList = new TStringList();
  2051. TMakeLocalFileListParams MakeFileListParam;
  2052. MakeFileListParam.FileList = RemoteFileList;
  2053. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2054. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2055. MakeFileListParam.Recursive =
  2056. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2057. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2058. if (!MakeFileListParam.Recursive)
  2059. {
  2060. RemoteFileTimes.clear();
  2061. RemoteFileListFull = new TStringList();
  2062. MakeFileListParam.FileList = RemoteFileListFull;
  2063. MakeFileListParam.Recursive = true;
  2064. MakeFileListParam.IncludeDirs = false;
  2065. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2066. }
  2067. else
  2068. {
  2069. RemoteFileListFull = RemoteFileList;
  2070. }
  2071. }
  2072. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2073. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2074. if (!NonBlocking)
  2075. {
  2076. int Count;
  2077. if (FileListCommand)
  2078. {
  2079. Count = 1;
  2080. }
  2081. else if (LocalFileCommand)
  2082. {
  2083. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2084. }
  2085. else
  2086. {
  2087. Count = RemoteFileList->Count;
  2088. }
  2089. Progress.Start(foCustomCommand, osRemote, Count);
  2090. DebugAssert(FProgressForm != NULL);
  2091. FProgressForm->ReadOnly = true;
  2092. }
  2093. try
  2094. {
  2095. if (FileListCommand)
  2096. {
  2097. UnicodeString LocalFile;
  2098. // MakeFileList does not delimit filenames
  2099. UnicodeString FileList = MakeFileList(RemoteFileList);
  2100. if (LocalFileCommand)
  2101. {
  2102. DebugAssert(LocalFileList->Count == 1);
  2103. LocalFile = LocalFileList->Strings[0];
  2104. }
  2105. TLocalCustomCommand CustomCommand(Data,
  2106. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2107. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2108. if (NonBlocking)
  2109. {
  2110. DebugAssert(!POutput);
  2111. ExecuteShellChecked(ShellCommand);
  2112. }
  2113. else
  2114. {
  2115. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2116. }
  2117. }
  2118. else if (LocalFileCommand)
  2119. {
  2120. if (LocalFileList->Count == 1)
  2121. {
  2122. UnicodeString LocalFile = LocalFileList->Strings[0];
  2123. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2124. {
  2125. UnicodeString FileName = RemoteFileList->Strings[Index];
  2126. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2127. Progress.SetFile(FileNameForProgress);
  2128. TLocalCustomCommand CustomCommand(Data,
  2129. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2130. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2131. TOnceDoneOperation OnceDoneOperation;
  2132. // Do not unselect anything, as it won't work with two panels anyway
  2133. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2134. }
  2135. }
  2136. else if (RemoteFileList->Count == 1)
  2137. {
  2138. UnicodeString FileName = RemoteFileList->Strings[0];
  2139. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2140. {
  2141. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2142. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2143. Progress.SetFile(LocalFileNameOnly);
  2144. TLocalCustomCommand CustomCommand(
  2145. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2146. FileName, LocalFileName, L"");
  2147. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2148. TOnceDoneOperation OnceDoneOperation;
  2149. // Do not unselect anything, as it won't work with two panels anyway
  2150. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2151. }
  2152. }
  2153. else
  2154. {
  2155. if (LocalFileList->Count != RemoteFileList->Count)
  2156. {
  2157. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2158. }
  2159. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2160. {
  2161. UnicodeString FileName = RemoteFileList->Strings[Index];
  2162. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2163. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2164. Progress.SetFile(LocalFileNameOnly); // sic
  2165. TLocalCustomCommand CustomCommand(
  2166. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2167. FileName, LocalFileName, L"");
  2168. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2169. TOnceDoneOperation OnceDoneOperation;
  2170. // Do not unselect anything, as it won't work with two panels anyway
  2171. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2172. }
  2173. }
  2174. }
  2175. else
  2176. {
  2177. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2178. {
  2179. UnicodeString FileName = RemoteFileList->Strings[Index];
  2180. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2181. Progress.SetFile(FileNameForProgress);
  2182. TLocalCustomCommand CustomCommand(Data,
  2183. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2184. FileName, L"", L"");
  2185. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2186. TOnceDoneOperation OnceDoneOperation;
  2187. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2188. }
  2189. }
  2190. }
  2191. __finally
  2192. {
  2193. if (!NonBlocking)
  2194. {
  2195. Progress.Stop();
  2196. }
  2197. }
  2198. DebugAssert(!FAutoOperation);
  2199. if (!RemoteFiles)
  2200. {
  2201. TempDir = IncludeTrailingBackslash(TempDir);
  2202. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2203. {
  2204. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2205. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2206. // Skip directories, process only nested files.
  2207. // The check is redundant as FileAge fails for directories anyway.
  2208. !DirectoryExists(FileName))
  2209. {
  2210. UnicodeString RemoteDir =
  2211. UnixExtractFileDir(
  2212. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2213. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  2214. TDateTime NewTime;
  2215. if (FileAge(FileName, NewTime) &&
  2216. (NewTime != RemoteFileTimes[Index]))
  2217. {
  2218. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2219. TemporaryFileCopyParam(CopyParam);
  2220. CopyParam.FileMask = L"";
  2221. FAutoOperation = true;
  2222. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2223. TemporaryFilesList->Add(FileName);
  2224. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2225. }
  2226. }
  2227. }
  2228. }
  2229. }
  2230. __finally
  2231. {
  2232. FAutoOperation = false;
  2233. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2234. {
  2235. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  2236. }
  2237. }
  2238. }
  2239. __finally
  2240. {
  2241. if (RemoteFileList != FileList)
  2242. {
  2243. delete RemoteFileList;
  2244. }
  2245. if (LocalFileList != ALocalFileList)
  2246. {
  2247. delete LocalFileList;
  2248. }
  2249. if (RemoteFileListFull != RemoteFileList)
  2250. {
  2251. delete RemoteFileListFull;
  2252. }
  2253. }
  2254. }
  2255. //---------------------------------------------------------------------------
  2256. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2257. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2258. bool FileListCommand, UnicodeString * POutput)
  2259. {
  2260. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2261. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2262. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2263. {
  2264. UnicodeString FileName = SelectedFileList->Strings[Index];
  2265. if (DirectoryExists(FileName))
  2266. {
  2267. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2268. {
  2269. LocalFileList->Add(FileName);
  2270. }
  2271. if (FLAGSET(ACommand.Params, ccRecursive))
  2272. {
  2273. TMakeLocalFileListParams MakeFileListParam;
  2274. MakeFileListParam.FileList = LocalFileList.get();
  2275. MakeFileListParam.FileTimes = NULL;
  2276. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2277. MakeFileListParam.Recursive = true;
  2278. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2279. }
  2280. }
  2281. else
  2282. {
  2283. LocalFileList->Add(FileName);
  2284. }
  2285. }
  2286. UnicodeString RemotePath;
  2287. if (Terminal != NULL)
  2288. {
  2289. RemotePath = Terminal->CurrentDirectory;
  2290. }
  2291. if (FileListCommand)
  2292. {
  2293. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2294. TLocalCustomCommand CustomCommand(
  2295. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2296. L"", L"", FileList);
  2297. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2298. }
  2299. else
  2300. {
  2301. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2302. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2303. DebugAssert(FProgressForm != NULL);
  2304. FProgressForm->ReadOnly = true;
  2305. try
  2306. {
  2307. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2308. {
  2309. UnicodeString FileName = LocalFileList->Strings[Index];
  2310. Progress.SetFile(FileName);
  2311. TLocalCustomCommand CustomCommand(
  2312. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2313. FileName, L"", L"");
  2314. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2315. TOnceDoneOperation OnceDoneOperation;
  2316. Progress.Finish(FileName, true, OnceDoneOperation);
  2317. }
  2318. }
  2319. __finally
  2320. {
  2321. Progress.Stop();
  2322. }
  2323. }
  2324. }
  2325. //---------------------------------------------------------------------------
  2326. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2327. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2328. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2329. {
  2330. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2331. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2332. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2333. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2334. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2335. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2336. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2337. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2338. std::unique_ptr<UnicodeString> POutput;
  2339. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2340. FLAGSET(ACommand.Params, ccCopyResults))
  2341. {
  2342. POutput.reset(new UnicodeString());
  2343. }
  2344. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  2345. if (!LocalCustomCommand.IsFileCommand(Command))
  2346. {
  2347. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2348. }
  2349. // remote files?
  2350. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2351. {
  2352. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2353. }
  2354. // local files
  2355. else
  2356. {
  2357. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2358. }
  2359. if (POutput.get() != NULL)
  2360. {
  2361. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2362. int P = POutput->Pos(sLineBreak);
  2363. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2364. {
  2365. POutput->SetLength(P - 1);
  2366. }
  2367. // Copy even empty output to clipboard
  2368. if (FLAGSET(ACommand.Params, ccCopyResults))
  2369. {
  2370. CopyToClipboard(*POutput);
  2371. }
  2372. // But do not show an empty message box.
  2373. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2374. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2375. !POutput->IsEmpty())
  2376. {
  2377. TClipboardHandler ClipboardHandler;
  2378. ClipboardHandler.Text = *POutput;
  2379. TMessageParams Params;
  2380. TQueryButtonAlias Aliases[1];
  2381. Aliases[0].Button = qaRetry;
  2382. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2383. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2384. Params.Aliases = Aliases;
  2385. Params.AliasesCount = LENOF(Aliases);
  2386. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2387. }
  2388. }
  2389. }
  2390. //---------------------------------------------------------------------------
  2391. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2392. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2393. {
  2394. TCustomCommandData Data;
  2395. UnicodeString Site;
  2396. UnicodeString RemotePath;
  2397. if (HasActiveTerminal())
  2398. {
  2399. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2400. Data = TCustomCommandData(SessionData.get());
  2401. Site = Terminal->SessionData->SessionKey;
  2402. RemotePath = Terminal->CurrentDirectory;
  2403. }
  2404. UnicodeString HelpKeyword = ACommand.HomePage;
  2405. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2406. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2407. {
  2408. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2409. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2410. {
  2411. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2412. }
  2413. else
  2414. {
  2415. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2416. }
  2417. if (!DoCustomCommandOptionsDialog(
  2418. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2419. {
  2420. Abort();
  2421. }
  2422. }
  2423. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2424. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2425. {
  2426. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2427. }
  2428. else
  2429. {
  2430. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2431. }
  2432. }
  2433. //---------------------------------------------------------------------------
  2434. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2435. const TCustomCommandType & Command)
  2436. {
  2437. DebugAssert(FCustomCommandLocalFileList != NULL);
  2438. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2439. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2440. TStrings * LocalFileList = new TStringList();
  2441. TStrings * RemoteFileList = new TStringList();
  2442. try
  2443. {
  2444. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2445. {
  2446. LocalFileList->Clear();
  2447. LocalFileList->AddObject(
  2448. FCustomCommandLocalFileList->Strings[Index],
  2449. FCustomCommandLocalFileList->Objects[Index]);
  2450. RemoteFileList->Clear();
  2451. RemoteFileList->AddObject(
  2452. FCustomCommandRemoteFileList->Strings[Index],
  2453. FCustomCommandRemoteFileList->Objects[Index]);
  2454. CustomCommand(RemoteFileList, Command, LocalFileList);
  2455. }
  2456. }
  2457. __finally
  2458. {
  2459. delete LocalFileList;
  2460. delete RemoteFileList;
  2461. }
  2462. }
  2463. //---------------------------------------------------------------------------
  2464. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2465. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2466. {
  2467. delete FCustomCommandLocalFileList;
  2468. delete FCustomCommandRemoteFileList;
  2469. // takeover ownership,
  2470. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2471. FCustomCommandLocalFileList = LocalFileList;
  2472. FCustomCommandRemoteFileList = RemoteFileList;
  2473. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2474. if (Button != NULL)
  2475. {
  2476. FCustomCommandMenu->Items->Clear();
  2477. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2478. MenuPopup(FCustomCommandMenu, Button);
  2479. }
  2480. else
  2481. {
  2482. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2483. }
  2484. }
  2485. //---------------------------------------------------------------------------
  2486. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2487. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2488. {
  2489. DebugAssert(FCapturedLog != NULL);
  2490. if ((OutputType == cotOutput) || (OutputType == cotError))
  2491. {
  2492. FCapturedLog->Add(AddedLine);
  2493. }
  2494. }
  2495. //---------------------------------------------------------------------------
  2496. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2497. TOperationSide Side)
  2498. {
  2499. return
  2500. (Side == osOther) &&
  2501. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2502. }
  2503. //---------------------------------------------------------------------------
  2504. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2505. TOperationSide Side, TTBXCustomItem * Item,
  2506. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2507. {
  2508. TCustomDirView * DView = DirView(Side);
  2509. bool IsDefault = false;
  2510. if (DView->ItemFocused != NULL)
  2511. {
  2512. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2513. TResolvedDoubleClickAction DefaultAction =
  2514. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2515. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2516. }
  2517. TTBItemOptions O = Item->Options;
  2518. if (IsDefault)
  2519. {
  2520. Item->Options = O << tboDefault;
  2521. }
  2522. else
  2523. {
  2524. Item->Options = O >> tboDefault;
  2525. }
  2526. }
  2527. //---------------------------------------------------------------------------
  2528. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2529. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2530. {
  2531. TCustomDirView * DView = DirView(Side);
  2532. TListItem * Item = DView->ItemFocused;
  2533. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2534. EnableFocusedOperation[Side])
  2535. {
  2536. TPoint ClientPoint;
  2537. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2538. TPoint(0, 0) : MousePos;
  2539. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2540. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2541. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2542. }
  2543. }
  2544. //---------------------------------------------------------------------------
  2545. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2546. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2547. {
  2548. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2549. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2550. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2551. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2552. Handled = true;
  2553. }
  2554. //---------------------------------------------------------------------------
  2555. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2556. {
  2557. }
  2558. //---------------------------------------------------------------------------
  2559. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2560. {
  2561. DebugAssert(FErrorList == NULL);
  2562. if (WinConfiguration->ContinueOnError)
  2563. {
  2564. FErrorList = new TStringList();
  2565. Configuration->Usage->Inc(L"ContinuationsOnError");
  2566. }
  2567. NonVisualDataModule->StartBusy();
  2568. }
  2569. //---------------------------------------------------------------------------
  2570. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2571. {
  2572. NonVisualDataModule->EndBusy();
  2573. if (FErrorList)
  2574. {
  2575. HandleErrorList(FErrorList);
  2576. }
  2577. }
  2578. //---------------------------------------------------------------------------
  2579. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2580. const TCopyParamType & CopyParam)
  2581. {
  2582. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2583. {
  2584. Configuration->Usage->Inc(L"FileMaskUses");
  2585. }
  2586. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2587. {
  2588. Configuration->Usage->Inc(L"OperationMaskUses");
  2589. }
  2590. }
  2591. //---------------------------------------------------------------------------
  2592. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2593. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2594. {
  2595. DebugAssert(!IsLocalBrowserMode());
  2596. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2597. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2598. TTransferOperationParam DefaultParam;
  2599. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2600. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2601. switch (Param.Queue)
  2602. {
  2603. case asOn:
  2604. CopyParam.Queue = true;
  2605. break;
  2606. case asOff:
  2607. CopyParam.Queue = false;
  2608. break;
  2609. case asAuto:
  2610. default:
  2611. // keep default
  2612. break;
  2613. }
  2614. bool Result =
  2615. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2616. if (Result)
  2617. {
  2618. DebugAssert(Terminal);
  2619. bool SelectionRestored = false;
  2620. TCustomDirView * DView = NULL;
  2621. if (HasDirView[Side])
  2622. {
  2623. DView = DirView(Side);
  2624. DView->SaveSelection();
  2625. DView->SaveSelectedNames();
  2626. }
  2627. UpdateCopyParamCounters(CopyParam);
  2628. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2629. DebugAssert(FTransferResumeList == NULL);
  2630. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2631. FMoveToQueue = false;
  2632. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2633. try
  2634. {
  2635. TStrings * PermanentFileList;
  2636. std::unique_ptr<TStrings> PermanentFileListOwner;
  2637. try
  2638. {
  2639. if (Side == osLocal)
  2640. {
  2641. PermanentFileList = FileList;
  2642. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2643. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2644. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2645. if (Operation == foMove)
  2646. {
  2647. ReloadLocalDirectory();
  2648. if (DView != NULL)
  2649. {
  2650. DView->RestoreSelection();
  2651. }
  2652. SelectionRestored = true;
  2653. }
  2654. }
  2655. else
  2656. {
  2657. // Clone the file list as it may refer to current directory files,
  2658. // which get destroyed, when the source directory is reloaded after foMove operation.
  2659. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2660. // But for a hotfix, we are not going to do such a big change.
  2661. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2662. PermanentFileList = PermanentFileListOwner.get();
  2663. try
  2664. {
  2665. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2666. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2667. }
  2668. __finally
  2669. {
  2670. if (Operation == foMove)
  2671. {
  2672. if (DView != NULL)
  2673. {
  2674. DView->RestoreSelection();
  2675. }
  2676. SelectionRestored = true;
  2677. }
  2678. ReloadLocalDirectory(Param.TargetDirectory);
  2679. }
  2680. }
  2681. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2682. if (FMoveToQueue)
  2683. {
  2684. Abort();
  2685. }
  2686. }
  2687. catch (EAbort &)
  2688. {
  2689. if (FMoveToQueue)
  2690. {
  2691. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2692. DebugAssert(CopyParam.TransferSkipList == NULL);
  2693. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2694. if (TransferResumeList->Count > 0)
  2695. {
  2696. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2697. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2698. }
  2699. CopyParam.TransferSkipList = TransferResumeList.release();
  2700. // not really needed, just to keep it consistent with TransferResumeList
  2701. FTransferResumeList = NULL;
  2702. FMoveToQueue = false;
  2703. Configuration->Usage->Inc("MovesToBackground");
  2704. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2705. ClearTransferSourceSelection(Direction);
  2706. }
  2707. throw;
  2708. }
  2709. }
  2710. __finally
  2711. {
  2712. if (!SelectionRestored && (DView != NULL))
  2713. {
  2714. DView->DiscardSavedSelection();
  2715. }
  2716. FTransferResumeList = NULL;
  2717. }
  2718. }
  2719. return Result;
  2720. }
  2721. //---------------------------------------------------------------------------
  2722. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2723. TOperationSide Side, TStrings * FileList, void * Param)
  2724. {
  2725. DebugAssert(FileList->Count);
  2726. // We deliberately do not toggle alternative flag (Param), but use OR,
  2727. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2728. // shortcut of CurrentDeleteAlternativeAction
  2729. bool Alternative =
  2730. bool(Param) || UseAlternativeFunction();
  2731. bool Recycle;
  2732. if (IsSideLocalBrowser(Side))
  2733. {
  2734. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2735. }
  2736. else
  2737. {
  2738. Recycle =
  2739. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2740. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2741. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2742. }
  2743. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2744. if (!Result)
  2745. {
  2746. UnicodeString Query;
  2747. if (FileList->Count == 1)
  2748. {
  2749. if (IsSideLocalBrowser(Side))
  2750. {
  2751. Query = ExtractFileName(FileList->Strings[0]);
  2752. }
  2753. else
  2754. {
  2755. Query = UnixExtractFileName(FileList->Strings[0]);
  2756. }
  2757. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2758. }
  2759. else
  2760. {
  2761. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2762. }
  2763. TMessageParams Params(mpNeverAskAgainCheck);
  2764. Params.ImageName = L"Delete file";
  2765. unsigned int Answer =
  2766. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2767. if (Answer == qaNeverAskAgain)
  2768. {
  2769. Result = true;
  2770. if (Recycle)
  2771. {
  2772. WinConfiguration->ConfirmRecycling = false;
  2773. }
  2774. else
  2775. {
  2776. WinConfiguration->ConfirmDeleting = false;
  2777. }
  2778. }
  2779. else
  2780. {
  2781. Result = (Answer == qaOK);
  2782. }
  2783. }
  2784. if (Result)
  2785. {
  2786. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2787. }
  2788. return Result;
  2789. }
  2790. //---------------------------------------------------------------------------
  2791. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2792. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2793. {
  2794. TAutoBatch AutoBatch(this);
  2795. bool Result;
  2796. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2797. {
  2798. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2799. }
  2800. else if (Operation == foRename)
  2801. {
  2802. DebugAssert(DirView(Side)->ItemFocused);
  2803. DirView(Side)->ItemFocused->EditCaption();
  2804. Result = true;
  2805. }
  2806. else if (Operation == foDelete)
  2807. {
  2808. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2809. }
  2810. else if (Operation == foSetProperties)
  2811. {
  2812. DirView(osRemote)->SaveSelectedNames();
  2813. Result = SetProperties(Side, FileList);
  2814. }
  2815. else if (Operation == foCustomCommand)
  2816. {
  2817. DebugAssert(Param);
  2818. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2819. DirView(osRemote)->SaveSelectedNames();
  2820. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2821. CustomCommand(FileList, *Command, NULL);
  2822. Result = true;
  2823. }
  2824. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2825. {
  2826. DebugAssert(!IsSideLocalBrowser(Side));
  2827. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2828. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2829. }
  2830. else if (Operation == foLock)
  2831. {
  2832. DebugAssert(!IsSideLocalBrowser(Side));
  2833. LockFiles(FileList, true);
  2834. Result = true;
  2835. }
  2836. else if (Operation == foUnlock)
  2837. {
  2838. DebugAssert(!IsSideLocalBrowser(Side));
  2839. LockFiles(FileList, false);
  2840. Result = true;
  2841. }
  2842. else
  2843. {
  2844. DebugFail();
  2845. }
  2846. return Result;
  2847. }
  2848. //---------------------------------------------------------------------------
  2849. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2850. {
  2851. if (Side == osCurrent)
  2852. {
  2853. Side = FCurrentSide;
  2854. }
  2855. return Side;
  2856. }
  2857. //---------------------------------------------------------------------------
  2858. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2859. {
  2860. TOperationSide Result;
  2861. switch (GetSide(Side))
  2862. {
  2863. case osLocal:
  2864. Result = osOther;
  2865. break;
  2866. case osOther:
  2867. Result = osLocal;
  2868. break;
  2869. default:
  2870. DebugFail();
  2871. Abort();
  2872. }
  2873. return Result;
  2874. }
  2875. //---------------------------------------------------------------------------
  2876. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2877. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2878. {
  2879. Side = GetSide(Side);
  2880. bool FullPath = IsSideLocalBrowser(Side);
  2881. TCustomDirView * ADirView = DirView(Side);
  2882. std::unique_ptr<TStringList> FileList(new TStringList());
  2883. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2884. bool ReloadProperties =
  2885. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2886. DebugAlwaysTrue(HasActiveTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2887. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2888. if (Result && ReloadProperties)
  2889. {
  2890. std::unique_ptr<TStringList> FileList2(new TStringList());
  2891. FileList->CaseSensitive = true;
  2892. FileList->Sort();
  2893. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2894. {
  2895. TListItem * Item = ADirView->Items->Item[Index];
  2896. UnicodeString FileName = ADirView->ItemFileName(Item);
  2897. int Index2;
  2898. if (FileList->Find(FileName, Index2))
  2899. {
  2900. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2901. }
  2902. }
  2903. LoadFilesProperties(FileList2.get());
  2904. }
  2905. return Result;
  2906. }
  2907. //---------------------------------------------------------------------------
  2908. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2909. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2910. bool NoConfirmation, void * Param)
  2911. {
  2912. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2913. {
  2914. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2915. {
  2916. DebugAssert(!IsLocalBrowserMode());
  2917. if (GetSide(Side) == osLocal)
  2918. {
  2919. Configuration->Usage->Inc(L"UploadsCommand");
  2920. }
  2921. else
  2922. {
  2923. Configuration->Usage->Inc(L"DownloadsCommand");
  2924. }
  2925. }
  2926. }
  2927. }
  2928. //---------------------------------------------------------------------------
  2929. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2930. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2931. {
  2932. TTransferOperationParam Param;
  2933. if ((WinConfiguration->Interface != ifCommander) ||
  2934. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2935. {
  2936. Flags &= ~cocShortCutHint;
  2937. }
  2938. TCustomDirView * DView = DirView(Side);
  2939. Param.Options =
  2940. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2941. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2942. if (FLAGSET(Flags, cocQueue))
  2943. {
  2944. Param.Queue = asOn;
  2945. }
  2946. else if (FLAGSET(Flags, cocNonQueue))
  2947. {
  2948. Param.Queue = asOff;
  2949. }
  2950. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2951. }
  2952. //---------------------------------------------------------------------------
  2953. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2954. {
  2955. int Count = ErrorList->Count;
  2956. try
  2957. {
  2958. if (ErrorList->Count)
  2959. {
  2960. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2961. if (MessageDialog(Message, qtError,
  2962. qaOK | qaCancel, HELP_NONE) == qaOK)
  2963. {
  2964. unsigned int Answer;
  2965. int Index = 0;
  2966. do
  2967. {
  2968. DebugAssert(Index >= 0 && Index < Count);
  2969. TQueryButtonAlias Aliases[2];
  2970. Aliases[0].Button = qaYes;
  2971. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2972. Aliases[1].Button = qaNo;
  2973. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2974. TMessageParams Params;
  2975. Params.Aliases = Aliases;
  2976. Params.AliasesCount = LENOF(Aliases);
  2977. int No = Index + 1;
  2978. UnicodeString Message = ErrorList->Strings[Index];
  2979. UnicodeString AMainInstructions;
  2980. UnicodeString Details;
  2981. if (ExtractMainInstructions(Message, AMainInstructions))
  2982. {
  2983. Details = Message;
  2984. Message = AMainInstructions;
  2985. }
  2986. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2987. Answer = MoreMessageDialog(
  2988. Message,
  2989. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2990. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2991. qaOK, HELP_NONE, &Params);
  2992. if (Answer == qaNo)
  2993. {
  2994. Index++;
  2995. }
  2996. if (Answer == qaYes)
  2997. {
  2998. Index--;
  2999. }
  3000. }
  3001. while (Answer != qaOK);
  3002. }
  3003. }
  3004. }
  3005. __finally
  3006. {
  3007. TStrings * List = ErrorList;
  3008. ErrorList = NULL;
  3009. for (int i = 0; i < Count; i++)
  3010. {
  3011. delete List->Objects[i];
  3012. }
  3013. delete List;
  3014. }
  3015. }
  3016. //---------------------------------------------------------------------------
  3017. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3018. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3019. {
  3020. // needed for checking filemasks, as there's no directory object
  3021. // associated with the file object
  3022. File->FullFileName = FullFileName;
  3023. TFileMasks::TParams MaskParams;
  3024. MaskParams.Size = File->Size;
  3025. MaskParams.Modification = File->Modification;
  3026. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3027. }
  3028. //---------------------------------------------------------------------------
  3029. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3030. {
  3031. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3032. Side = GetSide(Side);
  3033. TCustomDirView * DView = DirView(Side);
  3034. TListItem * FocusedItem = DView->ItemFocused;
  3035. UnicodeString Name;
  3036. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3037. {
  3038. Name = DView->ItemFileName(FocusedItem);
  3039. }
  3040. else
  3041. {
  3042. Name = LoadStr(NEW_FILE);
  3043. }
  3044. UnicodeString Names = Name;
  3045. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3046. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3047. HELP_EDIT_NEW, History.get(), true, NULL, true, 400))
  3048. {
  3049. while (!Names.IsEmpty())
  3050. {
  3051. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3052. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3053. UnicodeString TargetFileName;
  3054. UnicodeString LocalFileName;
  3055. UnicodeString RootTempDir;
  3056. UnicodeString TempDir;
  3057. UnicodeString RemoteDirectory;
  3058. bool ExistingFile = false;
  3059. if (!IsSideLocalBrowser(Side))
  3060. {
  3061. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3062. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3063. if ((File.get() != NULL) &&
  3064. !File->IsDirectory)
  3065. {
  3066. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3067. ExistingFile = true;
  3068. }
  3069. File.reset(NULL);
  3070. if (!ExistingFile)
  3071. {
  3072. RemoteDirectory = UnixExtractFilePath(Name);
  3073. TemporaryDirectoryForRemoteFiles(
  3074. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3075. TargetFileName = UnixExtractFileName(Name);
  3076. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3077. LocalFileName = TempDir +
  3078. // We probably do not want to trim the VMS version here
  3079. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3080. }
  3081. }
  3082. else
  3083. {
  3084. if (ExtractFilePath(Name).IsEmpty())
  3085. {
  3086. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3087. }
  3088. else
  3089. {
  3090. LocalFileName = ExpandFileName(Name);
  3091. }
  3092. TargetFileName = ExtractFileName(Name);
  3093. }
  3094. if (!ExistingFile)
  3095. {
  3096. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3097. if (NewFile)
  3098. {
  3099. int File = FileCreate(ApiPath(LocalFileName));
  3100. if (File < 0)
  3101. {
  3102. if (!RootTempDir.IsEmpty())
  3103. {
  3104. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3105. }
  3106. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3107. }
  3108. else
  3109. {
  3110. FileClose(File);
  3111. }
  3112. }
  3113. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3114. const TEditorData * ExternalEditor = NULL;
  3115. TFileMasks::TParams MaskParams; // size not known
  3116. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3117. false, MaskParams);
  3118. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3119. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3120. }
  3121. }
  3122. }
  3123. }
  3124. //---------------------------------------------------------------------------
  3125. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3126. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3127. {
  3128. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3129. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3130. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3131. return
  3132. ((ExecuteFileBy == efInternalEditor)) ||
  3133. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3134. }
  3135. //---------------------------------------------------------------------------
  3136. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3137. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3138. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3139. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3140. {
  3141. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3142. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3143. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3144. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3145. Side = GetSide(Side);
  3146. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3147. if (!IsSideLocalBrowser(Side))
  3148. {
  3149. Data->Terminal = Terminal;
  3150. Data->SessionData = CloneCurrentSessionData();
  3151. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3152. Data->RemoteDirectory = RemoteDirectory;
  3153. Data->SessionName = Terminal->SessionData->SessionName;
  3154. Data->LocalRootDirectory = LocalRootDirectory;
  3155. Data->OriginalFileName = OriginalFileName;
  3156. Data->Command = L""; // will be changed later for external editor
  3157. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3158. if (WinConfiguration->EditorCheckNotModified)
  3159. {
  3160. Data->SourceTimestamp = SourceTimestamp;
  3161. }
  3162. }
  3163. if (ExecuteFileBy == efInternalEditor)
  3164. {
  3165. if (!IsSideLocalBrowser(Side))
  3166. {
  3167. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3168. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3169. TForm * Editor;
  3170. try
  3171. {
  3172. Editor =
  3173. ShowEditorForm(
  3174. FileName, this,
  3175. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3176. SaveAllInternalEditors, AnyInternalEditorModified,
  3177. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3178. }
  3179. catch(...)
  3180. {
  3181. if (!LocalRootDirectory.IsEmpty())
  3182. {
  3183. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3184. }
  3185. throw;
  3186. }
  3187. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3188. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3189. }
  3190. else
  3191. {
  3192. DebugAssert(!StandaloneOperation);
  3193. TForm * Editor =
  3194. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3195. SaveAllInternalEditors, AnyInternalEditorModified,
  3196. L"", false, SessionColor, -1, NewFile);
  3197. FLocalEditors->Add(Editor);
  3198. }
  3199. }
  3200. else
  3201. {
  3202. HANDLE Process;
  3203. if (ExecuteFileBy == efExternalEditor)
  3204. {
  3205. UnicodeString Program, Params, Dir;
  3206. Data->Command = ExternalEditor->ExternalEditor;
  3207. ReformatFileNameCommand(Data->Command);
  3208. SplitCommand(Data->Command, Program, Params, Dir);
  3209. Params = ExpandFileNameCommand(Params, FileName);
  3210. Program = ExpandEnvironmentVariables(Program);
  3211. if (!ExecuteShell(Program, Params, Process))
  3212. {
  3213. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3214. }
  3215. }
  3216. else
  3217. {
  3218. DebugAssert(!IsSideLocalBrowser(Side));
  3219. if (!ExecuteShell(FileName, L"", Process))
  3220. {
  3221. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3222. }
  3223. }
  3224. if (IsSideLocalBrowser(Side) ||
  3225. ((ExecuteFileBy == efShell) &&
  3226. !WinConfiguration->Editor.SDIShellEditor) ||
  3227. ((ExecuteFileBy == efExternalEditor) &&
  3228. !ExternalEditor->SDIExternalEditor))
  3229. {
  3230. // no need for handle
  3231. if (Process != NULL)
  3232. {
  3233. DebugCheck(CloseHandle(Process));
  3234. }
  3235. Process = INVALID_HANDLE_VALUE;
  3236. }
  3237. else
  3238. {
  3239. if (Process == NULL)
  3240. {
  3241. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3242. }
  3243. }
  3244. if (!IsSideLocalBrowser(Side))
  3245. {
  3246. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3247. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3248. }
  3249. }
  3250. }
  3251. //---------------------------------------------------------------------------
  3252. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3253. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3254. void * /*Arg*/)
  3255. {
  3256. if (Token != NULL)
  3257. {
  3258. EditorFormFileSave(static_cast<TForm *>(Token));
  3259. }
  3260. }
  3261. //---------------------------------------------------------------------------
  3262. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3263. {
  3264. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3265. {
  3266. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3267. }
  3268. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3269. }
  3270. //---------------------------------------------------------------------------
  3271. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3272. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3273. void * Arg)
  3274. {
  3275. if ((Token != NULL) &&
  3276. IsEditorFormModified(static_cast<TForm *>(Token)))
  3277. {
  3278. *static_cast<bool *>(Arg) = true;
  3279. }
  3280. }
  3281. //---------------------------------------------------------------------------
  3282. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3283. TObject * /*Sender*/, bool & Modified)
  3284. {
  3285. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3286. {
  3287. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3288. {
  3289. Modified = true;
  3290. }
  3291. }
  3292. if (!Modified)
  3293. {
  3294. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3295. }
  3296. }
  3297. //---------------------------------------------------------------------------
  3298. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3299. {
  3300. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3301. }
  3302. //---------------------------------------------------------------------------
  3303. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3304. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3305. UnicodeString & Result, UnicodeString & RootDirectory)
  3306. {
  3307. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3308. {
  3309. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3310. Result = RootDirectory;
  3311. }
  3312. else
  3313. {
  3314. RootDirectory = L"";
  3315. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3316. Result = IncludeTrailingBackslash(Result);
  3317. }
  3318. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3319. {
  3320. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3321. }
  3322. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3323. {
  3324. UnicodeString ARemoteDirectory = RemoteDirectory;
  3325. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3326. {
  3327. ARemoteDirectory.Delete(1, 1);
  3328. }
  3329. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3330. }
  3331. if (!ForceDirectories(ApiPath(Result)))
  3332. {
  3333. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3334. }
  3335. }
  3336. //---------------------------------------------------------------------------
  3337. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3338. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3339. bool GetTargetNames, bool AutoOperation, bool SimpleTempDir)
  3340. {
  3341. DebugAssert(!IsLocalBrowserMode());
  3342. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3343. if (ForceText)
  3344. {
  3345. CopyParam.TransferMode = tmAscii;
  3346. }
  3347. TemporaryFileCopyParam(CopyParam);
  3348. if (TempDir.IsEmpty())
  3349. {
  3350. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3351. }
  3352. DebugAssert(!FAutoOperation);
  3353. FAutoOperation = AutoOperation;
  3354. Terminal->ExceptionOnFail = true;
  3355. try
  3356. {
  3357. try
  3358. {
  3359. // turn off confirmations, as for MDI editors we may possibly download
  3360. // the same file over
  3361. Terminal->CopyToLocal(
  3362. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3363. if (GetTargetNames)
  3364. {
  3365. for (int i = 0; i < FileList->Count; i++)
  3366. {
  3367. FileList->Strings[i] =
  3368. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3369. }
  3370. }
  3371. }
  3372. catch(...)
  3373. {
  3374. if (!RootTempDir.IsEmpty())
  3375. {
  3376. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3377. }
  3378. throw;
  3379. }
  3380. }
  3381. __finally
  3382. {
  3383. FAutoOperation = false;
  3384. Terminal->ExceptionOnFail = false;
  3385. }
  3386. }
  3387. //---------------------------------------------------------------------------
  3388. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3389. {
  3390. // Do not waste time checking for default editor list the next time,
  3391. // or testing if default editor is not notepad.
  3392. bool TryNextTime = false;
  3393. UnicodeString UsageState;
  3394. if (!WinConfiguration->EditorList->IsDefaultList())
  3395. {
  3396. UsageState = "H";
  3397. }
  3398. else
  3399. {
  3400. UnicodeString Executable;
  3401. UnicodeString ExecutableDescription;
  3402. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3403. {
  3404. UnicodeString Message =
  3405. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3406. unsigned int Answer =
  3407. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3408. if (Answer != qaOK)
  3409. {
  3410. UsageState = "R";
  3411. }
  3412. else
  3413. {
  3414. UsageState = "A";
  3415. TEditorData EditorData;
  3416. EditorData.Editor = edExternal;
  3417. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3418. EditorData.ExternalEditorOptionsAutodetect();
  3419. TEditorList EditorList;
  3420. EditorList = *WinConfiguration->EditorList;
  3421. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3422. WinConfiguration->EditorList = &EditorList;
  3423. }
  3424. }
  3425. }
  3426. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3427. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3428. }
  3429. //---------------------------------------------------------------------------
  3430. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3431. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3432. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3433. {
  3434. if (ExecuteFileBy == efDefaultEditor)
  3435. {
  3436. if (!WinConfiguration->OfferedEditorAutoConfig)
  3437. {
  3438. EditorAutoConfig();
  3439. }
  3440. const TEditorPreferences * Editor =
  3441. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3442. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3443. {
  3444. ExecuteFileBy = efInternalEditor;
  3445. ExternalEditor = NULL;
  3446. }
  3447. else if (Editor->Data->Editor == edOpen)
  3448. {
  3449. ExecuteFileBy = efShell;
  3450. ExternalEditor = NULL;
  3451. }
  3452. else
  3453. {
  3454. ExecuteFileBy = efExternalEditor;
  3455. ExternalEditor = Editor->Data;
  3456. }
  3457. }
  3458. }
  3459. //---------------------------------------------------------------------------
  3460. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3461. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3462. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3463. {
  3464. UnicodeString OriginalFileName;
  3465. UnicodeString LocalRootDirectory;
  3466. UnicodeString RemoteDirectory;
  3467. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3468. IsSideLocalBrowser(Side), MaskParams);
  3469. UnicodeString Counter;
  3470. UnicodeString LocalFileName;
  3471. bool Handled = false;
  3472. if (!IsSideLocalBrowser(Side))
  3473. {
  3474. // We need to trim VMS version here, so that we use name without version
  3475. // when uploading back to create a new version of the file
  3476. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3477. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3478. TObject * Token = NULL;
  3479. UnicodeString LocalDirectory;
  3480. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3481. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3482. LocalDirectory))
  3483. {
  3484. if (Token != NULL)
  3485. {
  3486. TForm * Form = dynamic_cast<TForm *>(Token);
  3487. if (Form->WindowState == wsMinimized)
  3488. {
  3489. ShowWindow(Form->Handle, SW_RESTORE);
  3490. }
  3491. else
  3492. {
  3493. Form->SetFocus();
  3494. }
  3495. Handled = true;
  3496. }
  3497. else
  3498. {
  3499. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3500. }
  3501. }
  3502. if (!Handled)
  3503. {
  3504. TStringList * FileList1 = new TStringList();
  3505. try
  3506. {
  3507. FileList1->AddObject(FullFileName, Object);
  3508. TemporarilyDownloadFiles(FileList1,
  3509. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3510. LocalRootDirectory, LocalDirectory, true, true, false);
  3511. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3512. }
  3513. __finally
  3514. {
  3515. delete FileList1;
  3516. }
  3517. switch (ExecuteFileBy)
  3518. {
  3519. case efShell:
  3520. Counter = "RemoteFilesExecuted";
  3521. break;
  3522. case efInternalEditor:
  3523. Counter = "RemoteFilesOpenedInInternalEditor";
  3524. break;
  3525. case efExternalEditor:
  3526. Counter = "RemoteFilesOpenedInExternalEditor";
  3527. break;
  3528. default:
  3529. DebugFail();
  3530. }
  3531. }
  3532. }
  3533. else
  3534. {
  3535. LocalFileName = FullFileName;
  3536. OriginalFileName = ExtractFileName(FullFileName);
  3537. switch (ExecuteFileBy)
  3538. {
  3539. case efShell:
  3540. Counter = "LocalFilesExecuted";
  3541. break;
  3542. case efInternalEditor:
  3543. Counter = "LocalFilesOpenedInInternalEditor";
  3544. break;
  3545. case efExternalEditor:
  3546. Counter = "LocalFilesOpenedInExternalEditor";
  3547. break;
  3548. default:
  3549. DebugFail();
  3550. }
  3551. }
  3552. if (!Handled)
  3553. {
  3554. Configuration->Usage->Inc(Counter);
  3555. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3556. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3557. }
  3558. }
  3559. //---------------------------------------------------------------------------
  3560. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3561. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3562. bool AllSelected, bool OnFocused)
  3563. {
  3564. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3565. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3566. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3567. Side = GetSide(Side);
  3568. TCustomDirView * DView = DirView(Side);
  3569. TStrings * FileList =
  3570. AllSelected ?
  3571. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3572. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3573. try
  3574. {
  3575. DebugAssert(AllSelected || (FileList->Count == 1));
  3576. for (int i = 0; i < FileList->Count; i++)
  3577. {
  3578. UnicodeString ListFileName = FileList->Strings[i];
  3579. UnicodeString FileNameOnly =
  3580. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3581. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3582. if (!DView->ItemIsDirectory(Item))
  3583. {
  3584. UnicodeString FullFileName;
  3585. if (!IsSideLocalBrowser(Side))
  3586. {
  3587. FullFileName = DirView(Side)->Path + ListFileName;
  3588. }
  3589. else
  3590. {
  3591. FullFileName = ListFileName;
  3592. }
  3593. TObject * Object = FileList->Objects[i];
  3594. TFileMasks::TParams MaskParams;
  3595. MaskParams.Size = DView->ItemFileSize(Item);
  3596. TDateTimePrecision Precision;
  3597. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3598. std::unique_ptr<TRemoteFile> File;
  3599. if (!IsSideLocalBrowser(Side))
  3600. {
  3601. File.reset(Terminal->TryReadFile(FullFileName));
  3602. if (File.get() != NULL)
  3603. {
  3604. File->FullFileName = FullFileName;
  3605. Object = File.get();
  3606. MaskParams.Size = File->Size;
  3607. MaskParams.Modification = File->Modification;
  3608. }
  3609. }
  3610. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3611. }
  3612. }
  3613. }
  3614. __finally
  3615. {
  3616. delete FileList;
  3617. }
  3618. }
  3619. //---------------------------------------------------------------------------
  3620. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3621. {
  3622. CopyParam.FileNameCase = ncNoChange;
  3623. CopyParam.PreserveRights = false;
  3624. CopyParam.PreserveReadOnly = false;
  3625. CopyParam.ReplaceInvalidChars = true;
  3626. CopyParam.IncludeFileMask = TFileMasks();
  3627. CopyParam.NewerOnly = false;
  3628. CopyParam.FileMask = L"";
  3629. }
  3630. //---------------------------------------------------------------------------
  3631. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3632. {
  3633. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3634. }
  3635. //---------------------------------------------------------------------------
  3636. class TEditorUploadQueueItem : public TUploadQueueItem
  3637. {
  3638. public:
  3639. __fastcall TEditorUploadQueueItem(
  3640. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3641. const TCopyParamType * CopyParam, int Params) :
  3642. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, true, false)
  3643. {
  3644. }
  3645. protected:
  3646. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3647. {
  3648. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3649. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3650. }
  3651. };
  3652. //---------------------------------------------------------------------------
  3653. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3654. {
  3655. if (WinConfiguration->EditorCheckNotModified) // optimization
  3656. {
  3657. UnicodeString RemoteFilePath;
  3658. {
  3659. TGuard Guard(FEditorManager->Section);
  3660. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3661. if (DebugAlwaysTrue(Data != NULL) &&
  3662. EditorCheckNotModified(Data))
  3663. {
  3664. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3665. }
  3666. }
  3667. if (!RemoteFilePath.IsEmpty())
  3668. {
  3669. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3670. if (File.get() != NULL)
  3671. {
  3672. TGuard Guard(FEditorManager->Section);
  3673. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3674. if (DebugAlwaysTrue(Data != NULL))
  3675. {
  3676. Data->SourceTimestamp = File->Modification;
  3677. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3678. }
  3679. }
  3680. }
  3681. }
  3682. }
  3683. //---------------------------------------------------------------------------
  3684. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3685. const UnicodeString & FileName, TEditedFileData * Data, HANDLE UploadCompleteEvent, bool & Retry)
  3686. {
  3687. TTerminalManager * Manager = TTerminalManager::Instance();
  3688. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3689. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3690. {
  3691. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3692. Retry = true;
  3693. }
  3694. else if (!IsActiveTerminal(Data->Terminal))
  3695. {
  3696. if (!NonVisualDataModule->Busy)
  3697. {
  3698. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3699. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3700. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3701. if (Data->Terminal == NULL)
  3702. {
  3703. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3704. if (SameSiteTerminal != NULL)
  3705. {
  3706. UnicodeString Message =
  3707. FMTLOAD(EDIT_SESSION_REATTACH,
  3708. (FileNameOnly, Data->SessionName, FileNameOnly));
  3709. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3710. {
  3711. Data->Terminal = SameSiteTerminal;
  3712. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3713. // We might also overwrite session data
  3714. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3715. }
  3716. else
  3717. {
  3718. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3719. Abort();
  3720. }
  3721. }
  3722. }
  3723. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3724. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3725. {
  3726. UnicodeString Message =
  3727. MainInstructions(
  3728. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3729. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3730. {
  3731. if (Terminal->Disconnected)
  3732. {
  3733. Manager->ActiveSession = Terminal;
  3734. ReconnectSession();
  3735. // Was it reconnected? (if not, Data->Terminal should be nulled now)
  3736. if (!IsActiveTerminal(Data->Terminal) || (Terminal != Data->Terminal))
  3737. {
  3738. Abort();
  3739. }
  3740. }
  3741. else
  3742. {
  3743. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3744. }
  3745. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3746. }
  3747. else
  3748. {
  3749. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3750. Abort();
  3751. }
  3752. }
  3753. }
  3754. if (!IsActiveTerminal(Data->Terminal))
  3755. {
  3756. Configuration->Usage->Inc(L"EditInactiveSession");
  3757. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3758. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3759. (ExtractFileName(FileName), Data->SessionName)));
  3760. }
  3761. }
  3762. if (!Retry && EditorCheckNotModified(Data))
  3763. {
  3764. if (NonVisualDataModule->Busy)
  3765. {
  3766. Retry = true;
  3767. }
  3768. else
  3769. {
  3770. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3771. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3772. if (File.get() != NULL)
  3773. {
  3774. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3775. if (File->Modification != Data->SourceTimestamp)
  3776. {
  3777. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3778. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3779. {
  3780. Abort();
  3781. }
  3782. }
  3783. }
  3784. }
  3785. }
  3786. if (!Retry)
  3787. {
  3788. TStrings * FileList = new TStringList();
  3789. try
  3790. {
  3791. FileList->Add(FileName);
  3792. // Consider using the same settings (preset) as when the file was downloaded.
  3793. // More over this does not reflect the actual session that will do the upload.
  3794. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3795. TemporaryFileCopyParam(CopyParam);
  3796. if (Data->ForceText)
  3797. {
  3798. CopyParam.TransferMode = tmAscii;
  3799. }
  3800. // so i do not need to worry if masking algorithm works in all cases
  3801. // ("" means "copy file name", no masking is actually done)
  3802. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3803. {
  3804. CopyParam.FileMask = L"";
  3805. }
  3806. else
  3807. {
  3808. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3809. }
  3810. int Params = cpNoConfirmation | cpTemporary;
  3811. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3812. {
  3813. TTerminalQueue * AQueue = Manager->FindQueueForTerminal(Data->Terminal);
  3814. TQueueItem * QueueItem =
  3815. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3816. QueueItem->CompleteEvent = UploadCompleteEvent;
  3817. AddQueueItem(AQueue, QueueItem, Data->Terminal);
  3818. }
  3819. else
  3820. {
  3821. if (NonVisualDataModule->Busy)
  3822. {
  3823. Retry = true;
  3824. }
  3825. else
  3826. {
  3827. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3828. SetEvent(UploadCompleteEvent);
  3829. }
  3830. }
  3831. }
  3832. __finally
  3833. {
  3834. delete FileList;
  3835. }
  3836. }
  3837. }
  3838. //---------------------------------------------------------------------------
  3839. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3840. const UnicodeString & FileName, TEditedFileData * Data)
  3841. {
  3842. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3843. DebugAssert(!NonVisualDataModule->Busy);
  3844. if (!IsActiveTerminal(Data->Terminal))
  3845. {
  3846. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3847. (ExtractFileName(FileName), Data->SessionName)));
  3848. }
  3849. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3850. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3851. NonVisualDataModule->StartBusy();
  3852. try
  3853. {
  3854. std::unique_ptr<TRemoteFile> File;
  3855. UnicodeString RemoteFileName =
  3856. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3857. Terminal->ExceptionOnFail = true;
  3858. try
  3859. {
  3860. File.reset(Terminal->ReadFile(RemoteFileName));
  3861. if (!File->HaveFullFileName)
  3862. {
  3863. File->FullFileName = RemoteFileName;
  3864. }
  3865. }
  3866. __finally
  3867. {
  3868. Terminal->ExceptionOnFail = false;
  3869. }
  3870. std::unique_ptr<TStrings> FileList(new TStringList());
  3871. FileList->AddObject(RemoteFileName, File.get());
  3872. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3873. UnicodeString TempDir = ExtractFilePath(FileName);
  3874. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, true, false);
  3875. if (EditorCheckNotModified(Data))
  3876. {
  3877. Data->SourceTimestamp = File->Modification;
  3878. }
  3879. // sanity check, the target file name should be still the same
  3880. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3881. }
  3882. __finally
  3883. {
  3884. NonVisualDataModule->EndBusy();
  3885. // it actually may not exist anymore...
  3886. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3887. }
  3888. }
  3889. //---------------------------------------------------------------------------
  3890. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3891. const TEditedFileData * Data, bool & KeepOpen)
  3892. {
  3893. // Command is set for external editors only (not for "shell" open).
  3894. if (!Data->Command.IsEmpty())
  3895. {
  3896. bool AnyFound = false;
  3897. bool AnyMDI = false;
  3898. bool AnyNonMDI = false;
  3899. bool AnyDetect = false;
  3900. TEditorList * EditorList = new TEditorList();
  3901. try
  3902. {
  3903. *EditorList = *WinConfiguration->EditorList;
  3904. for (int i = 0; i < EditorList->Count; i++)
  3905. {
  3906. const TEditorPreferences * Editor = EditorList->Editors[i];
  3907. if ((Editor->Data->Editor == edExternal) &&
  3908. (Editor->Data->ExternalEditor == Data->Command))
  3909. {
  3910. AnyFound = true;
  3911. if (Editor->Data->SDIExternalEditor)
  3912. {
  3913. AnyNonMDI = true;
  3914. if (Editor->Data->DetectMDIExternalEditor)
  3915. {
  3916. AnyDetect = true;
  3917. }
  3918. }
  3919. else
  3920. {
  3921. AnyMDI = true;
  3922. }
  3923. }
  3924. }
  3925. bool EnableMDI = false;
  3926. bool DisableDetect = false;
  3927. if (AnyMDI)
  3928. {
  3929. KeepOpen = true;
  3930. if (AnyNonMDI)
  3931. {
  3932. // there is at least one instance of the editor with MDI support enabled,
  3933. // and one with disabled, enable it for all instances
  3934. EnableMDI = true;
  3935. }
  3936. }
  3937. else if (AnyFound && !AnyDetect)
  3938. {
  3939. // at least once instance found but all have MDI autodetection disabled
  3940. // => close the file (default action)
  3941. }
  3942. else
  3943. {
  3944. // no instance of the editor has MDI support enabled
  3945. TMessageParams Params;
  3946. if (AnyFound)
  3947. {
  3948. // there is at least one instance of the editor
  3949. Params.Params |= mpNeverAskAgainCheck;
  3950. }
  3951. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3952. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3953. switch (Answer)
  3954. {
  3955. case qaNeverAskAgain:
  3956. DisableDetect = true;
  3957. break;
  3958. case qaNo:
  3959. EnableMDI = true;
  3960. KeepOpen = true;
  3961. break;
  3962. }
  3963. }
  3964. if (AnyFound && (EnableMDI || DisableDetect))
  3965. {
  3966. bool Changed = false;
  3967. for (int i = 0; i < EditorList->Count; i++)
  3968. {
  3969. const TEditorPreferences * Editor = EditorList->Editors[i];
  3970. if ((Editor->Data->Editor == edExternal) &&
  3971. (Editor->Data->ExternalEditor == Data->Command) &&
  3972. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3973. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3974. {
  3975. Changed = true;
  3976. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3977. if (EnableMDI)
  3978. {
  3979. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3980. }
  3981. if (DisableDetect)
  3982. {
  3983. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3984. }
  3985. EditorList->Change(i, UpdatedEditor);
  3986. }
  3987. }
  3988. if (Changed)
  3989. {
  3990. WinConfiguration->EditorList = EditorList;
  3991. }
  3992. }
  3993. }
  3994. __finally
  3995. {
  3996. delete EditorList;
  3997. }
  3998. }
  3999. else
  4000. {
  4001. // "open" case
  4002. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  4003. qaOK, HELP_APP_EARLY_CLOSED);
  4004. }
  4005. }
  4006. //---------------------------------------------------------------------------
  4007. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  4008. {
  4009. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  4010. }
  4011. //---------------------------------------------------------------------------
  4012. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  4013. {
  4014. SideEnter(osRemote);
  4015. }
  4016. //---------------------------------------------------------------------------
  4017. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4018. {
  4019. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4020. SideEnter(osRemote);
  4021. }
  4022. //---------------------------------------------------------------------------
  4023. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4024. {
  4025. FCurrentSide = Side;
  4026. if (Visible)
  4027. {
  4028. UpdateControls();
  4029. }
  4030. }
  4031. //---------------------------------------------------------------------------
  4032. void __fastcall TCustomScpExplorerForm::FileDeleted(TOperationSide Side, const UnicodeString & FileName, bool Success)
  4033. {
  4034. VisualiseOperationFinished(Side, FileName, Success);
  4035. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4036. {
  4037. FDeletedFiles->Add(FileName);
  4038. }
  4039. }
  4040. //---------------------------------------------------------------------------
  4041. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4042. TStrings * FileList, bool Alternative)
  4043. {
  4044. TCustomDirView * DView = DirView(Side);
  4045. DView->SaveSelection();
  4046. DView->SaveSelectedNames();
  4047. DebugAssert(!FAlternativeDelete);
  4048. FAlternativeDelete = Alternative;
  4049. try
  4050. {
  4051. if (!IsSideLocalBrowser(Side))
  4052. {
  4053. DebugAssert(Terminal != NULL);
  4054. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4055. std::unique_ptr<TStrings> PermanentFileList(TRemoteFileList::CloneStrings(FileList));
  4056. std::unique_ptr<TStringList> DeletedFiles(new TStringList());
  4057. DeletedFiles->CaseSensitive = DebugAlwaysTrue(!IsSideLocalBrowser(Side));
  4058. int Params = FLAGMASK(Alternative, dfAlternative);
  4059. try
  4060. {
  4061. DebugAssert(FDeletedFiles == NULL);
  4062. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles, DeletedFiles.get());
  4063. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4064. FOnFileOperationFinished = FileDeleted;
  4065. FMoveToQueue = false;
  4066. Terminal->DeleteFiles(FileList, Params);
  4067. // Probably not needed for deleting, just for consistency with transfer code
  4068. if (FMoveToQueue)
  4069. {
  4070. Abort();
  4071. }
  4072. }
  4073. catch (EAbort &)
  4074. {
  4075. if (FMoveToQueue)
  4076. {
  4077. DeletedFiles->Sorted = true;
  4078. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4079. {
  4080. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4081. {
  4082. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4083. DebugAssert(Index == 0);
  4084. PermanentFileList->Delete(Index);
  4085. Index--;
  4086. }
  4087. }
  4088. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4089. TQueueItem * QueueItem = new TDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4090. AddQueueItem(Queue, QueueItem, Terminal);
  4091. ClearOperationSelection(osRemote);
  4092. }
  4093. }
  4094. }
  4095. else
  4096. {
  4097. if (IsLocalBrowserMode())
  4098. {
  4099. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4100. }
  4101. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  4102. try
  4103. {
  4104. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  4105. }
  4106. __finally
  4107. {
  4108. ReloadLocalDirectory();
  4109. }
  4110. }
  4111. FAlternativeDelete = false;
  4112. }
  4113. catch(...)
  4114. {
  4115. FAlternativeDelete = false;
  4116. DView->DiscardSavedSelection();
  4117. throw;
  4118. }
  4119. DView->RestoreSelection();
  4120. }
  4121. //---------------------------------------------------------------------------
  4122. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4123. {
  4124. DebugAssert(Terminal);
  4125. DebugAssert(!IsLocalBrowserMode());
  4126. RemoteDirView->SaveSelection();
  4127. RemoteDirView->SaveSelectedNames();
  4128. try
  4129. {
  4130. if (Lock)
  4131. {
  4132. Terminal->LockFiles(FileList);
  4133. }
  4134. else
  4135. {
  4136. Terminal->UnlockFiles(FileList);
  4137. }
  4138. }
  4139. catch(...)
  4140. {
  4141. RemoteDirView->DiscardSavedSelection();
  4142. throw;
  4143. }
  4144. RemoteDirView->RestoreSelection();
  4145. }
  4146. //---------------------------------------------------------------------------
  4147. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4148. {
  4149. bool Result = false;
  4150. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4151. if (IsActiveTerminal(ATerminal))
  4152. {
  4153. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(Directory));
  4154. Result = File && File->IsDirectory;
  4155. }
  4156. return Result;
  4157. }
  4158. //---------------------------------------------------------------------------
  4159. bool TCustomScpExplorerForm::NeedSecondarySessionForRemoteCopy(TStrings * FileList)
  4160. {
  4161. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4162. return
  4163. !Terminal->IsCapable[fcRemoteCopy] ||
  4164. (CopyDirsOnSecondarySession && TRemoteFileList::AnyDirectory(FileList));
  4165. }
  4166. //---------------------------------------------------------------------------
  4167. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4168. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4169. bool NoConfirmation, bool Move)
  4170. {
  4171. DebugAssert(Terminal != NULL);
  4172. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4173. DebugAssert(!IsLocalBrowserMode());
  4174. if (Session == NULL)
  4175. {
  4176. Session = Terminal;
  4177. }
  4178. bool TargetConfirmed = false;
  4179. if (Session == Terminal)
  4180. {
  4181. if (RemoteDriveView->DropTarget != NULL)
  4182. {
  4183. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4184. TargetConfirmed = true;
  4185. }
  4186. else if (RemoteDirView->DropTarget != NULL)
  4187. {
  4188. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4189. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4190. TargetConfirmed = true;
  4191. }
  4192. else
  4193. {
  4194. Target = RemoteDirView->Path;
  4195. }
  4196. }
  4197. else
  4198. {
  4199. Target = GetSessionPath(Session, osRemote);
  4200. }
  4201. Target = UnixIncludeTrailingBackslash(Target);
  4202. if (FileList->Count == 1)
  4203. {
  4204. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4205. }
  4206. else
  4207. {
  4208. FileMask = AnyMask;
  4209. }
  4210. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4211. bool Result = true;
  4212. if (!NoConfirmation)
  4213. {
  4214. bool Multi = (FileList->Count > 1);
  4215. if (Move)
  4216. {
  4217. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4218. }
  4219. else
  4220. {
  4221. std::unique_ptr<TStrings> Sessions(new TStringList);
  4222. std::unique_ptr<TStrings> Directories(new TStringList);
  4223. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4224. for (int Index = 0; Index < SessionList->Count; Index++)
  4225. {
  4226. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4227. if (IsActiveTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4228. {
  4229. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4230. Directories->Add(GetSessionPath(ASession, osRemote));
  4231. }
  4232. }
  4233. bool AnyDirectory = false;
  4234. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4235. if (CopyDirsOnSecondarySession && !Terminal->CommandSessionOpened) // optimization
  4236. {
  4237. for (int Index = 0; !AnyDirectory && (Index < FileList->Count); Index++)
  4238. {
  4239. AnyDirectory = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]))->IsDirectory;
  4240. }
  4241. }
  4242. TDirectRemoteCopy AllowDirectCopy;
  4243. if (Terminal->CommandSessionOpened || !NeedSecondarySessionForRemoteCopy(FileList))
  4244. {
  4245. DebugAssert(DirectCopy);
  4246. AllowDirectCopy = drcAllow;
  4247. }
  4248. else if (Terminal->IsCapable[fcSecondaryShell])
  4249. {
  4250. DebugAssert(DirectCopy);
  4251. AllowDirectCopy = Terminal->IsCapable[fcRemoteCopy] ? drcConfirmCommandSessionDirs : drcConfirmCommandSession;
  4252. }
  4253. else
  4254. {
  4255. DebugAssert(!DirectCopy);
  4256. AllowDirectCopy = drcDisallow;
  4257. }
  4258. void * ASession = Session;
  4259. Result = DoRemoteCopyDialog(
  4260. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4261. DoDirectoryExists, TargetConfirmed);
  4262. Session = static_cast<TManagedTerminal *>(ASession);
  4263. }
  4264. }
  4265. return Result;
  4266. }
  4267. //---------------------------------------------------------------------------
  4268. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4269. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4270. {
  4271. DebugAssert(!IsLocalBrowserMode());
  4272. bool DirectCopy;
  4273. UnicodeString Target, FileMask;
  4274. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4275. if (Result)
  4276. {
  4277. if (!Move && !DirectCopy)
  4278. {
  4279. Configuration->Usage->Inc("RemoteCopyTemp");
  4280. UnicodeString RootTempDir;
  4281. UnicodeString TempDir;
  4282. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  4283. TStrings * TemporaryFilesList = new TStringList();
  4284. try
  4285. {
  4286. TMakeLocalFileListParams MakeFileListParam;
  4287. MakeFileListParam.FileList = TemporaryFilesList;
  4288. MakeFileListParam.FileTimes = NULL;
  4289. MakeFileListParam.IncludeDirs = true;
  4290. MakeFileListParam.Recursive = false;
  4291. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4292. TTerminalManager::Instance()->ActiveSession = Session;
  4293. if (TemporaryFilesList->Count > 0)
  4294. {
  4295. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4296. CopyParam.FileMask = FileMask;
  4297. DebugAssert(!FAutoOperation);
  4298. FAutoOperation = true;
  4299. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4300. }
  4301. }
  4302. __finally
  4303. {
  4304. delete TemporaryFilesList;
  4305. FAutoOperation = false;
  4306. if (!RootTempDir.IsEmpty())
  4307. {
  4308. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4309. }
  4310. }
  4311. }
  4312. else
  4313. {
  4314. RemoteDirView->SaveSelection();
  4315. RemoteDirView->SaveSelectedNames();
  4316. try
  4317. {
  4318. if (Move)
  4319. {
  4320. Configuration->Usage->Inc("RemoteMove");
  4321. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4322. }
  4323. else
  4324. {
  4325. Configuration->Usage->Inc("RemoteCopyDirect");
  4326. DebugAssert(DirectCopy);
  4327. DebugAssert(Session == Terminal);
  4328. if (!NeedSecondarySessionForRemoteCopy(FileList) ||
  4329. Terminal->CommandSessionOpened ||
  4330. CommandSessionFallback())
  4331. {
  4332. Terminal->CopyFiles(FileList, Target, FileMask, false);
  4333. }
  4334. }
  4335. }
  4336. catch(...)
  4337. {
  4338. RemoteDirView->DiscardSavedSelection();
  4339. throw;
  4340. }
  4341. RemoteDirView->RestoreSelection();
  4342. }
  4343. }
  4344. return Result;
  4345. }
  4346. //---------------------------------------------------------------------------
  4347. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4348. const UnicodeString & Path, TRemoteProperties & Properties)
  4349. {
  4350. DebugAssert(!IsLocalBrowserMode());
  4351. Properties.Valid = Properties.Valid << vpEncrypt;
  4352. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4353. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4354. }
  4355. //---------------------------------------------------------------------------
  4356. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4357. {
  4358. Side = GetSide(Side);
  4359. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4360. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4361. UnicodeString Name = LoadStr(NEW_FOLDER);
  4362. int AllowedChanges =
  4363. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4364. bool SaveSettings = false;
  4365. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4366. {
  4367. TWindowLock Lock(this);
  4368. if (!IsSideLocalBrowser(Side))
  4369. {
  4370. if (SaveSettings)
  4371. {
  4372. GUIConfiguration->NewDirectoryProperties = Properties;
  4373. }
  4374. CreateRemoteDirectory(Name, Properties);
  4375. }
  4376. else
  4377. {
  4378. DirView(Side)->CreateDirectory(Name);
  4379. }
  4380. }
  4381. }
  4382. //---------------------------------------------------------------------------
  4383. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4384. {
  4385. TWindowLock Lock(this);
  4386. DirView(Side)->ExecuteHomeDirectory();
  4387. }
  4388. //---------------------------------------------------------------------------
  4389. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4390. {
  4391. DoOpenDirectoryDialog(odBrowse, Side);
  4392. }
  4393. //---------------------------------------------------------------------------
  4394. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4395. {
  4396. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4397. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4398. bool Result = !Path.IsEmpty();
  4399. if (Result)
  4400. {
  4401. TryOpenDirectory(Side, Path);
  4402. }
  4403. return Result;
  4404. }
  4405. //---------------------------------------------------------------------------
  4406. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4407. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4408. bool & Close)
  4409. {
  4410. // terminal can be already closed (e.g. dropped connection)
  4411. if (Terminal != NULL)
  4412. {
  4413. try
  4414. {
  4415. TCalculateSizeParams Params;
  4416. Params.Stats = &Stats;
  4417. Terminal->CalculateFilesSize(FileList, Size, Params);
  4418. }
  4419. catch(...)
  4420. {
  4421. if (!Terminal->Active)
  4422. {
  4423. Close = true;
  4424. }
  4425. throw;
  4426. }
  4427. }
  4428. }
  4429. //---------------------------------------------------------------------------
  4430. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4431. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4432. bool & Close)
  4433. {
  4434. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4435. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4436. {
  4437. Configuration->Usage->Inc(L"ChecksumCalculated");
  4438. try
  4439. {
  4440. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4441. }
  4442. catch(...)
  4443. {
  4444. if (!Terminal->Active)
  4445. {
  4446. Close = true;
  4447. }
  4448. throw;
  4449. }
  4450. }
  4451. }
  4452. //---------------------------------------------------------------------------
  4453. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4454. {
  4455. if (Terminal->LoadFilesProperties(FileList))
  4456. {
  4457. RemoteDirView->Invalidate();
  4458. }
  4459. }
  4460. //---------------------------------------------------------------------------
  4461. bool TCustomScpExplorerForm::CanCalculateChecksum()
  4462. {
  4463. return
  4464. Terminal->IsCapable[fcCalculatingChecksum] ||
  4465. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles());
  4466. }
  4467. //---------------------------------------------------------------------------
  4468. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4469. {
  4470. bool Result;
  4471. if (!IsSideLocalBrowser(Side))
  4472. {
  4473. TRemoteTokenList * GroupList = NULL;
  4474. TRemoteTokenList * UserList = NULL;
  4475. try
  4476. {
  4477. TRemoteProperties CurrentProperties;
  4478. LoadFilesProperties(FileList);
  4479. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4480. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4481. if (CapableGroupChanging || CapableOwnerChanging)
  4482. {
  4483. if (CapableGroupChanging)
  4484. {
  4485. GroupList = Terminal->Groups->Duplicate();
  4486. }
  4487. if (CapableOwnerChanging)
  4488. {
  4489. UserList = Terminal->Users->Duplicate();
  4490. }
  4491. TRemoteDirectory * Files = Terminal->Files;
  4492. int Count = Files->Count;
  4493. if (Count > 100)
  4494. {
  4495. Count = 100;
  4496. }
  4497. for (int Index = 0; Index < Count; Index++)
  4498. {
  4499. TRemoteFile * File = Files->Files[Index];
  4500. if (CapableGroupChanging)
  4501. {
  4502. GroupList->AddUnique(File->Group);
  4503. }
  4504. if (CapableOwnerChanging)
  4505. {
  4506. UserList->AddUnique(File->Owner);
  4507. }
  4508. }
  4509. // if we haven't collected tokens for all files in current directory,
  4510. // make sure we collect them at least for all selected files.
  4511. // (note that so far the files in FileList has to be from current direcotry)
  4512. if (Count < Files->Count)
  4513. {
  4514. for (int Index = 0; Index < FileList->Count; Index++)
  4515. {
  4516. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4517. if (CapableGroupChanging)
  4518. {
  4519. GroupList->AddUnique(File->Group);
  4520. }
  4521. if (CapableOwnerChanging)
  4522. {
  4523. UserList->AddUnique(File->Owner);
  4524. }
  4525. }
  4526. }
  4527. }
  4528. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4529. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4530. if (CapableAclChanging && TRemoteFileList::AnyDirectory(FileList))
  4531. {
  4532. CapableAclChanging = false;
  4533. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4534. }
  4535. int Flags = 0;
  4536. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4537. if (CapableAclChanging) Flags |= cpAcl;
  4538. if (CapableOwnerChanging) Flags |= cpOwner;
  4539. if (CapableGroupChanging) Flags |= cpGroup;
  4540. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4541. if (CanCalculateChecksum())
  4542. {
  4543. CalculateChecksumEvent = CalculateChecksum;
  4544. }
  4545. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4546. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4547. TRemoteProperties NewProperties = CurrentProperties;
  4548. Result =
  4549. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4550. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4551. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4552. CalculateSize, CalculateChecksumEvent);
  4553. if (Result)
  4554. {
  4555. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4556. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4557. }
  4558. }
  4559. __finally
  4560. {
  4561. delete GroupList;
  4562. delete UserList;
  4563. }
  4564. }
  4565. else
  4566. {
  4567. DirView(Side)->DisplayPropertiesMenu();
  4568. Result = true;
  4569. }
  4570. return Result;
  4571. }
  4572. //---------------------------------------------------------------------------
  4573. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4574. {
  4575. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4576. {
  4577. FIgnoreNextDialogChar = Key;
  4578. }
  4579. Key = 0;
  4580. }
  4581. //---------------------------------------------------------------------------
  4582. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4583. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4584. {
  4585. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4586. if (Command != NULL)
  4587. {
  4588. KeyProcessed(Key, Shift);
  4589. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4590. {
  4591. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4592. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4593. false, false, const_cast<TCustomCommandType *>(Command));
  4594. }
  4595. }
  4596. }
  4597. //---------------------------------------------------------------------------
  4598. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4599. {
  4600. if (!NonVisualDataModule->Busy)
  4601. {
  4602. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4603. {
  4604. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4605. }
  4606. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4607. {
  4608. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4609. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4610. {
  4611. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4612. // But so far it's not a problem, as it does what we want.
  4613. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4614. if (((Action->ShortCut == KeyShortCut) ||
  4615. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4616. AllowedAction(Action, aaShortCut))
  4617. {
  4618. // Has to be called before the action as the dialog char is already in queue.
  4619. // So when the action consumes message queue, we already need to have the
  4620. // FIgnoreNextDialogChar set
  4621. KeyProcessed(Key, Shift);
  4622. // Reset reference to previous component (when menu/toolbar was clicked).
  4623. // Needed to detect that action was invoked by keyboard shortcut
  4624. // in TNonVisualDataModule::ExplorerActionsExecute
  4625. Action->ActionComponent = NULL;
  4626. Action->Execute();
  4627. return;
  4628. }
  4629. }
  4630. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4631. {
  4632. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4633. {
  4634. KeyProcessed(Key, Shift);
  4635. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4636. return;
  4637. }
  4638. }
  4639. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4640. {
  4641. KeyProcessed(Key, Shift);
  4642. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4643. }
  4644. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4645. if (IsCustomShortCut(CustomShortCut))
  4646. {
  4647. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4648. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4649. if (WinConfiguration->SharedBookmarks != NULL)
  4650. {
  4651. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4652. if ((Bookmark != NULL) &&
  4653. OpenBookmark(FCurrentSide, Bookmark))
  4654. {
  4655. KeyProcessed(Key, Shift);
  4656. }
  4657. }
  4658. }
  4659. }
  4660. }
  4661. TForm::KeyDown(Key, Shift);
  4662. }
  4663. //---------------------------------------------------------------------------
  4664. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4665. {
  4666. bool OpenedTerminal = false;
  4667. UnicodeString ProtocolName;
  4668. UnicodeString ProtocolNameHint;
  4669. UnicodeString SecurityProtocolName;
  4670. UnicodeString DurationHint;
  4671. // See the comment in TScpCommanderForm::UpdateControls()
  4672. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4673. if (ActiveTerminal != NULL)
  4674. {
  4675. // Active is not enough here
  4676. if (ActiveTerminal->Status == ssOpened)
  4677. {
  4678. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4679. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4680. if (FileSystemInfo.ProtocolName.IsEmpty())
  4681. {
  4682. ProtocolName = SessionInfo.ProtocolName;
  4683. }
  4684. else
  4685. {
  4686. ProtocolName = FileSystemInfo.ProtocolName;
  4687. }
  4688. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4689. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4690. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4691. OpenedTerminal = true;
  4692. }
  4693. else if (ActiveTerminal->Status > ssClosed)
  4694. {
  4695. ProtocolName = LoadStr(STATUS_CONNECTING);
  4696. }
  4697. else
  4698. {
  4699. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4700. }
  4701. }
  4702. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4703. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4704. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4705. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4706. if (ProtocolStatusPanel->Caption != ProtocolName)
  4707. {
  4708. ProtocolStatusPanel->Caption = ProtocolName;
  4709. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4710. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4711. }
  4712. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4713. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4714. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4715. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4716. SecurityStatusPanel->Enabled = SecurityEnabled;
  4717. UnicodeString SecurityProtocolHint;
  4718. if (SecurityEnabled)
  4719. {
  4720. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4721. }
  4722. else
  4723. {
  4724. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4725. }
  4726. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4727. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4728. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4729. DurationStatusPanel->Hint = DurationHint;
  4730. UpdateStatusBar();
  4731. }
  4732. //---------------------------------------------------------------------------
  4733. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4734. {
  4735. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4736. DebugAssert(SessionStatusBar != NULL);
  4737. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4738. if (!FNote.IsEmpty())
  4739. {
  4740. NoteStatusPanel->Caption = FNote;
  4741. }
  4742. else
  4743. {
  4744. UpdateStatusPanelText(NoteStatusPanel);
  4745. }
  4746. NoteStatusPanel->Hint = FNoteHints;
  4747. UnicodeString LoginTime;
  4748. // See the comment in TScpCommanderForm::UpdateControls()
  4749. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4750. // Active is not enough here
  4751. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4752. {
  4753. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4754. LoginTime = FormatDateTimeSpan(Now() - SessionInfo.LoginTime);
  4755. }
  4756. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4757. DurationStatusPanel->Caption = LoginTime;
  4758. }
  4759. //---------------------------------------------------------------------------
  4760. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4761. {
  4762. Panel->Caption = L"";
  4763. }
  4764. //---------------------------------------------------------------------------
  4765. void __fastcall TCustomScpExplorerForm::Idle()
  4766. {
  4767. if (FShowing ||
  4768. // Particularly for
  4769. // - Standalone editing
  4770. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4771. // while "keeping remote directory up to date".
  4772. StandaloneOperation)
  4773. {
  4774. FEditorManager->Check();
  4775. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4776. // that needs to know if queue view is visible (and it may be closed after queue update)
  4777. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4778. }
  4779. if (FShowing)
  4780. {
  4781. if (!NonVisualDataModule->Busy &&
  4782. // Menu is opened or drag&drop is going on
  4783. (Mouse->Capture == NULL))
  4784. {
  4785. if (FRefreshRemoteDirectory)
  4786. {
  4787. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4788. {
  4789. Terminal->RefreshDirectory();
  4790. }
  4791. FRefreshRemoteDirectory = false;
  4792. }
  4793. if (FRefreshLocalDirectory)
  4794. {
  4795. ReloadLocalDirectory();
  4796. FRefreshLocalDirectory = false;
  4797. }
  4798. if (WinConfiguration->RefreshRemotePanel)
  4799. {
  4800. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4801. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4802. {
  4803. RemoteDirView->ReloadDirectory();
  4804. }
  4805. }
  4806. }
  4807. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4808. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4809. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4810. // And the Alt key can be released even when other window or application is active, so handling the key up in explorer window won't do either.
  4811. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4812. MenuToolbar->Idle();
  4813. }
  4814. if (FShowing || StandaloneOperation)
  4815. {
  4816. if (FQueueStatusInvalidated)
  4817. {
  4818. UpdateQueueStatus(false);
  4819. }
  4820. RefreshQueueItems();
  4821. }
  4822. if (FShowing)
  4823. {
  4824. UpdateStatusBar();
  4825. }
  4826. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4827. {
  4828. FClipboardFakeMonitorsPendingReset = false;
  4829. FClipboardFakeMonitors.reset(NULL);
  4830. }
  4831. FIgnoreNextDialogChar = 0;
  4832. }
  4833. //---------------------------------------------------------------------------
  4834. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4835. {
  4836. try
  4837. {
  4838. FUserActionTimer->Enabled = false;
  4839. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4840. {
  4841. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4842. {
  4843. FPendingQueueActionItem->ProcessUserAction();
  4844. }
  4845. }
  4846. }
  4847. __finally
  4848. {
  4849. FPendingQueueActionItem = NULL;
  4850. }
  4851. }
  4852. //---------------------------------------------------------------------------
  4853. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4854. {
  4855. if (WinConfiguration->MinimizeToTray)
  4856. {
  4857. UpdateTrayIcon();
  4858. FTrayIcon->Visible = true;
  4859. if (Visible)
  4860. {
  4861. ShowWindow(Handle, SW_HIDE);
  4862. }
  4863. }
  4864. }
  4865. //---------------------------------------------------------------------------
  4866. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4867. {
  4868. // WORKAROUND
  4869. // When restoring maximized window from minimization,
  4870. // rarely some controls do not align properly.
  4871. // Two instances seen (both for Commander):
  4872. // - When restoring, window is temporarily narrower (not maximized),
  4873. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4874. // Once maximized already, top dock shinks back, but the session PageControl,
  4875. // do not align up, leaving space between TopDock and PageControl.
  4876. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4877. for (int Index = 0; Index < ControlCount; Index++)
  4878. {
  4879. RealignControl(Controls[Index]);
  4880. }
  4881. if (FTrayIcon->Visible)
  4882. {
  4883. FTrayIcon->Visible = false;
  4884. if (Visible)
  4885. {
  4886. ShowWindow(Handle, SW_SHOW);
  4887. }
  4888. }
  4889. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4890. {
  4891. FNeedSession = false;
  4892. NonVisualDataModule->StartBusy();
  4893. try
  4894. {
  4895. NeedSession(true);
  4896. }
  4897. __finally
  4898. {
  4899. NonVisualDataModule->EndBusy();
  4900. }
  4901. }
  4902. }
  4903. //---------------------------------------------------------------------------
  4904. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4905. {
  4906. FTrayIcon->Hint = GetMainForm()->Caption;
  4907. }
  4908. //---------------------------------------------------------------------------
  4909. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4910. {
  4911. UpdateTrayIcon();
  4912. }
  4913. //---------------------------------------------------------------------------
  4914. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4915. {
  4916. // workaround
  4917. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4918. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4919. // But WM_ACTIVATEAPP message can be received even when
  4920. // the main window is minimized to the tray and internal editor window is focused
  4921. // (after another application was previously active)
  4922. if (::IsIconic(Handle))
  4923. {
  4924. if (!IsAppIconic())
  4925. {
  4926. SetAppIconic(true);
  4927. }
  4928. }
  4929. ::ApplicationRestore();
  4930. Application->BringToFront();
  4931. }
  4932. //---------------------------------------------------------------------------
  4933. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4934. {
  4935. RestoreApp();
  4936. }
  4937. //---------------------------------------------------------------------------
  4938. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4939. {
  4940. if (OpenInNewWindow())
  4941. {
  4942. ExecuteNewInstance(SessionUrl);
  4943. }
  4944. else
  4945. {
  4946. TTerminalManager::Instance()->NewSession(SessionUrl);
  4947. }
  4948. }
  4949. //---------------------------------------------------------------------------
  4950. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4951. {
  4952. NewSession();
  4953. }
  4954. //---------------------------------------------------------------------------
  4955. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4956. {
  4957. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4958. StoredSessions->NewSession(SessionName, SessionData);
  4959. // modified only, explicit
  4960. StoredSessions->Save(false, true);
  4961. // encode session name because of slashes in hierarchical sessions
  4962. return EncodeUrlString(SessionName);
  4963. }
  4964. //---------------------------------------------------------------------------
  4965. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4966. {
  4967. // current working directories become defaults here, what is not right
  4968. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4969. return SaveHiddenDuplicateSession(SessionData.get());
  4970. }
  4971. //---------------------------------------------------------------------------
  4972. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  4973. {
  4974. if (OpenInNewWindow())
  4975. {
  4976. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4977. }
  4978. else
  4979. {
  4980. // current working directories become defaults here, what is not right
  4981. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4982. TTerminalManager * Manager = TTerminalManager::Instance();
  4983. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  4984. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  4985. // We definitely want these
  4986. ASession->Disconnected = ManagedSession->Disconnected;
  4987. // Not sure about these two
  4988. ASession->Permanent = ManagedSession->Permanent;
  4989. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  4990. Manager->ActiveSession = ASession;
  4991. }
  4992. }
  4993. //---------------------------------------------------------------------------
  4994. void __fastcall TCustomScpExplorerForm::RenameTab()
  4995. {
  4996. UnicodeString Name = ManagedSession->SessionData->SessionName;
  4997. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  4998. // When submitting the default name, do not fix it
  4999. (Name != ManagedSession->SessionData->SessionName))
  5000. {
  5001. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  5002. TSessionData::ValidateName(Name);
  5003. // This is inconsistent with how color (for example) is handled.
  5004. ManagedSession->SessionData->Name = Name;
  5005. UpdateControls();
  5006. // Add/Remove distinguishing paths from sessions of the same name.
  5007. SessionListChanged();
  5008. }
  5009. }
  5010. //---------------------------------------------------------------------------
  5011. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  5012. {
  5013. DebugAssert(Queue != NULL);
  5014. bool Result = Queue->IsEmpty;
  5015. if (!Result)
  5016. {
  5017. SetFocus();
  5018. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  5019. }
  5020. return Result;
  5021. }
  5022. //---------------------------------------------------------------------------
  5023. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  5024. {
  5025. return CanCloseQueue(FQueue);
  5026. }
  5027. //---------------------------------------------------------------------------
  5028. void __fastcall TCustomScpExplorerForm::CloseTab()
  5029. {
  5030. if (CanCloseQueue())
  5031. {
  5032. TTerminalManager::Instance()->FreeActiveTerminal();
  5033. }
  5034. }
  5035. //---------------------------------------------------------------------------
  5036. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5037. {
  5038. if (CanCloseQueue())
  5039. {
  5040. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5041. }
  5042. }
  5043. //---------------------------------------------------------------------------
  5044. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5045. {
  5046. DetachTerminal(Terminal);
  5047. RemoteDirView->Terminal = Terminal;
  5048. UpdateRemotePathComboBox(false);
  5049. InitStatusBar();
  5050. UpdateControls();
  5051. }
  5052. //---------------------------------------------------------------------------
  5053. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5054. {
  5055. InitStatusBar();
  5056. }
  5057. //---------------------------------------------------------------------------
  5058. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5059. {
  5060. if (DebugAlwaysTrue(!Terminal->Active))
  5061. {
  5062. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5063. }
  5064. }
  5065. //---------------------------------------------------------------------------
  5066. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5067. {
  5068. if (OpenInNewWindow())
  5069. {
  5070. // encode session name because of slashes in hierarchical sessions
  5071. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5072. }
  5073. else
  5074. {
  5075. TTerminalManager * Manager = TTerminalManager::Instance();
  5076. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5077. Manager->ActiveSession = Terminal;
  5078. }
  5079. }
  5080. //---------------------------------------------------------------------------
  5081. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5082. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5083. {
  5084. TTerminalManager * Manager = TTerminalManager::Instance();
  5085. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5086. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5087. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5088. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5089. {
  5090. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5091. // FirstSession can be null, if none of the workspace sites exist anymore
  5092. // or if all workspace sessions are not suported by the interface
  5093. // (when trying to open all local-local workspace in "explorer" interface)
  5094. if (FirstSession != NULL)
  5095. {
  5096. if (!ConnectFirstTerminal)
  5097. {
  5098. FirstSession->Disconnected = true;
  5099. FirstSession->DisconnectedTemporarily = true;
  5100. }
  5101. Manager->ActiveSession = FirstSession;
  5102. }
  5103. }
  5104. }
  5105. //---------------------------------------------------------------------------
  5106. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5107. {
  5108. if (OpenInNewWindow())
  5109. {
  5110. ExecuteNewInstance(Name);
  5111. }
  5112. else
  5113. {
  5114. DoOpenFolderOrWorkspace(Name, true, false);
  5115. }
  5116. }
  5117. //---------------------------------------------------------------------------
  5118. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5119. bool &CanClose)
  5120. {
  5121. AppLog(L"Windows close query");
  5122. // See the comment in CloseApp()
  5123. if (NonVisualDataModule->Busy)
  5124. {
  5125. CanClose = false;
  5126. }
  5127. else
  5128. {
  5129. TTerminalManager * Manager = TTerminalManager::Instance();
  5130. int ActiveSessions = 0;
  5131. for (int Index = 0; Index < Manager->Count; Index++)
  5132. {
  5133. if (Manager->Sessions[Index]->Active)
  5134. {
  5135. ActiveSessions++;
  5136. }
  5137. }
  5138. // Confirm, when there's at least one active remote session or
  5139. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5140. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5141. WinConfiguration->ConfirmClosingSession)
  5142. {
  5143. unsigned int Result;
  5144. TMessageParams Params(mpNeverAskAgainCheck);
  5145. UnicodeString Message;
  5146. int Answers = qaOK | qaCancel;
  5147. // The current session is the only active session
  5148. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5149. {
  5150. if (!WinConfiguration->AutoSaveWorkspace)
  5151. {
  5152. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5153. }
  5154. else
  5155. {
  5156. Message = LoadStr(CLOSE_SESSION);
  5157. }
  5158. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5159. }
  5160. // Multiple active sessions or one active session, but it's not the current one
  5161. else if (ActiveSessions > 0)
  5162. {
  5163. if (!WinConfiguration->AutoSaveWorkspace)
  5164. {
  5165. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5166. }
  5167. else
  5168. {
  5169. Message = LoadStr(CLOSE_SESSIONS);
  5170. }
  5171. }
  5172. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5173. else
  5174. {
  5175. DebugAlwaysTrue(Manager->Count > 1);
  5176. DebugAlwaysTrue(!WinConfiguration->AutoSaveWorkspace);
  5177. Message = LoadStr(CLOSE_WORKSPACE);
  5178. }
  5179. UnicodeString Note;
  5180. if (WinConfiguration->AutoSaveWorkspace)
  5181. {
  5182. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5183. }
  5184. else
  5185. {
  5186. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5187. Answers = qaYes | qaNo | qaCancel;
  5188. }
  5189. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5190. SetFocus();
  5191. Result = MessageDialog(Message, qtConfirmation,
  5192. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5193. if (Result == qaNeverAskAgain)
  5194. {
  5195. WinConfiguration->ConfirmClosingSession = false;
  5196. }
  5197. if (Result == qaNo)
  5198. {
  5199. CanClose = SaveWorkspace(true);
  5200. // note that the workspace will be saved redundatly again from FormClose
  5201. }
  5202. else
  5203. {
  5204. CanClose =
  5205. (Result == qaOK) ||
  5206. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5207. (Result == qaNeverAskAgain);
  5208. }
  5209. }
  5210. if (CanClose && HasActiveTerminal())
  5211. {
  5212. CanClose = CanCloseQueue();
  5213. }
  5214. }
  5215. if (CanClose)
  5216. {
  5217. CanClose =
  5218. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5219. FEditorManager->CloseExternalFilesWithoutProcess();
  5220. if (CanClose)
  5221. {
  5222. while (CanClose && (FLocalEditors->Count > 0))
  5223. {
  5224. int PrevCount = FLocalEditors->Count;
  5225. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5226. CanClose = (FLocalEditors->Count < PrevCount);
  5227. }
  5228. if (CanClose)
  5229. {
  5230. CanClose = FEditorManager->Empty(true);
  5231. if (!CanClose)
  5232. {
  5233. SetFocus();
  5234. CanClose =
  5235. (MessageDialog(
  5236. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5237. }
  5238. }
  5239. }
  5240. }
  5241. }
  5242. //---------------------------------------------------------------------------
  5243. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5244. {
  5245. TForm * Form = dynamic_cast<TForm *>(Sender);
  5246. DebugAssert(Form != NULL);
  5247. Form->Close();
  5248. }
  5249. //---------------------------------------------------------------------------
  5250. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5251. {
  5252. TForm * Form = dynamic_cast<TForm *>(Sender);
  5253. delete Form;
  5254. }
  5255. //---------------------------------------------------------------------------
  5256. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5257. {
  5258. while (FLocalEditors->Count > 0)
  5259. {
  5260. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5261. }
  5262. }
  5263. //---------------------------------------------------------------------------
  5264. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5265. TObject *Sender)
  5266. {
  5267. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5268. try
  5269. {
  5270. SetProperties(osRemote, FileList);
  5271. }
  5272. __finally
  5273. {
  5274. delete FileList;
  5275. }
  5276. }
  5277. //---------------------------------------------------------------------------
  5278. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5279. {
  5280. if (value)
  5281. {
  5282. if (Component == fcCustomCommandsBand)
  5283. {
  5284. UpdateCustomCommandsToolbar();
  5285. }
  5286. if (Component == fcQueueFileList)
  5287. {
  5288. DebugAssert(!QueueFileListSplitter->Visible);
  5289. AdjustQueueLayout();
  5290. UpdateQueueFileList();
  5291. }
  5292. }
  5293. }
  5294. //---------------------------------------------------------------------------
  5295. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5296. {
  5297. int MinHeightLimit =
  5298. GetStaticQueuePanelComponentsHeight() +
  5299. QueueFileListSplitter->Height +
  5300. QueueFileList->Height +
  5301. GetMinQueueViewHeight();
  5302. if (QueuePanel->ClientHeight < MinHeightLimit)
  5303. {
  5304. QueuePanel->ClientHeight = MinHeightLimit;
  5305. }
  5306. }
  5307. //---------------------------------------------------------------------------
  5308. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5309. {
  5310. TControl * Control = GetComponent(Component);
  5311. DebugAssert(Control);
  5312. bool Changed = (Control->Visible != value);
  5313. if (Changed)
  5314. {
  5315. ComponentShowing(Component, value);
  5316. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5317. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5318. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5319. if (value)
  5320. {
  5321. int RemainingHeight = Control->Parent->ClientHeight;
  5322. int RemainingWidth = Control->Parent->ClientWidth;
  5323. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5324. {
  5325. TControl * ChildControl = Control->Parent->Controls[i];
  5326. if (ChildControl->Visible)
  5327. {
  5328. switch (ChildControl->Align)
  5329. {
  5330. case alTop:
  5331. case alBottom:
  5332. RemainingHeight -= ChildControl->Height;
  5333. break;
  5334. case alLeft:
  5335. case alRight:
  5336. RemainingWidth -= ChildControl->Width;
  5337. break;
  5338. }
  5339. }
  5340. }
  5341. int Reserve = ScaleByTextHeight(this, 32);
  5342. // queue in explorer, trees in commander
  5343. if (Control->Height > RemainingHeight - Reserve)
  5344. {
  5345. Control->Height = RemainingHeight / 2;
  5346. }
  5347. if (Control->Width > RemainingWidth - Reserve)
  5348. {
  5349. Control->Width = RemainingWidth / 2;
  5350. }
  5351. }
  5352. Control->Visible = value;
  5353. if (WasFocused && Visible)
  5354. {
  5355. DirView(osCurrent)->SetFocus();
  5356. }
  5357. FixControlsPlacement();
  5358. }
  5359. }
  5360. //---------------------------------------------------------------------------
  5361. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5362. {
  5363. TControl * Control = GetComponent(Component);
  5364. if (Control == NULL)
  5365. {
  5366. return false;
  5367. }
  5368. else
  5369. {
  5370. return Control->Visible;
  5371. }
  5372. }
  5373. //---------------------------------------------------------------------------
  5374. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5375. {
  5376. bool Result;
  5377. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5378. {
  5379. Result = !IsUWP();
  5380. }
  5381. else
  5382. {
  5383. Result = true;
  5384. }
  5385. return Result;
  5386. }
  5387. //---------------------------------------------------------------------------
  5388. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5389. {
  5390. if (DirView->ItemFocused != NULL)
  5391. {
  5392. DirView->ItemFocused->MakeVisible(false);
  5393. }
  5394. }
  5395. //---------------------------------------------------------------------------
  5396. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5397. {
  5398. MakeFocusedItemVisible(RemoteDirView);
  5399. QueueSplitter->Visible = QueuePanel->Visible;
  5400. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5401. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5402. TControl * TopControlsOrder[] =
  5403. { TopDock, MessageDock, SessionsPageControl };
  5404. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5405. TControl * QueueControlsOrder[] =
  5406. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5407. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5408. }
  5409. //---------------------------------------------------------------------------
  5410. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5411. {
  5412. switch (Component) {
  5413. case fcStatusBar: return RemoteStatusBar;
  5414. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5415. case fcQueueView: return QueuePanel;
  5416. case fcQueueToolbar: return QueueDock;
  5417. case fcRemoteTree: return RemoteDrivePanel;
  5418. case fcSessionsTabs: return SessionsPageControl;
  5419. case fcQueueFileList: return QueueFileList;
  5420. default: return NULL;
  5421. }
  5422. }
  5423. //---------------------------------------------------------------------------
  5424. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5425. TObject *Sender, TListColumn *Column, TPoint &Point)
  5426. {
  5427. DebugAssert(NonVisualDataModule && Column && Sender);
  5428. NonVisualDataModule->ListColumn = Column;
  5429. TPopupMenu * DirViewColumnMenu;
  5430. if (Sender == DirView(osOther))
  5431. {
  5432. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5433. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5434. bool SizeColumn = (Column->Index == uvSize);
  5435. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5436. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5437. }
  5438. else
  5439. {
  5440. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5441. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5442. bool SizeColumn = (Column->Index == dvSize);
  5443. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5444. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5445. }
  5446. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5447. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5448. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5449. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5450. }
  5451. //---------------------------------------------------------------------------
  5452. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5453. TObject *Sender, TListItem *Item, bool &AllowExec)
  5454. {
  5455. DoDirViewExecFile(Sender, Item, AllowExec);
  5456. }
  5457. //---------------------------------------------------------------------------
  5458. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5459. TListItem * Item, bool & AllowExec)
  5460. {
  5461. DebugAssert(Sender && Item && Configuration);
  5462. DebugAssert(AllowExec);
  5463. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5464. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5465. bool Remote = !IsSideLocalBrowser(Side);
  5466. DebugAssert(Item == ADirView->ItemFocused);
  5467. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5468. TResolvedDoubleClickAction Action;
  5469. if (FForceExecution)
  5470. {
  5471. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5472. }
  5473. else
  5474. {
  5475. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5476. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5477. }
  5478. if (Action == rdcaCopy)
  5479. {
  5480. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5481. UnlockWindow();
  5482. try
  5483. {
  5484. if (IsLocalBrowserMode())
  5485. {
  5486. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5487. }
  5488. else
  5489. {
  5490. if (HasActiveTerminal())
  5491. {
  5492. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5493. }
  5494. }
  5495. }
  5496. __finally
  5497. {
  5498. LockWindow();
  5499. }
  5500. AllowExec = false;
  5501. }
  5502. else if (Action == rdcaEdit)
  5503. {
  5504. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5505. {
  5506. ExecuteFile(Side, efDefaultEditor);
  5507. AllowExec = false;
  5508. }
  5509. }
  5510. else if (Action == rdcaOpen)
  5511. {
  5512. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5513. {
  5514. ExecuteFile(osRemote, efShell);
  5515. AllowExec = false;
  5516. }
  5517. }
  5518. }
  5519. //---------------------------------------------------------------------------
  5520. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5521. {
  5522. return ((Side == osRemote) || (Side == osCurrent));
  5523. }
  5524. //---------------------------------------------------------------------------
  5525. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5526. {
  5527. DebugFail();
  5528. }
  5529. //---------------------------------------------------------------------------
  5530. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5531. {
  5532. DebugFail();
  5533. }
  5534. //---------------------------------------------------------------------------
  5535. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5536. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5537. {
  5538. TSynchronizeParamType Params;
  5539. Params.LocalDirectory = LocalDirectory;
  5540. Params.RemoteDirectory = RemoteDirectory;
  5541. int UnusedParams =
  5542. (GUIConfiguration->SynchronizeParams &
  5543. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5544. TTerminal::spCaseSensitive | TTerminal::spMirror | TTerminal::spByChecksum));
  5545. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5546. Params.Options = GUIConfiguration->SynchronizeOptions;
  5547. bool SaveSettings = false;
  5548. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5549. &DoSynchronizeTooManyDirectories);
  5550. DebugAssert(FSynchronizeController == NULL);
  5551. FSynchronizeController = &Controller;
  5552. bool Result;
  5553. try
  5554. {
  5555. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5556. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5557. int Options =
  5558. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5559. DebugAssert(FOnFeedSynchronizeError == NULL);
  5560. DebugAssert(FOnSynchronizeAbort == NULL);
  5561. DebugAssert(FSynchronizeTerminal == NULL);
  5562. FSynchronizeTerminal = Terminal;
  5563. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5564. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5565. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5566. if (Result)
  5567. {
  5568. if (SaveSettings)
  5569. {
  5570. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5571. GUIConfiguration->SynchronizeOptions = Params.Options;
  5572. }
  5573. else
  5574. {
  5575. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5576. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5577. FLAGSET(Params.Options, soSynchronize))
  5578. {
  5579. GUIConfiguration->SynchronizeOptions =
  5580. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5581. soSynchronize;
  5582. }
  5583. }
  5584. LocalDirectory = Params.LocalDirectory;
  5585. RemoteDirectory = Params.RemoteDirectory;
  5586. }
  5587. }
  5588. __finally
  5589. {
  5590. FSynchronizeController = NULL;
  5591. DebugAssert(FOnFeedSynchronizeError == NULL);
  5592. FOnFeedSynchronizeError = NULL;
  5593. DebugAssert(FOnSynchronizeAbort == NULL);
  5594. FOnSynchronizeAbort = NULL;
  5595. FSynchronizeTerminal = NULL;
  5596. }
  5597. return Result;
  5598. }
  5599. //---------------------------------------------------------------------------
  5600. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5601. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5602. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5603. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5604. TSynchronizeOptions * Options, bool Full)
  5605. {
  5606. // Keep-up-to-date mode
  5607. if (Terminal->Status == ssOpened)
  5608. {
  5609. try
  5610. {
  5611. int PParams = Params.Params;
  5612. if (!Full)
  5613. {
  5614. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5615. if (FLAGSET(Params.Options, soRecurse))
  5616. {
  5617. PParams |= TTerminal::spSubDirs;
  5618. }
  5619. }
  5620. else
  5621. {
  5622. // if keepuptodate is non-recursive,
  5623. // full sync before has to be non-recursive as well
  5624. if (FLAGCLEAR(Params.Options, soRecurse))
  5625. {
  5626. PParams |= TTerminal::spNoRecurse;
  5627. }
  5628. }
  5629. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5630. PParams, Checklist, Options);
  5631. }
  5632. catch (Exception & E)
  5633. {
  5634. if (!Terminal->Active)
  5635. {
  5636. ShowExtendedExceptionEx(Terminal, &E);
  5637. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5638. if (!Terminal->Active)
  5639. {
  5640. throw;
  5641. }
  5642. }
  5643. else
  5644. {
  5645. if (FLAGSET(Params.Options, soContinueOnError) &&
  5646. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5647. {
  5648. // noop, already logged in MoreMessageDialog
  5649. }
  5650. else
  5651. {
  5652. // We get mostly EAbort here, so this is noop.
  5653. // Exception is an error when listing directories while looking for differences.
  5654. ShowExtendedExceptionEx(Terminal, &E);
  5655. throw;
  5656. }
  5657. }
  5658. }
  5659. }
  5660. }
  5661. //---------------------------------------------------------------------------
  5662. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5663. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5664. const UnicodeString ErrorStr)
  5665. {
  5666. if (!Directory.IsEmpty())
  5667. {
  5668. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5669. }
  5670. else
  5671. {
  5672. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5673. }
  5674. }
  5675. //---------------------------------------------------------------------------
  5676. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5677. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5678. {
  5679. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5680. {
  5681. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5682. }
  5683. else
  5684. {
  5685. TMessageParams Params(mpNeverAskAgainCheck);
  5686. unsigned int Result = MessageDialog(
  5687. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5688. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5689. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5690. {
  5691. MaxDirectories *= 2;
  5692. if (Result == qaNeverAskAgain)
  5693. {
  5694. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5695. }
  5696. }
  5697. else
  5698. {
  5699. Abort();
  5700. }
  5701. }
  5702. }
  5703. //---------------------------------------------------------------------------
  5704. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5705. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5706. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5707. TSynchronizeOptions * Options)
  5708. {
  5709. // Keep-up-to-date mode
  5710. DebugAssert(!FAutoOperation);
  5711. void * BatchStorage;
  5712. BatchStart(BatchStorage);
  5713. FAutoOperation = true;
  5714. bool AnyOperation = false;
  5715. TDateTime StartTime = Now();
  5716. TSynchronizeChecklist * AChecklist = NULL;
  5717. try
  5718. {
  5719. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, -1);
  5720. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5721. {
  5722. FSynchronizeProgressForm->Start();
  5723. }
  5724. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5725. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5726. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5727. Options);
  5728. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5729. SAFE_DESTROY(FSynchronizeProgressForm);
  5730. AnyOperation = (AChecklist->CheckedCount > 0);
  5731. if (AnyOperation)
  5732. {
  5733. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5734. CreateProgressForm(&SynchronizeProgress);
  5735. try
  5736. {
  5737. Terminal->SynchronizeApply(
  5738. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5739. SynchronizeProcessedItem, NULL, NULL, NULL);
  5740. }
  5741. __finally
  5742. {
  5743. DestroyProgressForm();
  5744. }
  5745. }
  5746. }
  5747. __finally
  5748. {
  5749. if (Checklist == NULL)
  5750. {
  5751. delete AChecklist;
  5752. }
  5753. else
  5754. {
  5755. *Checklist = AChecklist;
  5756. }
  5757. FAutoOperation = false;
  5758. SAFE_DESTROY(FSynchronizeProgressForm);
  5759. BatchEnd(BatchStorage);
  5760. ReloadLocalDirectory();
  5761. if (AnyOperation)
  5762. {
  5763. OperationComplete(StartTime);
  5764. }
  5765. }
  5766. }
  5767. //---------------------------------------------------------------------------
  5768. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5769. {
  5770. // can be called from command line
  5771. return Visible &&
  5772. ((DirView(osRemote)->SelCount > 0) ||
  5773. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5774. }
  5775. //---------------------------------------------------------------------------
  5776. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5777. {
  5778. LogSynchronizeEvent(Terminal, Message);
  5779. }
  5780. //---------------------------------------------------------------------------
  5781. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5782. int Params, TSynchronizeOptions & Options)
  5783. {
  5784. DebugAssert(!IsLocalBrowserMode());
  5785. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5786. {
  5787. Options.Filter = new TStringList();
  5788. Options.Filter->CaseSensitive = false;
  5789. Options.Filter->Duplicates = Types::dupAccept;
  5790. if (DirView(osRemote)->SelCount > 0)
  5791. {
  5792. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5793. }
  5794. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5795. {
  5796. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5797. }
  5798. Options.Filter->Sort();
  5799. }
  5800. }
  5801. //---------------------------------------------------------------------------
  5802. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5803. {
  5804. TCopyParamType Defaults;
  5805. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5806. ConfigStorage->AccessMode = smRead;
  5807. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5808. {
  5809. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5810. }
  5811. ConfigStorage.reset(NULL);
  5812. std::unique_ptr<TStringList> Options(new TStringList());
  5813. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5814. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5815. UnicodeString Result;
  5816. if (Options->Count > 0)
  5817. {
  5818. Result =
  5819. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5820. }
  5821. return Result;
  5822. }
  5823. //---------------------------------------------------------------------------
  5824. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5825. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5826. {
  5827. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5828. UnicodeString AdditionalParams =
  5829. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5830. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5831. SerializeCopyParamForCommandLine(CopyParams),
  5832. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5833. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5834. ExecuteNewInstance(SessionName, AdditionalParams);
  5835. }
  5836. //---------------------------------------------------------------------------
  5837. struct TSynchronizeParams
  5838. {
  5839. UnicodeString LocalDirectory;
  5840. UnicodeString RemoteDirectory;
  5841. TSynchronizeMode Mode;
  5842. TSynchronizeChecklist * Checklist;
  5843. int Params;
  5844. TCopyParamType * CopyParam;
  5845. TDateTime CollectElapsed;
  5846. TDateTime * StartTime;
  5847. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5848. };
  5849. //---------------------------------------------------------------------------
  5850. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5851. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5852. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5853. {
  5854. DebugAssert(!FAutoOperation);
  5855. void * BatchStorage;
  5856. BatchStart(BatchStorage);
  5857. FAutoOperation = true;
  5858. TFileOperationStatistics Statistics;
  5859. TDateTime Start = Now();
  5860. try
  5861. {
  5862. Params.OnProcessedItem = OnProcessedItem;
  5863. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5864. CreateProgressForm(&SynchronizeProgress);
  5865. Terminal->SynchronizeApply(
  5866. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5867. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5868. &Statistics);
  5869. }
  5870. __finally
  5871. {
  5872. Params.OnProcessedItem = NULL;
  5873. FAutoOperation = false;
  5874. DestroyProgressForm();
  5875. BatchEnd(BatchStorage);
  5876. ReloadLocalDirectory();
  5877. }
  5878. if (WinConfiguration->SynchronizeSummary)
  5879. {
  5880. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5881. // The statistics should be 0 anyway in this case
  5882. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5883. {
  5884. Message += L"\n";
  5885. if (Statistics.FilesUploaded > 0)
  5886. {
  5887. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5888. }
  5889. if (Statistics.FilesDownloaded > 0)
  5890. {
  5891. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5892. }
  5893. if (Statistics.FilesDeletedLocal > 0)
  5894. {
  5895. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5896. }
  5897. if (Statistics.FilesDeletedRemote > 0)
  5898. {
  5899. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5900. }
  5901. }
  5902. TDateTime Elapsed = (Now() - Start);
  5903. Message +=
  5904. L"\n" +
  5905. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Params.CollectElapsed))) + L"\n" +
  5906. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Elapsed)));
  5907. TMessageParams Params(mpNeverAskAgainCheck);
  5908. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5909. if (Result == qaNeverAskAgain)
  5910. {
  5911. WinConfiguration->SynchronizeSummary = false;
  5912. }
  5913. }
  5914. }
  5915. //---------------------------------------------------------------------------
  5916. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5917. {
  5918. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5919. {
  5920. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5921. }
  5922. // Not set in keep-up-to-date mode - Synchronize() method
  5923. if (Token != NULL)
  5924. {
  5925. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5926. if (Params.OnProcessedItem != NULL)
  5927. {
  5928. Params.OnProcessedItem(NULL, ChecklistItem);
  5929. }
  5930. }
  5931. }
  5932. //---------------------------------------------------------------------------
  5933. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5934. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5935. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5936. {
  5937. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5938. *Params.StartTime = Now();
  5939. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5940. }
  5941. //---------------------------------------------------------------------------
  5942. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5943. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5944. {
  5945. // terminal can be already closed (e.g. dropped connection)
  5946. if (Terminal != NULL)
  5947. {
  5948. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5949. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5950. }
  5951. }
  5952. //---------------------------------------------------------------------------
  5953. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5954. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5955. {
  5956. DebugAssert(!IsLocalBrowserMode());
  5957. TAutoBatch AutoBatch(this);
  5958. TAutoFlag AutoOperationFlag(FAutoOperation);
  5959. if (Side == osRemote)
  5960. {
  5961. std::unique_ptr<TStrings> FileList(new TStringList());
  5962. FileList->AddObject(FileName, RemoteFile);
  5963. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5964. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5965. RemoteDirView->SaveSelection();
  5966. RemoteDirView->SaveSelectedNames();
  5967. try
  5968. {
  5969. Terminal->MoveFiles(FileList.get(), Target, FileMask, false);
  5970. }
  5971. catch(...)
  5972. {
  5973. RemoteDirView->DiscardSavedSelection();
  5974. throw;
  5975. }
  5976. RemoteDirView->RestoreSelection();
  5977. }
  5978. else if (DebugAlwaysTrue(Side == osLocal))
  5979. {
  5980. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5981. {
  5982. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5983. }
  5984. UnicodeString Directory = ExtractFileDir(FileName);
  5985. ReloadLocalDirectory(Directory);
  5986. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5987. if (!SamePaths(Directory, NewDirectory))
  5988. {
  5989. ReloadLocalDirectory(NewDirectory);
  5990. }
  5991. }
  5992. }
  5993. //---------------------------------------------------------------------------
  5994. void __fastcall TCustomScpExplorerForm::DoSynchronizeBrowse(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  5995. {
  5996. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  5997. if (Side == osLocal)
  5998. {
  5999. if (Action == TSynchronizeChecklist::saDownloadNew)
  6000. {
  6001. OpenFolderInExplorer(LocalPath);
  6002. }
  6003. else
  6004. {
  6005. OpenFileInExplorer(CombinePaths(LocalPath, Item->GetFileName()));
  6006. }
  6007. }
  6008. else if (DebugAlwaysTrue(Side == osRemote))
  6009. {
  6010. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  6011. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  6012. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  6013. if (!LocalPath.IsEmpty())
  6014. {
  6015. SessionData->LocalDirectory = LocalPath;
  6016. }
  6017. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  6018. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(BROWSE_SWITCH), Item->GetFileName())));
  6019. }
  6020. }
  6021. //---------------------------------------------------------------------------
  6022. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  6023. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6024. const TCopyParamType * CopyParams)
  6025. {
  6026. UnicodeString SessionName = CreateHiddenDuplicateSession();
  6027. UnicodeString AdditionalParams =
  6028. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  6029. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  6030. SerializeCopyParamForCommandLine(CopyParams),
  6031. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  6032. LocalDirectory, RemoteDirectory, Mode, Params));
  6033. ExecuteNewInstance(SessionName, AdditionalParams);
  6034. }
  6035. //---------------------------------------------------------------------------
  6036. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  6037. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  6038. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  6039. {
  6040. int Result;
  6041. bool SaveSettings = false;
  6042. int Options =
  6043. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6044. FLAGMASK(!CanCalculateChecksum(), fsoDisableByChecksum) |
  6045. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  6046. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  6047. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  6048. bool Continue =
  6049. ((UseDefaults == 0) ||
  6050. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  6051. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults)) &&
  6052. (FLAGCLEAR(Params, TTerminal::spByChecksum) || EnsureCommandSessionFallback(fcCalculatingChecksum));
  6053. if (Continue)
  6054. {
  6055. Configuration->Usage->Inc(L"Synchronizations");
  6056. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  6057. UpdateCopyParamCounters(CopyParam);
  6058. TSynchronizeOptions SynchronizeOptions;
  6059. GetSynchronizeOptions(Params, SynchronizeOptions);
  6060. if (SaveSettings)
  6061. {
  6062. GUIConfiguration->SynchronizeParams = Params;
  6063. }
  6064. else
  6065. {
  6066. SaveMode = false;
  6067. }
  6068. TDateTime StartTime = Now();
  6069. TSynchronizeChecklist * Checklist = NULL;
  6070. try
  6071. {
  6072. DebugAssert(!FAutoOperation);
  6073. FAutoOperation = true;
  6074. try
  6075. {
  6076. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6077. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6078. int Files = -1;
  6079. if (DataList->Count >= 1)
  6080. {
  6081. Files = StrToIntDef(DataList->Strings[0], Files);
  6082. }
  6083. else
  6084. {
  6085. DataList->Add(UnicodeString());
  6086. }
  6087. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6088. FSynchronizeProgressForm->Start();
  6089. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6090. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6091. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6092. &SynchronizeOptions);
  6093. if (Terminal->SessionData->CacheDirectories)
  6094. {
  6095. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6096. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6097. }
  6098. }
  6099. __finally
  6100. {
  6101. FAutoOperation = false;
  6102. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6103. SAFE_DESTROY(FSynchronizeProgressForm);
  6104. }
  6105. TSynchronizeParams SynchronizeParams;
  6106. SynchronizeParams.LocalDirectory = LocalDirectory;
  6107. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  6108. SynchronizeParams.Mode = Mode;
  6109. SynchronizeParams.CopyParam = &CopyParam;
  6110. SynchronizeParams.Params = Params;
  6111. SynchronizeParams.Checklist = Checklist;
  6112. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6113. SynchronizeParams.StartTime = &StartTime;
  6114. SynchronizeParams.OnProcessedItem = NULL;
  6115. Result = Checklist->Count;
  6116. if (Checklist->Count > 0)
  6117. {
  6118. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6119. {
  6120. if (!DoSynchronizeChecklistDialog(
  6121. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6122. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeBrowse, &SynchronizeParams))
  6123. {
  6124. Result = -1;
  6125. }
  6126. }
  6127. else
  6128. {
  6129. FullSynchronize(SynchronizeParams, NULL, NULL);
  6130. }
  6131. }
  6132. else
  6133. {
  6134. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6135. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6136. }
  6137. }
  6138. __finally
  6139. {
  6140. delete Checklist;
  6141. }
  6142. OperationComplete(StartTime);
  6143. }
  6144. else
  6145. {
  6146. Result = -1;
  6147. }
  6148. return Result;
  6149. }
  6150. //---------------------------------------------------------------------------
  6151. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6152. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6153. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6154. {
  6155. if (Collect)
  6156. {
  6157. DebugAssert(FSynchronizeProgressForm != NULL);
  6158. if (!FSynchronizeProgressForm->Started)
  6159. {
  6160. FSynchronizeProgressForm->Start();
  6161. }
  6162. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6163. SetTaskbarListProgressValue(CompareProgress);
  6164. }
  6165. else
  6166. {
  6167. DebugAssert(FSynchronizeProgressForm == NULL);
  6168. DebugAssert(FProgressForm != NULL);
  6169. }
  6170. }
  6171. //---------------------------------------------------------------------------
  6172. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6173. {
  6174. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6175. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6176. if (File.get() != NULL)
  6177. {
  6178. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6179. Application->ShowMainForm = false;
  6180. Application->Run();
  6181. }
  6182. }
  6183. //---------------------------------------------------------------------------
  6184. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6185. {
  6186. DebugFail();
  6187. }
  6188. //---------------------------------------------------------------------------
  6189. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6190. {
  6191. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6192. SessionData->Assign(ManagedSession->SessionData);
  6193. UpdateSessionData(SessionData.get());
  6194. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6195. if (IsActiveTerminal(ManagedSession))
  6196. {
  6197. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6198. }
  6199. if (!ManagedSession->SessionData->HasSessionName())
  6200. {
  6201. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6202. // once IsWorkspace is cleared
  6203. SessionData->Name = UnicodeString();
  6204. }
  6205. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6206. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6207. SessionData->IsWorkspace = false;
  6208. return SessionData.release();
  6209. }
  6210. //---------------------------------------------------------------------------
  6211. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6212. {
  6213. TSessionData * SessionData = CloneCurrentSessionData();
  6214. try
  6215. {
  6216. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6217. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6218. }
  6219. __finally
  6220. {
  6221. delete SessionData;
  6222. }
  6223. }
  6224. //---------------------------------------------------------------------------
  6225. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6226. {
  6227. TTerminalManager * Manager = TTerminalManager::Instance();
  6228. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6229. if (DebugAlwaysTrue(ManagedSession != NULL))
  6230. {
  6231. // Update ManagedSession->StateData
  6232. UpdateSession(ManagedSession);
  6233. }
  6234. Manager->SaveWorkspace(DataList.get());
  6235. return DataList.release();
  6236. }
  6237. //---------------------------------------------------------------------------
  6238. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6239. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6240. {
  6241. WinConfiguration->LastWorkspace = Name;
  6242. if (!SavePasswords)
  6243. {
  6244. for (int Index = 0; Index < DataList->Count; Index++)
  6245. {
  6246. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6247. if (SessionData->Link.IsEmpty())
  6248. {
  6249. SessionData->ClearSessionPasswords();
  6250. }
  6251. }
  6252. }
  6253. StoredSessions->NewWorkspace(Name, DataList);
  6254. // modified only
  6255. StoredSessions->Save(false, Explicit);
  6256. }
  6257. //---------------------------------------------------------------------------
  6258. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6259. {
  6260. return
  6261. DefaultStr(WinConfiguration->LastWorkspace,
  6262. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6263. }
  6264. //---------------------------------------------------------------------------
  6265. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6266. {
  6267. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6268. bool AnyNonStoredSessionWithPassword = false;
  6269. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6270. bool AllNonStoredSessionsAnonymous = true;
  6271. TTerminalManager * Manager = TTerminalManager::Instance();
  6272. for (int Index = 0; Index < DataList->Count; Index++)
  6273. {
  6274. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6275. if (SessionData->Link.IsEmpty())
  6276. {
  6277. if (SessionData->HasAnySessionPassword())
  6278. {
  6279. AnyNonStoredSessionWithPassword = true;
  6280. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6281. {
  6282. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6283. }
  6284. }
  6285. if (!SameText(SessionData->UserName, AnonymousUserName))
  6286. {
  6287. AllNonStoredSessionsAnonymous = false;
  6288. }
  6289. }
  6290. }
  6291. bool SavePasswords;
  6292. bool * PSavePasswords;
  6293. bool NotRecommendedSavingPasswords =
  6294. !CustomWinConfiguration->UseMasterPassword &&
  6295. !AllNonStoredSessionsAnonymous;
  6296. if (Configuration->DisablePasswordStoring ||
  6297. !AnyNonStoredSessionWithPassword)
  6298. {
  6299. PSavePasswords = NULL;
  6300. SavePasswords = false;
  6301. }
  6302. else
  6303. {
  6304. PSavePasswords = &SavePasswords;
  6305. SavePasswords =
  6306. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6307. !NotRecommendedSavingPasswords;
  6308. }
  6309. UnicodeString Name = WorkspaceName();
  6310. bool CreateShortcut = false;
  6311. bool Result =
  6312. DoSaveWorkspaceDialog(
  6313. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6314. EnableAutoSave);
  6315. if (Result)
  6316. {
  6317. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6318. if (CreateShortcut)
  6319. {
  6320. TOperationVisualizer Visualizer;
  6321. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6322. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6323. }
  6324. if (EnableAutoSave)
  6325. {
  6326. WinConfiguration->AutoSaveWorkspace = true;
  6327. WinConfiguration->AutoWorkspace = Name;
  6328. if (PSavePasswords != NULL)
  6329. {
  6330. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6331. }
  6332. }
  6333. }
  6334. return Result;
  6335. }
  6336. //---------------------------------------------------------------------------
  6337. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6338. {
  6339. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6340. DebugAssert(Session == ManagedSession);
  6341. if (!IsLocalBrowserMode())
  6342. {
  6343. SAFE_DESTROY(Session->RemoteExplorerState);
  6344. if (WinConfiguration->PreservePanelState)
  6345. {
  6346. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6347. }
  6348. }
  6349. UpdateSessionData(Session->StateData);
  6350. }
  6351. //---------------------------------------------------------------------------
  6352. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6353. {
  6354. // Keep in sync with TSessionData::CopyStateData
  6355. DebugAssert(Data != NULL);
  6356. // This is inconsistent with how color (for example) is handled.
  6357. Data->Name = ManagedSession->SessionData->Name;
  6358. if (!IsLocalBrowserMode())
  6359. {
  6360. // cannot use RemoteDirView->Path, because it is empty if connection
  6361. // was already closed
  6362. // also only peek, we may not be connected at all atm
  6363. // so make sure we do not try retrieving current directory from the server
  6364. // (particularly with FTP)
  6365. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6366. if (!ACurrentDirectory.IsEmpty())
  6367. {
  6368. Data->RemoteDirectory = ACurrentDirectory;
  6369. }
  6370. }
  6371. Data->Color = SessionColor;
  6372. }
  6373. //---------------------------------------------------------------------------
  6374. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6375. {
  6376. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6377. DebugAssert(Toolbar != NULL);
  6378. for (int i = 0; i < Toolbar->Items->Count; i++)
  6379. {
  6380. TTBXCustomDropDownItem * DropDownItem;
  6381. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6382. if (DropDownItem != NULL)
  6383. {
  6384. ToolbarItemResize(DropDownItem,
  6385. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6386. Toolbar->NonClientWidth);
  6387. break;
  6388. }
  6389. }
  6390. }
  6391. //---------------------------------------------------------------------------
  6392. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6393. {
  6394. Item->EditWidth = Width;
  6395. }
  6396. //---------------------------------------------------------------------------
  6397. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6398. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6399. {
  6400. for (int i = 0; i < Toolbar->Items->Count; i++)
  6401. {
  6402. TTBXCustomDropDownItem * DropDownItem;
  6403. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6404. if (DropDownItem != NULL)
  6405. {
  6406. ASize.x -= DropDownItem->EditWidth;
  6407. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  6408. }
  6409. }
  6410. }
  6411. //---------------------------------------------------------------------------
  6412. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6413. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6414. {
  6415. if (WinConfiguration->DDWarnLackOfTempSpace)
  6416. {
  6417. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6418. if (!ADrive.IsEmpty())
  6419. {
  6420. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6421. DebugAssert(RequiredSpace >= 0);
  6422. __int64 RequiredWithReserve;
  6423. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6424. if (FreeSpace < RequiredWithReserve)
  6425. {
  6426. unsigned int Result;
  6427. TMessageParams Params(mpNeverAskAgainCheck);
  6428. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6429. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6430. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6431. if (Result == qaNeverAskAgain)
  6432. {
  6433. WinConfiguration->DDWarnLackOfTempSpace = false;
  6434. }
  6435. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6436. }
  6437. }
  6438. }
  6439. }
  6440. //---------------------------------------------------------------------------
  6441. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6442. {
  6443. DoOpenDirectoryDialog(odAddBookmark, Side);
  6444. }
  6445. //---------------------------------------------------------------------------
  6446. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6447. {
  6448. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6449. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6450. try
  6451. {
  6452. TCustomDirView * DView = DirView(Side);
  6453. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6454. {
  6455. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6456. }
  6457. }
  6458. catch (...)
  6459. {
  6460. delete VisitedDirectories;
  6461. throw;
  6462. }
  6463. return VisitedDirectories;
  6464. }
  6465. //---------------------------------------------------------------------------
  6466. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6467. TOpenDirectoryMode Mode, TOperationSide Side)
  6468. {
  6469. bool Continue = true;
  6470. if (Mode == odAddBookmark)
  6471. {
  6472. TMessageParams Params(mpNeverAskAgainCheck);
  6473. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6474. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6475. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6476. unsigned int Answer =
  6477. MessageDialog(Message,
  6478. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6479. if (Answer == qaNeverAskAgain)
  6480. {
  6481. Continue = true;
  6482. WinConfiguration->UseSharedBookmarks = true;
  6483. }
  6484. else if (Answer == qaOK)
  6485. {
  6486. Continue = true;
  6487. WinConfiguration->UseSharedBookmarks = false;
  6488. }
  6489. else
  6490. {
  6491. Continue = false;
  6492. }
  6493. }
  6494. if (Continue)
  6495. {
  6496. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6497. try
  6498. {
  6499. UnicodeString Name = DirView(Side)->PathName;
  6500. bool Repeat;
  6501. do
  6502. {
  6503. Repeat = false;
  6504. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6505. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6506. // do not allow switching to location profiles,
  6507. // if we are not connected
  6508. HasDirView[osLocal] && (Terminal != NULL)))
  6509. {
  6510. TWindowLock Lock(this);
  6511. if (!TryOpenDirectory(Side, Name))
  6512. {
  6513. Repeat = true;
  6514. Mode = odBrowse;
  6515. }
  6516. }
  6517. }
  6518. while (Repeat);
  6519. }
  6520. __finally
  6521. {
  6522. delete VisitedDirectories;
  6523. }
  6524. }
  6525. }
  6526. //---------------------------------------------------------------------------
  6527. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6528. {
  6529. DebugAssert(!Terminal->CommandSessionOpened);
  6530. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6531. }
  6532. //---------------------------------------------------------------------------
  6533. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6534. {
  6535. bool Result = Terminal->IsCapable[Capability] ||
  6536. Terminal->CommandSessionOpened;
  6537. if (!Result)
  6538. {
  6539. // We might get here for example when "checksum" synchronization is requested from command-line
  6540. // on server that supports neither checksum nor shell
  6541. if (!Terminal->IsCapable[fcSecondaryShell])
  6542. {
  6543. NotSupported();
  6544. }
  6545. else if (!GUIConfiguration->ConfirmCommandSession)
  6546. {
  6547. Result = true;
  6548. }
  6549. else
  6550. {
  6551. TMessageParams Params(mpNeverAskAgainCheck);
  6552. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6553. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6554. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6555. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6556. if (Answer == qaNeverAskAgain)
  6557. {
  6558. GUIConfiguration->ConfirmCommandSession = false;
  6559. Result = true;
  6560. }
  6561. else if (Answer == qaOK)
  6562. {
  6563. Result = true;
  6564. }
  6565. }
  6566. if (Result)
  6567. {
  6568. Result = CommandSessionFallback();
  6569. }
  6570. }
  6571. return Result;
  6572. }
  6573. //---------------------------------------------------------------------------
  6574. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6575. {
  6576. if (EnsureCommandSessionFallback(fcAnyCommand))
  6577. {
  6578. DoConsoleDialog(Terminal, Command);
  6579. }
  6580. }
  6581. //---------------------------------------------------------------------------
  6582. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6583. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6584. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6585. {
  6586. if (!IsSideLocalBrowser(osRemote) &&
  6587. IsFileControl(DropSourceControl, osRemote) &&
  6588. (FDDExtMapFile != NULL))
  6589. {
  6590. Accept = true;
  6591. }
  6592. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6593. DebugAssert(FDDTargetControl != NULL);
  6594. }
  6595. //---------------------------------------------------------------------------
  6596. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6597. _di_IDataObject DataObj, int KeyState,
  6598. const TPoint & Point, int & Effect, bool & Accept)
  6599. {
  6600. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6601. }
  6602. //---------------------------------------------------------------------------
  6603. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6604. _di_IDataObject DataObj, int KeyState,
  6605. const TPoint & Point, int & Effect, bool & Accept)
  6606. {
  6607. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6608. }
  6609. //---------------------------------------------------------------------------
  6610. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6611. TObject * Sender)
  6612. {
  6613. DebugUsedParam(Sender);
  6614. DebugAssert(FDDTargetControl == Sender);
  6615. FDDTargetControl = NULL;
  6616. }
  6617. //---------------------------------------------------------------------------
  6618. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  6619. {
  6620. FileControlDDDragLeave(SessionsPageControl);
  6621. }
  6622. //---------------------------------------------------------------------------
  6623. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  6624. {
  6625. FileControlDDDragLeave(QueueView3);
  6626. }
  6627. //---------------------------------------------------------------------------
  6628. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6629. {
  6630. DebugAssert(!IsSideLocalBrowser(Side));
  6631. DebugUsedParam(Side);
  6632. bool Edit = false;
  6633. TRemoteFile * File = NULL;
  6634. UnicodeString FileName;
  6635. UnicodeString PointTo;
  6636. bool SymbolicLink = true;
  6637. if (RemoteDirView->ItemFocused)
  6638. {
  6639. DebugAssert(RemoteDirView->ItemFocused->Data);
  6640. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6641. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6642. if (Edit)
  6643. {
  6644. FileName = File->FileName;
  6645. PointTo = File->LinkTo;
  6646. }
  6647. else if (!File->IsParentDirectory)
  6648. {
  6649. PointTo = File->FileName;
  6650. }
  6651. }
  6652. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6653. Terminal->IsCapable[fcHardLink]))
  6654. {
  6655. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6656. if (Edit)
  6657. {
  6658. DebugAssert(File->FileName == FileName);
  6659. int Params = dfNoRecursive;
  6660. Terminal->ExceptionOnFail = true;
  6661. try
  6662. {
  6663. Terminal->DeleteFile(L"", File, &Params);
  6664. }
  6665. __finally
  6666. {
  6667. Terminal->ExceptionOnFail = false;
  6668. }
  6669. }
  6670. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6671. }
  6672. }
  6673. //---------------------------------------------------------------------------
  6674. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6675. {
  6676. return
  6677. (IsSideLocalBrowser(Side) ||
  6678. (HasActiveTerminal() &&
  6679. Terminal->ResolvingSymlinks &&
  6680. Terminal->IsCapable[fcSymbolicLink]));
  6681. }
  6682. //---------------------------------------------------------------------------
  6683. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6684. {
  6685. return
  6686. !IsSideLocalBrowser(FCurrentSide) &&
  6687. (RemoteDirView->ItemFocused != NULL) &&
  6688. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6689. Terminal->SessionData->ResolveSymlinks;
  6690. }
  6691. //---------------------------------------------------------------------------
  6692. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6693. {
  6694. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6695. FForceExecution = true;
  6696. try
  6697. {
  6698. DirView(osCurrent)->ExecuteCurrentFile();
  6699. }
  6700. __finally
  6701. {
  6702. FForceExecution = false;
  6703. }
  6704. }
  6705. //---------------------------------------------------------------------------
  6706. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6707. {
  6708. TEditorData ExternalEditor;
  6709. ExternalEditor.Editor = edExternal;
  6710. bool Remember = false;
  6711. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6712. {
  6713. if (Remember)
  6714. {
  6715. TEditorList * EditorList = new TEditorList;
  6716. try
  6717. {
  6718. *EditorList = *WinConfiguration->EditorList;
  6719. bool Found = false;
  6720. int i = 0;
  6721. while (!Found && (i < EditorList->Count))
  6722. {
  6723. const TEditorPreferences * Editor = EditorList->Editors[i];
  6724. if ((Editor->Data->Editor == edExternal) &&
  6725. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6726. {
  6727. Found = true;
  6728. }
  6729. i++;
  6730. }
  6731. if (!Found)
  6732. {
  6733. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6734. WinConfiguration->EditorList = EditorList;
  6735. }
  6736. }
  6737. __finally
  6738. {
  6739. delete EditorList;
  6740. }
  6741. }
  6742. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6743. }
  6744. }
  6745. //---------------------------------------------------------------------------
  6746. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6747. {
  6748. if (FFileFindTerminal == ATerminal)
  6749. {
  6750. FFileFindTerminal = NULL;
  6751. HideFileFindDialog();
  6752. }
  6753. if (FClipboardTerminal == ATerminal)
  6754. {
  6755. ClipboardClear(); // implies ClipboardStop
  6756. }
  6757. if ((FOnSynchronizeAbort != NULL) &&
  6758. (ATerminal == FManagedSession))
  6759. {
  6760. FOnSynchronizeAbort(NULL);
  6761. }
  6762. }
  6763. //---------------------------------------------------------------------------
  6764. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6765. {
  6766. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6767. DetachTerminal(Sender);
  6768. }
  6769. //---------------------------------------------------------------------------
  6770. void __fastcall TCustomScpExplorerForm::FileTerminalReplaced(
  6771. const UnicodeString FileName, TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6772. {
  6773. TManagedTerminal * ATerminal = static_cast<TManagedTerminal *>(Arg);
  6774. if (Data->Terminal == Terminal)
  6775. {
  6776. Data->Terminal = ATerminal;
  6777. }
  6778. }
  6779. //---------------------------------------------------------------------------
  6780. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6781. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6782. {
  6783. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6784. DebugAssert(Terminal != NULL);
  6785. if (Data->Terminal == Terminal)
  6786. {
  6787. Data->Terminal = NULL;
  6788. }
  6789. }
  6790. //---------------------------------------------------------------------------
  6791. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6792. {
  6793. return NULL;
  6794. }
  6795. //---------------------------------------------------------------------------
  6796. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6797. {
  6798. UpdateControls();
  6799. SessionColor = TColor(0);
  6800. UpdateRemotePathComboBox(false);
  6801. NeedSession(false);
  6802. }
  6803. //---------------------------------------------------------------------------
  6804. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6805. {
  6806. try
  6807. {
  6808. // Cache, as the login dialog can change its value.
  6809. // See also DoShow. Also see TTerminalManager::NewSession.
  6810. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6811. try
  6812. {
  6813. if (ShowLogin)
  6814. {
  6815. bool ReloadSessions = !Startup;
  6816. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6817. }
  6818. }
  6819. __finally
  6820. {
  6821. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6822. // (so there was no chance for the user to open any session yet)
  6823. if ((ShowLogin || !Startup) &&
  6824. !WinConfiguration->KeepOpenWhenNoSession &&
  6825. // this rules out the implicit Commander's local-local browser
  6826. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6827. {
  6828. TerminateApplication();
  6829. }
  6830. }
  6831. }
  6832. catch (EAbort &)
  6833. {
  6834. // swallow
  6835. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6836. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6837. }
  6838. }
  6839. //---------------------------------------------------------------------------
  6840. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6841. {
  6842. TTerminalManager * Manager = TTerminalManager::Instance();
  6843. DebugAssert(!Manager->Updating);
  6844. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6845. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6846. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6847. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6848. try
  6849. {
  6850. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6851. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6852. {
  6853. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6854. }
  6855. for (int Index = 0; Index <= Manager->Count; Index++)
  6856. {
  6857. TThemeTabSheet * TabSheet;
  6858. if (Index >= SessionsPageControl->PageCount)
  6859. {
  6860. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6861. TabSheet->PageControl = SessionsPageControl;
  6862. }
  6863. else
  6864. {
  6865. TabSheet = SessionsPageControl->Pages[Index];
  6866. }
  6867. bool IsSessionTab = (Index < Manager->Count);
  6868. if (IsSessionTab)
  6869. {
  6870. TTerminal * Terminal = Manager->Sessions[Index];
  6871. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6872. TabSheet->CaptionTruncation = WinConfiguration->SessionTabCaptionTruncation ? tttEllipsis : tttNone;
  6873. UpdateSessionTab(TabSheet);
  6874. }
  6875. else
  6876. {
  6877. TabSheet->Tag = 0; // not really needed
  6878. TabSheet->Shadowed = false;
  6879. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6880. TabSheet->CaptionTruncation = GetNewTabTabCaptionTruncation();
  6881. // We know that we are at the last page, otherwise we could not call this (it assumes that new session tab is the last one)
  6882. UpdateNewTabTab();
  6883. }
  6884. }
  6885. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6886. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6887. {
  6888. SessionsPageControl->UpdateTabsCaptionTruncation();
  6889. }
  6890. }
  6891. __finally
  6892. {
  6893. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6894. }
  6895. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6896. }
  6897. //---------------------------------------------------------------------------
  6898. TThemeTabCaptionTruncation TCustomScpExplorerForm::GetNewTabTabCaptionTruncation()
  6899. {
  6900. return WinConfiguration->SessionTabCaptionTruncation ? tttNoText : tttNone;
  6901. }
  6902. //---------------------------------------------------------------------------
  6903. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6904. {
  6905. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6906. }
  6907. //---------------------------------------------------------------------------
  6908. TThemeTabSheet * TCustomScpExplorerForm::GetNewTabTab()
  6909. {
  6910. return SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6911. }
  6912. //---------------------------------------------------------------------------
  6913. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  6914. {
  6915. TThemeTabSheet * TabSheet = GetNewTabTab();
  6916. UnicodeString TabCaption;
  6917. if (WinConfiguration->SelectiveToolbarText)
  6918. {
  6919. TabCaption = GetNewTabTabCaption();
  6920. }
  6921. TabSheet->BaseCaption = TabCaption;
  6922. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  6923. }
  6924. //---------------------------------------------------------------------------
  6925. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  6926. {
  6927. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  6928. }
  6929. //---------------------------------------------------------------------------
  6930. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  6931. {
  6932. DebugFail();
  6933. return UnicodeString();
  6934. }
  6935. //---------------------------------------------------------------------------
  6936. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  6937. {
  6938. if (DebugAlwaysTrue(TabSheet != NULL))
  6939. {
  6940. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  6941. if (DebugAlwaysTrue(ASession != NULL))
  6942. {
  6943. TColor Color = (ASession == Terminal) ? FSessionColor : ASession->StateData->Color;
  6944. if (ASession->LocalBrowser)
  6945. {
  6946. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  6947. }
  6948. else
  6949. {
  6950. TabSheet->ImageIndex = AddSessionColor(Color);
  6951. }
  6952. TTerminalManager * Manager = TTerminalManager::Instance();
  6953. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  6954. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  6955. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  6956. }
  6957. }
  6958. }
  6959. //---------------------------------------------------------------------------
  6960. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  6961. {
  6962. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  6963. }
  6964. //---------------------------------------------------------------------------
  6965. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6966. {
  6967. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6968. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  6969. bool Result = (Session != NULL);
  6970. if (Result)
  6971. {
  6972. TTerminalManager::Instance()->ActiveSession = Session;
  6973. }
  6974. else
  6975. {
  6976. try
  6977. {
  6978. NewTab();
  6979. }
  6980. __finally
  6981. {
  6982. SessionListChanged();
  6983. }
  6984. FSessionsPageControlNewTabTime = Now();
  6985. }
  6986. return Result;
  6987. }
  6988. //---------------------------------------------------------------------------
  6989. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  6990. {
  6991. TWindowLock Lock(this);
  6992. SessionTabSwitched();
  6993. }
  6994. //---------------------------------------------------------------------------
  6995. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  6996. {
  6997. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  6998. DebugAssert(TransferList != NULL);
  6999. UnicodeString Name;
  7000. if (TransferList->ItemIndex <= 0)
  7001. {
  7002. Name = L"";
  7003. }
  7004. else
  7005. {
  7006. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  7007. }
  7008. if (FCopyParamAutoSelected.IsEmpty())
  7009. {
  7010. // if previous preset was not autoselected, make new preset the "default"
  7011. FCopyParamDefault = Name;
  7012. }
  7013. GUIConfiguration->CopyParamCurrent = Name;
  7014. }
  7015. //---------------------------------------------------------------------------
  7016. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  7017. {
  7018. // sanity check
  7019. bool ExistingPreset =
  7020. (FTransferListHoverIndex >= 0) &&
  7021. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  7022. DebugAssert(ExistingPreset);
  7023. if (ExistingPreset)
  7024. {
  7025. HDC DC = GetDC(0);
  7026. TCanvas * Canvas = new TCanvas();
  7027. try
  7028. {
  7029. Canvas->Handle = DC;
  7030. Canvas->Font = GetToolbarFont(this);
  7031. UnicodeString Name;
  7032. if (FTransferListHoverIndex == 0)
  7033. {
  7034. Name = L"";
  7035. }
  7036. else
  7037. {
  7038. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  7039. }
  7040. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  7041. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  7042. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  7043. static_cast<TObject*>(GetComponent(fcTransferList)));
  7044. UnicodeString InfoStr =
  7045. GUIConfiguration->CopyParamPreset[Name].
  7046. GetInfoStr(L"; ",
  7047. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  7048. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  7049. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  7050. {
  7051. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  7052. {
  7053. InfoStr.SetLength(InfoStr.Length() - 1);
  7054. }
  7055. InfoStr += Ellipsis;
  7056. }
  7057. // UpdateCaption does not cause invalidation of whole submenu, while
  7058. // setting Caption property does.
  7059. // also it probably does not resize the label, even if necessary
  7060. // (we do not want that anyway)
  7061. TransferLabel->UpdateCaption(InfoStr);
  7062. }
  7063. __finally
  7064. {
  7065. Canvas->Handle = NULL;
  7066. ReleaseDC(0, DC);
  7067. delete Canvas;
  7068. }
  7069. }
  7070. }
  7071. //---------------------------------------------------------------------------
  7072. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7073. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7074. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7075. {
  7076. if (FTransferListHoverIndex != AHoverIndex)
  7077. {
  7078. FTransferListHoverIndex = AHoverIndex;
  7079. UpdateTransferLabel();
  7080. }
  7081. }
  7082. //---------------------------------------------------------------------------
  7083. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7084. {
  7085. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7086. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7087. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7088. {
  7089. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7090. {
  7091. if (!NonVisualDataModule->Busy)
  7092. {
  7093. OpenDirectory(GetSide(osCurrent));
  7094. }
  7095. Message.Result = 1;
  7096. }
  7097. else
  7098. {
  7099. TForm::Dispatch(&Message);
  7100. }
  7101. }
  7102. else
  7103. {
  7104. TForm::Dispatch(&Message);
  7105. }
  7106. }
  7107. //---------------------------------------------------------------------------
  7108. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7109. {
  7110. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7111. if ((FIgnoreNextDialogChar != 0) &&
  7112. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7113. {
  7114. Message.Result = 1;
  7115. }
  7116. else
  7117. {
  7118. TForm::Dispatch(&Message);
  7119. }
  7120. FIgnoreNextDialogChar = 0;
  7121. }
  7122. //---------------------------------------------------------------------------
  7123. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7124. {
  7125. // The four low-order bits are used internally by Windows
  7126. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7127. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7128. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7129. // 61730 - restore thru double click - undocumented
  7130. // 61490 - maximize thru double click - undocumented
  7131. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7132. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7133. {
  7134. SysResizing(Cmd);
  7135. }
  7136. TForm::Dispatch(&Message);
  7137. }
  7138. //---------------------------------------------------------------------------
  7139. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7140. {
  7141. AppLog(L"Windows session end query");
  7142. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7143. // Also there no point returning TRUE as we are not able to
  7144. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7145. // Hence the process termination might be safer :)
  7146. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7147. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7148. {
  7149. Message.Result = FALSE;
  7150. }
  7151. else
  7152. {
  7153. Message.Result = TRUE;
  7154. }
  7155. // Do not call default handling as that triggers OnCloseQuery,
  7156. // where our implementation will popup confirmation dialogs, what we do not want,
  7157. // as per Vista guidelines:
  7158. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7159. }
  7160. //---------------------------------------------------------------------------
  7161. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7162. {
  7163. AppLog(L"Windows session end");
  7164. if (Message.EndSession && IsApplicationMinimized())
  7165. {
  7166. // WORKAROUND
  7167. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7168. // when it receives WM_ENDSESSION,
  7169. // but that sometimes (particularly when application is minimized) cause crashes.
  7170. // Crash popups message that blocks log off.
  7171. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7172. // so we call ExitProcess() immediately, not even trying to cleanup.
  7173. // It still causes beep, so there's likely some popup, but it does not block
  7174. // log off.
  7175. ExitProcess(0);
  7176. }
  7177. TForm::Dispatch(&Message);
  7178. }
  7179. #ifdef _DEBUG
  7180. //---------------------------------------------------------------------------
  7181. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  7182. {
  7183. TForm::Dispatch(&Message);
  7184. }
  7185. #endif
  7186. //---------------------------------------------------------------------------
  7187. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7188. {
  7189. }
  7190. //---------------------------------------------------------------------------
  7191. void __fastcall TCustomScpExplorerForm::DoShow()
  7192. {
  7193. // Called from TCustomScpExplorerForm::CMShowingChanged
  7194. // only now are the controls resized finally, so the size constraints
  7195. // will not conflict with possibly very small window size
  7196. RestoreFormParams();
  7197. // This indicates that the form was rescaled after parameters were loaded and
  7198. // as most probably the parameters were actually saved with the current form scaling
  7199. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7200. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7201. // and no rounding problems will occur.
  7202. // See also RestoreForm.
  7203. // (we should be safe to call RestoreParams unconditionally)
  7204. if (PixelsPerInch != Screen->PixelsPerInch)
  7205. {
  7206. RestoreParams();
  7207. }
  7208. FixControlsPlacement();
  7209. if (Position == poDefaultPosOnly)
  7210. {
  7211. CutFormToDesktop(this);
  7212. }
  7213. TForm::DoShow();
  7214. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7215. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7216. // This was previously in NeedSession, where other related code is.
  7217. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7218. // unpleasantly shows briefly.
  7219. if ((ManagedSession == NULL) &&
  7220. !WinConfiguration->ShowLoginWhenNoSession &&
  7221. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7222. // This detects if workspace was saved the last time the main widow was closed
  7223. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7224. {
  7225. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7226. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7227. }
  7228. // Before main window displays
  7229. if (ManagedSession == NULL)
  7230. {
  7231. StartingWithoutSession();
  7232. }
  7233. UpdatePixelsPerInchMainWindowCounter();
  7234. FShowing = true;
  7235. }
  7236. //---------------------------------------------------------------------------
  7237. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7238. {
  7239. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7240. }
  7241. //---------------------------------------------------------------------------
  7242. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7243. {
  7244. SessionListChanged();
  7245. InitStatusBar();
  7246. UpdateControls();
  7247. }
  7248. //---------------------------------------------------------------------------
  7249. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7250. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7251. TNotifyEvent OnBalloonClick, TObject * UserData)
  7252. {
  7253. bool Do;
  7254. UnicodeString Message;
  7255. if (E == NULL)
  7256. {
  7257. Message = Str;
  7258. Do = true;
  7259. }
  7260. else
  7261. {
  7262. Do = ExceptionMessage(E, Message);
  7263. }
  7264. if (Do && WinConfiguration->BalloonNotifications)
  7265. {
  7266. UnicodeString Title;
  7267. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7268. {
  7269. Message = TrimLeft(Message);
  7270. }
  7271. else
  7272. {
  7273. Message = UnformatMessage(Message);
  7274. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7275. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7276. Title = LoadResourceString(Captions[Type]);
  7277. if (Terminal != NULL)
  7278. {
  7279. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal->PrimaryTerminal));
  7280. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7281. }
  7282. }
  7283. if (Seconds == 0)
  7284. {
  7285. Seconds = WinConfiguration->NotificationsTimeout;
  7286. }
  7287. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7288. }
  7289. }
  7290. //---------------------------------------------------------------------------
  7291. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7292. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7293. UnicodeString HelpKeyword, const TMessageParams * Params,
  7294. TTerminal * Terminal)
  7295. {
  7296. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7297. (FOnFeedSynchronizeError != NULL)) &&
  7298. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7299. {
  7300. if (FOnFeedSynchronizeError != NULL)
  7301. {
  7302. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7303. }
  7304. else
  7305. {
  7306. DebugAssert(FErrorList != NULL);
  7307. TStringList * MoreMessagesCopy = NULL;
  7308. if (MoreMessages)
  7309. {
  7310. MoreMessagesCopy = new TStringList();
  7311. MoreMessagesCopy->Assign(MoreMessages);
  7312. }
  7313. FErrorList->AddObject(Message, MoreMessagesCopy);
  7314. }
  7315. PopupTrayBalloon(Terminal, Message, Type);
  7316. return ContinueAnswer(Answers);
  7317. }
  7318. else
  7319. {
  7320. bool UseBalloon = FTrayIcon->Visible;
  7321. if (UseBalloon)
  7322. {
  7323. PopupTrayBalloon(Terminal, Message, Type);
  7324. }
  7325. unsigned int Result;
  7326. try
  7327. {
  7328. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7329. }
  7330. __finally
  7331. {
  7332. // cancel only balloon we popped up, otherwise we may cancel notification
  7333. // balloon that was there before the message dialog
  7334. // (such as "dd confirmation opt in balloon)
  7335. if (UseBalloon)
  7336. {
  7337. FTrayIcon->CancelBalloon();
  7338. }
  7339. }
  7340. return Result;
  7341. }
  7342. }
  7343. //---------------------------------------------------------------------------
  7344. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7345. TTerminal * Terminal, Exception * E)
  7346. {
  7347. if (FTrayIcon->Visible)
  7348. {
  7349. PopupTrayBalloon(Terminal, L"", qtError, E);
  7350. }
  7351. // particularly prevent opening new session from jump list,
  7352. // while exception is shown
  7353. NonVisualDataModule->StartBusy();
  7354. try
  7355. {
  7356. ShowExtendedExceptionEx(Terminal, E);
  7357. }
  7358. __finally
  7359. {
  7360. NonVisualDataModule->EndBusy();
  7361. FTrayIcon->CancelBalloon();
  7362. }
  7363. }
  7364. //---------------------------------------------------------------------------
  7365. void __fastcall TCustomScpExplorerForm::SessionReady()
  7366. {
  7367. InitStatusBar();
  7368. // cannot rely on active page being page for active terminal,
  7369. // as it can happen that active page is the "new session" page
  7370. // (e.g. when reconnecting active terminal, while login dialog
  7371. // invoked from "new session" page is modal)
  7372. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7373. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7374. }
  7375. //---------------------------------------------------------------------------
  7376. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  7377. TTerminal * Terminal, Exception * E)
  7378. {
  7379. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  7380. if (!Terminal->Active)
  7381. {
  7382. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7383. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7384. {
  7385. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7386. }
  7387. }
  7388. }
  7389. //---------------------------------------------------------------------------
  7390. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  7391. UnicodeString Message, TQueryType Type,
  7392. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7393. {
  7394. if ((E == NULL) ||
  7395. ExceptionMessage(E, Message))
  7396. {
  7397. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7398. if (Important)
  7399. {
  7400. Seconds *= 5;
  7401. }
  7402. UnicodeString NoteMessage(UnformatMessage(Message));
  7403. if (Terminal != NULL)
  7404. {
  7405. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7406. NoteMessage = FORMAT(L"%s: %s",
  7407. (TTerminalManager::Instance()->GetSessionTitle(Session, true), NoteMessage));
  7408. }
  7409. if (WinConfiguration->BalloonNotifications)
  7410. {
  7411. AddNote(NoteMessage);
  7412. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7413. }
  7414. else
  7415. {
  7416. FlashOnBackground();
  7417. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7418. }
  7419. }
  7420. }
  7421. //---------------------------------------------------------------------------
  7422. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7423. {
  7424. RestoreApp();
  7425. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7426. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7427. !NonVisualDataModule->Busy)
  7428. {
  7429. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7430. TTerminalManager::Instance()->ActiveSession = Terminal;
  7431. if (!ComponentVisible[fcQueueView])
  7432. {
  7433. ToggleQueueVisibility();
  7434. GoToQueue();
  7435. }
  7436. }
  7437. }
  7438. //---------------------------------------------------------------------------
  7439. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7440. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7441. {
  7442. UnicodeString Message;
  7443. TNotifyEvent OnClick = NULL;
  7444. TObject * UserData = NULL;
  7445. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7446. switch (Event)
  7447. {
  7448. case qeEmptyButMonitored:
  7449. if ((ATerminal != Terminal) || QueueInvisible)
  7450. {
  7451. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7452. OnClick = QueueEmptyNoteClicked;
  7453. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7454. TerminalNoteData->Terminal = ATerminal;
  7455. UserData = TerminalNoteData;
  7456. }
  7457. break;
  7458. case qeEmpty:
  7459. OperationComplete(ATerminal->QueueOperationStart);
  7460. break;
  7461. case qePendingUserAction:
  7462. if ((ATerminal != Terminal) ||
  7463. (QueueInvisible && !IsQueueAutoPopup()))
  7464. {
  7465. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7466. }
  7467. break;
  7468. default:
  7469. DebugFail();
  7470. }
  7471. if (!Message.IsEmpty())
  7472. {
  7473. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7474. }
  7475. }
  7476. //---------------------------------------------------------------------------
  7477. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7478. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7479. {
  7480. if (FDDExtMapFile != NULL)
  7481. {
  7482. CloseHandle(FDDExtMapFile);
  7483. FDDExtMapFile = NULL;
  7484. }
  7485. if (WinConfiguration->DDFakeFile)
  7486. {
  7487. DDFakeFileInitDrag(FileList, Created);
  7488. }
  7489. }
  7490. //---------------------------------------------------------------------------
  7491. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7492. {
  7493. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7494. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7495. {
  7496. FFakeFileDropTarget = FileName;
  7497. }
  7498. }
  7499. //---------------------------------------------------------------------------
  7500. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7501. {
  7502. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7503. if (!ForceDirectories(ApiPath(Result)))
  7504. {
  7505. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7506. }
  7507. FileSetAttr(ApiPath(Result), faHidden);
  7508. return Result;
  7509. }
  7510. //---------------------------------------------------------------------------
  7511. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7512. bool & Created)
  7513. {
  7514. FFakeFileDropTarget = UnicodeString();
  7515. FDragFakeDirectory = CreateFakeTransferDirectory();
  7516. FileList->AddItem(NULL, FDragFakeDirectory);
  7517. Created = true;
  7518. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7519. {
  7520. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7521. }
  7522. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7523. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7524. {
  7525. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7526. TDragExtCommStruct* CommStruct;
  7527. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7528. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7529. DebugAssert(CommStruct != NULL);
  7530. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7531. CommStruct->Dragging = true;
  7532. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7533. LENOF(CommStruct->DropDest));
  7534. NULL_TERMINATE(CommStruct->DropDest);
  7535. UnmapViewOfFile(CommStruct);
  7536. }
  7537. }
  7538. //---------------------------------------------------------------------------
  7539. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7540. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7541. {
  7542. bool Result;
  7543. DebugAssert(!IsLocalBrowserMode());
  7544. if (Sender == RemoteDirView)
  7545. {
  7546. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7547. }
  7548. else
  7549. {
  7550. DebugAssert(Sender == RemoteDriveView);
  7551. TStrings * FileList = RemoteDriveView->DragFileList();
  7552. try
  7553. {
  7554. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7555. }
  7556. __finally
  7557. {
  7558. delete FileList;
  7559. }
  7560. }
  7561. if (FDDTargetControl == RemoteDriveView)
  7562. {
  7563. RemoteDriveView->UpdateDropTarget();
  7564. }
  7565. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7566. // or from tree view to dir view.
  7567. // foMove happens when file/dir is dragged from remote tree view outside of
  7568. // application via dragex
  7569. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7570. (DropSourceControl == RemoteDriveView))
  7571. {
  7572. RemoteDriveView->UpdateDropSource();
  7573. }
  7574. return Result;
  7575. }
  7576. //---------------------------------------------------------------------------
  7577. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7578. {
  7579. DebugAssert(!IsLocalBrowserMode());
  7580. // This also handles drops of remote files to queue.
  7581. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7582. SAFE_DESTROY(FDDFileList);
  7583. if (!FFakeFileDropTarget.IsEmpty())
  7584. {
  7585. RemoveDir(ApiPath(FFakeFileDropTarget));
  7586. }
  7587. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7588. {
  7589. try
  7590. {
  7591. TDragResult DDResult = (Sender == RemoteDirView) ?
  7592. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7593. // Focus is moved to the target application,
  7594. // but as we are going to present the UI, we need to steal the focus back.
  7595. // This most likely won't work though (windows does not allow application
  7596. // to steal focus most of the time)
  7597. Application->BringToFront();
  7598. // On older version of Windows we never got drMove here, see also comment below.
  7599. // On Windows 10, we get the "move".
  7600. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7601. {
  7602. UnicodeString TargetDirectory;
  7603. TFileOperation Operation;
  7604. // drInvalid may mean drMove, see comment below
  7605. switch (DDResult)
  7606. {
  7607. case drCopy:
  7608. Operation = foCopy;
  7609. break;
  7610. case drMove:
  7611. Operation = foMove;
  7612. break;
  7613. default:
  7614. DebugFail();
  7615. case drInvalid:
  7616. // prefer "copy" for safety
  7617. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7618. break;
  7619. }
  7620. TTransferOperationParam Param;
  7621. UnicodeString CounterName;
  7622. bool ForceQueue;
  7623. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7624. {
  7625. // we get drInvalid both if d&d was intercepted by ddext,
  7626. // and when users drops on no-drop location.
  7627. // we tell the difference by existence of response from ddext,
  7628. // so we ignore absence of response in this case
  7629. if (DDResult != drInvalid)
  7630. {
  7631. // here we know that the extension is installed,
  7632. // as it is checked as soon as drag&drop starts from
  7633. // RemoteFileControlDDCreateDragFileList
  7634. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7635. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7636. {
  7637. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7638. }
  7639. else
  7640. {
  7641. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7642. }
  7643. }
  7644. }
  7645. else
  7646. {
  7647. // download using fake file
  7648. Param.Temp = false;
  7649. Param.DragDrop = true;
  7650. if (ForceQueue)
  7651. {
  7652. Param.Queue = asOn;
  7653. }
  7654. if (Sender == RemoteDirView)
  7655. {
  7656. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7657. }
  7658. if (RemoteFileControlFileOperation(Sender, Operation,
  7659. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7660. {
  7661. Configuration->Usage->Inc(CounterName);
  7662. }
  7663. }
  7664. }
  7665. }
  7666. __finally
  7667. {
  7668. CloseHandle(FDDExtMapFile);
  7669. FDDExtMapFile = NULL;
  7670. delete FDragFakeMonitors;
  7671. FDragFakeMonitors = NULL;
  7672. RemoveDir(ApiPath(FDragFakeDirectory));
  7673. FDragFakeDirectory = L"";
  7674. FFakeFileDropTarget = UnicodeString();
  7675. }
  7676. }
  7677. if (FDragDropSshTerminate.get() != NULL)
  7678. {
  7679. FDragDropSshTerminate->Rethrow();
  7680. }
  7681. }
  7682. //---------------------------------------------------------------------------
  7683. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7684. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7685. {
  7686. // Remember drop effect so we know (when user drops files), if we copy or move
  7687. FLastDropEffect = dwEffect;
  7688. }
  7689. //---------------------------------------------------------------------------
  7690. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7691. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7692. {
  7693. bool Result;
  7694. if (FDDTargetControl == QueueView3)
  7695. {
  7696. Directory = DefaultDownloadTargetDirectory();
  7697. Result = true;
  7698. CounterName = L"DownloadsDragDropQueue";
  7699. ForceQueue = true;
  7700. }
  7701. else if (!FFakeFileDropTarget.IsEmpty())
  7702. {
  7703. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7704. Result = true;
  7705. ForceQueue = false;
  7706. CounterName = L"DownloadsDragDropFakeFile";
  7707. }
  7708. else
  7709. {
  7710. ForceQueue = false;
  7711. Enabled = false;
  7712. try
  7713. {
  7714. int Timer = 0;
  7715. Result = false;
  7716. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7717. {
  7718. {
  7719. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7720. TDragExtCommStruct* CommStruct;
  7721. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7722. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7723. DebugAssert(CommStruct != NULL);
  7724. Result = !CommStruct->Dragging;
  7725. if (Result)
  7726. {
  7727. Directory = ExtractFilePath(CommStruct->DropDest);
  7728. CounterName = L"DownloadsDragDropExternalExt";
  7729. }
  7730. UnmapViewOfFile(CommStruct);
  7731. }
  7732. if (!Result)
  7733. {
  7734. Sleep(50);
  7735. Timer += 50;
  7736. Application->ProcessMessages();
  7737. }
  7738. }
  7739. }
  7740. __finally
  7741. {
  7742. Enabled = true;
  7743. }
  7744. }
  7745. return Result;
  7746. }
  7747. //---------------------------------------------------------------------------
  7748. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7749. const UnicodeString TempDir, int SecDelay)
  7750. {
  7751. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7752. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7753. if (FDelayedDeletionTimer == NULL)
  7754. {
  7755. DebugAssert(HandleAllocated());
  7756. FDelayedDeletionTimer = new TTimer(this);
  7757. FDelayedDeletionTimer->Interval = 10000;
  7758. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7759. }
  7760. else
  7761. {
  7762. FDelayedDeletionTimer->Enabled = true;
  7763. }
  7764. }
  7765. //---------------------------------------------------------------------------
  7766. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7767. {
  7768. DebugAssert(FDelayedDeletionList != NULL);
  7769. TDateTime N = Now();
  7770. TDateTime Alert;
  7771. UnicodeString Directory;
  7772. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7773. {
  7774. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7775. if ((N >= Alert) || (Sender == NULL))
  7776. {
  7777. Directory = FDelayedDeletionList->Strings[Index];
  7778. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7779. {
  7780. FDelayedDeletionList->Delete(Index);
  7781. }
  7782. }
  7783. }
  7784. if (FDelayedDeletionList->Count == 0)
  7785. {
  7786. FDelayedDeletionTimer->Enabled = false;
  7787. }
  7788. }
  7789. //---------------------------------------------------------------------------
  7790. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7791. {
  7792. DebugAssert(!IsLocalBrowserMode());
  7793. if (IsFileControl(FDDTargetControl, osRemote) ||
  7794. (FDDTargetControl == SessionsPageControl))
  7795. {
  7796. TManagedTerminal * TargetTerminal = NULL;
  7797. TFileOperation Operation = foNone;
  7798. if (FDDTargetControl == SessionsPageControl)
  7799. {
  7800. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7801. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7802. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7803. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7804. if (IsActiveTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7805. {
  7806. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7807. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7808. {
  7809. Operation = foRemoteMove;
  7810. }
  7811. else
  7812. {
  7813. Operation = foRemoteCopy;
  7814. }
  7815. }
  7816. }
  7817. else
  7818. {
  7819. if (FLastDropEffect == DROPEFFECT_MOVE)
  7820. {
  7821. Operation = foRemoteMove;
  7822. }
  7823. else if (FLastDropEffect == DROPEFFECT_COPY)
  7824. {
  7825. Operation = foRemoteCopy;
  7826. }
  7827. }
  7828. if (Operation != foNone)
  7829. {
  7830. RemoteFileControlFileOperation(DropSourceControl,
  7831. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7832. }
  7833. // abort drag&drop
  7834. Abort();
  7835. }
  7836. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7837. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7838. (FDDTargetControl != QueueView3))
  7839. {
  7840. DebugAssert(!FDragTempDir.IsEmpty());
  7841. TTransferType Type;
  7842. UnicodeString TempDir = FDragTempDir;
  7843. // We clear FDragTempDir before calling
  7844. // just in case it fail (raises exception)
  7845. FDragTempDir = L"";
  7846. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7847. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7848. // empty directory parameter means temp directory -> don't display it!
  7849. UnicodeString TargetDir = L"";
  7850. int Options = 0;
  7851. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7852. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7853. {
  7854. Abort();
  7855. }
  7856. // TargetDir is set when dropped on local file control
  7857. // (this was workaround for legacy dirview event handling, now it should be
  7858. // made prettier)
  7859. if (TargetDir.IsEmpty())
  7860. {
  7861. TargetDir = TempDir;
  7862. if (ForceDirectories(ApiPath(TargetDir)))
  7863. {
  7864. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7865. FPendingTempSpaceWarn = true;
  7866. try
  7867. {
  7868. FDragDropOperation = true;
  7869. int Params = cpTemporary |
  7870. (Type == ttMove ? cpDelete : 0);
  7871. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7872. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7873. }
  7874. __finally
  7875. {
  7876. FDragDropOperation = false;
  7877. FPendingTempSpaceWarn = false;
  7878. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7879. }
  7880. }
  7881. else
  7882. {
  7883. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7884. }
  7885. }
  7886. }
  7887. }
  7888. //---------------------------------------------------------------------------
  7889. void __fastcall TCustomScpExplorerForm::DDDownload(
  7890. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7891. {
  7892. DebugAssert(!IsLocalBrowserMode());
  7893. TAutoBatch AutoBatch(this);
  7894. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7895. UpdateCopyParamCounters(*CopyParam);
  7896. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7897. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7898. {
  7899. RemoteDriveView->UpdateDropSource();
  7900. }
  7901. }
  7902. //---------------------------------------------------------------------------
  7903. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7904. {
  7905. public:
  7906. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7907. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7908. {
  7909. }
  7910. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7911. {
  7912. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7913. TDataObjectFilesEx::AllowData(FormatEtc);
  7914. }
  7915. };
  7916. //---------------------------------------------------------------------------
  7917. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7918. TObject * Sender, TDataObject *& DataObject)
  7919. {
  7920. if (FDDExtMapFile != NULL)
  7921. {
  7922. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7923. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7924. {
  7925. Abort();
  7926. }
  7927. if (FileList->Count > 0)
  7928. {
  7929. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7930. if (!FilesObject->IsValid(true, true))
  7931. {
  7932. FilesObject->_Release();
  7933. }
  7934. else
  7935. {
  7936. DataObject = FilesObject;
  7937. }
  7938. }
  7939. }
  7940. }
  7941. //---------------------------------------------------------------------------
  7942. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7943. {
  7944. DebugFail();
  7945. }
  7946. //---------------------------------------------------------------------------
  7947. void __fastcall TCustomScpExplorerForm::GoToTree()
  7948. {
  7949. ComponentVisible[fcRemoteTree] = true;
  7950. DriveView(osRemote)->SetFocus();
  7951. }
  7952. //---------------------------------------------------------------------------
  7953. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7954. TPanelExport Export)
  7955. {
  7956. TCustomDirView * DirView = this->DirView(Side);
  7957. std::unique_ptr<TStrings> ExportData(new TStringList());
  7958. switch (Export)
  7959. {
  7960. case pePath:
  7961. ExportData->Add(DirView->PathName);
  7962. break;
  7963. case peFileList:
  7964. case peFullFileList:
  7965. {
  7966. bool FullPath = (Export == peFullFileList);
  7967. DirView->CreateFileList(false, FullPath, ExportData.get());
  7968. for (int Index = 0; Index < ExportData->Count; Index++)
  7969. {
  7970. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7971. {
  7972. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7973. }
  7974. }
  7975. }
  7976. break;
  7977. default:
  7978. DebugFail();
  7979. }
  7980. return ExportData.release();
  7981. }
  7982. //---------------------------------------------------------------------------
  7983. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7984. TPanelExport Export, TPanelExportDestination Destination)
  7985. {
  7986. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7987. PanelExportStore(Side, Export, Destination, ExportData.get());
  7988. }
  7989. //---------------------------------------------------------------------------
  7990. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  7991. TPanelExport /*Export*/, TPanelExportDestination Destination,
  7992. TStrings * ExportData)
  7993. {
  7994. if (Destination == pedClipboard)
  7995. {
  7996. TInstantOperationVisualizer Visualizer;
  7997. CopyToClipboard(ExportData);
  7998. }
  7999. else
  8000. {
  8001. DebugFail();
  8002. }
  8003. }
  8004. //---------------------------------------------------------------------------
  8005. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  8006. {
  8007. TCustomDirView * DirView = this->DirView(Side);
  8008. UnicodeString Mask = DirView->Mask;
  8009. if (DoFilterMaskDialog(DirView, Mask))
  8010. {
  8011. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  8012. Configuration->Usage->Inc(L"Filters");
  8013. }
  8014. }
  8015. //---------------------------------------------------------------------------
  8016. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  8017. {
  8018. return FQueueController->DefaultOperation();
  8019. }
  8020. //---------------------------------------------------------------------------
  8021. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  8022. TQueueOperation Operation, void ** Param)
  8023. {
  8024. switch (Operation)
  8025. {
  8026. case qoPreferences:
  8027. return true;
  8028. case qoGoTo:
  8029. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  8030. case qoOnceEmpty:
  8031. return IsAnythingQueued();
  8032. default:
  8033. return FQueueController->AllowOperation(Operation, Param);
  8034. }
  8035. }
  8036. //---------------------------------------------------------------------------
  8037. void __fastcall TCustomScpExplorerForm::GoToQueue()
  8038. {
  8039. if (DebugAlwaysTrue(QueueView3->Visible))
  8040. {
  8041. QueueView3->SetFocus();
  8042. }
  8043. }
  8044. //---------------------------------------------------------------------------
  8045. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  8046. TQueueOperation Operation, void * Param)
  8047. {
  8048. if (Operation == qoGoTo)
  8049. {
  8050. GoToQueue();
  8051. }
  8052. else if (Operation == qoPreferences)
  8053. {
  8054. PreferencesDialog(pmQueue);
  8055. }
  8056. else
  8057. {
  8058. FQueueController->ExecuteOperation(Operation, Param);
  8059. }
  8060. }
  8061. //---------------------------------------------------------------------------
  8062. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  8063. {
  8064. return (Queue != NULL) && Queue->Enabled;
  8065. }
  8066. //---------------------------------------------------------------------------
  8067. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8068. {
  8069. DebugAssert(Queue != NULL);
  8070. if (Queue != NULL)
  8071. {
  8072. Queue->Enabled = !Queue->Enabled;
  8073. }
  8074. }
  8075. //---------------------------------------------------------------------------
  8076. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8077. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8078. {
  8079. FQueueActedItem = QueueView3->ItemFocused;
  8080. }
  8081. //---------------------------------------------------------------------------
  8082. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8083. {
  8084. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8085. }
  8086. //---------------------------------------------------------------------------
  8087. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8088. {
  8089. return
  8090. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8091. (QueueDock->Visible ? QueueDock->Height : 0) +
  8092. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8093. }
  8094. //---------------------------------------------------------------------------
  8095. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8096. {
  8097. return ScaleByTextHeight(this, 48);
  8098. }
  8099. //---------------------------------------------------------------------------
  8100. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8101. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8102. {
  8103. // when queue is hidden by double-clicking splitter, stray attempt to
  8104. // resize the panel with strange value arrives, make sure it is ignored
  8105. if (ComponentVisible[fcQueueView])
  8106. {
  8107. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8108. if (NewSize > MaxHeightLimit)
  8109. {
  8110. NewSize = MaxHeightLimit;
  8111. }
  8112. int MinHeightLimit =
  8113. GetStaticQueuePanelComponentsHeight() +
  8114. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8115. GetMinQueueViewHeight();
  8116. if (NewSize < MinHeightLimit)
  8117. {
  8118. NewSize = MinHeightLimit;
  8119. }
  8120. }
  8121. else
  8122. {
  8123. Accept = false;
  8124. }
  8125. }
  8126. //---------------------------------------------------------------------------
  8127. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8128. {
  8129. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8130. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8131. if (QueueViewHeight < GetMinQueueViewHeight())
  8132. {
  8133. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8134. }
  8135. }
  8136. //---------------------------------------------------------------------------
  8137. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8138. TDragObject *& /*DragObject*/)
  8139. {
  8140. FQueueActedItem = QueueView3->ItemFocused;
  8141. FQueueScrollOnDragOver->StartDrag();
  8142. }
  8143. //---------------------------------------------------------------------------
  8144. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8145. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8146. {
  8147. FQueueScrollOnDragOver->EndDrag();
  8148. }
  8149. //---------------------------------------------------------------------------
  8150. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8151. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8152. {
  8153. Accept = true;
  8154. if (Source == QueueView3)
  8155. {
  8156. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8157. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8158. if (Accept)
  8159. {
  8160. TQueueItemProxy * QueueItem;
  8161. TQueueItemProxy * DestQueueItem;
  8162. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8163. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8164. Accept = (QueueItem != DestQueueItem) &&
  8165. (QueueItem->Status == TQueueItem::qsPending) &&
  8166. (DestQueueItem->Status == TQueueItem::qsPending);
  8167. }
  8168. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8169. }
  8170. }
  8171. //---------------------------------------------------------------------------
  8172. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8173. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8174. {
  8175. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8176. {
  8177. TQueueItemProxy * QueueItem;
  8178. TQueueItemProxy * DestQueueItem;
  8179. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8180. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8181. QueueItem->Move(DestQueueItem);
  8182. }
  8183. }
  8184. //---------------------------------------------------------------------------
  8185. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8186. {
  8187. if ((QueueView3->ItemFocused == NULL) &&
  8188. (QueueView3->Items->Count > 0))
  8189. {
  8190. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8191. }
  8192. QueueLabelUpdateStatus();
  8193. }
  8194. //---------------------------------------------------------------------------
  8195. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8196. {
  8197. QueueLabelUpdateStatus();
  8198. }
  8199. //---------------------------------------------------------------------------
  8200. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8201. {
  8202. QueueLabel->UpdateStatus();
  8203. }
  8204. //---------------------------------------------------------------------------
  8205. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8206. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8207. {
  8208. if (Selected)
  8209. {
  8210. NonVisualDataModule->UpdateNonVisibleActions();
  8211. }
  8212. }
  8213. //---------------------------------------------------------------------------
  8214. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8215. {
  8216. TDragDropFilesEx * Result = NULL;
  8217. if (Sender == SessionsPageControl)
  8218. {
  8219. Result = FSessionsDragDropFilesEx;
  8220. }
  8221. else if (Sender == QueueView3)
  8222. {
  8223. Result = FQueueDragDropFilesEx;
  8224. }
  8225. else
  8226. {
  8227. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8228. if (DirView != NULL)
  8229. {
  8230. Result = DirView->DragDropFilesEx;
  8231. }
  8232. else
  8233. {
  8234. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8235. if (DriveView != NULL)
  8236. {
  8237. Result = DriveView->DragDropFilesEx;
  8238. }
  8239. }
  8240. }
  8241. DebugAssert(Result != NULL);
  8242. return Result;
  8243. }
  8244. //---------------------------------------------------------------------------
  8245. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8246. {
  8247. return (DView->SelCount == DView->FilesCount);
  8248. }
  8249. //---------------------------------------------------------------------------
  8250. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8251. {
  8252. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8253. }
  8254. //---------------------------------------------------------------------------
  8255. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8256. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8257. {
  8258. DebugAssert(!IsLocalBrowserMode());
  8259. TFileOperation Operation;
  8260. switch (Effect)
  8261. {
  8262. case DROPEFFECT_MOVE:
  8263. Operation = foMove;
  8264. break;
  8265. case DROPEFFECT_COPY:
  8266. // occures on WinXP (reported by user)
  8267. default:
  8268. Operation = foCopy;
  8269. break;
  8270. };
  8271. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8272. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8273. if (DragDropFilesEx->FileList->Count > 0)
  8274. {
  8275. TStrings * FileList = new TStringList();
  8276. try
  8277. {
  8278. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8279. {
  8280. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8281. }
  8282. FDragDropOperation = true;
  8283. TTransferOperationParam Param;
  8284. Param.TargetDirectory = TargetPath;
  8285. // upload, no temp dirs
  8286. Param.Temp = false;
  8287. Param.DragDrop = DragDrop;
  8288. Param.Options =
  8289. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8290. if (ForceQueue)
  8291. {
  8292. Param.Queue = asOn;
  8293. }
  8294. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8295. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8296. {
  8297. if (IsFileControl(DropSourceControl, osLocal))
  8298. {
  8299. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8300. }
  8301. else
  8302. {
  8303. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8304. }
  8305. }
  8306. }
  8307. __finally
  8308. {
  8309. FDragDropOperation = false;
  8310. delete FileList;
  8311. }
  8312. }
  8313. }
  8314. //---------------------------------------------------------------------------
  8315. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8316. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8317. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8318. {
  8319. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8320. }
  8321. //---------------------------------------------------------------------------
  8322. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8323. TObject * Sender, int grfKeyState, int & dwEffect)
  8324. {
  8325. DebugAssert(!IsLocalBrowserMode());
  8326. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8327. if ((dwEffect != DROPEFFECT_NONE) &&
  8328. IsFileControl(DropSourceControl, osRemote))
  8329. {
  8330. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8331. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8332. (RemoteDirView->DropTarget == NULL))
  8333. {
  8334. dwEffect = DROPEFFECT_NONE;
  8335. }
  8336. else
  8337. {
  8338. if (dwEffect == DROPEFFECT_COPY)
  8339. {
  8340. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8341. // currently we support copying always (at least via temporary directory);
  8342. // remove associated checks once this all proves stable and working
  8343. bool CopyCapable = true;
  8344. // if we do not support neither of operations, there's no discussion
  8345. if (!MoveCapable && !CopyCapable)
  8346. {
  8347. dwEffect = DROPEFFECT_NONE;
  8348. }
  8349. else
  8350. {
  8351. // The default effect inside remote panel is move,
  8352. // unless we do not support it, but support copy
  8353. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8354. {
  8355. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8356. }
  8357. else
  8358. {
  8359. // with ctrl-down, we want copy unless it is not supported
  8360. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8361. }
  8362. }
  8363. }
  8364. }
  8365. }
  8366. }
  8367. //---------------------------------------------------------------------------
  8368. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8369. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8370. {
  8371. DebugAssert(!IsLocalBrowserMode());
  8372. if (FDDTotalSize >= 0)
  8373. {
  8374. if (File->IsDirectory)
  8375. {
  8376. FDDTotalSize = -1;
  8377. }
  8378. else
  8379. {
  8380. FDDTotalSize += File->Size;
  8381. }
  8382. }
  8383. DebugAssert(!FDragTempDir.IsEmpty());
  8384. // TODO: this is quite ineffective
  8385. // TODO: what if invalid character replacement is disabled?
  8386. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8387. UnicodeString TransferFileName;
  8388. if (Sender == RemoteDriveView)
  8389. {
  8390. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8391. }
  8392. else
  8393. {
  8394. TransferFileName = File->FileName;
  8395. }
  8396. FDDFileList->AddObject(TransferFileName, File);
  8397. }
  8398. //---------------------------------------------------------------------------
  8399. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8400. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8401. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8402. {
  8403. // sometimes we do not get DDEnd so the list is not released
  8404. SAFE_DESTROY(FDDFileList);
  8405. FDDFileList = new TStringList();
  8406. FDragTempDir = WinConfiguration->TemporaryDir();
  8407. FDDTotalSize = 0;
  8408. FDragDropSshTerminate.reset(NULL);
  8409. }
  8410. //---------------------------------------------------------------------------
  8411. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8412. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  8413. HRESULT & Result)
  8414. {
  8415. if (Result == DRAGDROP_S_DROP)
  8416. {
  8417. try
  8418. {
  8419. GlobalDragImageList->HideDragImage();
  8420. try
  8421. {
  8422. RemoteFileControlDDTargetDrop();
  8423. }
  8424. catch(ESshTerminate & E)
  8425. {
  8426. FDragDropSshTerminate.reset(E.Clone());
  8427. }
  8428. }
  8429. catch (Exception &E)
  8430. {
  8431. // If downloading fails we need to cancel drag&drop, otherwise
  8432. // Explorer shows error
  8433. // But by the way exception probably never reach this point as
  8434. // it's catched on way.
  8435. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8436. Result = DRAGDROP_S_CANCEL;
  8437. ShowExtendedException(Terminal, &E);
  8438. }
  8439. }
  8440. }
  8441. //---------------------------------------------------------------------------
  8442. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8443. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8444. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8445. {
  8446. TFileMasks::TParams MaskParams;
  8447. MaskParams.Size = Size;
  8448. MaskParams.Modification = Modification;
  8449. // this does not re-parse the mask if it is the same as the last time
  8450. FDirViewMatchMask = Masks;
  8451. bool ImplicitMatch;
  8452. Matches =
  8453. // Local and RecurseInclude parameters have no effect as there's no path.
  8454. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8455. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8456. (AllowImplicitMatches || !ImplicitMatch);
  8457. }
  8458. //---------------------------------------------------------------------------
  8459. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8460. TObject * Sender, TListItem * Item, WORD & Indexes)
  8461. {
  8462. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8463. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8464. {
  8465. Indexes |= oiPartial;
  8466. }
  8467. }
  8468. //---------------------------------------------------------------------------
  8469. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8470. {
  8471. return
  8472. DirViewEnabled(osCurrent) &&
  8473. DirView(osCurrent)->CanPasteFromClipBoard();
  8474. }
  8475. //---------------------------------------------------------------------------
  8476. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8477. {
  8478. bool Result = false;
  8479. if (CanPasteToDirViewFromClipBoard())
  8480. {
  8481. Result = true;
  8482. }
  8483. else
  8484. {
  8485. UnicodeString ClipboardText;
  8486. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8487. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8488. {
  8489. if (StoredSessions->IsUrl(ClipboardText))
  8490. {
  8491. Result = true;
  8492. }
  8493. else
  8494. {
  8495. Result = DirViewEnabled(osCurrent);
  8496. }
  8497. }
  8498. }
  8499. return Result;
  8500. }
  8501. //---------------------------------------------------------------------------
  8502. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8503. {
  8504. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8505. if (DoesClipboardContainOurFiles())
  8506. {
  8507. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8508. {
  8509. DebugAssert(!IsLocalBrowserMode());
  8510. TTerminalManager * Manager = TTerminalManager::Instance();
  8511. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8512. Manager->ActiveSession = FClipboardTerminal;
  8513. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8514. }
  8515. }
  8516. else if (CanPasteToDirViewFromClipBoard())
  8517. {
  8518. DirView(osCurrent)->PasteFromClipBoard();
  8519. }
  8520. else
  8521. {
  8522. UnicodeString ClipboardText;
  8523. if (NonEmptyTextFromClipboard(ClipboardText))
  8524. {
  8525. if (StoredSessions->IsUrl(ClipboardText))
  8526. {
  8527. NewSession(ClipboardText);
  8528. }
  8529. else
  8530. {
  8531. DirView(osCurrent)->Path = ClipboardText;
  8532. }
  8533. }
  8534. }
  8535. }
  8536. //---------------------------------------------------------------------------
  8537. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8538. {
  8539. // TBD
  8540. }
  8541. //---------------------------------------------------------------------------
  8542. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8543. {
  8544. TCustomDirView * ADirView = DirView(Side);
  8545. ADirView->SelectAll(Mode);
  8546. ADirView->SetFocus();
  8547. }
  8548. //---------------------------------------------------------------------------
  8549. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8550. {
  8551. TCustomDirView * ADirView = DirView(Side);
  8552. TFileFilter Filter;
  8553. DefaultFileFilter(Filter);
  8554. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8555. {
  8556. Configuration->Usage->Inc(L"MaskSelections");
  8557. ADirView->SelectFiles(Filter, Select);
  8558. ADirView->SetFocus();
  8559. }
  8560. }
  8561. //---------------------------------------------------------------------------
  8562. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8563. {
  8564. TCustomDirView * ADirView = DirView(Side);
  8565. ADirView->RestoreSelectedNames();
  8566. ADirView->SetFocus();
  8567. }
  8568. //---------------------------------------------------------------------------
  8569. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8570. {
  8571. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8572. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8573. {
  8574. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8575. UnicodeString Ext;
  8576. if (!IsSideLocalBrowser(osCurrent))
  8577. {
  8578. Ext = UnixExtractFileExt(FileName);
  8579. }
  8580. else
  8581. {
  8582. Ext = ExtractFileExt(FileName);
  8583. }
  8584. if (Ext.IsEmpty())
  8585. {
  8586. Ext = L".";
  8587. }
  8588. TFileFilter Filter;
  8589. Filter.Masks = FORMAT(L"*%s", (Ext));
  8590. Filter.Directories = false;
  8591. CurrentDirView->SelectFiles(Filter, Select);
  8592. }
  8593. }
  8594. //---------------------------------------------------------------------------
  8595. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8596. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8597. {
  8598. UnicodeString Result;
  8599. if (FIncrementalSearchState.Searching && (Side == GetSide(osCurrent)))
  8600. {
  8601. Result = FormatIncrementalSearchStatus(FIncrementalSearchState);
  8602. }
  8603. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8604. {
  8605. // noop
  8606. }
  8607. else
  8608. {
  8609. Result =
  8610. FMTLOAD(FILE_INFO_FORMAT,
  8611. (FormatBytes(FileInfo.SelectedSize),
  8612. FormatBytes(FileInfo.FilesSize),
  8613. FormatNumber(FileInfo.SelectedCount),
  8614. FormatNumber(FileInfo.FilesCount)));
  8615. }
  8616. return Result;
  8617. }
  8618. //---------------------------------------------------------------------------
  8619. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8620. TTBXStatusPanel * Panel, TOperationSide Side)
  8621. {
  8622. if (Panel->Index == 1)
  8623. {
  8624. ToggleShowHiddenFiles();
  8625. }
  8626. else if (Panel->Index == 2)
  8627. {
  8628. Filter(Side);
  8629. }
  8630. }
  8631. //---------------------------------------------------------------------------
  8632. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8633. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8634. {
  8635. DebugAssert(!StatusBar->SimplePanel);
  8636. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8637. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8638. }
  8639. //---------------------------------------------------------------------------
  8640. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8641. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8642. {
  8643. DebugAssert(StatusBar->Panels->Count >= 3);
  8644. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8645. if (FileInfo.HiddenCount > 0)
  8646. {
  8647. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8648. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8649. }
  8650. else
  8651. {
  8652. HiddenFilesPanel->ViewPriority = 0;
  8653. // not really necessary, just to cleanup no-longer-valid data
  8654. HiddenFilesPanel->Caption = L"";
  8655. }
  8656. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8657. if (FileInfo.FilteredCount > 0)
  8658. {
  8659. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8660. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8661. }
  8662. else
  8663. {
  8664. FilteredFilesPanel->ViewPriority = 0;
  8665. // not really necessary, just to cleanup no-longer-valid data
  8666. FilteredFilesPanel->Caption = L"";
  8667. }
  8668. }
  8669. //---------------------------------------------------------------------------
  8670. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8671. TObject * /*Sender*/)
  8672. {
  8673. if (DirView(osOther)->Enabled)
  8674. {
  8675. DirView(osOther)->SetFocus();
  8676. }
  8677. }
  8678. //---------------------------------------------------------------------------
  8679. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8680. {
  8681. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8682. switch (Config.Show)
  8683. {
  8684. case qvShow:
  8685. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8686. {
  8687. Config.Show = qvHide;
  8688. }
  8689. else
  8690. {
  8691. Config.Show = Config.LastHideShow;
  8692. }
  8693. break;
  8694. case qvHideWhenEmpty:
  8695. if (ComponentVisible[fcQueueView])
  8696. {
  8697. Config.Show = qvHide;
  8698. }
  8699. else
  8700. {
  8701. Config.LastHideShow = Config.Show;
  8702. Config.Show = qvShow;
  8703. }
  8704. break;
  8705. case qvHide:
  8706. Config.LastHideShow = Config.Show;
  8707. Config.Show = qvShow;
  8708. break;
  8709. }
  8710. WinConfiguration->QueueView = Config;
  8711. }
  8712. //---------------------------------------------------------------------------
  8713. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8714. {
  8715. UnicodeString Result;
  8716. if (Terminal != NULL)
  8717. {
  8718. switch (WinConfiguration->PathInCaption)
  8719. {
  8720. case picShort:
  8721. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8722. break;
  8723. case picFull:
  8724. Result = Terminal->CurrentDirectory;
  8725. break;
  8726. }
  8727. }
  8728. return Result;
  8729. }
  8730. //---------------------------------------------------------------------------
  8731. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8732. {
  8733. TColor Result = GetWindowColor(FSessionColor);
  8734. return Result;
  8735. }
  8736. //---------------------------------------------------------------------------
  8737. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8738. {
  8739. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8740. return Result;
  8741. }
  8742. //---------------------------------------------------------------------------
  8743. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8744. {
  8745. if (!FSessionChanging)
  8746. {
  8747. TTerminalManager::Instance()->UpdateAppTitle();
  8748. }
  8749. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8750. // background to gray on Windows 7 (works on Windows 10).
  8751. // See also EnableControl
  8752. if (Showing)
  8753. {
  8754. if (ManagedSession != NULL)
  8755. {
  8756. // Update path when it changes
  8757. if ((SessionsPageControl->ActivePage != NULL) &&
  8758. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8759. {
  8760. UpdateSessionTab(SessionsPageControl->ActivePage);
  8761. }
  8762. }
  8763. NonVisualDataModule->ReconnectSessionAction->Update();
  8764. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8765. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8766. CenterReconnectToolbar();
  8767. bool HasTerminal = HasActiveTerminal();
  8768. RemoteDirView->Enabled = HasTerminal;
  8769. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8770. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8771. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8772. RemoteDriveView->Color = RemoteDirView->Color;
  8773. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8774. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8775. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8776. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8777. QueueFileList->Enabled = QueueView3->Enabled;
  8778. QueueFileList->Color = QueueView3->Color;
  8779. QueueFileList->Font->Color = QueueView3->Font->Color;
  8780. QueueLabelUpdateStatus();
  8781. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8782. RemoteDirView->DarkMode = UseDarkTheme;
  8783. RemoteDriveView->DarkMode = RemoteDirView->DarkMode;
  8784. if (FImmersiveDarkMode != UseDarkTheme)
  8785. {
  8786. UpdateDarkMode();
  8787. }
  8788. SessionsPageControl->TabTheme = UseDarkTheme ? CurrentTheme : NULL;
  8789. UnicodeString CurrentHiContrastThemeName = (FHiContrastTheme != NULL) ? FHiContrastTheme->Name : EmptyStr;
  8790. bool HiContrast = WinConfiguration->HiContrast;
  8791. UnicodeString NewHiContrastThemeName = HiContrast ? GetThemeName(!UseDarkTheme) : EmptyStr;
  8792. if (CurrentHiContrastThemeName != NewHiContrastThemeName)
  8793. {
  8794. ReleaseHiContrastTheme();
  8795. if (!NewHiContrastThemeName.IsEmpty())
  8796. {
  8797. FHiContrastTheme = GetTBXTheme(NewHiContrastThemeName);
  8798. }
  8799. }
  8800. SessionsPageControl->ActiveTabTheme = HiContrast ? DebugNotNull(FHiContrastTheme) : NULL;
  8801. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8802. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8803. }
  8804. }
  8805. //---------------------------------------------------------------------------
  8806. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8807. {
  8808. UpdateControls();
  8809. }
  8810. //---------------------------------------------------------------------------
  8811. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8812. TObject * Sender)
  8813. {
  8814. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8815. DebugAssert(DirView != NULL);
  8816. DoDirViewLoaded(DirView);
  8817. TransferPresetAutoSelect();
  8818. }
  8819. //---------------------------------------------------------------------------
  8820. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8821. {
  8822. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8823. // first run after installation
  8824. if (double(Updates.LastCheck) == 0)
  8825. {
  8826. AppLog(L"First run, scheduling updates check for the next run");
  8827. // make sure next time there will be an update (if enabled)
  8828. Updates.LastCheck = TDateTime(1);
  8829. WinConfiguration->Updates = Updates;
  8830. }
  8831. else
  8832. {
  8833. TDateTime Period;
  8834. if (IsUWP() && !IsOfficialPackage())
  8835. {
  8836. Period = DefaultUpdatesPeriod;
  8837. AppLog(L"Thirdparty UWP package, using default updates check period");
  8838. }
  8839. else
  8840. {
  8841. Period = Updates.Period;
  8842. }
  8843. AppLogFmt(L"Updates check period: %.2f", (double(Period)));
  8844. if (double(Period) > 0)
  8845. {
  8846. TDateTime Interval = Now() - Updates.LastCheck;
  8847. AppLogFmt(L"Interval since the last updates check: %.2f", (double(Interval)));
  8848. if (Interval >= Period)
  8849. {
  8850. StartUpdateThread(UpdatesChecked);
  8851. }
  8852. }
  8853. }
  8854. }
  8855. //---------------------------------------------------------------------------
  8856. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8857. {
  8858. AppLog(L"Updates check done");
  8859. UnicodeString Message;
  8860. bool New;
  8861. TQueryType Type;
  8862. GetUpdatesMessage(Message, New, Type, false);
  8863. if (!Message.IsEmpty())
  8864. {
  8865. AppLogFmt(L"Updates check message: %s", (Message));
  8866. if (New)
  8867. {
  8868. AppLog(L"New version detected");
  8869. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8870. }
  8871. if (!New && (Type != qtWarning))
  8872. {
  8873. AppLog(L"Posting non-critical updates note");
  8874. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  8875. }
  8876. else
  8877. {
  8878. AppLog(L"Posting new version or critical message notification");
  8879. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8880. }
  8881. if (New)
  8882. {
  8883. Configuration->Usage->Inc(L"UpdateNotifications");
  8884. }
  8885. }
  8886. }
  8887. //---------------------------------------------------------------------------
  8888. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8889. {
  8890. RestoreApp();
  8891. bool CanDisplay = !NonVisualDataModule->Busy;
  8892. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8893. {
  8894. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8895. }
  8896. if (CanDisplay)
  8897. {
  8898. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8899. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  8900. NonVisualDataModule->StartBusy();
  8901. try
  8902. {
  8903. CheckForUpdates(true);
  8904. }
  8905. __finally
  8906. {
  8907. NonVisualDataModule->EndBusy();
  8908. }
  8909. }
  8910. else
  8911. {
  8912. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  8913. }
  8914. }
  8915. //---------------------------------------------------------------------------
  8916. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  8917. TCopyParamRuleData & Data)
  8918. {
  8919. DebugAssert(Terminal != NULL);
  8920. Data.HostName = Terminal->SessionData->HostNameExpanded;
  8921. Data.UserName = Terminal->SessionData->UserNameExpanded;
  8922. Data.RemoteDirectory = RemoteDirView->PathName;
  8923. }
  8924. //---------------------------------------------------------------------------
  8925. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  8926. {
  8927. // Terminal can be null when we are changing local directory implicitly,
  8928. // because it has been deleted, while no session is connected
  8929. // (Login dialog is open)
  8930. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  8931. {
  8932. DebugAssert(!IsLocalBrowserMode());
  8933. TCopyParamRuleData Data;
  8934. GetTransferPresetAutoSelectData(Data);
  8935. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  8936. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  8937. if (CopyParamIndex < 0)
  8938. {
  8939. // there is no preset that matches autoselection
  8940. // set preset that we consider "default"
  8941. FCopyParamAutoSelected = L""; // forget last autoselected preset
  8942. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  8943. }
  8944. else
  8945. {
  8946. // there is preset matching autoselection
  8947. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  8948. if (CopyParamName == FCopyParamAutoSelected)
  8949. {
  8950. // autoselected the same preset as the last time
  8951. // make no change (i.e. preserve custom user preset, if any)
  8952. }
  8953. else
  8954. {
  8955. // autoselected the different preset then the last time (or there
  8956. // was default preset set)
  8957. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  8958. GUIConfiguration->CopyParamCurrent = CopyParamName;
  8959. }
  8960. }
  8961. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  8962. {
  8963. if (CopyParamIndex >= 0)
  8964. {
  8965. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  8966. }
  8967. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  8968. try
  8969. {
  8970. int Fmt =
  8971. (CopyParamIndex < 0) ?
  8972. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8973. COPY_PARAM_AUTOSELECTED;
  8974. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  8975. Data->Message = MainInstructions(Message);
  8976. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  8977. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  8978. CopyParamAttrs);
  8979. if (CopyParamIndex >= 0)
  8980. {
  8981. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  8982. Info = FORMAT(L"%s\n \n%s", (Info,
  8983. FMTLOAD(COPY_PARAM_RULE,
  8984. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  8985. }
  8986. Data->Message += L"\n\n" + Info;
  8987. if (WinConfiguration->CopyParamAutoSelectNotice)
  8988. {
  8989. TransferPresetNoteMessage(Data, true);
  8990. }
  8991. else
  8992. {
  8993. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  8994. Data = NULL; // ownership passed
  8995. }
  8996. }
  8997. __finally
  8998. {
  8999. delete Data;
  9000. }
  9001. }
  9002. }
  9003. }
  9004. //---------------------------------------------------------------------------
  9005. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  9006. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  9007. {
  9008. DebugAssert(NoteData != NULL);
  9009. DebugAssert(!IsLocalBrowserMode());
  9010. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  9011. TQueryButtonAlias Aliases[1];
  9012. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  9013. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  9014. Params.Aliases = Aliases;
  9015. Params.AliasesCount = LENOF(Aliases);
  9016. unsigned int Result =
  9017. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  9018. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  9019. switch (Result)
  9020. {
  9021. case qaNeverAskAgain:
  9022. DebugAssert(AllowNeverAskAgain);
  9023. WinConfiguration->CopyParamAutoSelectNotice = false;
  9024. break;
  9025. case qaIgnore:
  9026. PreferencesDialog(pmPresets);
  9027. break;
  9028. }
  9029. }
  9030. //---------------------------------------------------------------------------
  9031. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  9032. {
  9033. // as of now useless, as this is used for notes only, never for balloons, ...
  9034. RestoreApp();
  9035. // .. and we should never be busy here
  9036. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  9037. {
  9038. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  9039. }
  9040. }
  9041. //---------------------------------------------------------------------------
  9042. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  9043. TPreferencesMode APreferencesMode)
  9044. {
  9045. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  9046. TCopyParamRuleData Data;
  9047. if (Terminal != NULL)
  9048. {
  9049. PreferencesData.reset(new TPreferencesDialogData());
  9050. GetTransferPresetAutoSelectData(Data);
  9051. PreferencesData->CopyParamRuleData = &Data;
  9052. }
  9053. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  9054. }
  9055. //---------------------------------------------------------------------------
  9056. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  9057. const TCustomCommandType & Command)
  9058. {
  9059. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  9060. {
  9061. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  9062. }
  9063. }
  9064. //---------------------------------------------------------------------------
  9065. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  9066. {
  9067. bool RemoteAllowed = CustomCommandRemoteAllowed();
  9068. TCustomCommandType Command;
  9069. // make sure we use local custom command when remote are not supported
  9070. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  9071. {
  9072. Command = FLastCustomCommand;
  9073. }
  9074. else
  9075. {
  9076. Command.Params = Command.Params | ccLocal;
  9077. }
  9078. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  9079. FEditingFocusedAdHocCommand = OnFocused;
  9080. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9081. int Options =
  9082. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9083. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9084. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9085. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9086. {
  9087. FLastCustomCommand = Command;
  9088. UpdateCustomCommandsToolbar();
  9089. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9090. }
  9091. }
  9092. //---------------------------------------------------------------------------
  9093. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9094. {
  9095. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9096. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9097. DebugAssert(State > 0);
  9098. if (State <= 0)
  9099. {
  9100. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9101. }
  9102. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9103. }
  9104. //---------------------------------------------------------------------------
  9105. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9106. TCustomCommandType & Command, int & State)
  9107. {
  9108. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9109. if (Result)
  9110. {
  9111. Command = FLastCustomCommand;
  9112. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9113. }
  9114. return Result;
  9115. }
  9116. //---------------------------------------------------------------------------
  9117. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9118. {
  9119. ResetIncrementalSearch();
  9120. }
  9121. //---------------------------------------------------------------------------
  9122. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9123. {
  9124. DebugAssert(ComponentVisible[Component]);
  9125. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9126. }
  9127. //---------------------------------------------------------------------------
  9128. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9129. {
  9130. // when queue panel is resized here directly, the status bar is stretched
  9131. // over whole space the panel occupied
  9132. PostComponentHide(fcQueueView);
  9133. }
  9134. //---------------------------------------------------------------------------
  9135. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9136. {
  9137. ComponentVisible[fcQueueFileList] = false;
  9138. }
  9139. //---------------------------------------------------------------------------
  9140. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9141. {
  9142. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9143. RefreshColorMode();
  9144. ResetSysDarkTheme();
  9145. ConfigurationChanged();
  9146. ConfigureInterface();
  9147. // Should be called for all controls
  9148. RemoteDirView->Perform(WM_THEMECHANGED, 0, 0);
  9149. }
  9150. //---------------------------------------------------------------------------
  9151. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9152. {
  9153. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9154. if (!FInvalid &&
  9155. (Message.LParam != 0) &&
  9156. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9157. {
  9158. ThemeChanged();
  9159. }
  9160. TForm::Dispatch(&Message);
  9161. }
  9162. //---------------------------------------------------------------------------
  9163. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9164. {
  9165. TMessage * M = static_cast<TMessage*>(Message);
  9166. switch (M->Msg)
  9167. {
  9168. case CM_DIALOGCHAR:
  9169. CMDialogChar(*M);
  9170. break;
  9171. case WM_APPCOMMAND:
  9172. WMAppCommand(*M);
  9173. break;
  9174. case WM_SYSCOMMAND:
  9175. WMSysCommand(*M);
  9176. break;
  9177. case WM_QUERYENDSESSION:
  9178. WMQueryEndSession(*M);
  9179. break;
  9180. case WM_ENDSESSION:
  9181. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9182. break;
  9183. #ifdef _DEBUG
  9184. case WM_WINDOWPOSCHANGED:
  9185. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  9186. break;
  9187. case CM_CUSTOMSTYLECHANGED:
  9188. TForm::Dispatch(Message);
  9189. break;
  9190. #endif
  9191. case WM_COMPONENT_HIDE:
  9192. {
  9193. Byte Component = static_cast<Byte>(M->WParam);
  9194. // sanity check
  9195. if (ComponentVisible[Component])
  9196. {
  9197. // special treatment
  9198. if (Component == fcQueueView)
  9199. {
  9200. ToggleQueueVisibility();
  9201. DebugAssert(!ComponentVisible[fcQueueView]);
  9202. }
  9203. else
  9204. {
  9205. ComponentVisible[Component] = false;
  9206. }
  9207. }
  9208. }
  9209. break;
  9210. case WM_COPYDATA:
  9211. WMCopyData(*M);
  9212. break;
  9213. case WM_MANAGES_CAPTION:
  9214. // caption managed in TTerminalManager::UpdateAppTitle()
  9215. M->Result = 1;
  9216. break;
  9217. case WM_WANTS_MOUSEWHEEL:
  9218. M->Result = 1;
  9219. break;
  9220. case CM_SHOWINGCHANGED:
  9221. CMShowingChanged(*M);
  9222. break;
  9223. case WM_CLOSE:
  9224. WMClose(*M);
  9225. break;
  9226. case WM_DPICHANGED:
  9227. WMDpiChanged(*M);
  9228. break;
  9229. case CM_DPICHANGED:
  9230. CMDpiChanged(*M);
  9231. break;
  9232. case WM_SETTINGCHANGE:
  9233. WMSettingChange(*M);
  9234. break;
  9235. case CM_DIALOGKEY:
  9236. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9237. break;
  9238. case WM_PASTE_FILES:
  9239. PasteFiles();
  9240. break;
  9241. case WM_IS_HIDDEN:
  9242. // To treat master password prompt as a main window while showing it when workspace is loading while
  9243. // the exporer is showing up (Visible is true already)
  9244. M->Result = !FShowing;
  9245. break;
  9246. case WM_SHOWWINDOW:
  9247. if (M->WParam)
  9248. {
  9249. AddStartupSequence(L"J");
  9250. }
  9251. TForm::Dispatch(Message);
  9252. break;
  9253. default:
  9254. TForm::Dispatch(Message);
  9255. break;
  9256. }
  9257. }
  9258. //---------------------------------------------------------------------------
  9259. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9260. {
  9261. // noop
  9262. }
  9263. //---------------------------------------------------------------------------
  9264. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  9265. {
  9266. TForm::Dispatch(&Message);
  9267. FSessionColors->Clear();
  9268. AddFixedSessionImages();
  9269. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9270. UpdateImages();
  9271. }
  9272. //---------------------------------------------------------------------------
  9273. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9274. {
  9275. TForm::Dispatch(&Message);
  9276. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9277. UpdatePixelsPerInchMainWindowCounter();
  9278. }
  9279. //---------------------------------------------------------------------------
  9280. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9281. {
  9282. AppLog(L"Main window WM_CLOSE");
  9283. // Cannot close window while we are busy.
  9284. // We cannot test this in FormCloseQuery as that is called also from
  9285. // Close(), which is called by CloseApplicationAction. So we can be busy
  9286. // there already even, when it is legitimate to close the application.
  9287. // Possibly a better place to handle this would be WMSysCommand.
  9288. if (NonVisualDataModule->Busy)
  9289. {
  9290. Message.Result = 1;
  9291. }
  9292. else
  9293. {
  9294. TForm::Dispatch(&Message);
  9295. }
  9296. }
  9297. //---------------------------------------------------------------------------
  9298. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9299. {
  9300. if (!FShowingChanged)
  9301. {
  9302. AddStartupSequence(L"D");
  9303. FShowingChanged = true;
  9304. }
  9305. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9306. bool NoSession = (ManagedSession == NULL);
  9307. // This calls TCustomScpExplorerForm::DoShow
  9308. TForm::Dispatch(&Message);
  9309. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9310. if (Showing && !FStarted)
  9311. {
  9312. FStarted = true;
  9313. InterfaceStarted();
  9314. }
  9315. if (Showing && NoSession)
  9316. {
  9317. // When we are starting minimized (i.e. from an installer),
  9318. // postpone showing Login dialog until we get restored.
  9319. // Otherwise the Login dialog (and Authentication window) show restored
  9320. // over invisible (minimized) main window.
  9321. if (WindowState == wsMinimized)
  9322. {
  9323. FNeedSession = true;
  9324. }
  9325. else
  9326. {
  9327. // This happens before application ever goes idle, so the toolbars would
  9328. // stay enabled (initial state) until the Login dialog is dismissed.
  9329. UpdateActions();
  9330. NonVisualDataModule->StartBusy();
  9331. try
  9332. {
  9333. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9334. // otherwise the dialog does not receive focus.
  9335. // With Commander interface the ProcessMessages is called already
  9336. // by TDriveView, but with Explorer interface, we need to call it explicily
  9337. Application->ProcessMessages();
  9338. // do not reload sessions, they have been loaded just now (optimization)
  9339. NeedSession(true);
  9340. }
  9341. __finally
  9342. {
  9343. NonVisualDataModule->EndBusy();
  9344. }
  9345. }
  9346. }
  9347. }
  9348. //---------------------------------------------------------------------------
  9349. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9350. {
  9351. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9352. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9353. }
  9354. //---------------------------------------------------------------------------
  9355. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9356. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9357. int & MaxHeight)
  9358. {
  9359. // workaround for bug in TWinControl.CalcConstraints
  9360. // Check for empty rect (restore from iconic state) is done there only after
  9361. // call to AdjustClientRect, which enlarges the rect (for forms).
  9362. TRect R = GetClientRect();
  9363. // when restoring from iconic state, place no restrictions
  9364. if (IsRectEmpty(R))
  9365. {
  9366. MinWidth = 0;
  9367. MinHeight = 0;
  9368. MaxWidth = 32000;
  9369. MaxHeight = 32000;
  9370. }
  9371. }
  9372. //---------------------------------------------------------------------------
  9373. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9374. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9375. {
  9376. // terminal can be already closed (e.g. dropped connection)
  9377. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9378. {
  9379. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9380. try
  9381. {
  9382. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9383. }
  9384. catch(...)
  9385. {
  9386. if (!Terminal->Active)
  9387. {
  9388. Close = true;
  9389. }
  9390. throw;
  9391. }
  9392. }
  9393. }
  9394. //---------------------------------------------------------------------------
  9395. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9396. {
  9397. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9398. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9399. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9400. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9401. {
  9402. OnGetSpaceAvailable = GetSpaceAvailable;
  9403. }
  9404. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9405. OnGetSpaceAvailable);
  9406. }
  9407. //---------------------------------------------------------------------------
  9408. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9409. {
  9410. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9411. Terminal->FillSessionDataForCode(Data.get());
  9412. return Data.release();
  9413. }
  9414. //---------------------------------------------------------------------------
  9415. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9416. {
  9417. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9418. DoGenerateUrlDialog(Data.get(), Paths);
  9419. }
  9420. //---------------------------------------------------------------------------
  9421. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9422. {
  9423. GenerateUrl(NULL);
  9424. }
  9425. //---------------------------------------------------------------------------
  9426. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9427. {
  9428. std::unique_ptr<TStrings> Paths(new TStringList());
  9429. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9430. GenerateUrl(Paths.get());
  9431. }
  9432. //---------------------------------------------------------------------------
  9433. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9434. {
  9435. FSessionColor = value;
  9436. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9437. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9438. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9439. DebugAssert(ColorItem != NULL);
  9440. ColorItem->Color = C;
  9441. NonVisualDataModule->ColorMenuItem->Color = C;
  9442. UpdateControls();
  9443. }
  9444. //---------------------------------------------------------------------------
  9445. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9446. {
  9447. if (value != FSessionColor)
  9448. {
  9449. UpdateSessionColor(value);
  9450. // Is null when called from LastTerminalClosed
  9451. if (Terminal != NULL)
  9452. {
  9453. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9454. }
  9455. }
  9456. }
  9457. //---------------------------------------------------------------------------
  9458. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9459. {
  9460. bool Result = FNoteTimer->Enabled;
  9461. if (Result)
  9462. {
  9463. // cannot cancel note too early
  9464. bool NotEarly =
  9465. (Now() - FNoteShown >
  9466. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9467. if (Force || NotEarly)
  9468. {
  9469. FNoteTimer->Enabled = false;
  9470. FNote = L"";
  9471. SAFE_DESTROY(FNoteData);
  9472. FOnNoteClick = NULL;
  9473. FNoteHints = FNotes->Text;
  9474. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9475. UpdateStatusBar();
  9476. }
  9477. }
  9478. return Result;
  9479. }
  9480. //---------------------------------------------------------------------------
  9481. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9482. {
  9483. DebugAssert(FNoteTimer->Enabled);
  9484. CancelNote(true);
  9485. }
  9486. //---------------------------------------------------------------------------
  9487. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9488. {
  9489. FNoteHints = FNotes->Text.TrimRight();
  9490. }
  9491. //---------------------------------------------------------------------------
  9492. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9493. {
  9494. int P = Note.Pos(L"\n");
  9495. if (P > 0)
  9496. {
  9497. Note.SetLength(P - 1);
  9498. }
  9499. FNotes->Add(FORMAT(L"[%s] %s",
  9500. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9501. while (FNotes->Count > 10)
  9502. {
  9503. FNotes->Delete(0);
  9504. }
  9505. if (UpdateNow)
  9506. {
  9507. UpdateNoteHints();
  9508. UpdateStatusBar();
  9509. }
  9510. }
  9511. //---------------------------------------------------------------------------
  9512. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  9513. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9514. {
  9515. int P = Note.Pos(L"\n");
  9516. if (P > 0)
  9517. {
  9518. Note.SetLength(P - 1);
  9519. }
  9520. UpdateNoteHints();
  9521. FNote = Note;
  9522. SAFE_DESTROY(FNoteData);
  9523. FNoteData = NoteData;
  9524. FOnNoteClick = OnNoteClick;
  9525. AddNote(Note, false);
  9526. UpdateStatusBar();
  9527. FNoteShown = Now();
  9528. FNoteTimer->Enabled = false;
  9529. if (Seconds == 0)
  9530. {
  9531. Seconds = WinConfiguration->NotificationsTimeout;
  9532. }
  9533. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9534. FNoteTimer->Enabled = true;
  9535. }
  9536. //---------------------------------------------------------------------------
  9537. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9538. {
  9539. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  9540. }
  9541. //---------------------------------------------------------------------------
  9542. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9543. {
  9544. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9545. {
  9546. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9547. }
  9548. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9549. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9550. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))),
  9551. 0, NULL, NULL);
  9552. }
  9553. //---------------------------------------------------------------------------
  9554. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9555. {
  9556. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9557. UnicodeString Note =
  9558. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9559. PostNote(Note, 0, NULL, NULL);
  9560. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9561. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9562. }
  9563. //---------------------------------------------------------------------------
  9564. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9565. {
  9566. WinConfiguration->FormatSizeBytes = Style;
  9567. }
  9568. //---------------------------------------------------------------------------
  9569. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9570. {
  9571. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9572. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9573. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9574. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  9575. }
  9576. //---------------------------------------------------------------------------
  9577. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9578. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9579. {
  9580. if (Panel->Index == 0)
  9581. {
  9582. if (FOnNoteClick != NULL)
  9583. {
  9584. // prevent the user data from being freed by possible call
  9585. // to CancelNote or PostNote during call to OnNoteClick
  9586. std::unique_ptr<TObject> NoteData(FNoteData);
  9587. TNotifyEvent OnNoteClick = FOnNoteClick;
  9588. FNoteData = NULL;
  9589. // need to cancel the note as we are going to delete its user data
  9590. CancelNote(true);
  9591. OnNoteClick(NoteData.get());
  9592. }
  9593. }
  9594. if (HasActiveTerminal() &&
  9595. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9596. {
  9597. FileSystemInfo();
  9598. }
  9599. }
  9600. //---------------------------------------------------------------------------
  9601. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9602. {
  9603. // workaround:
  9604. // 1) for unknown reason, disabling window, while minimized,
  9605. // prevents it from restoring, even if it was enabled again meanwhile
  9606. // 2) when disabling the main window, while another has focus
  9607. // minimize is no longer possible
  9608. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9609. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9610. // Shouldn't we use IsApplicationMinimized() here?
  9611. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9612. {
  9613. Enabled = false;
  9614. }
  9615. FLockLevel++;
  9616. }
  9617. //---------------------------------------------------------------------------
  9618. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9619. {
  9620. DebugAssert(FLockLevel > 0);
  9621. FLockLevel--;
  9622. if (FLockLevel == 0)
  9623. {
  9624. DebugAssert(FLockSuspendLevel == 0);
  9625. Enabled = true;
  9626. // VCL_COPY (TCustomForm.SetWindowFocus)
  9627. if (Active && (ActiveControl != NULL))
  9628. {
  9629. ::SetFocus(ActiveControl->Handle);
  9630. if (GetFocus() == ActiveControl->Handle)
  9631. {
  9632. ActiveControl->Perform(CM_UIACTIVATE, 0, 0);
  9633. }
  9634. }
  9635. }
  9636. }
  9637. //---------------------------------------------------------------------------
  9638. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9639. {
  9640. // We need to make sure that window is enabled when the last modal window closes
  9641. // otherwise focus is not restored correctly.
  9642. // So we re-enable the window when modal window opens and
  9643. // disable it back after is closes
  9644. if (FLockLevel > 0)
  9645. {
  9646. // while we have nesting counter, we know that we never be called
  9647. // recursivelly as Application->OnModalBegin is called only
  9648. // for the top-level modal window
  9649. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9650. {
  9651. // won't be disabled when conditions in LockWindow() were not satisfied
  9652. FDisabledOnLockSuspend = !Enabled;
  9653. // When minimized to tray (or actually when set to SW_HIDE),
  9654. // setting Enabled makes the window focusable even when there's
  9655. // modal window over it
  9656. if (!FTrayIcon->Visible)
  9657. {
  9658. Enabled = true;
  9659. }
  9660. }
  9661. FLockSuspendLevel++;
  9662. }
  9663. }
  9664. //---------------------------------------------------------------------------
  9665. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9666. {
  9667. if (FLockSuspendLevel > 0)
  9668. {
  9669. DebugAssert(FLockLevel > 0);
  9670. FLockSuspendLevel--;
  9671. // see comment in SuspendWindowLock
  9672. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9673. {
  9674. // Note that window can be enabled here, when we were minized to tray when
  9675. // was SuspendWindowLock() called.
  9676. // We should possibly do the same check as in LockWindow(),
  9677. // if it is ever possible that the consitions change between
  9678. // SuspendWindowLock() and ResumeWindowLock()
  9679. Enabled = !FDisabledOnLockSuspend;
  9680. }
  9681. }
  9682. }
  9683. //---------------------------------------------------------------------------
  9684. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9685. {
  9686. TTBXComboBoxItem * RemotePathComboBox =
  9687. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9688. if (!TextOnly)
  9689. {
  9690. TStrings * Items = RemotePathComboBox->Strings;
  9691. Items->BeginUpdate();
  9692. try
  9693. {
  9694. Items->Clear();
  9695. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9696. {
  9697. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9698. while (!IsUnixRootPath(APath))
  9699. {
  9700. int P = APath.LastDelimiter(L'/');
  9701. DebugAssert(P >= 0);
  9702. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9703. APath.SetLength(P - 1);
  9704. }
  9705. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9706. }
  9707. }
  9708. __finally
  9709. {
  9710. Items->EndUpdate();
  9711. }
  9712. }
  9713. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9714. // Setting ItemIndex to -1 does not reset its text
  9715. if (RemotePathComboBox->Strings->Count == 0)
  9716. {
  9717. RemotePathComboBox->Text = L"";
  9718. }
  9719. }
  9720. //---------------------------------------------------------------------------
  9721. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9722. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9723. {
  9724. if (AIndex < 0)
  9725. {
  9726. AIndex = Sender->ItemIndex;
  9727. }
  9728. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9729. }
  9730. //---------------------------------------------------------------------------
  9731. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9732. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9733. int & ImageIndex)
  9734. {
  9735. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9736. }
  9737. //---------------------------------------------------------------------------
  9738. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9739. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9740. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9741. {
  9742. if (!IsLocalBrowserMode())
  9743. {
  9744. ARect.Left += (10 * AIndex);
  9745. }
  9746. }
  9747. //---------------------------------------------------------------------------
  9748. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9749. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9750. {
  9751. AWidth += (10 * AIndex);
  9752. }
  9753. //---------------------------------------------------------------------------
  9754. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9755. {
  9756. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9757. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9758. int Index = RemotePathComboBox->ItemIndex;
  9759. while (Index < RemotePathComboBox->Strings->Count - 1)
  9760. {
  9761. APath = UnixExtractFileDir(APath);
  9762. Index++;
  9763. }
  9764. // VanDyke style paths
  9765. if (APath.IsEmpty())
  9766. {
  9767. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9768. APath = ROOTDIRECTORY;
  9769. }
  9770. if (RemoteDirView->Path != APath)
  9771. {
  9772. RemoteDirView->Path = APath;
  9773. }
  9774. }
  9775. //---------------------------------------------------------------------------
  9776. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9777. {
  9778. DoRemotePathComboBoxItemClick(Sender);
  9779. }
  9780. //---------------------------------------------------------------------------
  9781. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9782. {
  9783. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9784. DebugUsedParam(Sender);
  9785. UpdateRemotePathComboBox(true);
  9786. }
  9787. //---------------------------------------------------------------------------
  9788. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9789. {
  9790. DoRemotePathComboBoxCancel(Sender);
  9791. }
  9792. //---------------------------------------------------------------------------
  9793. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9794. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9795. {
  9796. ResetIncrementalSearch();
  9797. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9798. DebugAssert(DirView != NULL);
  9799. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9800. {
  9801. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9802. // OnEditing is called also from TCustomListView::CanEdit
  9803. if (Edit != NULL)
  9804. {
  9805. EditSelectBaseName(Edit);
  9806. }
  9807. }
  9808. }
  9809. //---------------------------------------------------------------------------
  9810. //---------------------------------------------------------------------------
  9811. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9812. {
  9813. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9814. Result->AutoDetectDnD = false;
  9815. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9816. Result->RenderDataOn = rdoEnterAndDropSync;
  9817. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9818. return Result;
  9819. }
  9820. //---------------------------------------------------------------------------
  9821. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9822. {
  9823. if (IsWin10Build(19041))
  9824. {
  9825. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9826. BOOL DarkMode = FImmersiveDarkMode ? TRUE : FALSE;
  9827. const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
  9828. DwmSetWindowAttribute(Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, &DarkMode, sizeof(DarkMode));
  9829. }
  9830. }
  9831. //---------------------------------------------------------------------------
  9832. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9833. {
  9834. TForm::CreateWnd();
  9835. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9836. UpdateDarkMode();
  9837. if (FSessionsDragDropFilesEx == NULL)
  9838. {
  9839. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9840. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9841. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9842. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9843. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9844. }
  9845. if (FQueueDragDropFilesEx == NULL)
  9846. {
  9847. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9848. // No need to set OnDragOver as we do not have any restrictions
  9849. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9850. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9851. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9852. }
  9853. }
  9854. //---------------------------------------------------------------------------
  9855. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9856. {
  9857. TForm::DestroyWnd();
  9858. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9859. FQueueDragDropFilesEx->DragDropControl = NULL;
  9860. }
  9861. //---------------------------------------------------------------------------
  9862. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9863. {
  9864. SideEnter(FCurrentSide);
  9865. FEverShown = true;
  9866. }
  9867. //---------------------------------------------------------------------------
  9868. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9869. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9870. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9871. {
  9872. if (!NonVisualDataModule->Busy)
  9873. {
  9874. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9875. Configuration->Usage->Inc(L"FileFinds");
  9876. LockWindow(true);
  9877. NonVisualDataModule->StartBusy();
  9878. WinConfiguration->LockedInterface = true;
  9879. try
  9880. {
  9881. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9882. }
  9883. __finally
  9884. {
  9885. WinConfiguration->LockedInterface = false;
  9886. NonVisualDataModule->EndBusy();
  9887. UnlockWindow();
  9888. }
  9889. }
  9890. }
  9891. //---------------------------------------------------------------------------
  9892. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9893. {
  9894. if (!NonVisualDataModule->Busy)
  9895. {
  9896. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9897. SetFocus();
  9898. RemoteDirView->Path = UnixExtractFilePath(Path);
  9899. UnicodeString FileName = UnixExtractFileName(Path);
  9900. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9901. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9902. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  9903. if (Item == NULL)
  9904. {
  9905. ReloadDirectory(osRemote);
  9906. Item = RemoteDirView->FindFileItem(FileName);
  9907. }
  9908. if (Item != NULL)
  9909. {
  9910. RemoteDirView->ItemFocused = Item;
  9911. RemoteDirView->ItemFocused->MakeVisible(false);
  9912. RemoteDirView->SetFocus();
  9913. }
  9914. }
  9915. }
  9916. //---------------------------------------------------------------------------
  9917. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  9918. {
  9919. bool Result = !NonVisualDataModule->Busy;
  9920. if (Result)
  9921. {
  9922. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9923. }
  9924. return Result;
  9925. }
  9926. //---------------------------------------------------------------------------
  9927. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  9928. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9929. {
  9930. if (CanOperateOnFoundFiles(ATerminal))
  9931. {
  9932. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished, OnFileOperationFinished);
  9933. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  9934. }
  9935. }
  9936. //---------------------------------------------------------------------------
  9937. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  9938. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9939. {
  9940. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  9941. }
  9942. //---------------------------------------------------------------------------
  9943. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  9944. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9945. {
  9946. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  9947. }
  9948. //---------------------------------------------------------------------------
  9949. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  9950. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9951. {
  9952. if (CanOperateOnFoundFiles(ATerminal))
  9953. {
  9954. for (int Index = 0; Index < FileList->Count; Index++)
  9955. {
  9956. UnicodeString FileName = FileList->Strings[Index];
  9957. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  9958. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  9959. OnFileOperationFinished(osRemote, FileName, true);
  9960. }
  9961. }
  9962. }
  9963. //---------------------------------------------------------------------------
  9964. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  9965. {
  9966. FFileFindTerminal = Terminal;
  9967. ShowFileFindDialog(
  9968. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  9969. DoDownloadFoundFiles, DoEditFoundFiles);
  9970. }
  9971. //---------------------------------------------------------------------------
  9972. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  9973. {
  9974. FTaskbarList = TaskbarList;
  9975. }
  9976. //---------------------------------------------------------------------------
  9977. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  9978. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  9979. {
  9980. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9981. if (Index >= 0)
  9982. {
  9983. if (Button == mbLeft)
  9984. {
  9985. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  9986. // If switching tab (switching session) takes long enough for user
  9987. // to actually release the button, "mouse down" is still raised,
  9988. // but we do not get "mouse up" event, so dragging is not cancelled,
  9989. // prevent that by not beginning dragging in the first place.
  9990. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  9991. if (IsKeyPressed(Key))
  9992. {
  9993. // when user clicks the "+", we get mouse down only after the session
  9994. // is closed, when new session tab is already on X:Y, so dragging
  9995. // starts, prevent that
  9996. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  9997. {
  9998. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9999. if (Terminal != NULL)
  10000. {
  10001. SessionsPageControl->BeginDrag(false);
  10002. }
  10003. }
  10004. }
  10005. }
  10006. else if (Button == mbMiddle)
  10007. {
  10008. // ignore middle-click for "New session tab" and the last local-local tab
  10009. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10010. if ((Session != NULL) && CanCloseSession(Session))
  10011. {
  10012. CloseSessionTab(Index);
  10013. }
  10014. }
  10015. }
  10016. }
  10017. //---------------------------------------------------------------------------
  10018. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  10019. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  10020. {
  10021. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10022. // do not allow dropping on the "+" tab
  10023. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10024. if ((TargetTerminal != NULL) &&
  10025. (SessionsPageControl->ActivePage->PageIndex != Index))
  10026. {
  10027. Configuration->Usage->Inc(L"SessionTabMoves");
  10028. // this is almost redundant as we would recreate tabs in SessionListChanged,
  10029. // but we want to actually prevent that to avoid flicker
  10030. SessionsPageControl->ActivePage->PageIndex = Index;
  10031. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  10032. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  10033. }
  10034. }
  10035. //---------------------------------------------------------------------------
  10036. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  10037. TObject * Sender, TObject * Source, int X, int Y,
  10038. TDragState /*State*/, bool & Accept)
  10039. {
  10040. Accept = (Sender == Source);
  10041. if (Accept)
  10042. {
  10043. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10044. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10045. // do not allow dragging to the "+" tab
  10046. Accept = (Terminal != NULL);
  10047. }
  10048. }
  10049. //---------------------------------------------------------------------------
  10050. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  10051. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  10052. {
  10053. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10054. if (Index < 0)
  10055. {
  10056. Effect = DROPEFFECT_NONE;
  10057. }
  10058. else
  10059. {
  10060. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10061. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  10062. if (!IsActiveTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  10063. {
  10064. Effect = DROPEFFECT_NONE;
  10065. }
  10066. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  10067. {
  10068. Effect = DROPEFFECT_COPY;
  10069. }
  10070. }
  10071. }
  10072. //---------------------------------------------------------------------------
  10073. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  10074. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  10075. {
  10076. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10077. // do not allow dropping on local-local, disconnected and the "+" tab
  10078. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  10079. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10080. if (DebugAlwaysTrue(IsActiveTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  10081. {
  10082. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  10083. if (!IsFileControl(DropSourceControl, osRemote))
  10084. {
  10085. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  10086. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  10087. // Why don't we use Terminal->CurrentDirectory directly?
  10088. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10089. // do not force queue, drag drop
  10090. false, true);
  10091. }
  10092. }
  10093. }
  10094. //---------------------------------------------------------------------------
  10095. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10096. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10097. {
  10098. // Downloads are handled in RemoteFileControlDDEnd
  10099. if (!IsFileControl(DropSourceControl, osRemote))
  10100. {
  10101. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10102. Terminal->CurrentDirectory,
  10103. // force queue, drag drop
  10104. true, true);
  10105. }
  10106. }
  10107. //---------------------------------------------------------------------------
  10108. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10109. {
  10110. FShowing = false;
  10111. // Do not save empty workspace
  10112. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10113. {
  10114. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10115. UnicodeString Name = WorkspaceName();
  10116. DoSaveWorkspace(
  10117. Name, DataList.get(),
  10118. !Configuration->DisablePasswordStoring &&
  10119. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10120. WinConfiguration->LastStoredSession = Name;
  10121. }
  10122. AppLog(L"Closing main window");
  10123. }
  10124. //---------------------------------------------------------------------------
  10125. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10126. {
  10127. TManagedTerminal * ManagedTerminal =
  10128. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10129. if (ManagedTerminal != NULL)
  10130. {
  10131. ManagedTerminal->DirectoryLoaded = Now();
  10132. }
  10133. }
  10134. //---------------------------------------------------------------------------
  10135. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10136. TListItem * /*Item*/, bool /*Selected*/)
  10137. {
  10138. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10139. switch (DirView->LastSelectMethod)
  10140. {
  10141. case smKeyboard:
  10142. Configuration->Usage->Inc(L"KeyboardSelections");
  10143. break;
  10144. case smMouse:
  10145. Configuration->Usage->Inc(L"MouseSelections");
  10146. break;
  10147. }
  10148. }
  10149. //---------------------------------------------------------------------------
  10150. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10151. {
  10152. if (Color != 0)
  10153. {
  10154. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10155. }
  10156. else
  10157. {
  10158. return FSessionTabImageIndex;
  10159. }
  10160. }
  10161. //---------------------------------------------------------------------------
  10162. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10163. {
  10164. TPngImageCollectionItem * Item =
  10165. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10166. FSessionColors->AddPng(Item->PngImage);
  10167. return FSessionColors->Count - 1;
  10168. }
  10169. //---------------------------------------------------------------------------
  10170. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10171. {
  10172. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10173. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10174. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10175. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10176. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10177. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10178. }
  10179. //---------------------------------------------------------------------------
  10180. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10181. {
  10182. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10183. }
  10184. //---------------------------------------------------------------------------
  10185. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10186. {
  10187. switch (Side)
  10188. {
  10189. case osLocal:
  10190. return FNewLocalTabTabImageIndex;
  10191. case osRemote:
  10192. case osCurrent:
  10193. return FNewRemoteTabTabImageIndex;
  10194. default:
  10195. DebugFail();
  10196. return -1;
  10197. }
  10198. }
  10199. //---------------------------------------------------------------------------
  10200. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10201. {
  10202. for (int Index = 0; Index < Control->ControlCount; Index++)
  10203. {
  10204. TControl * AControl = Control->Controls[Index];
  10205. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10206. if (WinControl != NULL)
  10207. {
  10208. CollectItemsWithTextDisplayMode(WinControl);
  10209. }
  10210. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10211. if (Toolbar != NULL)
  10212. {
  10213. // we care for top-level items only
  10214. TTBCustomItem * Items = Toolbar->Items;
  10215. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10216. {
  10217. TTBCustomItem * Item = Items->Items[ItemIndex];
  10218. if (((Item->DisplayMode == nbdmImageAndText) ||
  10219. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10220. EligibleForImageDisplayMode(Item))
  10221. {
  10222. FItemsWithTextDisplayMode.insert(Item);
  10223. }
  10224. }
  10225. }
  10226. }
  10227. }
  10228. //---------------------------------------------------------------------------
  10229. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10230. {
  10231. return true;
  10232. }
  10233. //---------------------------------------------------------------------------
  10234. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10235. {
  10236. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10237. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10238. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10239. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10240. bool Result = true;
  10241. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10242. {
  10243. TTBCustomItem * Item = *i;
  10244. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10245. if (Label != NULL)
  10246. {
  10247. // optimization
  10248. if (Label->Visible == SelectiveToolbarText)
  10249. {
  10250. Result = false;
  10251. }
  10252. else
  10253. {
  10254. Label->Visible = SelectiveToolbarText;
  10255. }
  10256. }
  10257. else
  10258. {
  10259. // optimization
  10260. if (Item->DisplayMode == DisplayMode)
  10261. {
  10262. Result = false;
  10263. }
  10264. else
  10265. {
  10266. Item->DisplayMode = DisplayMode;
  10267. }
  10268. }
  10269. ++i;
  10270. }
  10271. UpdateNewTabTab();
  10272. return Result;
  10273. }
  10274. //---------------------------------------------------------------------------
  10275. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10276. {
  10277. DebugFail();
  10278. }
  10279. //---------------------------------------------------------------------------
  10280. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10281. {
  10282. // Among other, a lock level is non zero, while directory is being loaded,
  10283. // even when it happens as a result of dirview navigation,
  10284. // i.e. when TNonVisualDataModule is NOT FBusy.
  10285. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10286. // Among other this prevents a panel auto update to occur while
  10287. // directory is changing.
  10288. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10289. }
  10290. //---------------------------------------------------------------------------
  10291. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10292. {
  10293. // While the window is disabled, we still seem to process menu shortcuts at least,
  10294. // so stop it at least here.
  10295. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10296. bool Result;
  10297. if (Allowed == aaUpdate)
  10298. {
  10299. Result = true;
  10300. }
  10301. else
  10302. {
  10303. Result = !NonVisualDataModule->Busy;
  10304. if (Result && (Allowed == aaShortCut))
  10305. {
  10306. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10307. Action->Update();
  10308. Result = Action->Enabled;
  10309. }
  10310. }
  10311. return Result;
  10312. }
  10313. //---------------------------------------------------------------------------
  10314. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10315. {
  10316. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10317. }
  10318. //---------------------------------------------------------------------------
  10319. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10320. {
  10321. // This is somewhat redundant to LockWindow() call from
  10322. // TTerminalManager::TerminalReadDirectoryProgress.
  10323. // But disabling window is known not to block keyboard shorcuts
  10324. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10325. if (Busy > 0)
  10326. {
  10327. if (NonVisualDataModule->Busy)
  10328. {
  10329. State = false;
  10330. }
  10331. else
  10332. {
  10333. NonVisualDataModule->StartBusy();
  10334. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10335. LockWindow();
  10336. }
  10337. }
  10338. else if (Busy < 0)
  10339. {
  10340. UnlockWindow();
  10341. NonVisualDataModule->EndBusy();
  10342. }
  10343. else
  10344. {
  10345. State = NonVisualDataModule->Busy;
  10346. }
  10347. }
  10348. //---------------------------------------------------------------------------
  10349. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10350. {
  10351. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10352. if (Index >= 0)
  10353. {
  10354. TPopupMenu * PopupMenu = NULL;
  10355. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10356. if (Session != NULL)
  10357. {
  10358. SessionsPageControl->ActivePageIndex = Index;
  10359. if (DebugAlwaysTrue(SessionTabSwitched()))
  10360. {
  10361. // copied from TControl.WMContextMenu
  10362. SendCancelMode(SessionsPageControl);
  10363. // explicit popup instead of using PopupMenu property
  10364. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10365. // while connecting yet not-connected session and hence
  10366. // allowing an access to commands over not-completely connected session
  10367. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10368. }
  10369. }
  10370. else
  10371. {
  10372. if (SupportsLocalBrowser())
  10373. {
  10374. PopupMenu = NonVisualDataModule->NewTabPopup;
  10375. }
  10376. }
  10377. if (PopupMenu != NULL)
  10378. {
  10379. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10380. PopupMenu->PopupComponent = SessionsPageControl;
  10381. PopupMenu->Popup(Point.x, Point.y);
  10382. }
  10383. }
  10384. Handled = true;
  10385. }
  10386. //---------------------------------------------------------------------------
  10387. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10388. {
  10389. return HasActiveTerminal() && Terminal->IsCapable[fcChangePassword];
  10390. }
  10391. //---------------------------------------------------------------------------
  10392. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10393. {
  10394. Configuration->Usage->Inc(L"PasswordChanges");
  10395. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10396. ChangePasswordData->DisableAuthentationsExceptPassword();
  10397. ChangePasswordData->ChangePassword = true;
  10398. std::unique_ptr<TTerminal> ChangePasswordSession(
  10399. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10400. ChangePasswordSession->AutoReadDirectory = false;
  10401. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10402. {
  10403. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10404. }
  10405. else
  10406. {
  10407. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10408. }
  10409. }
  10410. //---------------------------------------------------------------------------
  10411. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10412. {
  10413. // No nice way to assert SSH2
  10414. return HasActiveTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10415. }
  10416. //---------------------------------------------------------------------------
  10417. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10418. {
  10419. TOperationVisualizer OperationVisualizer;
  10420. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10421. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10422. }
  10423. //---------------------------------------------------------------------------
  10424. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  10425. {
  10426. TForm::ChangeScale(M, D);
  10427. int APixelsPerInch = GetControlPixelsPerInch(this);
  10428. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  10429. try
  10430. {
  10431. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  10432. }
  10433. __finally
  10434. {
  10435. GUIConfiguration->ChangeResourceModule(ResourceModule);
  10436. }
  10437. }
  10438. //---------------------------------------------------------------------------
  10439. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10440. {
  10441. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10442. }
  10443. //---------------------------------------------------------------------
  10444. class TPublicControl : public TControl
  10445. {
  10446. friend class TCustomScpExplorerForm;
  10447. };
  10448. //---------------------------------------------------------------------------
  10449. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10450. {
  10451. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10452. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10453. }
  10454. //---------------------------------------------------------------------------
  10455. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10456. {
  10457. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10458. OpenBookmark(Side, Bookmark);
  10459. }
  10460. //---------------------------------------------------------------------------
  10461. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10462. {
  10463. DoBookmarkClick(osLocal, Sender);
  10464. }
  10465. //---------------------------------------------------------------------------
  10466. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10467. {
  10468. DoBookmarkClick(osRemote, Sender);
  10469. }
  10470. //---------------------------------------------------------------------------
  10471. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10472. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10473. {
  10474. if (BookmarkList != NULL)
  10475. {
  10476. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10477. if (IsLocalBrowserMode())
  10478. {
  10479. Side = osLocal;
  10480. }
  10481. if (!WinConfiguration->UseLocationProfiles)
  10482. {
  10483. std::unique_ptr<TStringList> Directories(new TStringList());
  10484. Directories->CaseSensitive = (Side == osRemote);
  10485. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10486. {
  10487. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10488. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10489. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10490. {
  10491. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10492. Item->Caption = EscapeHotkey(Directory);
  10493. Item->ShortCut = Bookmark->ShortCut;
  10494. Item->OnClick = OnBookmarkClick;
  10495. Item->Tag = reinterpret_cast<int>(Bookmark);
  10496. Directories->Add(Directory);
  10497. Menu->Add(Item.release());
  10498. }
  10499. }
  10500. }
  10501. else
  10502. {
  10503. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10504. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10505. {
  10506. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10507. if (!Bookmark->Node.IsEmpty())
  10508. {
  10509. Folders->Add(Bookmark->Node);
  10510. }
  10511. }
  10512. for (int Index = 0; Index < Folders->Count; Index++)
  10513. {
  10514. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10515. Item->Caption = Folders->Strings[Index];
  10516. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10517. Folders->Objects[Index] = Item.get();
  10518. Menu->Add(Item.release());
  10519. }
  10520. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10521. {
  10522. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10523. TTBCustomItem * Parent;
  10524. if (!Bookmark->Node.IsEmpty())
  10525. {
  10526. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10527. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10528. }
  10529. else
  10530. {
  10531. Parent = Menu;
  10532. }
  10533. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10534. Item->Caption = Bookmark->Name;
  10535. Item->ShortCut = Bookmark->ShortCut;
  10536. Item->OnClick = OnBookmarkClick;
  10537. Item->Tag = reinterpret_cast<int>(Bookmark);
  10538. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10539. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10540. {
  10541. // No hint for location profiles that are actually mere "bookmarks"
  10542. }
  10543. else
  10544. {
  10545. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10546. UnicodeString LongHint;
  10547. if (!Bookmark->Local.IsEmpty())
  10548. {
  10549. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10550. }
  10551. if (!Bookmark->Remote.IsEmpty())
  10552. {
  10553. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10554. }
  10555. AddToList(Hint, LongHint, L"|");
  10556. Item->Hint = Hint;
  10557. }
  10558. Parent->Add(Item.release());
  10559. }
  10560. }
  10561. AddMenuSeparator(Menu);
  10562. }
  10563. }
  10564. //---------------------------------------------------------------------------
  10565. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10566. {
  10567. Menu->Clear();
  10568. std::unique_ptr<TTBCustomItem> Item;
  10569. Item.reset(new TTBXItem(Owner));
  10570. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10571. Item->Options = Item->Options << tboDefault;
  10572. Menu->Add(Item.release());
  10573. AddMenuSeparator(Menu);
  10574. if (Terminal != NULL)
  10575. {
  10576. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10577. }
  10578. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10579. Item.reset(new TTBXItem(Owner));
  10580. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10581. Menu->Add(Item.release());
  10582. }
  10583. //---------------------------------------------------------------------------
  10584. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10585. {
  10586. bool Result = true;
  10587. bool Remote = !IsSideLocalBrowser(Side);
  10588. try
  10589. {
  10590. UnicodeString APath = Path;
  10591. if (Remote)
  10592. {
  10593. Terminal->ExceptionOnFail = true;
  10594. }
  10595. else
  10596. {
  10597. APath = ExpandEnvironmentVariables(Path);
  10598. }
  10599. try
  10600. {
  10601. DirView(Side)->Path = APath;
  10602. }
  10603. __finally
  10604. {
  10605. if (Remote)
  10606. {
  10607. Terminal->ExceptionOnFail = false;
  10608. }
  10609. }
  10610. }
  10611. catch (Exception & E)
  10612. {
  10613. if (!Remote || Terminal->Active)
  10614. {
  10615. ShowExtendedExceptionEx(Terminal, &E);
  10616. Result = false;
  10617. }
  10618. else
  10619. {
  10620. throw;
  10621. }
  10622. }
  10623. return Result;
  10624. }
  10625. //---------------------------------------------------------------------------
  10626. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10627. {
  10628. // Make sure there some feedback even when loading tiny local folders
  10629. TInstantOperationVisualizer Visualizer;
  10630. DirView(Side)->ReloadDirectory();
  10631. }
  10632. //---------------------------------------------------------------------------
  10633. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10634. {
  10635. if (Index == SessionsPageControl->TabIndex)
  10636. {
  10637. CloseTab();
  10638. }
  10639. else
  10640. {
  10641. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10642. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10643. TTerminalManager * Manager = TTerminalManager::Instance();
  10644. if (!Terminal->Active)
  10645. {
  10646. Manager->FreeTerminal(Terminal);
  10647. }
  10648. else
  10649. {
  10650. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10651. if (CanCloseQueue(Queue))
  10652. {
  10653. Manager->FreeTerminal(Terminal);
  10654. }
  10655. }
  10656. }
  10657. }
  10658. //---------------------------------------------------------------------------
  10659. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10660. {
  10661. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10662. if (Session == NULL)
  10663. {
  10664. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10665. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10666. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10667. //P = SessionsPageControl->ClientToScreen(P);
  10668. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10669. }
  10670. else
  10671. {
  10672. CloseSessionTab(Index);
  10673. }
  10674. }
  10675. //---------------------------------------------------------------------------
  10676. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10677. {
  10678. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10679. {
  10680. TInstantOperationVisualizer Visualizer;
  10681. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10682. // before we create a new data object
  10683. ClipboardClear();
  10684. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10685. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10686. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10687. // Intermediate variable to WORKAROUND a crash in compiler
  10688. TObjectList * ClipboardFakeMonitors =
  10689. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10690. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10691. if (FClipboardDragDropFilesEx.get() == NULL)
  10692. {
  10693. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10694. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10695. }
  10696. FClipboardDragDropFilesEx->FileList->Clear();
  10697. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10698. FClipboardDragDropFilesEx->CopyToClipboard();
  10699. FClipboardTerminal = Terminal;
  10700. // Need full paths, as cwd can be different once files are pasted
  10701. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10702. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10703. {
  10704. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10705. }
  10706. AppLogFmt(L"Created fake clipboard directory \"%s\" and started drive monitors", (FClipboardFakeDirectory));
  10707. }
  10708. }
  10709. //---------------------------------------------------------------------------
  10710. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10711. {
  10712. if (OpenClipboard(0))
  10713. {
  10714. AppLog(L"Clearing clipboard");
  10715. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10716. CloseClipboard();
  10717. }
  10718. }
  10719. //---------------------------------------------------------------------------
  10720. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10721. {
  10722. return !FClipboardFakeDirectory.IsEmpty();
  10723. }
  10724. //---------------------------------------------------------------------------
  10725. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10726. {
  10727. bool Deleted = RemoveDir(ApiPath(FClipboardFakeDirectory));
  10728. AppLogFmt(L"Clearing clipboard, deleted clipboard temporary folder \"%s\" - %d", (FClipboardFakeDirectory, int(Deleted)));
  10729. FClipboardFakeDirectory = UnicodeString();
  10730. FClipboardTerminal = NULL;
  10731. if (FDownloadingFromClipboard)
  10732. {
  10733. // We are called by the monitor, so attempt to release it would deadlock
  10734. FClipboardFakeMonitorsPendingReset = true;
  10735. }
  10736. else
  10737. {
  10738. FClipboardFakeMonitors.reset(NULL);
  10739. }
  10740. }
  10741. //---------------------------------------------------------------------------
  10742. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10743. {
  10744. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10745. {
  10746. ClipboardStop();
  10747. }
  10748. }
  10749. //---------------------------------------------------------------------------
  10750. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10751. {
  10752. TTerminalManager * Manager = TTerminalManager::Instance();
  10753. Manager->ActiveSession = FClipboardTerminal;
  10754. TTransferOperationParam Params;
  10755. Params.TargetDirectory = TargetDirectory;
  10756. Params.DragDrop = DragDrop;
  10757. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10758. }
  10759. //---------------------------------------------------------------------------
  10760. void TCustomScpExplorerForm::PasteFiles()
  10761. {
  10762. // Guard against possible race conditions
  10763. if (!FClipboardPasteTarget.IsEmpty())
  10764. {
  10765. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10766. UnicodeString Target = FClipboardPasteTarget;
  10767. FClipboardPasteTarget = EmptyStr;
  10768. // Can fail as it can be e.g. locked by AV, so we retry that later
  10769. bool Removed = RemoveDir(ApiPath(Target));
  10770. AppLogFmt(L"First attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10771. try
  10772. {
  10773. if (NonVisualDataModule->Busy)
  10774. {
  10775. AppLog(L"Is busy, cannot paste");
  10776. }
  10777. else
  10778. {
  10779. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10780. FClipboardFakeMonitorsPendingReset = false;
  10781. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10782. TAutoFlag Flag(FDownloadingFromClipboard);
  10783. AppLog(L"Downloading to paste target...");
  10784. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10785. AppLog(L"Downloaded to paste target...");
  10786. }
  10787. }
  10788. __finally
  10789. {
  10790. if (!Removed)
  10791. {
  10792. Removed = RemoveDir(ApiPath(Target));
  10793. AppLogFmt(L"Second attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10794. }
  10795. }
  10796. }
  10797. }
  10798. //---------------------------------------------------------------------------
  10799. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10800. {
  10801. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10802. // (as it pumps a Windows message queue while being shutted down)
  10803. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10804. // Is can happen that creation of our temporary directory is detected (even though we are creating it before starting the monitors).
  10805. // It tent do happen with later copy-pastes, probably because everything is cached already and monitors start quickly.
  10806. !IsPathToSameFile(FClipboardFakeDirectory, FileName) &&
  10807. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10808. {
  10809. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10810. FClipboardPasteTarget = FileName;
  10811. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10812. // Postponing removing (or actually whole pasting operation) seems to help.
  10813. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10814. }
  10815. }
  10816. //---------------------------------------------------------------------------
  10817. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10818. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10819. {
  10820. TFileMasks::TParams MaskParams;
  10821. MaskParams.Size = Size;
  10822. MaskParams.Modification = Modification;
  10823. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10824. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10825. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10826. if (!Local && Directory)
  10827. {
  10828. FileName = UnixExcludeTrailingBackslash(FileName);
  10829. }
  10830. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10831. {
  10832. bool ImplicitMatch;
  10833. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10834. !ImplicitMatch)
  10835. {
  10836. Color = Iter->Color;
  10837. break;
  10838. }
  10839. }
  10840. }
  10841. //---------------------------------------------------------------------------
  10842. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10843. {
  10844. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10845. if (!DirView->IsEditing())
  10846. {
  10847. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10848. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10849. // while searching
  10850. if (Key == VK_BACK)
  10851. {
  10852. if (FIncrementalSearchState.Searching)
  10853. {
  10854. if (FIncrementalSearchState.Text.Length() <= 1)
  10855. {
  10856. ResetIncrementalSearch();
  10857. }
  10858. else
  10859. {
  10860. UnicodeString NewText = LeftStr(FIncrementalSearchState.Text, FIncrementalSearchState.Text.Length() - 1);
  10861. IncrementalSearch(NewText, false, false);
  10862. }
  10863. Key = 0;
  10864. }
  10865. }
  10866. }
  10867. }
  10868. //---------------------------------------------------------------------------
  10869. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10870. {
  10871. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10872. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10873. {
  10874. // Filter control sequences.
  10875. // When not searching yet, prefer use of the space for toggling file selection
  10876. // (so we cannot incrementally search for a string starting with a space).
  10877. if ((Key > VK_SPACE) ||
  10878. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && !FIncrementalSearchState.Searching))
  10879. {
  10880. IncrementalSearch(FIncrementalSearchState.Text + Key, false, false);
  10881. Key = 0;
  10882. }
  10883. }
  10884. }
  10885. //---------------------------------------------------------------------------
  10886. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10887. {
  10888. if (FIncrementalSearchState.Searching)
  10889. {
  10890. FIncrementalSearchState.Reset();
  10891. DirView(osCurrent)->UpdateStatusBar();
  10892. }
  10893. }
  10894. //---------------------------------------------------------------------------
  10895. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10896. {
  10897. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  10898. if (Item == NULL)
  10899. {
  10900. MessageBeep(MB_ICONHAND);
  10901. }
  10902. else
  10903. {
  10904. TCustomDirView * ADirView = DirView(osCurrent);
  10905. {
  10906. TAutoNestingCounter Guard(FIncrementalSearching);
  10907. ADirView->FocusItem(Item);
  10908. if (ADirView->NortonLike == nlOff)
  10909. {
  10910. if ((ADirView->Selected != Item) ||
  10911. (ADirView->SelCount > 1))
  10912. {
  10913. ADirView->ClearSelection();
  10914. ADirView->Selected = Item;
  10915. }
  10916. }
  10917. }
  10918. FIncrementalSearchState.Searching = true;
  10919. FIncrementalSearchState.Text = Text;
  10920. Item->MakeVisible(false);
  10921. TListItem * NextItem = SearchFile(Text, true, Reverse);
  10922. FIncrementalSearchState.HaveNext = (NextItem != NULL) && (NextItem != Item);
  10923. ADirView->UpdateStatusBar();
  10924. }
  10925. }
  10926. //---------------------------------------------------------------------------
  10927. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  10928. {
  10929. int Index = Item->Index;
  10930. if (!Reverse)
  10931. {
  10932. Index++;
  10933. if (Index >= Item->Owner->Count)
  10934. {
  10935. Index = 0;
  10936. }
  10937. }
  10938. else
  10939. {
  10940. Index--;
  10941. if (Index < 0)
  10942. {
  10943. Index = Item->Owner->Count - 1;
  10944. }
  10945. }
  10946. return Item->Owner->Item[Index];
  10947. }
  10948. //---------------------------------------------------------------------------
  10949. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10950. {
  10951. TCustomDirView * ADirView = DirView(osCurrent);
  10952. if (ADirView->Items->Count == 0)
  10953. {
  10954. return NULL;
  10955. }
  10956. else
  10957. {
  10958. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  10959. TListItem * Item = CurrentItem;
  10960. if (SkipCurrent)
  10961. {
  10962. Item = DebugNotNull(GetNextFile(Item, Reverse));
  10963. }
  10964. while (true)
  10965. {
  10966. bool Matches = false;
  10967. switch (WinConfiguration->PanelSearch)
  10968. {
  10969. case isNameStartOnly:
  10970. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  10971. break;
  10972. case isName:
  10973. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  10974. break;
  10975. case isAll:
  10976. int ColCount = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Count : 1;
  10977. int Index = 0;
  10978. while ((Index < ColCount) && !Matches)
  10979. {
  10980. bool Visible = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Visible[Index] : true;
  10981. if (Visible)
  10982. {
  10983. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  10984. }
  10985. Index++;
  10986. }
  10987. break;
  10988. }
  10989. if (Matches)
  10990. {
  10991. return Item;
  10992. }
  10993. Item = GetNextFile(Item, Reverse);
  10994. if (Item == CurrentItem)
  10995. {
  10996. return NULL;
  10997. }
  10998. }
  10999. }
  11000. }
  11001. //---------------------------------------------------------------------------
  11002. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  11003. {
  11004. ResetIncrementalSearch();
  11005. }
  11006. //---------------------------------------------------------------------------
  11007. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  11008. {
  11009. if (Message.CharCode == VK_TAB)
  11010. {
  11011. if (!FIncrementalSearchState.Text.IsEmpty())
  11012. {
  11013. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  11014. bool Reverse = Shift.Contains(ssShift);
  11015. IncrementalSearch(FIncrementalSearchState.Text, true, Reverse);
  11016. Message.Result = 1;
  11017. return;
  11018. }
  11019. }
  11020. else if (Message.CharCode == VK_ESCAPE)
  11021. {
  11022. if (FIncrementalSearchState.Searching)
  11023. {
  11024. ResetIncrementalSearch();
  11025. Message.Result = 1;
  11026. return;
  11027. }
  11028. }
  11029. TForm::Dispatch(&Message);
  11030. }
  11031. //---------------------------------------------------------------------------
  11032. void __fastcall TCustomScpExplorerForm::Deactivate()
  11033. {
  11034. TForm::Deactivate();
  11035. // E.g. when switching to an internal editor window
  11036. ResetIncrementalSearch();
  11037. }
  11038. //---------------------------------------------------------------------------
  11039. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  11040. {
  11041. // When switching to another application
  11042. ResetIncrementalSearch();
  11043. }
  11044. //---------------------------------------------------------------------------
  11045. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  11046. {
  11047. ResetIncrementalSearch();
  11048. }
  11049. //---------------------------------------------------------------------------
  11050. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  11051. {
  11052. if (FIncrementalSearching <= 0)
  11053. {
  11054. ResetIncrementalSearch();
  11055. }
  11056. }
  11057. //---------------------------------------------------------------------------
  11058. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  11059. {
  11060. CountClicksForWindowPrint(this);
  11061. }
  11062. //---------------------------------------------------------------------------
  11063. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  11064. {
  11065. CenterReconnectToolbar();
  11066. }
  11067. //---------------------------------------------------------------------------
  11068. void TCustomScpExplorerForm::DoBrowseFile(TCustomDirView * DirView, const UnicodeString & FileName)
  11069. {
  11070. if (!FileName.IsEmpty())
  11071. {
  11072. DirView->RestoreFocus(FileName);
  11073. if (DirView->ItemFocused != NULL)
  11074. {
  11075. DirView->ItemFocused->Selected = true;
  11076. }
  11077. }
  11078. }
  11079. //---------------------------------------------------------------------------
  11080. void __fastcall TCustomScpExplorerForm::BrowseFile(const UnicodeString & FileName)
  11081. {
  11082. DoBrowseFile(RemoteDirView, FileName);
  11083. }
  11084. //---------------------------------------------------------------------------
  11085. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  11086. {
  11087. if (!FQueueStatusUpdating)
  11088. {
  11089. bool Refresh;
  11090. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  11091. {
  11092. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  11093. }
  11094. else
  11095. {
  11096. if (FQueueFileList->GetCount() > 0)
  11097. {
  11098. FQueueFileList->Clear();
  11099. Refresh = true;
  11100. }
  11101. }
  11102. int Count = FQueueFileList->GetCount();
  11103. if (QueueFileList->Items->Count != Count)
  11104. {
  11105. DebugAssert(Refresh);
  11106. QueueFileList->Items->Count = Count;
  11107. }
  11108. if (Refresh)
  11109. {
  11110. QueueFileList->Invalidate();
  11111. }
  11112. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  11113. }
  11114. }
  11115. //---------------------------------------------------------------------------
  11116. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  11117. {
  11118. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  11119. }
  11120. //---------------------------------------------------------------------------
  11121. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  11122. {
  11123. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  11124. // See TSynchronizeChecklistDialog::UpdateTimer
  11125. if (QueueFileList->Items->Count > 0)
  11126. {
  11127. QueueFileList->Items->Item[0]->MakeVisible(false);
  11128. }
  11129. UpdateQueueFileList();
  11130. }
  11131. //---------------------------------------------------------------------------
  11132. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  11133. {
  11134. Active = QueueView3->Focused() || QueueFileList->Focused();
  11135. }
  11136. //---------------------------------------------------------------------------
  11137. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11138. {
  11139. QueueLabelUpdateStatus();
  11140. }
  11141. //---------------------------------------------------------------------------
  11142. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11143. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11144. {
  11145. int State = FQueueFileList->GetState(Item->Index);
  11146. if (State == qfsProcessed)
  11147. {
  11148. Sender->Canvas->Font->Color = clGrayText;
  11149. }
  11150. }
  11151. //---------------------------------------------------------------------------
  11152. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11153. {
  11154. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11155. QueueFileList->Column[0]->Width =
  11156. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11157. }
  11158. //---------------------------------------------------------------------------
  11159. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11160. {
  11161. QueueFileListColumnAutoSize();
  11162. }
  11163. //---------------------------------------------------------------------------
  11164. void __fastcall TCustomScpExplorerForm::CloseApp()
  11165. {
  11166. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11167. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11168. // So we clear the flag here.
  11169. DebugAssert(NonVisualDataModule->Busy);
  11170. NonVisualDataModule->EndBusy();
  11171. try
  11172. {
  11173. Close();
  11174. }
  11175. __finally
  11176. {
  11177. NonVisualDataModule->StartBusy();
  11178. }
  11179. }
  11180. //---------------------------------------------------------------------------
  11181. bool __fastcall TCustomScpExplorerForm::IsActiveTerminal(TTerminal * Terminal)
  11182. {
  11183. return (Terminal != NULL) && Terminal->Active;
  11184. }
  11185. //---------------------------------------------------------------------------
  11186. bool __fastcall TCustomScpExplorerForm::HasManagedSession()
  11187. {
  11188. return (ManagedSession != NULL);
  11189. }
  11190. //---------------------------------------------------------------------------
  11191. bool __fastcall TCustomScpExplorerForm::HasActiveTerminal()
  11192. {
  11193. return IsActiveTerminal(Terminal);
  11194. }
  11195. //---------------------------------------------------------------------------
  11196. void TCustomScpExplorerForm::LocalLocalCopy(
  11197. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11198. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11199. {
  11200. DebugFail();
  11201. }
  11202. //---------------------------------------------------------------------------
  11203. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11204. {
  11205. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11206. }
  11207. //---------------------------------------------------------------------------
  11208. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11209. {
  11210. // 1) Changing tab list triggers the OnResize.
  11211. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11212. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11213. {
  11214. // UpdateTabsCaptionTruncation should be enough
  11215. SessionListChanged(true);
  11216. }
  11217. }
  11218. //---------------------------------------------------------------------------
  11219. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11220. {
  11221. if (ASession == ManagedSession)
  11222. {
  11223. UpdateSession(ASession);
  11224. }
  11225. TSessionData * Data = ASession->StateData;
  11226. UnicodeString Result;
  11227. if (Side == osLocal)
  11228. {
  11229. Result = Data->LocalDirectory;
  11230. }
  11231. else if (DebugAlwaysTrue(Side == osOther))
  11232. {
  11233. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11234. }
  11235. return Result;
  11236. }
  11237. //---------------------------------------------------------------------------
  11238. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11239. {
  11240. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11241. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11242. if (Title == Result)
  11243. {
  11244. Result = EmptyStr;
  11245. }
  11246. else
  11247. {
  11248. Result += L"\n";
  11249. }
  11250. return Result;
  11251. }
  11252. //---------------------------------------------------------------------------
  11253. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11254. {
  11255. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11256. if (!ASession->Active)
  11257. {
  11258. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11259. }
  11260. else
  11261. {
  11262. Result += GetSessionPath(ASession, osRemote);
  11263. }
  11264. return Result;
  11265. }
  11266. //---------------------------------------------------------------------------
  11267. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11268. {
  11269. return LoadStr(NEW_REMOTE_TAB_HINT);
  11270. }
  11271. //---------------------------------------------------------------------------
  11272. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11273. {
  11274. if (Index >= 0)
  11275. {
  11276. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11277. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11278. if (TabSession == NULL)
  11279. {
  11280. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11281. if (NewTabTabCaption != TabSheet->Caption)
  11282. {
  11283. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11284. }
  11285. }
  11286. else
  11287. {
  11288. TTerminalManager * Manager = TTerminalManager::Instance();
  11289. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11290. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11291. }
  11292. }
  11293. }
  11294. //---------------------------------------------------------------------------
  11295. typedef std::vector<TListItem *> TListItemsVector;
  11296. struct TCalculateSizeOperation
  11297. {
  11298. TCalculateSizeStats Stats;
  11299. TListItemsVector ListItems;
  11300. size_t Index;
  11301. };
  11302. //---------------------------------------------------------------------------
  11303. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11304. {
  11305. TCalculateSizeOperation CalculateSizeOperation;
  11306. Side = GetSide(Side);
  11307. TCustomDirView * ADirView = DirView(Side);
  11308. bool LocalSide = IsSideLocalBrowser(Side);
  11309. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11310. std::unique_ptr<TStrings> FileList(new TStringList());
  11311. for (int Index = 0; Index < AllFileList->Count; Index++)
  11312. {
  11313. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11314. if (ADirView->ItemIsDirectory(Item))
  11315. {
  11316. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11317. CalculateSizeOperation.ListItems.push_back(Item);
  11318. }
  11319. }
  11320. CalculateSizeOperation.Index = 0;
  11321. __int64 Size = 0;
  11322. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation, &CalculateSizeOperation);
  11323. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11324. FOnFileOperationFinished = DirectorySizeCalculated;
  11325. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation, foCalculateSize);
  11326. TCalculatedSizes CalculatedSizes;
  11327. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11328. if (LocalSide)
  11329. {
  11330. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, Side);
  11331. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11332. }
  11333. else
  11334. {
  11335. TCalculateSizeParams Params;
  11336. Params.Stats = &CalculateSizeOperation.Stats;
  11337. Params.UseCache = true;
  11338. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11339. }
  11340. }
  11341. //---------------------------------------------------------------------------
  11342. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(TOperationSide Side, const UnicodeString & FileName, bool Success)
  11343. {
  11344. DebugAlwaysTrue(FCalculateSizeOperation != NULL);
  11345. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11346. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11347. // optimization
  11348. bool GotExpectedItem =
  11349. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11350. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11351. int Index = -1;
  11352. if (DebugAlwaysTrue(GotExpectedItem))
  11353. {
  11354. Index = FCalculateSizeOperation->Index;
  11355. FCalculateSizeOperation->Index++;
  11356. }
  11357. else
  11358. {
  11359. TListItemsVector::iterator I =
  11360. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11361. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11362. {
  11363. Index = I - FCalculateSizeOperation->ListItems.begin();
  11364. }
  11365. }
  11366. if (DebugAlwaysTrue(Index >= 0) && Success)
  11367. {
  11368. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11369. ADirView->SetItemCalculatedSize(Item, Size);
  11370. }
  11371. }
  11372. //---------------------------------------------------------------------------
  11373. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11374. {
  11375. Accept = false;
  11376. }
  11377. //---------------------------------------------------------------------------
  11378. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11379. {
  11380. // Send Ctrl+Gray+ to the list view
  11381. TKeyboardState KeyState;
  11382. GetKeyboardState(KeyState);
  11383. TKeyboardState NewKeyState;
  11384. memset(NewKeyState, 0, sizeof(NewKeyState));
  11385. NewKeyState[VK_CONTROL] = 0x81;
  11386. SetKeyboardState(NewKeyState);
  11387. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11388. SetKeyboardState(KeyState);
  11389. }
  11390. //---------------------------------------------------------------------------
  11391. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11392. {
  11393. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11394. }
  11395. //---------------------------------------------------------------------------
  11396. void * TCustomScpExplorerForm::SaveFocus()
  11397. {
  11398. return NULL;
  11399. }
  11400. //---------------------------------------------------------------------------
  11401. void TCustomScpExplorerForm::RestoreFocus(void * Focus)
  11402. {
  11403. DebugUsedParam(Focus);
  11404. DebugAssert(Focus == NULL);
  11405. }
  11406. //---------------------------------------------------------------------------
  11407. void TCustomScpExplorerForm::IncrementalSearchStart()
  11408. {
  11409. TCustomDirView * ADirView = DirView(osCurrent);
  11410. ADirView->SetFocus();
  11411. if (!FIncrementalSearchState.Searching)
  11412. {
  11413. FIncrementalSearchState.Searching = true;
  11414. FIncrementalSearchState.HaveNext = false;
  11415. DebugAssert(FIncrementalSearchState.Text.IsEmpty());
  11416. ADirView->UpdateStatusBar();
  11417. }
  11418. }