CustomScpExplorer.cpp 406 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134
  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. AppLog(L"Destroying main window");
  277. FInvalid = true;
  278. ReleaseHiContrastTheme();
  279. if (FClipboardTerminal != NULL)
  280. {
  281. ClipboardClear(); // implies ClipboardStop
  282. }
  283. // this has to be one of the very first things to do
  284. StopUpdateThread();
  285. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  286. TTerminalManager::Instance()->ScpExplorer = NULL;
  287. delete FCustomCommandLocalFileList;
  288. delete FCustomCommandRemoteFileList;
  289. delete FCustomCommandMenu;
  290. delete FTrayIcon;
  291. FTrayIcon = NULL;
  292. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  293. delete FEditorManager;
  294. ForceCloseLocalEditors();
  295. delete FLocalEditors;
  296. HideFileFindDialog();
  297. if (FDelayedDeletionTimer)
  298. {
  299. DoDelayedDeletion(NULL);
  300. SAFE_DESTROY(FDelayedDeletionTimer);
  301. }
  302. SAFE_DESTROY(FDelayedDeletionList);
  303. // sometimes we do not get DDEnd so the list is not released
  304. SAFE_DESTROY(FDDFileList);
  305. DebugAssert(FSynchronizeController == NULL);
  306. CloseHandle(FDDExtMutex);
  307. FDDExtMutex = NULL;
  308. FreeLibrary(FOle32Library);
  309. FOle32Library = NULL;
  310. FDragMoveCursor = NULL;
  311. DebugAssert(!FErrorList);
  312. if (FEverShown)
  313. {
  314. // when window is never shown (like when running command-line operation),
  315. // particularly window site is not restored correctly (BoundsRect value set
  316. // in RestoreForm gets lost during handle allocation), so we do not want
  317. // it to be stored
  318. AppLog(L"Storing main window configuration");
  319. StoreParams();
  320. }
  321. ManagedSession = NULL;
  322. Queue = NULL;
  323. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  324. NonVisualDataModule->ScpExplorer = NULL;
  325. delete FQueueScrollOnDragOver;
  326. FQueueScrollOnDragOver = NULL;
  327. delete FQueueController;
  328. FQueueController = NULL;
  329. delete FQueueStatusSection;
  330. FQueueStatusSection = NULL;
  331. delete FQueueStatus;
  332. FQueueStatus = NULL;
  333. delete FUserActionTimer;
  334. FUserActionTimer = NULL;
  335. delete FNoteTimer;
  336. delete FNotes;
  337. delete FNoteData;
  338. SAFE_DESTROY(FDocks);
  339. SessionsPageControl->Images = NULL;
  340. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  341. SAFE_DESTROY(FSessionColors);
  342. SAFE_DESTROY(FSessionsDragDropFilesEx);
  343. SAFE_DESTROY(FHistoryMenu[0][0]);
  344. SAFE_DESTROY(FHistoryMenu[0][1]);
  345. SAFE_DESTROY(FHistoryMenu[1][0]);
  346. SAFE_DESTROY(FHistoryMenu[1][1]);
  347. if (FHiddenWindow != NULL)
  348. {
  349. DestroyWindow(FHiddenWindow);
  350. FHiddenWindow = NULL;
  351. }
  352. AppLog(L"Main window destroyed");
  353. }
  354. //---------------------------------------------------------------------------
  355. void TCustomScpExplorerForm::ReleaseHiContrastTheme()
  356. {
  357. if (FHiContrastTheme != NULL)
  358. {
  359. ReleaseTBXTheme(FHiContrastTheme);
  360. FHiContrastTheme = NULL;
  361. }
  362. }
  363. //---------------------------------------------------------------------------
  364. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  365. {
  366. std::unique_ptr<TSessionData> Data;
  367. if (!Session.IsEmpty())
  368. {
  369. bool DefaultsOnly;
  370. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  371. }
  372. TTerminalManager * Manager = TTerminalManager::Instance();
  373. for (int Index = 0; Index < Manager->Count; Index++)
  374. {
  375. TTerminal * Terminal = Manager->Sessions[Index];
  376. if (Session.IsEmpty() ||
  377. Manager->IsActiveTerminalForSite(Terminal, Data.get()))
  378. {
  379. if (Path.IsEmpty())
  380. {
  381. Terminal->ClearCaches();
  382. }
  383. else
  384. {
  385. Terminal->DirectoryModified(Path, true);
  386. }
  387. }
  388. }
  389. // We should flag a pending refresh for the background terminals or busy foreground terminals
  390. if (HasActiveTerminal() &&
  391. CanCommandLineFromAnotherInstance() &&
  392. (Session.IsEmpty() || Manager->IsActiveTerminalForSite(Terminal, Data.get())) &&
  393. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  394. {
  395. Terminal->ReloadDirectory();
  396. }
  397. }
  398. //---------------------------------------------------------------------------
  399. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  400. {
  401. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  402. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  403. size_t MessageSize = sizeof(TCopyDataMessage);
  404. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  405. if (Result)
  406. {
  407. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  408. Result = (Message.Version == TCopyDataMessage::Version1);
  409. if (Result)
  410. {
  411. switch (Message.Command)
  412. {
  413. case TCopyDataMessage::CommandCanCommandLine:
  414. Result = CanCommandLineFromAnotherInstance();
  415. if (Result)
  416. {
  417. AppLog(L"Can process command-line from other instance");
  418. }
  419. else
  420. {
  421. AppLog(L"Cannot process command-line from other instance");
  422. }
  423. break;
  424. case TCopyDataMessage::CommandCommandLine:
  425. {
  426. UnicodeString CommandLine(Message.CommandLine);
  427. Result = CommandLineFromAnotherInstance(CommandLine);
  428. }
  429. break;
  430. case TCopyDataMessage::RefreshPanel:
  431. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  432. break;
  433. case TCopyDataMessage::MainWindowCheck:
  434. Result = true;
  435. break;
  436. default:
  437. Result = false;
  438. break;
  439. }
  440. }
  441. }
  442. Message.Result = Result ? 1 : 0;
  443. }
  444. //---------------------------------------------------------------------------
  445. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  446. {
  447. WNDCLASS WindowClass = {0};
  448. WindowClass.lpfnWndProc = DefWindowProc;
  449. WindowClass.hInstance = HInstance;
  450. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  451. FHiddenWindow = NULL;
  452. if (RegisterClass(&WindowClass))
  453. {
  454. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  455. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  456. }
  457. }
  458. //---------------------------------------------------------------------------
  459. bool __fastcall TCustomScpExplorerForm::CanConsole()
  460. {
  461. return
  462. HasActiveTerminal() &&
  463. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  464. }
  465. //---------------------------------------------------------------------------
  466. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  467. {
  468. bool Result = Visible && !NonVisualDataModule->Busy;
  469. return Result;
  470. }
  471. //---------------------------------------------------------------------------
  472. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  473. const UnicodeString & CommandLine)
  474. {
  475. TProgramParams Params(CommandLine);
  476. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  477. if (Result)
  478. {
  479. NonVisualDataModule->StartBusy();
  480. try
  481. {
  482. // this action is initiated from another process,
  483. // so it's likely that our window is not visible,
  484. // and user won't see what is going on
  485. Application->BringToFront();
  486. // reload sessions as we may be asked to open a session
  487. // just stored by another instance
  488. StoredSessions->Reload();
  489. UnicodeString SessionName = Params.Param[1];
  490. std::unique_ptr<TObjectList> DataList(new TObjectList());
  491. try
  492. {
  493. UnicodeString DownloadFile; // unused
  494. int Flags = GetCommandLineParseUrlFlags(&Params);
  495. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  496. }
  497. catch (EAbort &)
  498. {
  499. // Happens when opening session in PuTTY and in other situations,
  500. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  501. // to process the command-line on its own (or to pass it to yet another instance)
  502. }
  503. if (DataList->Count > 0)
  504. {
  505. TTerminalManager * Manager = TTerminalManager::Instance();
  506. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  507. }
  508. }
  509. __finally
  510. {
  511. NonVisualDataModule->EndBusy();
  512. }
  513. }
  514. return Result;
  515. }
  516. //---------------------------------------------------------------------------
  517. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  518. {
  519. TManagedTerminal * Result;
  520. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  521. {
  522. Result = FManagedSession;
  523. }
  524. else
  525. {
  526. Result = NULL;
  527. }
  528. return Result;
  529. }
  530. //---------------------------------------------------------------------------
  531. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  532. {
  533. if (FManagedSession != value)
  534. {
  535. TWindowLock Lock(this);
  536. SessionChanging();
  537. DoSetManagedSession(value, false);
  538. }
  539. }
  540. //---------------------------------------------------------------------------
  541. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  542. {
  543. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  544. FManagedSession = value;
  545. {
  546. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect, false);
  547. TAutoFlag SessionChangingFlag(FSessionChanging);
  548. SessionChanged(Replace);
  549. }
  550. if (Terminal != NULL)
  551. {
  552. TransferPresetAutoSelect();
  553. }
  554. // Update app and tab titles, prevented above by FSessionChanging.
  555. UpdateControls();
  556. }
  557. //---------------------------------------------------------------------------
  558. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  559. {
  560. FEditorManager->ProcessFiles(FileTerminalReplaced, value);
  561. DoSetManagedSession(value, true);
  562. }
  563. //---------------------------------------------------------------------------
  564. void __fastcall TCustomScpExplorerForm::SessionChanging()
  565. {
  566. if (ManagedSession != NULL)
  567. {
  568. UpdateSession(ManagedSession);
  569. }
  570. }
  571. //---------------------------------------------------------------------------
  572. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  573. {
  574. if (ManagedSession != NULL)
  575. {
  576. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  577. }
  578. if (!TTerminalManager::Instance()->Updating)
  579. {
  580. SessionListChanged();
  581. }
  582. if (Terminal != NULL)
  583. {
  584. TObject * State = NULL;
  585. if (WinConfiguration->PreservePanelState)
  586. {
  587. State = Terminal->RemoteExplorerState;
  588. DirView(osRemote)->AnnounceState(State);
  589. }
  590. try
  591. {
  592. if (Replaced)
  593. {
  594. RemoteDirView->ReplaceTerminal(Terminal);
  595. }
  596. else
  597. {
  598. RemoteDirView->Terminal = Terminal;
  599. }
  600. if (Terminal->Active)
  601. {
  602. Terminal->RefreshDirectory();
  603. }
  604. if (State != NULL)
  605. {
  606. DirView(osRemote)->RestoreState(State);
  607. }
  608. }
  609. __finally
  610. {
  611. DirView(osRemote)->AnnounceState(NULL);
  612. }
  613. }
  614. else
  615. {
  616. RemoteDirView->Terminal = NULL;
  617. }
  618. InitStatusBar();
  619. UpdateTransferList();
  620. // Update panels Enable state before refreshing the labels
  621. UpdateControls();
  622. }
  623. //---------------------------------------------------------------------------
  624. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  625. {
  626. if (Queue != value)
  627. {
  628. if (FQueue != NULL)
  629. {
  630. FQueue->OnListUpdate = NULL;
  631. FQueue->OnQueueItemUpdate = NULL;
  632. }
  633. FQueue = value;
  634. if (FQueue != NULL)
  635. {
  636. DebugAssert(FQueue->OnListUpdate == NULL);
  637. FQueue->OnListUpdate = QueueListUpdate;
  638. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  639. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  640. }
  641. QueueChanged();
  642. }
  643. }
  644. //---------------------------------------------------------------------------
  645. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  646. TListItem * Item)
  647. {
  648. if (FQueueActedItem == Item)
  649. {
  650. FQueueActedItem = NULL;
  651. if ((QueueView3->PopupMenu != NULL) &&
  652. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  653. {
  654. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  655. ReleaseCapture();
  656. }
  657. }
  658. if (Item->Data == FPendingQueueActionItem)
  659. {
  660. FPendingQueueActionItem = NULL;
  661. }
  662. }
  663. //---------------------------------------------------------------------------
  664. bool TCustomScpExplorerForm::IsAnythingQueued()
  665. {
  666. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  667. }
  668. //---------------------------------------------------------------------------
  669. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  670. {
  671. {
  672. TGuard Guard(FQueueStatusSection);
  673. FQueueStatusInvalidated = false;
  674. if (FQueue != NULL)
  675. {
  676. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  677. }
  678. }
  679. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  680. {
  681. FMaxQueueLength = FQueueStatus->Count;
  682. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  683. }
  684. {
  685. TAutoFlag Flag(FQueueStatusUpdating);
  686. FQueueController->UpdateQueueStatus(FQueueStatus);
  687. }
  688. UpdateQueueFileList();
  689. SetQueueProgress();
  690. UpdateQueueView();
  691. bool IsEmpty = !IsAnythingQueued();
  692. if (IsEmpty && (Terminal != NULL))
  693. {
  694. TOnceDoneOperation OnceDoneOperation =
  695. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  696. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  697. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  698. {
  699. FQueue->Enabled = false;
  700. }
  701. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  702. {
  703. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  704. }
  705. }
  706. }
  707. //---------------------------------------------------------------------------
  708. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  709. {
  710. UnicodeString Result;
  711. if (FQueueStatus != NULL)
  712. {
  713. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  714. {
  715. TFileOperationProgressType * ProgressData =
  716. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  717. if ((ProgressData != NULL) && ProgressData->InProgress)
  718. {
  719. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  720. }
  721. }
  722. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  723. {
  724. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  725. }
  726. }
  727. return Result;
  728. }
  729. //---------------------------------------------------------------------------
  730. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  731. {
  732. ComponentVisible[fcQueueView] =
  733. !IsLocalBrowserMode() &&
  734. ((WinConfiguration->QueueView.Show == qvShow) ||
  735. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  736. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  737. }
  738. //---------------------------------------------------------------------------
  739. void __fastcall TCustomScpExplorerForm::QueueChanged()
  740. {
  741. if (FQueueStatus != NULL)
  742. {
  743. // UpdateFileList implementation relies on the status being recreated when session changes
  744. delete FQueueStatus;
  745. FQueueStatus = NULL;
  746. }
  747. UpdateQueueStatus(true);
  748. }
  749. //---------------------------------------------------------------------------
  750. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  751. {
  752. if (FQueue == Queue)
  753. {
  754. FQueueStatusInvalidated = true;
  755. }
  756. }
  757. //---------------------------------------------------------------------------
  758. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  759. TQueueItem * Item)
  760. {
  761. if (FQueue == Queue)
  762. {
  763. TGuard Guard(FQueueStatusSection);
  764. // this may be running in parallel with QueueChanged
  765. if (FQueueStatus != NULL)
  766. {
  767. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  768. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  769. {
  770. FRefreshLocalDirectory = (QueueItem == NULL) ||
  771. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  772. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  773. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  774. }
  775. if (QueueItem != NULL)
  776. {
  777. QueueItem->UserData = (void*)true;
  778. FQueueItemInvalidated = true;
  779. }
  780. }
  781. }
  782. }
  783. //---------------------------------------------------------------------------
  784. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  785. {
  786. // during standalone editing, we have no way to see/control queue,
  787. // so we have to always popup prompts automatically
  788. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  789. }
  790. //---------------------------------------------------------------------------
  791. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  792. {
  793. if (FQueueStatus != NULL)
  794. {
  795. bool QueueAutoPopup = IsQueueAutoPopup();
  796. bool NeedRefresh = FQueueController->NeedRefresh();
  797. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  798. FQueueItemInvalidated = false;
  799. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  800. bool Updated = false;
  801. TQueueItemProxy * QueueItem;
  802. bool WasUserAction;
  803. for (int Index = 0; Index < Limit; Index++)
  804. {
  805. bool Update = false;
  806. QueueItem = FQueueStatus->Items[Index];
  807. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  808. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  809. (FPendingQueueActionItem == NULL))
  810. {
  811. FPendingQueueActionItem = QueueItem;
  812. FUserActionTimer->Enabled = true;
  813. }
  814. if ((bool)QueueItem->UserData)
  815. {
  816. QueueItem->UserData = (void*)false;
  817. QueueItem->Update();
  818. Updated = true;
  819. Update = true;
  820. }
  821. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  822. {
  823. Update = true;
  824. }
  825. if (Update)
  826. {
  827. FQueueController->RefreshQueueItem(QueueItem);
  828. }
  829. }
  830. if (Updated)
  831. {
  832. NonVisualDataModule->UpdateNonVisibleActions();
  833. SetQueueProgress();
  834. UpdateQueueFileList();
  835. }
  836. }
  837. }
  838. //---------------------------------------------------------------------------
  839. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  840. {
  841. if (FTaskbarList != NULL)
  842. {
  843. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  844. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  845. }
  846. }
  847. //---------------------------------------------------------------------------
  848. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  849. {
  850. if (Progress >= 0)
  851. {
  852. if (FTaskbarList != NULL)
  853. {
  854. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  855. }
  856. }
  857. else
  858. {
  859. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  860. }
  861. }
  862. //---------------------------------------------------------------------------
  863. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  864. {
  865. int OverallProgress;
  866. // FProgressForm is null when this is called from SetQueueProgress
  867. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  868. {
  869. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  870. }
  871. else if (!ProgressData->IsIndeterminate())
  872. {
  873. OverallProgress = ProgressData->OverallProgress();
  874. }
  875. else
  876. {
  877. OverallProgress = -1;
  878. }
  879. SetTaskbarListProgressValue(OverallProgress);
  880. }
  881. //---------------------------------------------------------------------------
  882. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  883. {
  884. TTerminalManager::Instance()->QueueStatusUpdated();
  885. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  886. {
  887. // Do not animate task bar button, when items are queued, but processing is disabled
  888. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  889. {
  890. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  891. {
  892. TFileOperationProgressType * ProgressData = NULL;
  893. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  894. {
  895. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  896. }
  897. if ((ProgressData != NULL) &&
  898. ProgressData->InProgress)
  899. {
  900. SetTaskbarListProgressValue(ProgressData);
  901. }
  902. else
  903. {
  904. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  905. }
  906. }
  907. else
  908. {
  909. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  910. }
  911. }
  912. else
  913. {
  914. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  915. }
  916. }
  917. UpdateQueueLabel();
  918. }
  919. //---------------------------------------------------------------------------
  920. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  921. {
  922. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  923. if (FQueueStatus != NULL)
  924. {
  925. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  926. if (ActiveAndPendingPrimaryCount > 0)
  927. {
  928. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  929. }
  930. }
  931. QueueLabel->Caption = Caption;
  932. }
  933. //---------------------------------------------------------------------------
  934. void TCustomScpExplorerForm::CheckStoreTransition()
  935. {
  936. if (WinConfiguration->StoreTransition == stInit)
  937. {
  938. if (IsUWP())
  939. {
  940. WinConfiguration->StoreTransition = stStoreFresh;
  941. AppLog(L"Fresh UWP/store installation");
  942. }
  943. else
  944. {
  945. WinConfiguration->StoreTransition = stStandard;
  946. AppLog(L"Fresh standard installation");
  947. }
  948. }
  949. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  950. {
  951. WinConfiguration->StoreTransition = stStoreMigrated;
  952. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  953. AppLog(L"Standard installation migrated to store installation");
  954. }
  955. if (WinConfiguration->StoreTransition == stStoreMigrated)
  956. {
  957. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  958. Toolbar->Parent = MessageDock;
  959. Toolbar->FullSize = true;
  960. Toolbar->Color = Application->HintColor;
  961. TTBXLabelItem * LabelItem;
  962. LabelItem = new TTBXLabelItem(Toolbar);
  963. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  964. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  965. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  966. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  967. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  968. Toolbar->Items->Add(LabelItem);
  969. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  970. LinkItem->FontSettings->Color = LinkColor;
  971. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  972. LinkItem->OnClick = StoreTransitionLinkClick;
  973. Toolbar->Items->Add(LinkItem);
  974. AddMenuSeparator(Toolbar->Items);
  975. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  976. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  977. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  978. CloseItem->OnClick = StoreTransitionCloseClick;
  979. Toolbar->Items->Add(CloseItem);
  980. GiveTBItemPriority(CloseItem);
  981. }
  982. }
  983. //---------------------------------------------------------------------------
  984. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  985. {
  986. ShowHelp(HELP_STORE_TRANSITION);
  987. }
  988. //---------------------------------------------------------------------------
  989. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  990. {
  991. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  992. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  993. delete Toolbar;
  994. WinConfiguration->StoreTransition = stStoreAcknowledged;
  995. UpdateControls();
  996. }
  997. //---------------------------------------------------------------------------
  998. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  999. {
  1000. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  1001. static_cast<TComponent*>(GetComponent(fcTransferList)));
  1002. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  1003. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  1004. TransferList->Strings->BeginUpdate();
  1005. try
  1006. {
  1007. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  1008. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  1009. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  1010. if (FTransferDropDownHint.IsEmpty())
  1011. {
  1012. FTransferDropDownHint = TransferDropDown->Hint;
  1013. }
  1014. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1015. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1016. TransferDropDown->Text = StripHotkey(Name);
  1017. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1018. (FTransferDropDownHint, StripHotkey(Name),
  1019. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1020. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1021. // update the label, otherwise when it is updated only on the first draw
  1022. // of the list, it is drawn "bold" for some reason
  1023. FTransferListHoverIndex = TransferList->ItemIndex;
  1024. UpdateTransferLabel();
  1025. }
  1026. __finally
  1027. {
  1028. TransferList->Strings->EndUpdate();
  1029. }
  1030. }
  1031. //---------------------------------------------------------------------------
  1032. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1033. {
  1034. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1035. DebugAssert(Toolbar != NULL);
  1036. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1037. }
  1038. //---------------------------------------------------------------------------
  1039. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1040. {
  1041. TForm::UpdateActions();
  1042. if (ComponentVisible[fcCustomCommandsBand])
  1043. {
  1044. UpdateCustomCommandsToolbar();
  1045. }
  1046. }
  1047. //---------------------------------------------------------------------------
  1048. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1049. {
  1050. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1051. }
  1052. //---------------------------------------------------------------------------
  1053. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1054. {
  1055. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1056. {
  1057. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1058. // Without this, the panel turns gray and unused part of header turns black
  1059. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1060. }
  1061. }
  1062. //---------------------------------------------------------------------------
  1063. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1064. {
  1065. Color = GetBtnFaceColor();
  1066. DebugAssert(Configuration && RemoteDirView);
  1067. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1068. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1069. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1070. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1071. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1072. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1073. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1074. UpdateRowSelect(RemoteDirView);
  1075. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1076. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1077. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1078. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1079. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1080. UpdateSessionsPageControlHeight();
  1081. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1082. UpdateToolbarDisplayMode();
  1083. UpdateTransferList();
  1084. if (Terminal != NULL)
  1085. {
  1086. TransferPresetAutoSelect();
  1087. }
  1088. UpdateQueueView();
  1089. UpdateControls();
  1090. // this can be called even before constuctor finishes.
  1091. if (FEditorManager != NULL)
  1092. {
  1093. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1094. }
  1095. // this can be called even before constuctor finishes.
  1096. if (FLocalEditors != NULL)
  1097. {
  1098. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1099. {
  1100. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1101. }
  1102. }
  1103. if (ComponentVisible[fcCustomCommandsBand])
  1104. {
  1105. UpdateCustomCommandsToolbar();
  1106. }
  1107. // show only when keeping queue items forever,
  1108. // otherwise, it's enough to have it in the context menu
  1109. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1110. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1111. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1112. {
  1113. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1114. FFileColorsCurrent = WinConfiguration->FileColors;
  1115. FileColorsChanged();
  1116. }
  1117. if ((GetNewTabTab()->CaptionTruncation != GetNewTabTabCaptionTruncation()) &&
  1118. (FSessionColors != NULL))
  1119. {
  1120. SessionListChanged();
  1121. }
  1122. }
  1123. //---------------------------------------------------------------------------
  1124. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1125. {
  1126. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1127. DirView->Invalidate();
  1128. }
  1129. //---------------------------------------------------------------------------
  1130. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1131. {
  1132. DoFileColorsChanged(RemoteDirView);
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1136. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  1137. void * /*Arg*/)
  1138. {
  1139. if (Token != NULL)
  1140. {
  1141. TForm * Editor = dynamic_cast<TForm*>(Token);
  1142. DebugAssert(Editor != NULL);
  1143. ReconfigureEditorForm(Editor);
  1144. }
  1145. }
  1146. //---------------------------------------------------------------------------
  1147. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1148. {
  1149. WinConfiguration->DDTransferConfirmation = asOn;
  1150. }
  1151. //---------------------------------------------------------------------------
  1152. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1153. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1154. {
  1155. // noop
  1156. }
  1157. //---------------------------------------------------------------------------
  1158. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1159. {
  1160. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1164. {
  1165. if (DoNotShowAgain)
  1166. {
  1167. if (DragDrop)
  1168. {
  1169. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1170. {
  1171. PopupTrayBalloon(
  1172. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1173. }
  1174. WinConfiguration->DDTransferConfirmation = asOff;
  1175. }
  1176. else
  1177. {
  1178. WinConfiguration->ConfirmTransferring = false;
  1179. }
  1180. }
  1181. else
  1182. {
  1183. // User explicitly unchecked "do not show again",
  1184. // so show him the dialog the next time
  1185. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1186. {
  1187. WinConfiguration->DDTransferConfirmation = asOn;
  1188. }
  1189. }
  1190. }
  1191. //---------------------------------------------------------------------------
  1192. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1193. TTransferDirection Direction, TTransferType Type, bool Temp,
  1194. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1195. bool Confirm, bool DragDrop, int Options)
  1196. {
  1197. bool Result = true;
  1198. DebugAssert(HasActiveTerminal());
  1199. // these parameters are known in advance
  1200. int Params =
  1201. FLAGMASK(Type == ttMove, cpDelete);
  1202. bool ToTemp = (Temp && (Direction == tdToLocal));
  1203. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1204. {
  1205. bool DisableNewerOnly =
  1206. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1207. ToTemp;
  1208. Options |=
  1209. FLAGMASK(ToTemp, coTemp) |
  1210. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1211. coDoNotShowAgain;
  1212. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1213. int CopyParamAttrs = (Direction == tdToRemote ?
  1214. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1215. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1216. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1217. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1218. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1219. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1220. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1221. if (Result)
  1222. {
  1223. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1224. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1225. }
  1226. }
  1227. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1228. {
  1229. Configuration->Usage->Inc(L"TransfersOnBackground");
  1230. // these parameter are known only after transfer dialog
  1231. Params |=
  1232. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1233. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1234. Result = false;
  1235. ClearTransferSourceSelection(Direction);
  1236. }
  1237. return Result;
  1238. }
  1239. //---------------------------------------------------------------------------
  1240. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1241. {
  1242. if (FOnFileOperationFinished != NULL)
  1243. {
  1244. FOnFileOperationFinished(Side, UnicodeString(), true);
  1245. }
  1246. else
  1247. {
  1248. if (HasDirView[Side])
  1249. {
  1250. DirView(Side)->SelectAll(smNone);
  1251. }
  1252. }
  1253. }
  1254. //---------------------------------------------------------------------------
  1255. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1256. {
  1257. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1258. ClearOperationSelection(Side);
  1259. }
  1260. //---------------------------------------------------------------------------
  1261. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1262. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1263. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1264. int Params)
  1265. {
  1266. DebugAssert(Queue != NULL);
  1267. bool SingleFile = false;
  1268. if (FileList->Count == 1)
  1269. {
  1270. if (Direction == tdToRemote)
  1271. {
  1272. UnicodeString FileName = FileList->Strings[0];
  1273. SingleFile = FileExists(ApiPath(FileName));
  1274. }
  1275. else
  1276. {
  1277. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1278. SingleFile = !File->IsDirectory;
  1279. }
  1280. }
  1281. TQueueItem * QueueItem;
  1282. if (Direction == tdToRemote)
  1283. {
  1284. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1285. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1286. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1287. }
  1288. else
  1289. {
  1290. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1291. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1292. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1293. }
  1294. AddQueueItem(Queue, QueueItem, Terminal);
  1295. }
  1296. //---------------------------------------------------------------------------
  1297. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1298. {
  1299. if (Queue->IsEmpty)
  1300. {
  1301. Terminal->QueueOperationStart = Now();
  1302. }
  1303. Queue->AddItem(QueueItem);
  1304. }
  1305. //---------------------------------------------------------------------------
  1306. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1307. {
  1308. }
  1309. //---------------------------------------------------------------------------
  1310. void __fastcall TCustomScpExplorerForm::InitControls()
  1311. {
  1312. DebugAssert(FDocks != NULL);
  1313. for (int Index = 0; Index < ComponentCount; Index++)
  1314. {
  1315. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1316. if ((Dock != NULL) && (Dock->Tag == 0))
  1317. {
  1318. FDocks->Add(Dock);
  1319. }
  1320. }
  1321. CollectItemsWithTextDisplayMode(this);
  1322. }
  1323. //---------------------------------------------------------------------------
  1324. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1325. {
  1326. ConfigurationChanged();
  1327. QueuePanel->Height =
  1328. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1329. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1330. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1331. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1332. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1333. QueueFileList->Height =
  1334. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1335. if (QueueFileList->Visible)
  1336. {
  1337. AdjustQueueLayout();
  1338. }
  1339. UpdateCustomCommandsToolbar();
  1340. }
  1341. //---------------------------------------------------------------------------
  1342. void __fastcall TCustomScpExplorerForm::StoreParams()
  1343. {
  1344. int APixelsPerInch = GetControlPixelsPerInch(this);
  1345. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1346. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1347. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1348. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1349. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1350. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1351. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1352. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1356. {
  1357. if (!FFormRestored)
  1358. {
  1359. FFormRestored = true;
  1360. RestoreFormParams();
  1361. }
  1362. TForm::CreateParams(Params);
  1363. }
  1364. //---------------------------------------------------------------------------
  1365. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1366. {
  1367. DebugAssert(FDocks != NULL);
  1368. for (int Index = 0; Index < FDocks->Count; Index++)
  1369. {
  1370. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1371. }
  1372. }
  1373. //---------------------------------------------------------------------------
  1374. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1375. {
  1376. SetDockAllowDrag(true);
  1377. while (!ButtonsStr.IsEmpty())
  1378. {
  1379. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1380. UnicodeString Name = CutToChar(S, L'=', true);
  1381. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1382. {
  1383. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1384. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1385. {
  1386. while (!S.IsEmpty())
  1387. {
  1388. UnicodeString S2 = CutToChar(S, L',', true);
  1389. UnicodeString Name = CutToChar(S2, L':', true);
  1390. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1391. {
  1392. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1393. if (SameText(GetToolbarItemName(Item), Name))
  1394. {
  1395. // forward compatibility
  1396. UnicodeString S3 = CutToChar(S2, L':', true);
  1397. bool Visible = StrToIntDef(S3, 0);
  1398. Item->Visible = Visible;
  1399. }
  1400. }
  1401. }
  1402. }
  1403. }
  1404. }
  1405. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1406. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1407. }
  1408. //---------------------------------------------------------------------------
  1409. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1410. {
  1411. UnicodeString Result;
  1412. SetDockAllowDrag(true);
  1413. Result = ::GetToolbarsLayoutStr(this);
  1414. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1415. return Result;
  1416. }
  1417. //---------------------------------------------------------------------------
  1418. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1419. {
  1420. UnicodeString Result;
  1421. if (Item->Action != NULL)
  1422. {
  1423. Result = Item->Action->Name;
  1424. Result = RemoveSuffix(Result, L"Action", true);
  1425. }
  1426. else
  1427. {
  1428. Result = Item->Name;
  1429. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1430. Result = RemoveSuffix(Result, L"Item", true);
  1431. }
  1432. return Result;
  1433. }
  1434. //---------------------------------------------------------------------------
  1435. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1436. {
  1437. UnicodeString Result;
  1438. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1439. {
  1440. UnicodeString ToolbarStr;
  1441. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1442. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1443. {
  1444. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1445. {
  1446. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1447. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1448. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1449. // and save the changes here only.
  1450. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1451. {
  1452. UnicodeString Name = GetToolbarItemName(Item);
  1453. DebugAssert(Name.Pos(L"TBX") == 0);
  1454. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1455. }
  1456. }
  1457. }
  1458. if (!ToolbarStr.IsEmpty())
  1459. {
  1460. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1461. }
  1462. }
  1463. return Result;
  1464. }
  1465. //---------------------------------------------------------------------------
  1466. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1467. {
  1468. DebugAssert(FProgressForm == NULL);
  1469. bool AllowSkip = HasActiveTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1470. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1471. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1472. FProgressForm->DeleteLocalToRecycleBin =
  1473. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1474. FProgressForm->DeleteRemoteToRecycleBin =
  1475. HasActiveTerminal() &&
  1476. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1477. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1478. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1479. LockWindow();
  1480. // Actually, do not know what hides the progress once the operation finishes
  1481. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1482. SetTaskbarListProgressState(TBPF_NORMAL);
  1483. }
  1484. //---------------------------------------------------------------------------
  1485. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1486. {
  1487. UnlockWindow();
  1488. SAFE_DESTROY(FProgressForm);
  1489. SetQueueProgress();
  1490. }
  1491. //---------------------------------------------------------------------------
  1492. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1493. TFileOperationProgressType & ProgressData)
  1494. {
  1495. // Download to temporary local directory
  1496. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1497. {
  1498. bool Continue = true;
  1499. FPendingTempSpaceWarn = false;
  1500. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1501. if (!Continue)
  1502. {
  1503. Abort();
  1504. }
  1505. }
  1506. // operation is being executed and we still didn't show up progress form
  1507. if (ProgressData.InProgress && !FProgressForm)
  1508. {
  1509. CreateProgressForm(NULL);
  1510. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1511. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1512. }
  1513. // operation is finished (or terminated), so we hide progress form
  1514. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1515. {
  1516. DestroyProgressForm();
  1517. if (ProgressData.Operation == foCalculateSize)
  1518. {
  1519. // When calculating size before transfer, the abort caused by
  1520. // cancel flag set due to "MoveToQueue" below,
  1521. // is not propagated back to us in ExecuteFileOperation,
  1522. // as it is silently swallowed.
  1523. // So we explicitly (re)throw it here.
  1524. if (FMoveToQueue)
  1525. {
  1526. Abort();
  1527. }
  1528. }
  1529. else
  1530. {
  1531. if ((ProgressData.Cancel == csContinue) &&
  1532. !FAutoOperation)
  1533. {
  1534. OperationComplete(ProgressData.StartTime);
  1535. }
  1536. }
  1537. }
  1538. if (FProgressForm &&
  1539. // Can happen only during synchronization, when ending one of the operations
  1540. ProgressData.InProgress)
  1541. {
  1542. FProgressForm->SetProgressData(ProgressData);
  1543. DebugAssert(ProgressData.InProgress);
  1544. SetTaskbarListProgressValue(&ProgressData);
  1545. if (FProgressForm->Cancel > csContinue)
  1546. {
  1547. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1548. if (FProgressForm->Cancel == csCancelFile)
  1549. {
  1550. FProgressForm->ClearCancel();
  1551. }
  1552. // cancel cancels even the move
  1553. FMoveToQueue = false;
  1554. }
  1555. else if (FProgressForm->MoveToQueue)
  1556. {
  1557. FMoveToQueue = true;
  1558. ProgressData.SetCancelAtLeast(csCancel);
  1559. }
  1560. if ((FTransferResumeList != NULL) &&
  1561. ProgressData.InProgress &&
  1562. ProgressData.IsTransfer() &&
  1563. !ProgressData.FullFileName.IsEmpty())
  1564. {
  1565. if ((FTransferResumeList->Count == 0) ||
  1566. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1567. {
  1568. // note that we do not recognize directories from files here
  1569. FTransferResumeList->Add(ProgressData.FullFileName);
  1570. }
  1571. }
  1572. }
  1573. }
  1574. //---------------------------------------------------------------------------
  1575. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1576. const TDateTime & StartTime)
  1577. {
  1578. if (GUIConfiguration->BeepOnFinish &&
  1579. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1580. {
  1581. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1582. DWORD Sound;
  1583. if (!ExtractFileExt(BeepSound).IsEmpty())
  1584. {
  1585. Sound = SND_FILENAME;
  1586. }
  1587. else
  1588. {
  1589. Sound = SND_ALIAS;
  1590. }
  1591. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1592. }
  1593. }
  1594. //---------------------------------------------------------------------------
  1595. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1596. TFileOperationProgressType & ProgressData)
  1597. {
  1598. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1599. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1600. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1601. FileOperationProgress(ProgressData);
  1602. }
  1603. //---------------------------------------------------------------------------
  1604. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1605. {
  1606. UnicodeString Result;
  1607. if (FProgressForm != NULL)
  1608. {
  1609. Result = FProgressForm->ProgressStr();
  1610. }
  1611. return Result;
  1612. }
  1613. //---------------------------------------------------------------------------
  1614. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1615. bool DragDrop)
  1616. {
  1617. return (!DragDrop && (DropSourceControl == NULL)) ||
  1618. (DropSourceControl == DirView(osOther));
  1619. }
  1620. //---------------------------------------------------------------------------
  1621. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1622. {
  1623. TCustomDirView * ADirView = DirView(Side);
  1624. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1625. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1626. // this can happen when local drive is unplugged in the middle of the operation
  1627. if (Item != NULL)
  1628. {
  1629. if (Unselect)
  1630. {
  1631. Item->Selected = false;
  1632. }
  1633. ADirView->MakeProgressVisible(Item);
  1634. }
  1635. return Item;
  1636. }
  1637. //---------------------------------------------------------------------------
  1638. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1639. TFileOperation Operation, TOperationSide Side,
  1640. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1641. TOnceDoneOperation & OnceDoneOperation)
  1642. {
  1643. if (!FAutoOperation)
  1644. {
  1645. // no selection on "/upload", form serves only as event handler
  1646. // (it is not displayed)
  1647. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1648. ((Operation == FPrimaryOperation) ||
  1649. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1650. {
  1651. TOperationSide DViewSide;
  1652. if ((FProgressSide != osCurrent) &&
  1653. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1654. {
  1655. // assume the operation is over the focused panel
  1656. DViewSide = FProgressSide;
  1657. }
  1658. else
  1659. {
  1660. DViewSide = Side;
  1661. }
  1662. if (FOnFileOperationFinished != NULL)
  1663. {
  1664. FOnFileOperationFinished(DViewSide, FileName, Success);
  1665. }
  1666. else
  1667. {
  1668. VisualiseOperationFinished(DViewSide, FileName, Success);
  1669. }
  1670. }
  1671. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1672. {
  1673. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1674. {
  1675. if (Side == osLocal)
  1676. {
  1677. Configuration->Usage->Inc(L"UploadedFiles");
  1678. }
  1679. else
  1680. {
  1681. Configuration->Usage->Inc(L"DownloadedFiles");
  1682. }
  1683. }
  1684. }
  1685. }
  1686. if (Success && (FSynchronizeController != NULL))
  1687. {
  1688. DebugAssert(!IsSideLocalBrowser(osRemote));
  1689. if (Operation == foCopy)
  1690. {
  1691. DebugAssert(Side == osLocal);
  1692. FSynchronizeController->LogOperation(soUpload, FileName);
  1693. }
  1694. else if (Operation == foDelete)
  1695. {
  1696. DebugAssert(Side == osRemote);
  1697. FSynchronizeController->LogOperation(soDelete, FileName);
  1698. }
  1699. }
  1700. if (FProgressForm)
  1701. {
  1702. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1703. }
  1704. }
  1705. //---------------------------------------------------------------------------
  1706. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1707. TFileOperation Operation, TOperationSide Side,
  1708. bool Temp, const UnicodeString & FileName, Boolean Success,
  1709. TOnceDoneOperation & OnceDoneOperation)
  1710. {
  1711. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1712. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1713. OnceDoneOperation);
  1714. }
  1715. //---------------------------------------------------------------------------
  1716. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1717. {
  1718. return false;
  1719. }
  1720. //---------------------------------------------------------------------------
  1721. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1722. {
  1723. return false;
  1724. }
  1725. //---------------------------------------------------------------------------
  1726. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1727. {
  1728. return false;
  1729. }
  1730. //---------------------------------------------------------------------------
  1731. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1732. {
  1733. return NULL;
  1734. }
  1735. //---------------------------------------------------------------------------
  1736. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1737. {
  1738. DebugAssert(GetSide(Side) == osRemote);
  1739. DebugUsedParam(Side);
  1740. return RemoteDirView;
  1741. }
  1742. //---------------------------------------------------------------------------
  1743. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1744. {
  1745. DebugAssert(GetSide(Side) == osRemote);
  1746. DebugUsedParam(Side);
  1747. return RemoteDriveView;
  1748. }
  1749. //---------------------------------------------------------------------------
  1750. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1751. {
  1752. DebugAssert(GetSide(Side) == osRemote);
  1753. DebugUsedParam(Side);
  1754. return HasActiveTerminal();
  1755. }
  1756. //---------------------------------------------------------------------------
  1757. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1758. TOperationSide Side, int FilesOnly)
  1759. {
  1760. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1761. }
  1762. //---------------------------------------------------------------------------
  1763. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1764. TOperationSide Side, int FilesOnly)
  1765. {
  1766. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1767. }
  1768. //---------------------------------------------------------------------------
  1769. struct THistoryItemData
  1770. {
  1771. short int Side;
  1772. short int Index;
  1773. };
  1774. //---------------------------------------------------------------------------
  1775. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1776. {
  1777. DirView(Side)->HistoryGo(Index);
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1781. {
  1782. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1783. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1784. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1785. }
  1786. //---------------------------------------------------------------------------
  1787. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1788. bool Back)
  1789. {
  1790. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1791. {
  1792. TCustomDirView * DView = DirView(Side);
  1793. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1794. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1795. if (ICount > 10)
  1796. {
  1797. ICount = 10;
  1798. }
  1799. Menu->Items->Clear();
  1800. THistoryItemData Data;
  1801. Data.Side = Side;
  1802. for (short int i = 1; i <= ICount; i++)
  1803. {
  1804. TTBCustomItem * Item = new TTBXItem(Menu);
  1805. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1806. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1807. Item->Hint = DView->HistoryPath[Data.Index];
  1808. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1809. Item->Tag = *reinterpret_cast<int*>(&Data);
  1810. Item->OnClick = HistoryItemClick;
  1811. Menu->Items->Add(Item);
  1812. }
  1813. }
  1814. }
  1815. //---------------------------------------------------------------------------
  1816. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1817. TOperationSide Side, bool Back)
  1818. {
  1819. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1820. {
  1821. // workaround
  1822. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1823. // operator new allocates memory in Pascal code, but calls inline
  1824. // constructor in C++, leading in problems, the function does
  1825. // both in Pascal code
  1826. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1827. UpdateHistoryMenu(Side, Back);
  1828. }
  1829. return FHistoryMenu[Side == osLocal][Back];
  1830. }
  1831. //---------------------------------------------------------------------------
  1832. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1833. TCustomDirView *Sender)
  1834. {
  1835. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1836. UpdateHistoryMenu(Side, true);
  1837. UpdateHistoryMenu(Side, false);
  1838. }
  1839. //---------------------------------------------------------------------------
  1840. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1841. {
  1842. // remote custom commands can be executed only if the server supports shell commands
  1843. // or have secondary shell
  1844. return HasActiveTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1845. }
  1846. //---------------------------------------------------------------------------
  1847. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1848. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1849. {
  1850. // -1 = hidden, 0 = disabled, 1 = enabled
  1851. int Result;
  1852. TFileCustomCommand RemoteCustomCommand;
  1853. TLocalCustomCommand LocalCustomCommand;
  1854. TFileCustomCommand * NonInteractiveCustomCommand =
  1855. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1856. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1857. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1858. if (FLAGCLEAR(Command.Params, ccLocal))
  1859. {
  1860. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1861. // custom command that does not operate with files can be executed anytime ...
  1862. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1863. {
  1864. // ... but do not show such command in remote file menu
  1865. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1866. {
  1867. Result = AllowedState;
  1868. }
  1869. else
  1870. {
  1871. Result = -1;
  1872. }
  1873. }
  1874. else
  1875. {
  1876. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1877. {
  1878. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1879. }
  1880. else
  1881. {
  1882. Result = -1;
  1883. }
  1884. }
  1885. }
  1886. else
  1887. {
  1888. // custom command that does not operate with files can be executed anytime
  1889. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1890. {
  1891. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1892. }
  1893. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1894. {
  1895. if ((ListType == ccltAll) || (ListType == ccltFile))
  1896. {
  1897. // special case is "diff"-style command that can be executed over any side,
  1898. // if we have both sides
  1899. Result =
  1900. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1901. // directly (instead of EnableSelectedOperation) to pass
  1902. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1903. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1904. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1905. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1906. }
  1907. else if (ListType == ccltBoth)
  1908. {
  1909. DebugAssert(!IsLocalBrowserMode());
  1910. Result = 1;
  1911. }
  1912. else
  1913. {
  1914. Result = -1;
  1915. }
  1916. }
  1917. else
  1918. {
  1919. if ((ListType == ccltAll) ||
  1920. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1921. {
  1922. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1923. }
  1924. else
  1925. {
  1926. Result = -1;
  1927. }
  1928. }
  1929. if ((Result > 0) &&
  1930. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1931. !HasActiveTerminal())
  1932. {
  1933. Result = 0;
  1934. }
  1935. }
  1936. return Result;
  1937. }
  1938. //---------------------------------------------------------------------------
  1939. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1940. TStrings * FileList, const TCustomCommandType & ACommand,
  1941. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1942. {
  1943. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1944. {
  1945. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1946. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1947. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1948. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1949. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1950. bool Capture =
  1951. FLAGSET(ACommand.Params, ccShowResults) ||
  1952. FLAGSET(ACommand.Params, ccCopyResults) ||
  1953. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1954. TCaptureOutputEvent OutputEvent = NULL;
  1955. DebugAssert(FCapturedLog == NULL);
  1956. if (Capture)
  1957. {
  1958. FCapturedLog = new TStringList();
  1959. OutputEvent = TerminalCaptureLog;
  1960. }
  1961. try
  1962. {
  1963. if (!RemoteCustomCommand.IsFileCommand(Command))
  1964. {
  1965. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1966. OutputEvent);
  1967. }
  1968. else
  1969. {
  1970. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1971. }
  1972. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1973. {
  1974. if (FLAGSET(ACommand.Params, ccCopyResults))
  1975. {
  1976. CopyToClipboard(FCapturedLog);
  1977. }
  1978. if (FLAGSET(ACommand.Params, ccShowResults))
  1979. {
  1980. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1981. }
  1982. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1983. {
  1984. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1985. }
  1986. }
  1987. }
  1988. __finally
  1989. {
  1990. SAFE_DESTROY(FCapturedLog);
  1991. }
  1992. }
  1993. }
  1994. //---------------------------------------------------------------------------
  1995. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1996. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1997. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1998. {
  1999. DebugAssert(!IsLocalBrowserMode());
  2000. TStrings * LocalFileList = NULL;
  2001. TStrings * RemoteFileList = NULL;
  2002. TStrings * RemoteFileListFull = NULL;
  2003. try
  2004. {
  2005. if (LocalFileCommand)
  2006. {
  2007. if (ALocalFileList == NULL)
  2008. {
  2009. DebugAssert(HasDirView[osLocal]);
  2010. // Cannot have focus on both panels, so we have to call AnyFileSelected
  2011. // directly (instead of EnableSelectedOperation) to pass
  2012. // false to FocusedFileOnlyWhenFocused
  2013. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  2014. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  2015. }
  2016. else
  2017. {
  2018. LocalFileList = ALocalFileList;
  2019. }
  2020. if (FileListCommand)
  2021. {
  2022. if (LocalFileList->Count != 1)
  2023. {
  2024. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2025. }
  2026. }
  2027. else
  2028. {
  2029. if ((LocalFileList->Count != 1) &&
  2030. (FileList->Count != 1) &&
  2031. (LocalFileList->Count != FileList->Count))
  2032. {
  2033. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2034. }
  2035. }
  2036. }
  2037. UnicodeString RootTempDir;
  2038. UnicodeString TempDir;
  2039. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2040. if (!RemoteFiles)
  2041. {
  2042. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true, true);
  2043. }
  2044. try
  2045. {
  2046. TDateTimes RemoteFileTimes;
  2047. if (RemoteFiles)
  2048. {
  2049. RemoteFileList = FileList;
  2050. }
  2051. else
  2052. {
  2053. RemoteFileList = new TStringList();
  2054. TMakeLocalFileListParams MakeFileListParam;
  2055. MakeFileListParam.FileList = RemoteFileList;
  2056. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2057. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2058. MakeFileListParam.Recursive =
  2059. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2060. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2061. if (!MakeFileListParam.Recursive)
  2062. {
  2063. RemoteFileTimes.clear();
  2064. RemoteFileListFull = new TStringList();
  2065. MakeFileListParam.FileList = RemoteFileListFull;
  2066. MakeFileListParam.Recursive = true;
  2067. MakeFileListParam.IncludeDirs = false;
  2068. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2069. }
  2070. else
  2071. {
  2072. RemoteFileListFull = RemoteFileList;
  2073. }
  2074. }
  2075. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2076. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2077. if (!NonBlocking)
  2078. {
  2079. int Count;
  2080. if (FileListCommand)
  2081. {
  2082. Count = 1;
  2083. }
  2084. else if (LocalFileCommand)
  2085. {
  2086. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2087. }
  2088. else
  2089. {
  2090. Count = RemoteFileList->Count;
  2091. }
  2092. Progress.Start(foCustomCommand, osRemote, Count);
  2093. DebugAssert(FProgressForm != NULL);
  2094. FProgressForm->ReadOnly = true;
  2095. }
  2096. try
  2097. {
  2098. if (FileListCommand)
  2099. {
  2100. UnicodeString LocalFile;
  2101. // MakeFileList does not delimit filenames
  2102. UnicodeString FileList = MakeFileList(RemoteFileList);
  2103. if (LocalFileCommand)
  2104. {
  2105. DebugAssert(LocalFileList->Count == 1);
  2106. LocalFile = LocalFileList->Strings[0];
  2107. }
  2108. TLocalCustomCommand CustomCommand(Data,
  2109. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2110. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2111. if (NonBlocking)
  2112. {
  2113. DebugAssert(!POutput);
  2114. ExecuteShellChecked(ShellCommand);
  2115. }
  2116. else
  2117. {
  2118. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2119. }
  2120. }
  2121. else if (LocalFileCommand)
  2122. {
  2123. if (LocalFileList->Count == 1)
  2124. {
  2125. UnicodeString LocalFile = LocalFileList->Strings[0];
  2126. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2127. {
  2128. UnicodeString FileName = RemoteFileList->Strings[Index];
  2129. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2130. Progress.SetFile(FileNameForProgress);
  2131. TLocalCustomCommand CustomCommand(Data,
  2132. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2133. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2134. TOnceDoneOperation OnceDoneOperation;
  2135. // Do not unselect anything, as it won't work with two panels anyway
  2136. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2137. }
  2138. }
  2139. else if (RemoteFileList->Count == 1)
  2140. {
  2141. UnicodeString FileName = RemoteFileList->Strings[0];
  2142. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2143. {
  2144. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2145. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2146. Progress.SetFile(LocalFileNameOnly);
  2147. TLocalCustomCommand CustomCommand(
  2148. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2149. FileName, LocalFileName, L"");
  2150. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2151. TOnceDoneOperation OnceDoneOperation;
  2152. // Do not unselect anything, as it won't work with two panels anyway
  2153. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2154. }
  2155. }
  2156. else
  2157. {
  2158. if (LocalFileList->Count != RemoteFileList->Count)
  2159. {
  2160. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2161. }
  2162. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2163. {
  2164. UnicodeString FileName = RemoteFileList->Strings[Index];
  2165. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2166. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2167. Progress.SetFile(LocalFileNameOnly); // sic
  2168. TLocalCustomCommand CustomCommand(
  2169. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2170. FileName, LocalFileName, L"");
  2171. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2172. TOnceDoneOperation OnceDoneOperation;
  2173. // Do not unselect anything, as it won't work with two panels anyway
  2174. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2175. }
  2176. }
  2177. }
  2178. else
  2179. {
  2180. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2181. {
  2182. UnicodeString FileName = RemoteFileList->Strings[Index];
  2183. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2184. Progress.SetFile(FileNameForProgress);
  2185. TLocalCustomCommand CustomCommand(Data,
  2186. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2187. FileName, L"", L"");
  2188. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2189. TOnceDoneOperation OnceDoneOperation;
  2190. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2191. }
  2192. }
  2193. }
  2194. __finally
  2195. {
  2196. if (!NonBlocking)
  2197. {
  2198. Progress.Stop();
  2199. }
  2200. }
  2201. DebugAssert(!FAutoOperation);
  2202. if (!RemoteFiles)
  2203. {
  2204. TempDir = IncludeTrailingBackslash(TempDir);
  2205. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2206. {
  2207. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2208. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2209. // Skip directories, process only nested files.
  2210. // The check is redundant as FileAge fails for directories anyway.
  2211. !DirectoryExists(FileName))
  2212. {
  2213. UnicodeString RemoteDir =
  2214. UnixExtractFileDir(
  2215. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2216. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  2217. TDateTime NewTime;
  2218. if (FileAge(FileName, NewTime) &&
  2219. (NewTime != RemoteFileTimes[Index]))
  2220. {
  2221. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2222. TemporaryFileCopyParam(CopyParam);
  2223. CopyParam.FileMask = L"";
  2224. FAutoOperation = true;
  2225. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2226. TemporaryFilesList->Add(FileName);
  2227. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2228. }
  2229. }
  2230. }
  2231. }
  2232. }
  2233. __finally
  2234. {
  2235. FAutoOperation = false;
  2236. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2237. {
  2238. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  2239. }
  2240. }
  2241. }
  2242. __finally
  2243. {
  2244. if (RemoteFileList != FileList)
  2245. {
  2246. delete RemoteFileList;
  2247. }
  2248. if (LocalFileList != ALocalFileList)
  2249. {
  2250. delete LocalFileList;
  2251. }
  2252. if (RemoteFileListFull != RemoteFileList)
  2253. {
  2254. delete RemoteFileListFull;
  2255. }
  2256. }
  2257. }
  2258. //---------------------------------------------------------------------------
  2259. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2260. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2261. bool FileListCommand, UnicodeString * POutput)
  2262. {
  2263. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2264. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2265. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2266. {
  2267. UnicodeString FileName = SelectedFileList->Strings[Index];
  2268. if (DirectoryExists(FileName))
  2269. {
  2270. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2271. {
  2272. LocalFileList->Add(FileName);
  2273. }
  2274. if (FLAGSET(ACommand.Params, ccRecursive))
  2275. {
  2276. TMakeLocalFileListParams MakeFileListParam;
  2277. MakeFileListParam.FileList = LocalFileList.get();
  2278. MakeFileListParam.FileTimes = NULL;
  2279. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2280. MakeFileListParam.Recursive = true;
  2281. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2282. }
  2283. }
  2284. else
  2285. {
  2286. LocalFileList->Add(FileName);
  2287. }
  2288. }
  2289. UnicodeString RemotePath;
  2290. if (Terminal != NULL)
  2291. {
  2292. RemotePath = Terminal->CurrentDirectory;
  2293. }
  2294. if (FileListCommand)
  2295. {
  2296. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2297. TLocalCustomCommand CustomCommand(
  2298. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2299. L"", L"", FileList);
  2300. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2301. }
  2302. else
  2303. {
  2304. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2305. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2306. DebugAssert(FProgressForm != NULL);
  2307. FProgressForm->ReadOnly = true;
  2308. try
  2309. {
  2310. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2311. {
  2312. UnicodeString FileName = LocalFileList->Strings[Index];
  2313. Progress.SetFile(FileName);
  2314. TLocalCustomCommand CustomCommand(
  2315. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2316. FileName, L"", L"");
  2317. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2318. TOnceDoneOperation OnceDoneOperation;
  2319. Progress.Finish(FileName, true, OnceDoneOperation);
  2320. }
  2321. }
  2322. __finally
  2323. {
  2324. Progress.Stop();
  2325. }
  2326. }
  2327. }
  2328. //---------------------------------------------------------------------------
  2329. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2330. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2331. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2332. {
  2333. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2334. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2335. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2336. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2337. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2338. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2339. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2340. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2341. std::unique_ptr<UnicodeString> POutput;
  2342. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2343. FLAGSET(ACommand.Params, ccCopyResults))
  2344. {
  2345. POutput.reset(new UnicodeString());
  2346. }
  2347. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  2348. if (!LocalCustomCommand.IsFileCommand(Command))
  2349. {
  2350. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2351. }
  2352. // remote files?
  2353. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2354. {
  2355. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2356. }
  2357. // local files
  2358. else
  2359. {
  2360. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2361. }
  2362. if (POutput.get() != NULL)
  2363. {
  2364. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2365. int P = POutput->Pos(sLineBreak);
  2366. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2367. {
  2368. POutput->SetLength(P - 1);
  2369. }
  2370. // Copy even empty output to clipboard
  2371. if (FLAGSET(ACommand.Params, ccCopyResults))
  2372. {
  2373. CopyToClipboard(*POutput);
  2374. }
  2375. // But do not show an empty message box.
  2376. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2377. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2378. !POutput->IsEmpty())
  2379. {
  2380. TClipboardHandler ClipboardHandler;
  2381. ClipboardHandler.Text = *POutput;
  2382. TMessageParams Params;
  2383. TQueryButtonAlias Aliases[1];
  2384. Aliases[0].Button = qaRetry;
  2385. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2386. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2387. Params.Aliases = Aliases;
  2388. Params.AliasesCount = LENOF(Aliases);
  2389. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2390. }
  2391. }
  2392. }
  2393. //---------------------------------------------------------------------------
  2394. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2395. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2396. {
  2397. TCustomCommandData Data;
  2398. UnicodeString Site;
  2399. UnicodeString RemotePath;
  2400. if (HasActiveTerminal())
  2401. {
  2402. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2403. Data = TCustomCommandData(SessionData.get());
  2404. Site = Terminal->SessionData->SessionKey;
  2405. RemotePath = Terminal->CurrentDirectory;
  2406. }
  2407. UnicodeString HelpKeyword = ACommand.HomePage;
  2408. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2409. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2410. {
  2411. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2412. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2413. {
  2414. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2415. }
  2416. else
  2417. {
  2418. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2419. }
  2420. if (!DoCustomCommandOptionsDialog(
  2421. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2422. {
  2423. Abort();
  2424. }
  2425. }
  2426. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2427. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2428. {
  2429. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2430. }
  2431. else
  2432. {
  2433. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2434. }
  2435. }
  2436. //---------------------------------------------------------------------------
  2437. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2438. const TCustomCommandType & Command)
  2439. {
  2440. DebugAssert(FCustomCommandLocalFileList != NULL);
  2441. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2442. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2443. TStrings * LocalFileList = new TStringList();
  2444. TStrings * RemoteFileList = new TStringList();
  2445. try
  2446. {
  2447. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2448. {
  2449. LocalFileList->Clear();
  2450. LocalFileList->AddObject(
  2451. FCustomCommandLocalFileList->Strings[Index],
  2452. FCustomCommandLocalFileList->Objects[Index]);
  2453. RemoteFileList->Clear();
  2454. RemoteFileList->AddObject(
  2455. FCustomCommandRemoteFileList->Strings[Index],
  2456. FCustomCommandRemoteFileList->Objects[Index]);
  2457. CustomCommand(RemoteFileList, Command, LocalFileList);
  2458. }
  2459. }
  2460. __finally
  2461. {
  2462. delete LocalFileList;
  2463. delete RemoteFileList;
  2464. }
  2465. }
  2466. //---------------------------------------------------------------------------
  2467. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2468. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2469. {
  2470. delete FCustomCommandLocalFileList;
  2471. delete FCustomCommandRemoteFileList;
  2472. // takeover ownership,
  2473. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2474. FCustomCommandLocalFileList = LocalFileList;
  2475. FCustomCommandRemoteFileList = RemoteFileList;
  2476. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2477. if (Button != NULL)
  2478. {
  2479. FCustomCommandMenu->Items->Clear();
  2480. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2481. MenuPopup(FCustomCommandMenu, Button);
  2482. }
  2483. else
  2484. {
  2485. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2486. }
  2487. }
  2488. //---------------------------------------------------------------------------
  2489. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2490. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2491. {
  2492. DebugAssert(FCapturedLog != NULL);
  2493. if ((OutputType == cotOutput) || (OutputType == cotError))
  2494. {
  2495. FCapturedLog->Add(AddedLine);
  2496. }
  2497. }
  2498. //---------------------------------------------------------------------------
  2499. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2500. TOperationSide Side)
  2501. {
  2502. return
  2503. (Side == osOther) &&
  2504. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2505. }
  2506. //---------------------------------------------------------------------------
  2507. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2508. TOperationSide Side, TTBXCustomItem * Item,
  2509. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2510. {
  2511. TCustomDirView * DView = DirView(Side);
  2512. bool IsDefault = false;
  2513. if (DView->ItemFocused != NULL)
  2514. {
  2515. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2516. TResolvedDoubleClickAction DefaultAction =
  2517. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2518. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2519. }
  2520. TTBItemOptions O = Item->Options;
  2521. if (IsDefault)
  2522. {
  2523. Item->Options = O << tboDefault;
  2524. }
  2525. else
  2526. {
  2527. Item->Options = O >> tboDefault;
  2528. }
  2529. }
  2530. //---------------------------------------------------------------------------
  2531. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2532. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2533. {
  2534. TCustomDirView * DView = DirView(Side);
  2535. TListItem * Item = DView->ItemFocused;
  2536. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2537. EnableFocusedOperation[Side])
  2538. {
  2539. TPoint ClientPoint;
  2540. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2541. TPoint(0, 0) : MousePos;
  2542. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2543. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2544. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2545. }
  2546. }
  2547. //---------------------------------------------------------------------------
  2548. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2549. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2550. {
  2551. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2552. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2553. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2554. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2555. Handled = true;
  2556. }
  2557. //---------------------------------------------------------------------------
  2558. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2559. {
  2560. }
  2561. //---------------------------------------------------------------------------
  2562. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2563. {
  2564. DebugAssert(FErrorList == NULL);
  2565. if (WinConfiguration->ContinueOnError)
  2566. {
  2567. FErrorList = new TStringList();
  2568. Configuration->Usage->Inc(L"ContinuationsOnError");
  2569. }
  2570. NonVisualDataModule->StartBusy();
  2571. }
  2572. //---------------------------------------------------------------------------
  2573. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2574. {
  2575. NonVisualDataModule->EndBusy();
  2576. if (FErrorList)
  2577. {
  2578. HandleErrorList(FErrorList);
  2579. }
  2580. }
  2581. //---------------------------------------------------------------------------
  2582. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2583. const TCopyParamType & CopyParam)
  2584. {
  2585. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2586. {
  2587. Configuration->Usage->Inc(L"FileMaskUses");
  2588. }
  2589. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2590. {
  2591. Configuration->Usage->Inc(L"OperationMaskUses");
  2592. }
  2593. }
  2594. //---------------------------------------------------------------------------
  2595. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2596. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2597. {
  2598. DebugAssert(!IsLocalBrowserMode());
  2599. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2600. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2601. TTransferOperationParam DefaultParam;
  2602. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2603. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2604. switch (Param.Queue)
  2605. {
  2606. case asOn:
  2607. CopyParam.Queue = true;
  2608. break;
  2609. case asOff:
  2610. CopyParam.Queue = false;
  2611. break;
  2612. case asAuto:
  2613. default:
  2614. // keep default
  2615. break;
  2616. }
  2617. bool Result =
  2618. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2619. if (Result)
  2620. {
  2621. DebugAssert(Terminal);
  2622. bool SelectionRestored = false;
  2623. TCustomDirView * DView = NULL;
  2624. if (HasDirView[Side])
  2625. {
  2626. DView = DirView(Side);
  2627. DView->SaveSelection();
  2628. DView->SaveSelectedNames();
  2629. }
  2630. UpdateCopyParamCounters(CopyParam);
  2631. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2632. DebugAssert(FTransferResumeList == NULL);
  2633. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2634. FMoveToQueue = false;
  2635. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2636. try
  2637. {
  2638. TStrings * PermanentFileList;
  2639. std::unique_ptr<TStrings> PermanentFileListOwner;
  2640. try
  2641. {
  2642. if (Side == osLocal)
  2643. {
  2644. PermanentFileList = FileList;
  2645. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2646. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2647. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2648. if (Operation == foMove)
  2649. {
  2650. ReloadLocalDirectory();
  2651. if (DView != NULL)
  2652. {
  2653. DView->RestoreSelection();
  2654. }
  2655. SelectionRestored = true;
  2656. }
  2657. }
  2658. else
  2659. {
  2660. // Clone the file list as it may refer to current directory files,
  2661. // which get destroyed, when the source directory is reloaded after foMove operation.
  2662. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2663. // But for a hotfix, we are not going to do such a big change.
  2664. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2665. PermanentFileList = PermanentFileListOwner.get();
  2666. try
  2667. {
  2668. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2669. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2670. }
  2671. __finally
  2672. {
  2673. if (Operation == foMove)
  2674. {
  2675. if (DView != NULL)
  2676. {
  2677. DView->RestoreSelection();
  2678. }
  2679. SelectionRestored = true;
  2680. }
  2681. ReloadLocalDirectory(Param.TargetDirectory);
  2682. }
  2683. }
  2684. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2685. if (FMoveToQueue)
  2686. {
  2687. Abort();
  2688. }
  2689. }
  2690. catch (EAbort &)
  2691. {
  2692. if (FMoveToQueue)
  2693. {
  2694. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2695. DebugAssert(CopyParam.TransferSkipList == NULL);
  2696. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2697. if (TransferResumeList->Count > 0)
  2698. {
  2699. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2700. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2701. }
  2702. CopyParam.TransferSkipList = TransferResumeList.release();
  2703. // not really needed, just to keep it consistent with TransferResumeList
  2704. FTransferResumeList = NULL;
  2705. FMoveToQueue = false;
  2706. Configuration->Usage->Inc("MovesToBackground");
  2707. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2708. ClearTransferSourceSelection(Direction);
  2709. }
  2710. throw;
  2711. }
  2712. }
  2713. __finally
  2714. {
  2715. if (!SelectionRestored && (DView != NULL))
  2716. {
  2717. DView->DiscardSavedSelection();
  2718. }
  2719. FTransferResumeList = NULL;
  2720. }
  2721. }
  2722. return Result;
  2723. }
  2724. //---------------------------------------------------------------------------
  2725. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2726. TOperationSide Side, TStrings * FileList, void * Param)
  2727. {
  2728. DebugAssert(FileList->Count);
  2729. // We deliberately do not toggle alternative flag (Param), but use OR,
  2730. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2731. // shortcut of CurrentDeleteAlternativeAction
  2732. bool Alternative =
  2733. bool(Param) || UseAlternativeFunction();
  2734. bool Recycle;
  2735. if (IsSideLocalBrowser(Side))
  2736. {
  2737. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2738. }
  2739. else
  2740. {
  2741. Recycle =
  2742. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2743. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2744. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2745. }
  2746. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2747. if (!Result)
  2748. {
  2749. UnicodeString Query;
  2750. if (FileList->Count == 1)
  2751. {
  2752. if (IsSideLocalBrowser(Side))
  2753. {
  2754. Query = ExtractFileName(FileList->Strings[0]);
  2755. }
  2756. else
  2757. {
  2758. Query = UnixExtractFileName(FileList->Strings[0]);
  2759. }
  2760. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2761. }
  2762. else
  2763. {
  2764. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2765. }
  2766. TMessageParams Params(mpNeverAskAgainCheck);
  2767. Params.ImageName = L"Delete file";
  2768. unsigned int Answer =
  2769. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2770. if (Answer == qaNeverAskAgain)
  2771. {
  2772. Result = true;
  2773. if (Recycle)
  2774. {
  2775. WinConfiguration->ConfirmRecycling = false;
  2776. }
  2777. else
  2778. {
  2779. WinConfiguration->ConfirmDeleting = false;
  2780. }
  2781. }
  2782. else
  2783. {
  2784. Result = (Answer == qaOK);
  2785. }
  2786. }
  2787. if (Result)
  2788. {
  2789. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2790. }
  2791. return Result;
  2792. }
  2793. //---------------------------------------------------------------------------
  2794. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2795. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2796. {
  2797. TAutoBatch AutoBatch(this);
  2798. bool Result;
  2799. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2800. {
  2801. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2802. }
  2803. else if (Operation == foRename)
  2804. {
  2805. DebugAssert(DirView(Side)->ItemFocused);
  2806. DirView(Side)->ItemFocused->EditCaption();
  2807. Result = true;
  2808. }
  2809. else if (Operation == foDelete)
  2810. {
  2811. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2812. }
  2813. else if (Operation == foSetProperties)
  2814. {
  2815. DirView(osRemote)->SaveSelectedNames();
  2816. Result = SetProperties(Side, FileList);
  2817. }
  2818. else if (Operation == foCustomCommand)
  2819. {
  2820. DebugAssert(Param);
  2821. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2822. DirView(osRemote)->SaveSelectedNames();
  2823. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2824. CustomCommand(FileList, *Command, NULL);
  2825. Result = true;
  2826. }
  2827. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2828. {
  2829. DebugAssert(!IsSideLocalBrowser(Side));
  2830. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2831. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2832. }
  2833. else if (Operation == foLock)
  2834. {
  2835. DebugAssert(!IsSideLocalBrowser(Side));
  2836. LockFiles(FileList, true);
  2837. Result = true;
  2838. }
  2839. else if (Operation == foUnlock)
  2840. {
  2841. DebugAssert(!IsSideLocalBrowser(Side));
  2842. LockFiles(FileList, false);
  2843. Result = true;
  2844. }
  2845. else
  2846. {
  2847. DebugFail();
  2848. }
  2849. return Result;
  2850. }
  2851. //---------------------------------------------------------------------------
  2852. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2853. {
  2854. if (Side == osCurrent)
  2855. {
  2856. Side = FCurrentSide;
  2857. }
  2858. return Side;
  2859. }
  2860. //---------------------------------------------------------------------------
  2861. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2862. {
  2863. TOperationSide Result;
  2864. switch (GetSide(Side))
  2865. {
  2866. case osLocal:
  2867. Result = osOther;
  2868. break;
  2869. case osOther:
  2870. Result = osLocal;
  2871. break;
  2872. default:
  2873. DebugFail();
  2874. Abort();
  2875. }
  2876. return Result;
  2877. }
  2878. //---------------------------------------------------------------------------
  2879. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2880. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2881. {
  2882. Side = GetSide(Side);
  2883. bool FullPath = IsSideLocalBrowser(Side);
  2884. TCustomDirView * ADirView = DirView(Side);
  2885. std::unique_ptr<TStringList> FileList(new TStringList());
  2886. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2887. bool ReloadProperties =
  2888. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2889. DebugAlwaysTrue(HasActiveTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2890. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2891. if (Result && ReloadProperties)
  2892. {
  2893. std::unique_ptr<TStringList> FileList2(new TStringList());
  2894. FileList->CaseSensitive = true;
  2895. FileList->Sort();
  2896. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2897. {
  2898. TListItem * Item = ADirView->Items->Item[Index];
  2899. UnicodeString FileName = ADirView->ItemFileName(Item);
  2900. int Index2;
  2901. if (FileList->Find(FileName, Index2))
  2902. {
  2903. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2904. }
  2905. }
  2906. LoadFilesProperties(FileList2.get());
  2907. }
  2908. return Result;
  2909. }
  2910. //---------------------------------------------------------------------------
  2911. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2912. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2913. bool NoConfirmation, void * Param)
  2914. {
  2915. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2916. {
  2917. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2918. {
  2919. DebugAssert(!IsLocalBrowserMode());
  2920. if (GetSide(Side) == osLocal)
  2921. {
  2922. Configuration->Usage->Inc(L"UploadsCommand");
  2923. }
  2924. else
  2925. {
  2926. Configuration->Usage->Inc(L"DownloadsCommand");
  2927. }
  2928. }
  2929. }
  2930. }
  2931. //---------------------------------------------------------------------------
  2932. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2933. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2934. {
  2935. TTransferOperationParam Param;
  2936. if ((WinConfiguration->Interface != ifCommander) ||
  2937. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2938. {
  2939. Flags &= ~cocShortCutHint;
  2940. }
  2941. TCustomDirView * DView = DirView(Side);
  2942. Param.Options =
  2943. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2944. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2945. if (FLAGSET(Flags, cocQueue))
  2946. {
  2947. Param.Queue = asOn;
  2948. }
  2949. else if (FLAGSET(Flags, cocNonQueue))
  2950. {
  2951. Param.Queue = asOff;
  2952. }
  2953. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2954. }
  2955. //---------------------------------------------------------------------------
  2956. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2957. {
  2958. int Count = ErrorList->Count;
  2959. try
  2960. {
  2961. if (ErrorList->Count)
  2962. {
  2963. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2964. if (MessageDialog(Message, qtError,
  2965. qaOK | qaCancel, HELP_NONE) == qaOK)
  2966. {
  2967. unsigned int Answer;
  2968. int Index = 0;
  2969. do
  2970. {
  2971. DebugAssert(Index >= 0 && Index < Count);
  2972. TQueryButtonAlias Aliases[2];
  2973. Aliases[0].Button = qaYes;
  2974. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2975. Aliases[1].Button = qaNo;
  2976. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2977. TMessageParams Params;
  2978. Params.Aliases = Aliases;
  2979. Params.AliasesCount = LENOF(Aliases);
  2980. int No = Index + 1;
  2981. UnicodeString Message = ErrorList->Strings[Index];
  2982. UnicodeString AMainInstructions;
  2983. UnicodeString Details;
  2984. if (ExtractMainInstructions(Message, AMainInstructions))
  2985. {
  2986. Details = Message;
  2987. Message = AMainInstructions;
  2988. }
  2989. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2990. Answer = MoreMessageDialog(
  2991. Message,
  2992. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2993. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2994. qaOK, HELP_NONE, &Params);
  2995. if (Answer == qaNo)
  2996. {
  2997. Index++;
  2998. }
  2999. if (Answer == qaYes)
  3000. {
  3001. Index--;
  3002. }
  3003. }
  3004. while (Answer != qaOK);
  3005. }
  3006. }
  3007. }
  3008. __finally
  3009. {
  3010. TStrings * List = ErrorList;
  3011. ErrorList = NULL;
  3012. for (int i = 0; i < Count; i++)
  3013. {
  3014. delete List->Objects[i];
  3015. }
  3016. delete List;
  3017. }
  3018. }
  3019. //---------------------------------------------------------------------------
  3020. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3021. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3022. {
  3023. // needed for checking filemasks, as there's no directory object
  3024. // associated with the file object
  3025. File->FullFileName = FullFileName;
  3026. TFileMasks::TParams MaskParams;
  3027. MaskParams.Size = File->Size;
  3028. MaskParams.Modification = File->Modification;
  3029. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3030. }
  3031. //---------------------------------------------------------------------------
  3032. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3033. {
  3034. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3035. Side = GetSide(Side);
  3036. TCustomDirView * DView = DirView(Side);
  3037. TListItem * FocusedItem = DView->ItemFocused;
  3038. UnicodeString Name;
  3039. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3040. {
  3041. Name = DView->ItemFileName(FocusedItem);
  3042. }
  3043. else
  3044. {
  3045. Name = LoadStr(NEW_FILE);
  3046. }
  3047. UnicodeString Names = Name;
  3048. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3049. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3050. HELP_EDIT_NEW, History.get(), true, NULL, true, 400))
  3051. {
  3052. while (!Names.IsEmpty())
  3053. {
  3054. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3055. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3056. UnicodeString TargetFileName;
  3057. UnicodeString LocalFileName;
  3058. UnicodeString RootTempDir;
  3059. UnicodeString TempDir;
  3060. UnicodeString RemoteDirectory;
  3061. bool ExistingFile = false;
  3062. if (!IsSideLocalBrowser(Side))
  3063. {
  3064. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3065. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3066. if ((File.get() != NULL) &&
  3067. !File->IsDirectory)
  3068. {
  3069. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3070. ExistingFile = true;
  3071. }
  3072. File.reset(NULL);
  3073. if (!ExistingFile)
  3074. {
  3075. RemoteDirectory = UnixExtractFilePath(Name);
  3076. TemporaryDirectoryForRemoteFiles(
  3077. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3078. TargetFileName = UnixExtractFileName(Name);
  3079. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3080. LocalFileName = TempDir +
  3081. // We probably do not want to trim the VMS version here
  3082. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3083. }
  3084. }
  3085. else
  3086. {
  3087. if (ExtractFilePath(Name).IsEmpty())
  3088. {
  3089. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3090. }
  3091. else
  3092. {
  3093. LocalFileName = ExpandFileName(Name);
  3094. }
  3095. TargetFileName = ExtractFileName(Name);
  3096. }
  3097. if (!ExistingFile)
  3098. {
  3099. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3100. if (NewFile)
  3101. {
  3102. int File = FileCreate(ApiPath(LocalFileName));
  3103. if (File < 0)
  3104. {
  3105. if (!RootTempDir.IsEmpty())
  3106. {
  3107. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3108. }
  3109. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3110. }
  3111. else
  3112. {
  3113. FileClose(File);
  3114. }
  3115. }
  3116. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3117. const TEditorData * ExternalEditor = NULL;
  3118. TFileMasks::TParams MaskParams; // size not known
  3119. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3120. false, MaskParams);
  3121. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3122. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3123. }
  3124. }
  3125. }
  3126. }
  3127. //---------------------------------------------------------------------------
  3128. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3129. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3130. {
  3131. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3132. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3133. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3134. return
  3135. ((ExecuteFileBy == efInternalEditor)) ||
  3136. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3137. }
  3138. //---------------------------------------------------------------------------
  3139. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3140. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3141. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3142. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3143. {
  3144. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3145. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3146. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3147. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3148. Side = GetSide(Side);
  3149. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3150. if (!IsSideLocalBrowser(Side))
  3151. {
  3152. Data->Terminal = Terminal;
  3153. Data->SessionData = CloneCurrentSessionData();
  3154. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3155. Data->RemoteDirectory = RemoteDirectory;
  3156. Data->SessionName = Terminal->SessionData->SessionName;
  3157. Data->LocalRootDirectory = LocalRootDirectory;
  3158. Data->OriginalFileName = OriginalFileName;
  3159. Data->Command = L""; // will be changed later for external editor
  3160. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3161. if (WinConfiguration->EditorCheckNotModified)
  3162. {
  3163. Data->SourceTimestamp = SourceTimestamp;
  3164. }
  3165. }
  3166. if (ExecuteFileBy == efInternalEditor)
  3167. {
  3168. if (!IsSideLocalBrowser(Side))
  3169. {
  3170. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3171. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3172. TForm * Editor;
  3173. try
  3174. {
  3175. Editor =
  3176. ShowEditorForm(
  3177. FileName, this,
  3178. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3179. SaveAllInternalEditors, AnyInternalEditorModified,
  3180. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3181. }
  3182. catch(...)
  3183. {
  3184. if (!LocalRootDirectory.IsEmpty())
  3185. {
  3186. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3187. }
  3188. throw;
  3189. }
  3190. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3191. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3192. }
  3193. else
  3194. {
  3195. DebugAssert(!StandaloneOperation);
  3196. TForm * Editor =
  3197. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3198. SaveAllInternalEditors, AnyInternalEditorModified,
  3199. L"", false, SessionColor, -1, NewFile);
  3200. FLocalEditors->Add(Editor);
  3201. }
  3202. }
  3203. else
  3204. {
  3205. HANDLE Process;
  3206. if (ExecuteFileBy == efExternalEditor)
  3207. {
  3208. UnicodeString Program, Params, Dir;
  3209. Data->Command = ExternalEditor->ExternalEditor;
  3210. ReformatFileNameCommand(Data->Command);
  3211. SplitCommand(Data->Command, Program, Params, Dir);
  3212. Params = ExpandFileNameCommand(Params, FileName);
  3213. Program = ExpandEnvironmentVariables(Program);
  3214. if (!ExecuteShell(Program, Params, Process))
  3215. {
  3216. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3217. }
  3218. }
  3219. else
  3220. {
  3221. DebugAssert(!IsSideLocalBrowser(Side));
  3222. if (!ExecuteShell(FileName, L"", Process))
  3223. {
  3224. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3225. }
  3226. }
  3227. if (IsSideLocalBrowser(Side) ||
  3228. ((ExecuteFileBy == efShell) &&
  3229. !WinConfiguration->Editor.SDIShellEditor) ||
  3230. ((ExecuteFileBy == efExternalEditor) &&
  3231. !ExternalEditor->SDIExternalEditor))
  3232. {
  3233. // no need for handle
  3234. if (Process != NULL)
  3235. {
  3236. DebugCheck(CloseHandle(Process));
  3237. }
  3238. Process = INVALID_HANDLE_VALUE;
  3239. }
  3240. else
  3241. {
  3242. if (Process == NULL)
  3243. {
  3244. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3245. }
  3246. }
  3247. if (!IsSideLocalBrowser(Side))
  3248. {
  3249. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3250. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3251. }
  3252. }
  3253. }
  3254. //---------------------------------------------------------------------------
  3255. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3256. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3257. void * /*Arg*/)
  3258. {
  3259. if (Token != NULL)
  3260. {
  3261. EditorFormFileSave(static_cast<TForm *>(Token));
  3262. }
  3263. }
  3264. //---------------------------------------------------------------------------
  3265. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3266. {
  3267. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3268. {
  3269. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3270. }
  3271. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3272. }
  3273. //---------------------------------------------------------------------------
  3274. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3275. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3276. void * Arg)
  3277. {
  3278. if ((Token != NULL) &&
  3279. IsEditorFormModified(static_cast<TForm *>(Token)))
  3280. {
  3281. *static_cast<bool *>(Arg) = true;
  3282. }
  3283. }
  3284. //---------------------------------------------------------------------------
  3285. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3286. TObject * /*Sender*/, bool & Modified)
  3287. {
  3288. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3289. {
  3290. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3291. {
  3292. Modified = true;
  3293. }
  3294. }
  3295. if (!Modified)
  3296. {
  3297. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3298. }
  3299. }
  3300. //---------------------------------------------------------------------------
  3301. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3302. {
  3303. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3304. }
  3305. //---------------------------------------------------------------------------
  3306. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3307. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3308. UnicodeString & Result, UnicodeString & RootDirectory)
  3309. {
  3310. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3311. {
  3312. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3313. Result = RootDirectory;
  3314. }
  3315. else
  3316. {
  3317. RootDirectory = L"";
  3318. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3319. Result = IncludeTrailingBackslash(Result);
  3320. }
  3321. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3322. {
  3323. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3324. }
  3325. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3326. {
  3327. UnicodeString ARemoteDirectory = RemoteDirectory;
  3328. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3329. {
  3330. ARemoteDirectory.Delete(1, 1);
  3331. }
  3332. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3333. }
  3334. if (!ForceDirectories(ApiPath(Result)))
  3335. {
  3336. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3337. }
  3338. }
  3339. //---------------------------------------------------------------------------
  3340. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3341. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3342. bool GetTargetNames, bool AutoOperation, bool SimpleTempDir)
  3343. {
  3344. DebugAssert(!IsLocalBrowserMode());
  3345. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3346. if (ForceText)
  3347. {
  3348. CopyParam.TransferMode = tmAscii;
  3349. }
  3350. TemporaryFileCopyParam(CopyParam);
  3351. if (TempDir.IsEmpty())
  3352. {
  3353. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3354. }
  3355. DebugAssert(!FAutoOperation);
  3356. FAutoOperation = AutoOperation;
  3357. Terminal->ExceptionOnFail = true;
  3358. try
  3359. {
  3360. try
  3361. {
  3362. // turn off confirmations, as for MDI editors we may possibly download
  3363. // the same file over
  3364. Terminal->CopyToLocal(
  3365. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3366. if (GetTargetNames)
  3367. {
  3368. for (int i = 0; i < FileList->Count; i++)
  3369. {
  3370. FileList->Strings[i] =
  3371. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3372. }
  3373. }
  3374. }
  3375. catch(...)
  3376. {
  3377. if (!RootTempDir.IsEmpty())
  3378. {
  3379. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3380. }
  3381. throw;
  3382. }
  3383. }
  3384. __finally
  3385. {
  3386. FAutoOperation = false;
  3387. Terminal->ExceptionOnFail = false;
  3388. }
  3389. }
  3390. //---------------------------------------------------------------------------
  3391. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3392. {
  3393. // Do not waste time checking for default editor list the next time,
  3394. // or testing if default editor is not notepad.
  3395. bool TryNextTime = false;
  3396. UnicodeString UsageState;
  3397. if (!WinConfiguration->EditorList->IsDefaultList())
  3398. {
  3399. UsageState = "H";
  3400. }
  3401. else
  3402. {
  3403. UnicodeString Executable;
  3404. UnicodeString ExecutableDescription;
  3405. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3406. {
  3407. UnicodeString Message =
  3408. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3409. unsigned int Answer =
  3410. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3411. if (Answer != qaOK)
  3412. {
  3413. UsageState = "R";
  3414. }
  3415. else
  3416. {
  3417. UsageState = "A";
  3418. TEditorData EditorData;
  3419. EditorData.Editor = edExternal;
  3420. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3421. EditorData.ExternalEditorOptionsAutodetect();
  3422. TEditorList EditorList;
  3423. EditorList = *WinConfiguration->EditorList;
  3424. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3425. WinConfiguration->EditorList = &EditorList;
  3426. }
  3427. }
  3428. }
  3429. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3430. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3431. }
  3432. //---------------------------------------------------------------------------
  3433. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3434. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3435. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3436. {
  3437. if (ExecuteFileBy == efDefaultEditor)
  3438. {
  3439. if (!WinConfiguration->OfferedEditorAutoConfig)
  3440. {
  3441. EditorAutoConfig();
  3442. }
  3443. const TEditorPreferences * Editor =
  3444. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3445. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3446. {
  3447. ExecuteFileBy = efInternalEditor;
  3448. ExternalEditor = NULL;
  3449. }
  3450. else if (Editor->Data->Editor == edOpen)
  3451. {
  3452. ExecuteFileBy = efShell;
  3453. ExternalEditor = NULL;
  3454. }
  3455. else
  3456. {
  3457. ExecuteFileBy = efExternalEditor;
  3458. ExternalEditor = Editor->Data;
  3459. }
  3460. }
  3461. }
  3462. //---------------------------------------------------------------------------
  3463. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3464. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3465. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3466. {
  3467. UnicodeString OriginalFileName;
  3468. UnicodeString LocalRootDirectory;
  3469. UnicodeString RemoteDirectory;
  3470. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3471. IsSideLocalBrowser(Side), MaskParams);
  3472. UnicodeString Counter;
  3473. UnicodeString LocalFileName;
  3474. bool Handled = false;
  3475. if (!IsSideLocalBrowser(Side))
  3476. {
  3477. // We need to trim VMS version here, so that we use name without version
  3478. // when uploading back to create a new version of the file
  3479. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3480. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3481. TObject * Token = NULL;
  3482. UnicodeString LocalDirectory;
  3483. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3484. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3485. LocalDirectory))
  3486. {
  3487. if (Token != NULL)
  3488. {
  3489. TForm * Form = dynamic_cast<TForm *>(Token);
  3490. if (Form->WindowState == wsMinimized)
  3491. {
  3492. ShowWindow(Form->Handle, SW_RESTORE);
  3493. }
  3494. else
  3495. {
  3496. Form->SetFocus();
  3497. }
  3498. Handled = true;
  3499. }
  3500. else
  3501. {
  3502. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3503. }
  3504. }
  3505. if (!Handled)
  3506. {
  3507. TStringList * FileList1 = new TStringList();
  3508. try
  3509. {
  3510. FileList1->AddObject(FullFileName, Object);
  3511. TemporarilyDownloadFiles(FileList1,
  3512. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3513. LocalRootDirectory, LocalDirectory, true, true, false);
  3514. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3515. }
  3516. __finally
  3517. {
  3518. delete FileList1;
  3519. }
  3520. switch (ExecuteFileBy)
  3521. {
  3522. case efShell:
  3523. Counter = "RemoteFilesExecuted";
  3524. break;
  3525. case efInternalEditor:
  3526. Counter = "RemoteFilesOpenedInInternalEditor";
  3527. break;
  3528. case efExternalEditor:
  3529. Counter = "RemoteFilesOpenedInExternalEditor";
  3530. break;
  3531. default:
  3532. DebugFail();
  3533. }
  3534. }
  3535. }
  3536. else
  3537. {
  3538. LocalFileName = FullFileName;
  3539. OriginalFileName = ExtractFileName(FullFileName);
  3540. switch (ExecuteFileBy)
  3541. {
  3542. case efShell:
  3543. Counter = "LocalFilesExecuted";
  3544. break;
  3545. case efInternalEditor:
  3546. Counter = "LocalFilesOpenedInInternalEditor";
  3547. break;
  3548. case efExternalEditor:
  3549. Counter = "LocalFilesOpenedInExternalEditor";
  3550. break;
  3551. default:
  3552. DebugFail();
  3553. }
  3554. }
  3555. if (!Handled)
  3556. {
  3557. Configuration->Usage->Inc(Counter);
  3558. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3559. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3560. }
  3561. }
  3562. //---------------------------------------------------------------------------
  3563. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3564. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3565. bool AllSelected, bool OnFocused)
  3566. {
  3567. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3568. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3569. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3570. Side = GetSide(Side);
  3571. TCustomDirView * DView = DirView(Side);
  3572. TStrings * FileList =
  3573. AllSelected ?
  3574. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3575. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3576. try
  3577. {
  3578. DebugAssert(AllSelected || (FileList->Count == 1));
  3579. for (int i = 0; i < FileList->Count; i++)
  3580. {
  3581. UnicodeString ListFileName = FileList->Strings[i];
  3582. UnicodeString FileNameOnly =
  3583. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3584. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3585. if (!DView->ItemIsDirectory(Item))
  3586. {
  3587. UnicodeString FullFileName;
  3588. if (!IsSideLocalBrowser(Side))
  3589. {
  3590. FullFileName = DirView(Side)->Path + ListFileName;
  3591. }
  3592. else
  3593. {
  3594. FullFileName = ListFileName;
  3595. }
  3596. TObject * Object = FileList->Objects[i];
  3597. TFileMasks::TParams MaskParams;
  3598. MaskParams.Size = DView->ItemFileSize(Item);
  3599. TDateTimePrecision Precision;
  3600. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3601. std::unique_ptr<TRemoteFile> File;
  3602. if (!IsSideLocalBrowser(Side))
  3603. {
  3604. File.reset(Terminal->TryReadFile(FullFileName));
  3605. if (File.get() != NULL)
  3606. {
  3607. File->FullFileName = FullFileName;
  3608. Object = File.get();
  3609. MaskParams.Size = File->Size;
  3610. MaskParams.Modification = File->Modification;
  3611. }
  3612. }
  3613. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3614. }
  3615. }
  3616. }
  3617. __finally
  3618. {
  3619. delete FileList;
  3620. }
  3621. }
  3622. //---------------------------------------------------------------------------
  3623. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3624. {
  3625. CopyParam.FileNameCase = ncNoChange;
  3626. CopyParam.PreserveRights = false;
  3627. CopyParam.PreserveReadOnly = false;
  3628. CopyParam.ReplaceInvalidChars = true;
  3629. CopyParam.IncludeFileMask = TFileMasks();
  3630. CopyParam.NewerOnly = false;
  3631. CopyParam.FileMask = L"";
  3632. }
  3633. //---------------------------------------------------------------------------
  3634. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3635. {
  3636. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3637. }
  3638. //---------------------------------------------------------------------------
  3639. class TEditorUploadQueueItem : public TUploadQueueItem
  3640. {
  3641. public:
  3642. __fastcall TEditorUploadQueueItem(
  3643. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3644. const TCopyParamType * CopyParam, int Params) :
  3645. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, true, false)
  3646. {
  3647. }
  3648. protected:
  3649. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3650. {
  3651. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3652. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3653. }
  3654. };
  3655. //---------------------------------------------------------------------------
  3656. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3657. {
  3658. if (WinConfiguration->EditorCheckNotModified) // optimization
  3659. {
  3660. UnicodeString RemoteFilePath;
  3661. {
  3662. TGuard Guard(FEditorManager->Section);
  3663. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3664. if (DebugAlwaysTrue(Data != NULL) &&
  3665. EditorCheckNotModified(Data))
  3666. {
  3667. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3668. }
  3669. }
  3670. if (!RemoteFilePath.IsEmpty())
  3671. {
  3672. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3673. if (File.get() != NULL)
  3674. {
  3675. TGuard Guard(FEditorManager->Section);
  3676. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3677. if (DebugAlwaysTrue(Data != NULL))
  3678. {
  3679. Data->SourceTimestamp = File->Modification;
  3680. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3681. }
  3682. }
  3683. }
  3684. }
  3685. }
  3686. //---------------------------------------------------------------------------
  3687. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3688. const UnicodeString & FileName, TEditedFileData * Data, HANDLE UploadCompleteEvent, bool & Retry)
  3689. {
  3690. TTerminalManager * Manager = TTerminalManager::Instance();
  3691. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3692. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3693. {
  3694. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3695. Retry = true;
  3696. }
  3697. else if (!IsActiveTerminal(Data->Terminal))
  3698. {
  3699. if (!NonVisualDataModule->Busy)
  3700. {
  3701. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3702. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3703. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3704. if (Data->Terminal == NULL)
  3705. {
  3706. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3707. if (SameSiteTerminal != NULL)
  3708. {
  3709. UnicodeString Message =
  3710. FMTLOAD(EDIT_SESSION_REATTACH,
  3711. (FileNameOnly, Data->SessionName, FileNameOnly));
  3712. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3713. {
  3714. Data->Terminal = SameSiteTerminal;
  3715. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3716. // We might also overwrite session data
  3717. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3718. }
  3719. else
  3720. {
  3721. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3722. Abort();
  3723. }
  3724. }
  3725. }
  3726. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3727. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3728. {
  3729. UnicodeString Message =
  3730. MainInstructions(
  3731. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3732. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3733. {
  3734. if (Terminal->Disconnected)
  3735. {
  3736. Manager->ActiveSession = Terminal;
  3737. ReconnectSession();
  3738. // Was it reconnected? (if not, Data->Terminal should be nulled now)
  3739. if (!IsActiveTerminal(Data->Terminal) || (Terminal != Data->Terminal))
  3740. {
  3741. Abort();
  3742. }
  3743. }
  3744. else
  3745. {
  3746. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3747. }
  3748. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3749. }
  3750. else
  3751. {
  3752. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3753. Abort();
  3754. }
  3755. }
  3756. }
  3757. if (!IsActiveTerminal(Data->Terminal))
  3758. {
  3759. Configuration->Usage->Inc(L"EditInactiveSession");
  3760. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3761. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3762. (ExtractFileName(FileName), Data->SessionName)));
  3763. }
  3764. }
  3765. if (!Retry && EditorCheckNotModified(Data))
  3766. {
  3767. if (NonVisualDataModule->Busy)
  3768. {
  3769. Retry = true;
  3770. }
  3771. else
  3772. {
  3773. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3774. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3775. if (File.get() != NULL)
  3776. {
  3777. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3778. if (File->Modification != Data->SourceTimestamp)
  3779. {
  3780. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3781. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3782. {
  3783. Abort();
  3784. }
  3785. }
  3786. }
  3787. }
  3788. }
  3789. if (!Retry)
  3790. {
  3791. TStrings * FileList = new TStringList();
  3792. try
  3793. {
  3794. FileList->Add(FileName);
  3795. // Consider using the same settings (preset) as when the file was downloaded.
  3796. // More over this does not reflect the actual session that will do the upload.
  3797. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3798. TemporaryFileCopyParam(CopyParam);
  3799. if (Data->ForceText)
  3800. {
  3801. CopyParam.TransferMode = tmAscii;
  3802. }
  3803. // so i do not need to worry if masking algorithm works in all cases
  3804. // ("" means "copy file name", no masking is actually done)
  3805. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3806. {
  3807. CopyParam.FileMask = L"";
  3808. }
  3809. else
  3810. {
  3811. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3812. }
  3813. int Params = cpNoConfirmation | cpTemporary;
  3814. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3815. {
  3816. TTerminalQueue * AQueue = Manager->FindQueueForTerminal(Data->Terminal);
  3817. TQueueItem * QueueItem =
  3818. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3819. QueueItem->CompleteEvent = UploadCompleteEvent;
  3820. AddQueueItem(AQueue, QueueItem, Data->Terminal);
  3821. }
  3822. else
  3823. {
  3824. if (NonVisualDataModule->Busy)
  3825. {
  3826. Retry = true;
  3827. }
  3828. else
  3829. {
  3830. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3831. SetEvent(UploadCompleteEvent);
  3832. }
  3833. }
  3834. }
  3835. __finally
  3836. {
  3837. delete FileList;
  3838. }
  3839. }
  3840. }
  3841. //---------------------------------------------------------------------------
  3842. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3843. const UnicodeString & FileName, TEditedFileData * Data)
  3844. {
  3845. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3846. DebugAssert(!NonVisualDataModule->Busy);
  3847. if (!IsActiveTerminal(Data->Terminal))
  3848. {
  3849. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3850. (ExtractFileName(FileName), Data->SessionName)));
  3851. }
  3852. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3853. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3854. NonVisualDataModule->StartBusy();
  3855. try
  3856. {
  3857. std::unique_ptr<TRemoteFile> File;
  3858. UnicodeString RemoteFileName =
  3859. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3860. Terminal->ExceptionOnFail = true;
  3861. try
  3862. {
  3863. File.reset(Terminal->ReadFile(RemoteFileName));
  3864. if (!File->HaveFullFileName)
  3865. {
  3866. File->FullFileName = RemoteFileName;
  3867. }
  3868. }
  3869. __finally
  3870. {
  3871. Terminal->ExceptionOnFail = false;
  3872. }
  3873. std::unique_ptr<TStrings> FileList(new TStringList());
  3874. FileList->AddObject(RemoteFileName, File.get());
  3875. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3876. UnicodeString TempDir = ExtractFilePath(FileName);
  3877. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, true, false);
  3878. if (EditorCheckNotModified(Data))
  3879. {
  3880. Data->SourceTimestamp = File->Modification;
  3881. }
  3882. // sanity check, the target file name should be still the same
  3883. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3884. }
  3885. __finally
  3886. {
  3887. NonVisualDataModule->EndBusy();
  3888. // it actually may not exist anymore...
  3889. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3890. }
  3891. }
  3892. //---------------------------------------------------------------------------
  3893. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3894. const TEditedFileData * Data, bool & KeepOpen)
  3895. {
  3896. // Command is set for external editors only (not for "shell" open).
  3897. if (!Data->Command.IsEmpty())
  3898. {
  3899. bool AnyFound = false;
  3900. bool AnyMDI = false;
  3901. bool AnyNonMDI = false;
  3902. bool AnyDetect = false;
  3903. TEditorList * EditorList = new TEditorList();
  3904. try
  3905. {
  3906. *EditorList = *WinConfiguration->EditorList;
  3907. for (int i = 0; i < EditorList->Count; i++)
  3908. {
  3909. const TEditorPreferences * Editor = EditorList->Editors[i];
  3910. if ((Editor->Data->Editor == edExternal) &&
  3911. (Editor->Data->ExternalEditor == Data->Command))
  3912. {
  3913. AnyFound = true;
  3914. if (Editor->Data->SDIExternalEditor)
  3915. {
  3916. AnyNonMDI = true;
  3917. if (Editor->Data->DetectMDIExternalEditor)
  3918. {
  3919. AnyDetect = true;
  3920. }
  3921. }
  3922. else
  3923. {
  3924. AnyMDI = true;
  3925. }
  3926. }
  3927. }
  3928. bool EnableMDI = false;
  3929. bool DisableDetect = false;
  3930. if (AnyMDI)
  3931. {
  3932. KeepOpen = true;
  3933. if (AnyNonMDI)
  3934. {
  3935. // there is at least one instance of the editor with MDI support enabled,
  3936. // and one with disabled, enable it for all instances
  3937. EnableMDI = true;
  3938. }
  3939. }
  3940. else if (AnyFound && !AnyDetect)
  3941. {
  3942. // at least once instance found but all have MDI autodetection disabled
  3943. // => close the file (default action)
  3944. }
  3945. else
  3946. {
  3947. // no instance of the editor has MDI support enabled
  3948. TMessageParams Params;
  3949. if (AnyFound)
  3950. {
  3951. // there is at least one instance of the editor
  3952. Params.Params |= mpNeverAskAgainCheck;
  3953. }
  3954. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3955. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3956. switch (Answer)
  3957. {
  3958. case qaNeverAskAgain:
  3959. DisableDetect = true;
  3960. break;
  3961. case qaNo:
  3962. EnableMDI = true;
  3963. KeepOpen = true;
  3964. break;
  3965. }
  3966. }
  3967. if (AnyFound && (EnableMDI || DisableDetect))
  3968. {
  3969. bool Changed = false;
  3970. for (int i = 0; i < EditorList->Count; i++)
  3971. {
  3972. const TEditorPreferences * Editor = EditorList->Editors[i];
  3973. if ((Editor->Data->Editor == edExternal) &&
  3974. (Editor->Data->ExternalEditor == Data->Command) &&
  3975. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3976. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3977. {
  3978. Changed = true;
  3979. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3980. if (EnableMDI)
  3981. {
  3982. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3983. }
  3984. if (DisableDetect)
  3985. {
  3986. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3987. }
  3988. EditorList->Change(i, UpdatedEditor);
  3989. }
  3990. }
  3991. if (Changed)
  3992. {
  3993. WinConfiguration->EditorList = EditorList;
  3994. }
  3995. }
  3996. }
  3997. __finally
  3998. {
  3999. delete EditorList;
  4000. }
  4001. }
  4002. else
  4003. {
  4004. // "open" case
  4005. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  4006. qaOK, HELP_APP_EARLY_CLOSED);
  4007. }
  4008. }
  4009. //---------------------------------------------------------------------------
  4010. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  4011. {
  4012. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  4013. }
  4014. //---------------------------------------------------------------------------
  4015. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  4016. {
  4017. SideEnter(osRemote);
  4018. }
  4019. //---------------------------------------------------------------------------
  4020. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4021. {
  4022. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4023. SideEnter(osRemote);
  4024. }
  4025. //---------------------------------------------------------------------------
  4026. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4027. {
  4028. FCurrentSide = Side;
  4029. if (Visible)
  4030. {
  4031. UpdateControls();
  4032. }
  4033. }
  4034. //---------------------------------------------------------------------------
  4035. void __fastcall TCustomScpExplorerForm::FileDeleted(TOperationSide Side, const UnicodeString & FileName, bool Success)
  4036. {
  4037. VisualiseOperationFinished(Side, FileName, Success);
  4038. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4039. {
  4040. FDeletedFiles->Add(FileName);
  4041. }
  4042. }
  4043. //---------------------------------------------------------------------------
  4044. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4045. TStrings * FileList, bool Alternative)
  4046. {
  4047. TCustomDirView * DView = DirView(Side);
  4048. DView->SaveSelection();
  4049. DView->SaveSelectedNames();
  4050. DebugAssert(!FAlternativeDelete);
  4051. FAlternativeDelete = Alternative;
  4052. try
  4053. {
  4054. if (!IsSideLocalBrowser(Side))
  4055. {
  4056. DebugAssert(Terminal != NULL);
  4057. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4058. std::unique_ptr<TStrings> PermanentFileList(TRemoteFileList::CloneStrings(FileList));
  4059. std::unique_ptr<TStringList> DeletedFiles(new TStringList());
  4060. DeletedFiles->CaseSensitive = DebugAlwaysTrue(!IsSideLocalBrowser(Side));
  4061. int Params = FLAGMASK(Alternative, dfAlternative);
  4062. try
  4063. {
  4064. DebugAssert(FDeletedFiles == NULL);
  4065. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles, DeletedFiles.get());
  4066. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4067. FOnFileOperationFinished = FileDeleted;
  4068. FMoveToQueue = false;
  4069. Terminal->DeleteFiles(FileList, Params);
  4070. // Probably not needed for deleting, just for consistency with transfer code
  4071. if (FMoveToQueue)
  4072. {
  4073. Abort();
  4074. }
  4075. }
  4076. catch (EAbort &)
  4077. {
  4078. if (FMoveToQueue)
  4079. {
  4080. DeletedFiles->Sorted = true;
  4081. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4082. {
  4083. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4084. {
  4085. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4086. DebugAssert(Index == 0);
  4087. PermanentFileList->Delete(Index);
  4088. Index--;
  4089. }
  4090. }
  4091. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4092. TQueueItem * QueueItem = new TDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4093. AddQueueItem(Queue, QueueItem, Terminal);
  4094. ClearOperationSelection(osRemote);
  4095. }
  4096. }
  4097. }
  4098. else
  4099. {
  4100. if (IsLocalBrowserMode())
  4101. {
  4102. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4103. }
  4104. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  4105. try
  4106. {
  4107. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  4108. }
  4109. __finally
  4110. {
  4111. ReloadLocalDirectory();
  4112. }
  4113. }
  4114. FAlternativeDelete = false;
  4115. }
  4116. catch(...)
  4117. {
  4118. FAlternativeDelete = false;
  4119. DView->DiscardSavedSelection();
  4120. throw;
  4121. }
  4122. DView->RestoreSelection();
  4123. }
  4124. //---------------------------------------------------------------------------
  4125. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4126. {
  4127. DebugAssert(Terminal);
  4128. DebugAssert(!IsLocalBrowserMode());
  4129. RemoteDirView->SaveSelection();
  4130. RemoteDirView->SaveSelectedNames();
  4131. try
  4132. {
  4133. if (Lock)
  4134. {
  4135. Terminal->LockFiles(FileList);
  4136. }
  4137. else
  4138. {
  4139. Terminal->UnlockFiles(FileList);
  4140. }
  4141. }
  4142. catch(...)
  4143. {
  4144. RemoteDirView->DiscardSavedSelection();
  4145. throw;
  4146. }
  4147. RemoteDirView->RestoreSelection();
  4148. }
  4149. //---------------------------------------------------------------------------
  4150. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4151. {
  4152. bool Result = false;
  4153. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4154. if (IsActiveTerminal(ATerminal))
  4155. {
  4156. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(Directory));
  4157. Result = File && File->IsDirectory;
  4158. }
  4159. return Result;
  4160. }
  4161. //---------------------------------------------------------------------------
  4162. bool TCustomScpExplorerForm::NeedSecondarySessionForRemoteCopy(TStrings * FileList)
  4163. {
  4164. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4165. return
  4166. !Terminal->IsCapable[fcRemoteCopy] ||
  4167. (CopyDirsOnSecondarySession && TRemoteFileList::AnyDirectory(FileList));
  4168. }
  4169. //---------------------------------------------------------------------------
  4170. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4171. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4172. bool NoConfirmation, bool Move)
  4173. {
  4174. DebugAssert(Terminal != NULL);
  4175. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4176. DebugAssert(!IsLocalBrowserMode());
  4177. if (Session == NULL)
  4178. {
  4179. Session = Terminal;
  4180. }
  4181. bool TargetConfirmed = false;
  4182. if (Session == Terminal)
  4183. {
  4184. if (RemoteDriveView->DropTarget != NULL)
  4185. {
  4186. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4187. TargetConfirmed = true;
  4188. }
  4189. else if (RemoteDirView->DropTarget != NULL)
  4190. {
  4191. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4192. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4193. TargetConfirmed = true;
  4194. }
  4195. else
  4196. {
  4197. Target = RemoteDirView->Path;
  4198. }
  4199. }
  4200. else
  4201. {
  4202. Target = GetSessionPath(Session, osRemote);
  4203. }
  4204. Target = UnixIncludeTrailingBackslash(Target);
  4205. if (FileList->Count == 1)
  4206. {
  4207. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4208. }
  4209. else
  4210. {
  4211. FileMask = AnyMask;
  4212. }
  4213. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4214. bool Result = true;
  4215. if (!NoConfirmation)
  4216. {
  4217. bool Multi = (FileList->Count > 1);
  4218. if (Move)
  4219. {
  4220. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4221. }
  4222. else
  4223. {
  4224. std::unique_ptr<TStrings> Sessions(new TStringList);
  4225. std::unique_ptr<TStrings> Directories(new TStringList);
  4226. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4227. for (int Index = 0; Index < SessionList->Count; Index++)
  4228. {
  4229. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4230. if (IsActiveTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4231. {
  4232. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4233. Directories->Add(GetSessionPath(ASession, osRemote));
  4234. }
  4235. }
  4236. bool AnyDirectory = false;
  4237. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4238. if (CopyDirsOnSecondarySession && !Terminal->CommandSessionOpened) // optimization
  4239. {
  4240. for (int Index = 0; !AnyDirectory && (Index < FileList->Count); Index++)
  4241. {
  4242. AnyDirectory = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]))->IsDirectory;
  4243. }
  4244. }
  4245. TDirectRemoteCopy AllowDirectCopy;
  4246. if (Terminal->CommandSessionOpened || !NeedSecondarySessionForRemoteCopy(FileList))
  4247. {
  4248. DebugAssert(DirectCopy);
  4249. AllowDirectCopy = drcAllow;
  4250. }
  4251. else if (Terminal->IsCapable[fcSecondaryShell])
  4252. {
  4253. DebugAssert(DirectCopy);
  4254. AllowDirectCopy = Terminal->IsCapable[fcRemoteCopy] ? drcConfirmCommandSessionDirs : drcConfirmCommandSession;
  4255. }
  4256. else
  4257. {
  4258. DebugAssert(!DirectCopy);
  4259. AllowDirectCopy = drcDisallow;
  4260. }
  4261. void * ASession = Session;
  4262. Result = DoRemoteCopyDialog(
  4263. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4264. DoDirectoryExists, TargetConfirmed);
  4265. Session = static_cast<TManagedTerminal *>(ASession);
  4266. }
  4267. }
  4268. return Result;
  4269. }
  4270. //---------------------------------------------------------------------------
  4271. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4272. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4273. {
  4274. DebugAssert(!IsLocalBrowserMode());
  4275. bool DirectCopy;
  4276. UnicodeString Target, FileMask;
  4277. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4278. if (Result)
  4279. {
  4280. if (!Move && !DirectCopy)
  4281. {
  4282. Configuration->Usage->Inc("RemoteCopyTemp");
  4283. UnicodeString RootTempDir;
  4284. UnicodeString TempDir;
  4285. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  4286. TStrings * TemporaryFilesList = new TStringList();
  4287. try
  4288. {
  4289. TMakeLocalFileListParams MakeFileListParam;
  4290. MakeFileListParam.FileList = TemporaryFilesList;
  4291. MakeFileListParam.FileTimes = NULL;
  4292. MakeFileListParam.IncludeDirs = true;
  4293. MakeFileListParam.Recursive = false;
  4294. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4295. TTerminalManager::Instance()->ActiveSession = Session;
  4296. if (TemporaryFilesList->Count > 0)
  4297. {
  4298. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4299. CopyParam.FileMask = FileMask;
  4300. DebugAssert(!FAutoOperation);
  4301. FAutoOperation = true;
  4302. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4303. }
  4304. }
  4305. __finally
  4306. {
  4307. delete TemporaryFilesList;
  4308. FAutoOperation = false;
  4309. if (!RootTempDir.IsEmpty())
  4310. {
  4311. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4312. }
  4313. }
  4314. }
  4315. else
  4316. {
  4317. RemoteDirView->SaveSelection();
  4318. RemoteDirView->SaveSelectedNames();
  4319. try
  4320. {
  4321. if (Move)
  4322. {
  4323. Configuration->Usage->Inc("RemoteMove");
  4324. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4325. }
  4326. else
  4327. {
  4328. Configuration->Usage->Inc("RemoteCopyDirect");
  4329. DebugAssert(DirectCopy);
  4330. DebugAssert(Session == Terminal);
  4331. if (!NeedSecondarySessionForRemoteCopy(FileList) ||
  4332. Terminal->CommandSessionOpened ||
  4333. CommandSessionFallback())
  4334. {
  4335. Terminal->CopyFiles(FileList, Target, FileMask, false);
  4336. }
  4337. }
  4338. }
  4339. catch(...)
  4340. {
  4341. RemoteDirView->DiscardSavedSelection();
  4342. throw;
  4343. }
  4344. RemoteDirView->RestoreSelection();
  4345. }
  4346. }
  4347. return Result;
  4348. }
  4349. //---------------------------------------------------------------------------
  4350. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4351. const UnicodeString & Path, TRemoteProperties & Properties)
  4352. {
  4353. DebugAssert(!IsLocalBrowserMode());
  4354. Properties.Valid = Properties.Valid << vpEncrypt;
  4355. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4356. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4357. }
  4358. //---------------------------------------------------------------------------
  4359. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4360. {
  4361. Side = GetSide(Side);
  4362. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4363. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4364. UnicodeString Name = LoadStr(NEW_FOLDER);
  4365. int AllowedChanges =
  4366. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4367. bool SaveSettings = false;
  4368. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4369. {
  4370. TWindowLock Lock(this);
  4371. if (!IsSideLocalBrowser(Side))
  4372. {
  4373. if (SaveSettings)
  4374. {
  4375. GUIConfiguration->NewDirectoryProperties = Properties;
  4376. }
  4377. CreateRemoteDirectory(Name, Properties);
  4378. }
  4379. else
  4380. {
  4381. DirView(Side)->CreateDirectory(Name);
  4382. }
  4383. }
  4384. }
  4385. //---------------------------------------------------------------------------
  4386. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4387. {
  4388. TWindowLock Lock(this);
  4389. DirView(Side)->ExecuteHomeDirectory();
  4390. }
  4391. //---------------------------------------------------------------------------
  4392. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4393. {
  4394. DoOpenDirectoryDialog(odBrowse, Side);
  4395. }
  4396. //---------------------------------------------------------------------------
  4397. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4398. {
  4399. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4400. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4401. bool Result = !Path.IsEmpty();
  4402. if (Result)
  4403. {
  4404. TryOpenDirectory(Side, Path);
  4405. }
  4406. return Result;
  4407. }
  4408. //---------------------------------------------------------------------------
  4409. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4410. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4411. bool & Close)
  4412. {
  4413. // terminal can be already closed (e.g. dropped connection)
  4414. if (Terminal != NULL)
  4415. {
  4416. try
  4417. {
  4418. TCalculateSizeParams Params;
  4419. Params.Stats = &Stats;
  4420. Terminal->CalculateFilesSize(FileList, Size, Params);
  4421. }
  4422. catch(...)
  4423. {
  4424. if (!Terminal->Active)
  4425. {
  4426. Close = true;
  4427. }
  4428. throw;
  4429. }
  4430. }
  4431. }
  4432. //---------------------------------------------------------------------------
  4433. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4434. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4435. bool & Close)
  4436. {
  4437. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4438. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4439. {
  4440. Configuration->Usage->Inc(L"ChecksumCalculated");
  4441. try
  4442. {
  4443. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4444. }
  4445. catch(...)
  4446. {
  4447. if (!Terminal->Active)
  4448. {
  4449. Close = true;
  4450. }
  4451. throw;
  4452. }
  4453. }
  4454. }
  4455. //---------------------------------------------------------------------------
  4456. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4457. {
  4458. if (Terminal->LoadFilesProperties(FileList))
  4459. {
  4460. RemoteDirView->Invalidate();
  4461. }
  4462. }
  4463. //---------------------------------------------------------------------------
  4464. bool TCustomScpExplorerForm::CanCalculateChecksum()
  4465. {
  4466. return
  4467. Terminal->IsCapable[fcCalculatingChecksum] ||
  4468. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles());
  4469. }
  4470. //---------------------------------------------------------------------------
  4471. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4472. {
  4473. bool Result;
  4474. if (!IsSideLocalBrowser(Side))
  4475. {
  4476. TRemoteTokenList * GroupList = NULL;
  4477. TRemoteTokenList * UserList = NULL;
  4478. try
  4479. {
  4480. TRemoteProperties CurrentProperties;
  4481. LoadFilesProperties(FileList);
  4482. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4483. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4484. if (CapableGroupChanging || CapableOwnerChanging)
  4485. {
  4486. if (CapableGroupChanging)
  4487. {
  4488. GroupList = Terminal->Groups->Duplicate();
  4489. }
  4490. if (CapableOwnerChanging)
  4491. {
  4492. UserList = Terminal->Users->Duplicate();
  4493. }
  4494. TRemoteDirectory * Files = Terminal->Files;
  4495. int Count = Files->Count;
  4496. if (Count > 100)
  4497. {
  4498. Count = 100;
  4499. }
  4500. for (int Index = 0; Index < Count; Index++)
  4501. {
  4502. TRemoteFile * File = Files->Files[Index];
  4503. if (CapableGroupChanging)
  4504. {
  4505. GroupList->AddUnique(File->Group);
  4506. }
  4507. if (CapableOwnerChanging)
  4508. {
  4509. UserList->AddUnique(File->Owner);
  4510. }
  4511. }
  4512. // if we haven't collected tokens for all files in current directory,
  4513. // make sure we collect them at least for all selected files.
  4514. // (note that so far the files in FileList has to be from current direcotry)
  4515. if (Count < Files->Count)
  4516. {
  4517. for (int Index = 0; Index < FileList->Count; Index++)
  4518. {
  4519. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4520. if (CapableGroupChanging)
  4521. {
  4522. GroupList->AddUnique(File->Group);
  4523. }
  4524. if (CapableOwnerChanging)
  4525. {
  4526. UserList->AddUnique(File->Owner);
  4527. }
  4528. }
  4529. }
  4530. }
  4531. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4532. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4533. if (CapableAclChanging && TRemoteFileList::AnyDirectory(FileList))
  4534. {
  4535. CapableAclChanging = false;
  4536. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4537. }
  4538. int Flags = 0;
  4539. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4540. if (CapableAclChanging) Flags |= cpAcl;
  4541. if (CapableOwnerChanging) Flags |= cpOwner;
  4542. if (CapableGroupChanging) Flags |= cpGroup;
  4543. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4544. if (CanCalculateChecksum())
  4545. {
  4546. CalculateChecksumEvent = CalculateChecksum;
  4547. }
  4548. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4549. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4550. TRemoteProperties NewProperties = CurrentProperties;
  4551. Result =
  4552. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4553. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4554. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4555. CalculateSize, CalculateChecksumEvent);
  4556. if (Result)
  4557. {
  4558. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4559. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4560. }
  4561. }
  4562. __finally
  4563. {
  4564. delete GroupList;
  4565. delete UserList;
  4566. }
  4567. }
  4568. else
  4569. {
  4570. DirView(Side)->DisplayPropertiesMenu();
  4571. Result = true;
  4572. }
  4573. return Result;
  4574. }
  4575. //---------------------------------------------------------------------------
  4576. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4577. {
  4578. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4579. {
  4580. FIgnoreNextDialogChar = Key;
  4581. }
  4582. Key = 0;
  4583. }
  4584. //---------------------------------------------------------------------------
  4585. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4586. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4587. {
  4588. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4589. if (Command != NULL)
  4590. {
  4591. KeyProcessed(Key, Shift);
  4592. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4593. {
  4594. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4595. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4596. false, false, const_cast<TCustomCommandType *>(Command));
  4597. }
  4598. }
  4599. }
  4600. //---------------------------------------------------------------------------
  4601. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4602. {
  4603. if (!NonVisualDataModule->Busy)
  4604. {
  4605. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4606. {
  4607. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4608. }
  4609. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4610. {
  4611. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4612. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4613. {
  4614. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4615. // But so far it's not a problem, as it does what we want.
  4616. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4617. if (((Action->ShortCut == KeyShortCut) ||
  4618. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4619. AllowedAction(Action, aaShortCut))
  4620. {
  4621. // Has to be called before the action as the dialog char is already in queue.
  4622. // So when the action consumes message queue, we already need to have the
  4623. // FIgnoreNextDialogChar set
  4624. KeyProcessed(Key, Shift);
  4625. // Reset reference to previous component (when menu/toolbar was clicked).
  4626. // Needed to detect that action was invoked by keyboard shortcut
  4627. // in TNonVisualDataModule::ExplorerActionsExecute
  4628. Action->ActionComponent = NULL;
  4629. Action->Execute();
  4630. return;
  4631. }
  4632. }
  4633. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4634. {
  4635. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4636. {
  4637. KeyProcessed(Key, Shift);
  4638. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4639. return;
  4640. }
  4641. }
  4642. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4643. {
  4644. KeyProcessed(Key, Shift);
  4645. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4646. }
  4647. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4648. if (IsCustomShortCut(CustomShortCut))
  4649. {
  4650. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4651. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4652. if (WinConfiguration->SharedBookmarks != NULL)
  4653. {
  4654. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4655. if ((Bookmark != NULL) &&
  4656. OpenBookmark(FCurrentSide, Bookmark))
  4657. {
  4658. KeyProcessed(Key, Shift);
  4659. }
  4660. }
  4661. }
  4662. }
  4663. }
  4664. TForm::KeyDown(Key, Shift);
  4665. }
  4666. //---------------------------------------------------------------------------
  4667. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4668. {
  4669. bool OpenedTerminal = false;
  4670. UnicodeString ProtocolName;
  4671. UnicodeString ProtocolNameHint;
  4672. UnicodeString SecurityProtocolName;
  4673. UnicodeString DurationHint;
  4674. // See the comment in TScpCommanderForm::UpdateControls()
  4675. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4676. if (ActiveTerminal != NULL)
  4677. {
  4678. // Active is not enough here
  4679. if (ActiveTerminal->Status == ssOpened)
  4680. {
  4681. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4682. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4683. if (FileSystemInfo.ProtocolName.IsEmpty())
  4684. {
  4685. ProtocolName = SessionInfo.ProtocolName;
  4686. }
  4687. else
  4688. {
  4689. ProtocolName = FileSystemInfo.ProtocolName;
  4690. }
  4691. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4692. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4693. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4694. OpenedTerminal = true;
  4695. }
  4696. else if (ActiveTerminal->Status > ssClosed)
  4697. {
  4698. ProtocolName = LoadStr(STATUS_CONNECTING);
  4699. }
  4700. else
  4701. {
  4702. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4703. }
  4704. }
  4705. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4706. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4707. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4708. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4709. if (ProtocolStatusPanel->Caption != ProtocolName)
  4710. {
  4711. ProtocolStatusPanel->Caption = ProtocolName;
  4712. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4713. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4714. }
  4715. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4716. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4717. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4718. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4719. SecurityStatusPanel->Enabled = SecurityEnabled;
  4720. UnicodeString SecurityProtocolHint;
  4721. if (SecurityEnabled)
  4722. {
  4723. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4724. }
  4725. else
  4726. {
  4727. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4728. }
  4729. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4730. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4731. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4732. DurationStatusPanel->Hint = DurationHint;
  4733. UpdateStatusBar();
  4734. }
  4735. //---------------------------------------------------------------------------
  4736. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4737. {
  4738. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4739. DebugAssert(SessionStatusBar != NULL);
  4740. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4741. if (!FNote.IsEmpty())
  4742. {
  4743. NoteStatusPanel->Caption = FNote;
  4744. }
  4745. else
  4746. {
  4747. UpdateStatusPanelText(NoteStatusPanel);
  4748. }
  4749. NoteStatusPanel->Hint = FNoteHints;
  4750. UnicodeString LoginTime;
  4751. // See the comment in TScpCommanderForm::UpdateControls()
  4752. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4753. // Active is not enough here
  4754. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4755. {
  4756. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4757. LoginTime = FormatDateTimeSpan(Now() - SessionInfo.LoginTime);
  4758. }
  4759. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4760. DurationStatusPanel->Caption = LoginTime;
  4761. }
  4762. //---------------------------------------------------------------------------
  4763. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4764. {
  4765. Panel->Caption = L"";
  4766. }
  4767. //---------------------------------------------------------------------------
  4768. void __fastcall TCustomScpExplorerForm::Idle()
  4769. {
  4770. if (FShowing ||
  4771. // Particularly for
  4772. // - Standalone editing
  4773. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4774. // while "keeping remote directory up to date".
  4775. StandaloneOperation)
  4776. {
  4777. FEditorManager->Check();
  4778. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4779. // that needs to know if queue view is visible (and it may be closed after queue update)
  4780. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4781. }
  4782. if (FShowing)
  4783. {
  4784. if (!NonVisualDataModule->Busy &&
  4785. // Menu is opened or drag&drop is going on
  4786. (Mouse->Capture == NULL))
  4787. {
  4788. if (FRefreshRemoteDirectory)
  4789. {
  4790. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4791. {
  4792. Terminal->RefreshDirectory();
  4793. }
  4794. FRefreshRemoteDirectory = false;
  4795. }
  4796. if (FRefreshLocalDirectory)
  4797. {
  4798. ReloadLocalDirectory();
  4799. FRefreshLocalDirectory = false;
  4800. }
  4801. if (WinConfiguration->RefreshRemotePanel)
  4802. {
  4803. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4804. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4805. {
  4806. RemoteDirView->ReloadDirectory();
  4807. }
  4808. }
  4809. }
  4810. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4811. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4812. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4813. // 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.
  4814. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4815. MenuToolbar->Idle();
  4816. }
  4817. if (FShowing || StandaloneOperation)
  4818. {
  4819. if (FQueueStatusInvalidated)
  4820. {
  4821. UpdateQueueStatus(false);
  4822. }
  4823. RefreshQueueItems();
  4824. }
  4825. if (FShowing)
  4826. {
  4827. UpdateStatusBar();
  4828. }
  4829. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4830. {
  4831. FClipboardFakeMonitorsPendingReset = false;
  4832. FClipboardFakeMonitors.reset(NULL);
  4833. }
  4834. FIgnoreNextDialogChar = 0;
  4835. }
  4836. //---------------------------------------------------------------------------
  4837. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4838. {
  4839. try
  4840. {
  4841. FUserActionTimer->Enabled = false;
  4842. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4843. {
  4844. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4845. {
  4846. FPendingQueueActionItem->ProcessUserAction();
  4847. }
  4848. }
  4849. }
  4850. __finally
  4851. {
  4852. FPendingQueueActionItem = NULL;
  4853. }
  4854. }
  4855. //---------------------------------------------------------------------------
  4856. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4857. {
  4858. if (WinConfiguration->MinimizeToTray)
  4859. {
  4860. UpdateTrayIcon();
  4861. FTrayIcon->Visible = true;
  4862. if (Visible)
  4863. {
  4864. ShowWindow(Handle, SW_HIDE);
  4865. }
  4866. }
  4867. }
  4868. //---------------------------------------------------------------------------
  4869. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4870. {
  4871. // WORKAROUND
  4872. // When restoring maximized window from minimization,
  4873. // rarely some controls do not align properly.
  4874. // Two instances seen (both for Commander):
  4875. // - When restoring, window is temporarily narrower (not maximized),
  4876. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4877. // Once maximized already, top dock shinks back, but the session PageControl,
  4878. // do not align up, leaving space between TopDock and PageControl.
  4879. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4880. for (int Index = 0; Index < ControlCount; Index++)
  4881. {
  4882. RealignControl(Controls[Index]);
  4883. }
  4884. if (FTrayIcon->Visible)
  4885. {
  4886. FTrayIcon->Visible = false;
  4887. if (Visible)
  4888. {
  4889. ShowWindow(Handle, SW_SHOW);
  4890. }
  4891. }
  4892. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4893. {
  4894. FNeedSession = false;
  4895. NonVisualDataModule->StartBusy();
  4896. try
  4897. {
  4898. NeedSession(true);
  4899. }
  4900. __finally
  4901. {
  4902. NonVisualDataModule->EndBusy();
  4903. }
  4904. }
  4905. }
  4906. //---------------------------------------------------------------------------
  4907. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4908. {
  4909. FTrayIcon->Hint = GetMainForm()->Caption;
  4910. }
  4911. //---------------------------------------------------------------------------
  4912. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4913. {
  4914. UpdateTrayIcon();
  4915. }
  4916. //---------------------------------------------------------------------------
  4917. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4918. {
  4919. // workaround
  4920. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4921. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4922. // But WM_ACTIVATEAPP message can be received even when
  4923. // the main window is minimized to the tray and internal editor window is focused
  4924. // (after another application was previously active)
  4925. if (::IsIconic(Handle))
  4926. {
  4927. if (!IsAppIconic())
  4928. {
  4929. SetAppIconic(true);
  4930. }
  4931. }
  4932. ::ApplicationRestore();
  4933. Application->BringToFront();
  4934. }
  4935. //---------------------------------------------------------------------------
  4936. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4937. {
  4938. RestoreApp();
  4939. }
  4940. //---------------------------------------------------------------------------
  4941. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4942. {
  4943. if (OpenInNewWindow())
  4944. {
  4945. ExecuteNewInstance(SessionUrl);
  4946. }
  4947. else
  4948. {
  4949. TTerminalManager::Instance()->NewSession(SessionUrl);
  4950. }
  4951. }
  4952. //---------------------------------------------------------------------------
  4953. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4954. {
  4955. NewSession();
  4956. }
  4957. //---------------------------------------------------------------------------
  4958. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4959. {
  4960. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4961. StoredSessions->NewSession(SessionName, SessionData);
  4962. // modified only, explicit
  4963. StoredSessions->Save(false, true);
  4964. // encode session name because of slashes in hierarchical sessions
  4965. return EncodeUrlString(SessionName);
  4966. }
  4967. //---------------------------------------------------------------------------
  4968. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4969. {
  4970. // current working directories become defaults here, what is not right
  4971. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4972. return SaveHiddenDuplicateSession(SessionData.get());
  4973. }
  4974. //---------------------------------------------------------------------------
  4975. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  4976. {
  4977. if (OpenInNewWindow())
  4978. {
  4979. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4980. }
  4981. else
  4982. {
  4983. // current working directories become defaults here, what is not right
  4984. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4985. TTerminalManager * Manager = TTerminalManager::Instance();
  4986. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  4987. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  4988. // We definitely want these
  4989. ASession->Disconnected = ManagedSession->Disconnected;
  4990. // Not sure about these two
  4991. ASession->Permanent = ManagedSession->Permanent;
  4992. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  4993. Manager->ActiveSession = ASession;
  4994. }
  4995. }
  4996. //---------------------------------------------------------------------------
  4997. void __fastcall TCustomScpExplorerForm::RenameTab()
  4998. {
  4999. UnicodeString Name = ManagedSession->SessionData->SessionName;
  5000. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  5001. // When submitting the default name, do not fix it
  5002. (Name != ManagedSession->SessionData->SessionName))
  5003. {
  5004. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  5005. TSessionData::ValidateName(Name);
  5006. // This is inconsistent with how color (for example) is handled.
  5007. ManagedSession->SessionData->Name = Name;
  5008. UpdateControls();
  5009. // Add/Remove distinguishing paths from sessions of the same name.
  5010. SessionListChanged();
  5011. }
  5012. }
  5013. //---------------------------------------------------------------------------
  5014. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  5015. {
  5016. DebugAssert(Queue != NULL);
  5017. bool Result = Queue->IsEmpty;
  5018. if (!Result)
  5019. {
  5020. SetFocus();
  5021. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  5022. }
  5023. return Result;
  5024. }
  5025. //---------------------------------------------------------------------------
  5026. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  5027. {
  5028. return CanCloseQueue(FQueue);
  5029. }
  5030. //---------------------------------------------------------------------------
  5031. void __fastcall TCustomScpExplorerForm::CloseTab()
  5032. {
  5033. if (CanCloseQueue())
  5034. {
  5035. TTerminalManager::Instance()->FreeActiveTerminal();
  5036. }
  5037. }
  5038. //---------------------------------------------------------------------------
  5039. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5040. {
  5041. if (CanCloseQueue())
  5042. {
  5043. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5044. }
  5045. }
  5046. //---------------------------------------------------------------------------
  5047. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5048. {
  5049. DetachTerminal(Terminal);
  5050. RemoteDirView->Terminal = Terminal;
  5051. UpdateRemotePathComboBox(false);
  5052. InitStatusBar();
  5053. UpdateControls();
  5054. }
  5055. //---------------------------------------------------------------------------
  5056. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5057. {
  5058. InitStatusBar();
  5059. }
  5060. //---------------------------------------------------------------------------
  5061. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5062. {
  5063. if (DebugAlwaysTrue(!Terminal->Active))
  5064. {
  5065. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5066. }
  5067. }
  5068. //---------------------------------------------------------------------------
  5069. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5070. {
  5071. if (OpenInNewWindow())
  5072. {
  5073. // encode session name because of slashes in hierarchical sessions
  5074. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5075. }
  5076. else
  5077. {
  5078. TTerminalManager * Manager = TTerminalManager::Instance();
  5079. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5080. Manager->ActiveSession = Terminal;
  5081. }
  5082. }
  5083. //---------------------------------------------------------------------------
  5084. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5085. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5086. {
  5087. TTerminalManager * Manager = TTerminalManager::Instance();
  5088. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5089. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5090. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5091. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5092. {
  5093. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5094. // FirstSession can be null, if none of the workspace sites exist anymore
  5095. // or if all workspace sessions are not suported by the interface
  5096. // (when trying to open all local-local workspace in "explorer" interface)
  5097. if (FirstSession != NULL)
  5098. {
  5099. if (!ConnectFirstTerminal)
  5100. {
  5101. FirstSession->Disconnected = true;
  5102. FirstSession->DisconnectedTemporarily = true;
  5103. }
  5104. Manager->ActiveSession = FirstSession;
  5105. }
  5106. }
  5107. }
  5108. //---------------------------------------------------------------------------
  5109. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5110. {
  5111. if (OpenInNewWindow())
  5112. {
  5113. ExecuteNewInstance(Name);
  5114. }
  5115. else
  5116. {
  5117. DoOpenFolderOrWorkspace(Name, true, false);
  5118. }
  5119. }
  5120. //---------------------------------------------------------------------------
  5121. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5122. bool &CanClose)
  5123. {
  5124. AppLog(L"Windows close query");
  5125. // See the comment in CloseApp()
  5126. if (NonVisualDataModule->Busy)
  5127. {
  5128. CanClose = false;
  5129. }
  5130. else
  5131. {
  5132. TTerminalManager * Manager = TTerminalManager::Instance();
  5133. int ActiveSessions = 0;
  5134. for (int Index = 0; Index < Manager->Count; Index++)
  5135. {
  5136. if (Manager->Sessions[Index]->Active)
  5137. {
  5138. ActiveSessions++;
  5139. }
  5140. }
  5141. // Confirm, when there's at least one active remote session or
  5142. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5143. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5144. WinConfiguration->ConfirmClosingSession)
  5145. {
  5146. unsigned int Result;
  5147. TMessageParams Params(mpNeverAskAgainCheck);
  5148. UnicodeString Message;
  5149. int Answers = qaOK | qaCancel;
  5150. // The current session is the only active session
  5151. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5152. {
  5153. if (!WinConfiguration->AutoSaveWorkspace)
  5154. {
  5155. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5156. }
  5157. else
  5158. {
  5159. Message = LoadStr(CLOSE_SESSION);
  5160. }
  5161. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5162. }
  5163. // Multiple active sessions or one active session, but it's not the current one
  5164. else if (ActiveSessions > 0)
  5165. {
  5166. if (!WinConfiguration->AutoSaveWorkspace)
  5167. {
  5168. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5169. }
  5170. else
  5171. {
  5172. Message = LoadStr(CLOSE_SESSIONS);
  5173. }
  5174. }
  5175. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5176. else
  5177. {
  5178. DebugAlwaysTrue(Manager->Count > 1);
  5179. DebugAlwaysTrue(!WinConfiguration->AutoSaveWorkspace);
  5180. Message = LoadStr(CLOSE_WORKSPACE);
  5181. }
  5182. UnicodeString Note;
  5183. if (WinConfiguration->AutoSaveWorkspace)
  5184. {
  5185. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5186. }
  5187. else
  5188. {
  5189. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5190. Answers = qaYes | qaNo | qaCancel;
  5191. }
  5192. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5193. SetFocus();
  5194. Result = MessageDialog(Message, qtConfirmation,
  5195. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5196. if (Result == qaNeverAskAgain)
  5197. {
  5198. WinConfiguration->ConfirmClosingSession = false;
  5199. }
  5200. if (Result == qaNo)
  5201. {
  5202. CanClose = SaveWorkspace(true);
  5203. // note that the workspace will be saved redundatly again from FormClose
  5204. }
  5205. else
  5206. {
  5207. CanClose =
  5208. (Result == qaOK) ||
  5209. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5210. (Result == qaNeverAskAgain);
  5211. }
  5212. }
  5213. if (CanClose && HasActiveTerminal())
  5214. {
  5215. CanClose = CanCloseQueue();
  5216. }
  5217. }
  5218. if (CanClose)
  5219. {
  5220. CanClose =
  5221. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5222. FEditorManager->CloseExternalFilesWithoutProcess();
  5223. if (CanClose)
  5224. {
  5225. while (CanClose && (FLocalEditors->Count > 0))
  5226. {
  5227. int PrevCount = FLocalEditors->Count;
  5228. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5229. CanClose = (FLocalEditors->Count < PrevCount);
  5230. }
  5231. if (CanClose)
  5232. {
  5233. CanClose = FEditorManager->Empty(true);
  5234. if (!CanClose)
  5235. {
  5236. SetFocus();
  5237. CanClose =
  5238. (MessageDialog(
  5239. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5240. }
  5241. }
  5242. }
  5243. }
  5244. }
  5245. //---------------------------------------------------------------------------
  5246. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5247. {
  5248. TForm * Form = dynamic_cast<TForm *>(Sender);
  5249. DebugAssert(Form != NULL);
  5250. Form->Close();
  5251. }
  5252. //---------------------------------------------------------------------------
  5253. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5254. {
  5255. TForm * Form = dynamic_cast<TForm *>(Sender);
  5256. delete Form;
  5257. }
  5258. //---------------------------------------------------------------------------
  5259. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5260. {
  5261. while (FLocalEditors->Count > 0)
  5262. {
  5263. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5264. }
  5265. }
  5266. //---------------------------------------------------------------------------
  5267. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5268. TObject *Sender)
  5269. {
  5270. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5271. try
  5272. {
  5273. SetProperties(osRemote, FileList);
  5274. }
  5275. __finally
  5276. {
  5277. delete FileList;
  5278. }
  5279. }
  5280. //---------------------------------------------------------------------------
  5281. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5282. {
  5283. if (value)
  5284. {
  5285. if (Component == fcCustomCommandsBand)
  5286. {
  5287. UpdateCustomCommandsToolbar();
  5288. }
  5289. if (Component == fcQueueFileList)
  5290. {
  5291. DebugAssert(!QueueFileListSplitter->Visible);
  5292. AdjustQueueLayout();
  5293. UpdateQueueFileList();
  5294. }
  5295. }
  5296. }
  5297. //---------------------------------------------------------------------------
  5298. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5299. {
  5300. int MinHeightLimit =
  5301. GetStaticQueuePanelComponentsHeight() +
  5302. QueueFileListSplitter->Height +
  5303. QueueFileList->Height +
  5304. GetMinQueueViewHeight();
  5305. if (QueuePanel->ClientHeight < MinHeightLimit)
  5306. {
  5307. QueuePanel->ClientHeight = MinHeightLimit;
  5308. }
  5309. }
  5310. //---------------------------------------------------------------------------
  5311. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5312. {
  5313. TControl * Control = GetComponent(Component);
  5314. DebugAssert(Control);
  5315. bool Changed = (Control->Visible != value);
  5316. if (Changed)
  5317. {
  5318. ComponentShowing(Component, value);
  5319. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5320. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5321. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5322. if (value)
  5323. {
  5324. int RemainingHeight = Control->Parent->ClientHeight;
  5325. int RemainingWidth = Control->Parent->ClientWidth;
  5326. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5327. {
  5328. TControl * ChildControl = Control->Parent->Controls[i];
  5329. if (ChildControl->Visible)
  5330. {
  5331. switch (ChildControl->Align)
  5332. {
  5333. case alTop:
  5334. case alBottom:
  5335. RemainingHeight -= ChildControl->Height;
  5336. break;
  5337. case alLeft:
  5338. case alRight:
  5339. RemainingWidth -= ChildControl->Width;
  5340. break;
  5341. }
  5342. }
  5343. }
  5344. int Reserve = ScaleByTextHeight(this, 32);
  5345. // queue in explorer, trees in commander
  5346. if (Control->Height > RemainingHeight - Reserve)
  5347. {
  5348. Control->Height = RemainingHeight / 2;
  5349. }
  5350. if (Control->Width > RemainingWidth - Reserve)
  5351. {
  5352. Control->Width = RemainingWidth / 2;
  5353. }
  5354. }
  5355. Control->Visible = value;
  5356. if (WasFocused && Visible)
  5357. {
  5358. DirView(osCurrent)->SetFocus();
  5359. }
  5360. FixControlsPlacement();
  5361. }
  5362. }
  5363. //---------------------------------------------------------------------------
  5364. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5365. {
  5366. TControl * Control = GetComponent(Component);
  5367. if (Control == NULL)
  5368. {
  5369. return false;
  5370. }
  5371. else
  5372. {
  5373. return Control->Visible;
  5374. }
  5375. }
  5376. //---------------------------------------------------------------------------
  5377. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5378. {
  5379. bool Result;
  5380. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5381. {
  5382. Result = !IsUWP();
  5383. }
  5384. else
  5385. {
  5386. Result = true;
  5387. }
  5388. return Result;
  5389. }
  5390. //---------------------------------------------------------------------------
  5391. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5392. {
  5393. if (DirView->ItemFocused != NULL)
  5394. {
  5395. DirView->ItemFocused->MakeVisible(false);
  5396. }
  5397. }
  5398. //---------------------------------------------------------------------------
  5399. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5400. {
  5401. MakeFocusedItemVisible(RemoteDirView);
  5402. QueueSplitter->Visible = QueuePanel->Visible;
  5403. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5404. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5405. TControl * TopControlsOrder[] =
  5406. { TopDock, MessageDock, SessionsPageControl };
  5407. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5408. TControl * QueueControlsOrder[] =
  5409. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5410. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5411. }
  5412. //---------------------------------------------------------------------------
  5413. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5414. {
  5415. switch (Component) {
  5416. case fcStatusBar: return RemoteStatusBar;
  5417. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5418. case fcQueueView: return QueuePanel;
  5419. case fcQueueToolbar: return QueueDock;
  5420. case fcRemoteTree: return RemoteDrivePanel;
  5421. case fcSessionsTabs: return SessionsPageControl;
  5422. case fcQueueFileList: return QueueFileList;
  5423. default: return NULL;
  5424. }
  5425. }
  5426. //---------------------------------------------------------------------------
  5427. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5428. TObject *Sender, TListColumn *Column, TPoint &Point)
  5429. {
  5430. DebugAssert(NonVisualDataModule && Column && Sender);
  5431. NonVisualDataModule->ListColumn = Column;
  5432. TPopupMenu * DirViewColumnMenu;
  5433. if (Sender == DirView(osOther))
  5434. {
  5435. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5436. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5437. bool SizeColumn = (Column->Index == uvSize);
  5438. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5439. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5440. }
  5441. else
  5442. {
  5443. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5444. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5445. bool SizeColumn = (Column->Index == dvSize);
  5446. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5447. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5448. }
  5449. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5450. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5451. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5452. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5453. }
  5454. //---------------------------------------------------------------------------
  5455. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5456. TObject *Sender, TListItem *Item, bool &AllowExec)
  5457. {
  5458. DoDirViewExecFile(Sender, Item, AllowExec);
  5459. }
  5460. //---------------------------------------------------------------------------
  5461. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5462. TListItem * Item, bool & AllowExec)
  5463. {
  5464. DebugAssert(Sender && Item && Configuration);
  5465. DebugAssert(AllowExec);
  5466. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5467. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5468. bool Remote = !IsSideLocalBrowser(Side);
  5469. DebugAssert(Item == ADirView->ItemFocused);
  5470. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5471. TResolvedDoubleClickAction Action;
  5472. if (FForceExecution)
  5473. {
  5474. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5475. }
  5476. else
  5477. {
  5478. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5479. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5480. }
  5481. if (Action == rdcaCopy)
  5482. {
  5483. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5484. UnlockWindow();
  5485. try
  5486. {
  5487. if (IsLocalBrowserMode())
  5488. {
  5489. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5490. }
  5491. else
  5492. {
  5493. if (HasActiveTerminal())
  5494. {
  5495. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5496. }
  5497. }
  5498. }
  5499. __finally
  5500. {
  5501. LockWindow();
  5502. }
  5503. AllowExec = false;
  5504. }
  5505. else if (Action == rdcaEdit)
  5506. {
  5507. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5508. {
  5509. ExecuteFile(Side, efDefaultEditor);
  5510. AllowExec = false;
  5511. }
  5512. }
  5513. else if (Action == rdcaOpen)
  5514. {
  5515. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5516. {
  5517. ExecuteFile(osRemote, efShell);
  5518. AllowExec = false;
  5519. }
  5520. }
  5521. }
  5522. //---------------------------------------------------------------------------
  5523. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5524. {
  5525. return ((Side == osRemote) || (Side == osCurrent));
  5526. }
  5527. //---------------------------------------------------------------------------
  5528. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5529. {
  5530. DebugFail();
  5531. }
  5532. //---------------------------------------------------------------------------
  5533. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5534. {
  5535. DebugFail();
  5536. }
  5537. //---------------------------------------------------------------------------
  5538. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5539. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5540. {
  5541. TSynchronizeParamType Params;
  5542. Params.LocalDirectory = LocalDirectory;
  5543. Params.RemoteDirectory = RemoteDirectory;
  5544. int UnusedParams =
  5545. (GUIConfiguration->SynchronizeParams &
  5546. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5547. TTerminal::spCaseSensitive | TTerminal::spMirror | TTerminal::spByChecksum));
  5548. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5549. Params.Options = GUIConfiguration->SynchronizeOptions;
  5550. bool SaveSettings = false;
  5551. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5552. &DoSynchronizeTooManyDirectories);
  5553. DebugAssert(FSynchronizeController == NULL);
  5554. FSynchronizeController = &Controller;
  5555. bool Result;
  5556. try
  5557. {
  5558. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5559. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5560. int Options =
  5561. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5562. DebugAssert(FOnFeedSynchronizeError == NULL);
  5563. DebugAssert(FOnSynchronizeAbort == NULL);
  5564. DebugAssert(FSynchronizeTerminal == NULL);
  5565. FSynchronizeTerminal = Terminal;
  5566. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5567. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5568. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5569. if (Result)
  5570. {
  5571. if (SaveSettings)
  5572. {
  5573. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5574. GUIConfiguration->SynchronizeOptions = Params.Options;
  5575. }
  5576. else
  5577. {
  5578. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5579. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5580. FLAGSET(Params.Options, soSynchronize))
  5581. {
  5582. GUIConfiguration->SynchronizeOptions =
  5583. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5584. soSynchronize;
  5585. }
  5586. }
  5587. LocalDirectory = Params.LocalDirectory;
  5588. RemoteDirectory = Params.RemoteDirectory;
  5589. }
  5590. }
  5591. __finally
  5592. {
  5593. FSynchronizeController = NULL;
  5594. DebugAssert(FOnFeedSynchronizeError == NULL);
  5595. FOnFeedSynchronizeError = NULL;
  5596. DebugAssert(FOnSynchronizeAbort == NULL);
  5597. FOnSynchronizeAbort = NULL;
  5598. FSynchronizeTerminal = NULL;
  5599. }
  5600. return Result;
  5601. }
  5602. //---------------------------------------------------------------------------
  5603. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5604. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5605. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5606. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5607. TSynchronizeOptions * Options, bool Full)
  5608. {
  5609. // Keep-up-to-date mode
  5610. if (Terminal->Status == ssOpened)
  5611. {
  5612. try
  5613. {
  5614. int PParams = Params.Params;
  5615. if (!Full)
  5616. {
  5617. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5618. if (FLAGSET(Params.Options, soRecurse))
  5619. {
  5620. PParams |= TTerminal::spSubDirs;
  5621. }
  5622. }
  5623. else
  5624. {
  5625. // if keepuptodate is non-recursive,
  5626. // full sync before has to be non-recursive as well
  5627. if (FLAGCLEAR(Params.Options, soRecurse))
  5628. {
  5629. PParams |= TTerminal::spNoRecurse;
  5630. }
  5631. }
  5632. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5633. PParams, Checklist, Options);
  5634. }
  5635. catch (Exception & E)
  5636. {
  5637. if (!Terminal->Active)
  5638. {
  5639. ShowExtendedExceptionEx(Terminal, &E);
  5640. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5641. if (!Terminal->Active)
  5642. {
  5643. throw;
  5644. }
  5645. }
  5646. else
  5647. {
  5648. if (FLAGSET(Params.Options, soContinueOnError) &&
  5649. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5650. {
  5651. // noop, already logged in MoreMessageDialog
  5652. }
  5653. else
  5654. {
  5655. // We get mostly EAbort here, so this is noop.
  5656. // Exception is an error when listing directories while looking for differences.
  5657. ShowExtendedExceptionEx(Terminal, &E);
  5658. throw;
  5659. }
  5660. }
  5661. }
  5662. }
  5663. }
  5664. //---------------------------------------------------------------------------
  5665. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5666. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5667. const UnicodeString ErrorStr)
  5668. {
  5669. if (!Directory.IsEmpty())
  5670. {
  5671. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5672. }
  5673. else
  5674. {
  5675. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5676. }
  5677. }
  5678. //---------------------------------------------------------------------------
  5679. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5680. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5681. {
  5682. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5683. {
  5684. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5685. }
  5686. else
  5687. {
  5688. TMessageParams Params(mpNeverAskAgainCheck);
  5689. unsigned int Result = MessageDialog(
  5690. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5691. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5692. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5693. {
  5694. MaxDirectories *= 2;
  5695. if (Result == qaNeverAskAgain)
  5696. {
  5697. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5698. }
  5699. }
  5700. else
  5701. {
  5702. Abort();
  5703. }
  5704. }
  5705. }
  5706. //---------------------------------------------------------------------------
  5707. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5708. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5709. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5710. TSynchronizeOptions * Options)
  5711. {
  5712. // Keep-up-to-date mode
  5713. DebugAssert(!FAutoOperation);
  5714. void * BatchStorage;
  5715. BatchStart(BatchStorage);
  5716. FAutoOperation = true;
  5717. bool AnyOperation = false;
  5718. TDateTime StartTime = Now();
  5719. TSynchronizeChecklist * AChecklist = NULL;
  5720. try
  5721. {
  5722. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, -1);
  5723. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5724. {
  5725. FSynchronizeProgressForm->Start();
  5726. }
  5727. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5728. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5729. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5730. Options);
  5731. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5732. SAFE_DESTROY(FSynchronizeProgressForm);
  5733. AnyOperation = (AChecklist->CheckedCount > 0);
  5734. if (AnyOperation)
  5735. {
  5736. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5737. CreateProgressForm(&SynchronizeProgress);
  5738. try
  5739. {
  5740. Terminal->SynchronizeApply(
  5741. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5742. SynchronizeProcessedItem, NULL, NULL, NULL);
  5743. }
  5744. __finally
  5745. {
  5746. DestroyProgressForm();
  5747. }
  5748. }
  5749. }
  5750. __finally
  5751. {
  5752. if (Checklist == NULL)
  5753. {
  5754. delete AChecklist;
  5755. }
  5756. else
  5757. {
  5758. *Checklist = AChecklist;
  5759. }
  5760. FAutoOperation = false;
  5761. SAFE_DESTROY(FSynchronizeProgressForm);
  5762. BatchEnd(BatchStorage);
  5763. ReloadLocalDirectory();
  5764. if (AnyOperation)
  5765. {
  5766. OperationComplete(StartTime);
  5767. }
  5768. }
  5769. }
  5770. //---------------------------------------------------------------------------
  5771. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5772. {
  5773. // can be called from command line
  5774. return Visible &&
  5775. ((DirView(osRemote)->SelCount > 0) ||
  5776. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5777. }
  5778. //---------------------------------------------------------------------------
  5779. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5780. {
  5781. LogSynchronizeEvent(Terminal, Message);
  5782. }
  5783. //---------------------------------------------------------------------------
  5784. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5785. int Params, TSynchronizeOptions & Options)
  5786. {
  5787. DebugAssert(!IsLocalBrowserMode());
  5788. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5789. {
  5790. Options.Filter = new TStringList();
  5791. Options.Filter->CaseSensitive = false;
  5792. Options.Filter->Duplicates = Types::dupAccept;
  5793. if (DirView(osRemote)->SelCount > 0)
  5794. {
  5795. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5796. }
  5797. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5798. {
  5799. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5800. }
  5801. Options.Filter->Sort();
  5802. }
  5803. }
  5804. //---------------------------------------------------------------------------
  5805. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5806. {
  5807. TCopyParamType Defaults;
  5808. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5809. ConfigStorage->AccessMode = smRead;
  5810. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5811. {
  5812. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5813. }
  5814. ConfigStorage.reset(NULL);
  5815. std::unique_ptr<TStringList> Options(new TStringList());
  5816. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5817. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5818. UnicodeString Result;
  5819. if (Options->Count > 0)
  5820. {
  5821. Result =
  5822. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5823. }
  5824. return Result;
  5825. }
  5826. //---------------------------------------------------------------------------
  5827. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5828. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5829. {
  5830. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5831. UnicodeString AdditionalParams =
  5832. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5833. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5834. SerializeCopyParamForCommandLine(CopyParams),
  5835. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5836. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5837. ExecuteNewInstance(SessionName, AdditionalParams);
  5838. }
  5839. //---------------------------------------------------------------------------
  5840. struct TSynchronizeParams
  5841. {
  5842. UnicodeString LocalDirectory;
  5843. UnicodeString RemoteDirectory;
  5844. TSynchronizeMode Mode;
  5845. TSynchronizeChecklist * Checklist;
  5846. int Params;
  5847. TCopyParamType * CopyParam;
  5848. TDateTime CollectElapsed;
  5849. TDateTime * StartTime;
  5850. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5851. };
  5852. //---------------------------------------------------------------------------
  5853. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5854. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5855. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5856. {
  5857. DebugAssert(!FAutoOperation);
  5858. void * BatchStorage;
  5859. BatchStart(BatchStorage);
  5860. FAutoOperation = true;
  5861. TFileOperationStatistics Statistics;
  5862. TDateTime Start = Now();
  5863. try
  5864. {
  5865. Params.OnProcessedItem = OnProcessedItem;
  5866. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5867. CreateProgressForm(&SynchronizeProgress);
  5868. Terminal->SynchronizeApply(
  5869. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5870. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5871. &Statistics);
  5872. }
  5873. __finally
  5874. {
  5875. Params.OnProcessedItem = NULL;
  5876. FAutoOperation = false;
  5877. DestroyProgressForm();
  5878. BatchEnd(BatchStorage);
  5879. ReloadLocalDirectory();
  5880. }
  5881. if (WinConfiguration->SynchronizeSummary)
  5882. {
  5883. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5884. // The statistics should be 0 anyway in this case
  5885. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5886. {
  5887. Message += L"\n";
  5888. if (Statistics.FilesUploaded > 0)
  5889. {
  5890. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5891. }
  5892. if (Statistics.FilesDownloaded > 0)
  5893. {
  5894. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5895. }
  5896. if (Statistics.FilesDeletedLocal > 0)
  5897. {
  5898. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5899. }
  5900. if (Statistics.FilesDeletedRemote > 0)
  5901. {
  5902. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5903. }
  5904. }
  5905. TDateTime Elapsed = (Now() - Start);
  5906. Message +=
  5907. L"\n" +
  5908. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Params.CollectElapsed))) + L"\n" +
  5909. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Elapsed)));
  5910. TMessageParams Params(mpNeverAskAgainCheck);
  5911. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5912. if (Result == qaNeverAskAgain)
  5913. {
  5914. WinConfiguration->SynchronizeSummary = false;
  5915. }
  5916. }
  5917. }
  5918. //---------------------------------------------------------------------------
  5919. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5920. {
  5921. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5922. {
  5923. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5924. }
  5925. // Not set in keep-up-to-date mode - Synchronize() method
  5926. if (Token != NULL)
  5927. {
  5928. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5929. if (Params.OnProcessedItem != NULL)
  5930. {
  5931. Params.OnProcessedItem(NULL, ChecklistItem);
  5932. }
  5933. }
  5934. }
  5935. //---------------------------------------------------------------------------
  5936. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5937. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5938. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5939. {
  5940. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5941. *Params.StartTime = Now();
  5942. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5943. }
  5944. //---------------------------------------------------------------------------
  5945. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5946. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5947. {
  5948. // terminal can be already closed (e.g. dropped connection)
  5949. if (Terminal != NULL)
  5950. {
  5951. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5952. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5953. }
  5954. }
  5955. //---------------------------------------------------------------------------
  5956. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5957. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5958. {
  5959. DebugAssert(!IsLocalBrowserMode());
  5960. TAutoBatch AutoBatch(this);
  5961. TAutoFlag AutoOperationFlag(FAutoOperation);
  5962. if (Side == osRemote)
  5963. {
  5964. std::unique_ptr<TStrings> FileList(new TStringList());
  5965. FileList->AddObject(FileName, RemoteFile);
  5966. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5967. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5968. RemoteDirView->SaveSelection();
  5969. RemoteDirView->SaveSelectedNames();
  5970. try
  5971. {
  5972. Terminal->MoveFiles(FileList.get(), Target, FileMask, false);
  5973. }
  5974. catch(...)
  5975. {
  5976. RemoteDirView->DiscardSavedSelection();
  5977. throw;
  5978. }
  5979. RemoteDirView->RestoreSelection();
  5980. }
  5981. else if (DebugAlwaysTrue(Side == osLocal))
  5982. {
  5983. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5984. {
  5985. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5986. }
  5987. UnicodeString Directory = ExtractFileDir(FileName);
  5988. ReloadLocalDirectory(Directory);
  5989. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5990. if (!SamePaths(Directory, NewDirectory))
  5991. {
  5992. ReloadLocalDirectory(NewDirectory);
  5993. }
  5994. }
  5995. }
  5996. //---------------------------------------------------------------------------
  5997. void __fastcall TCustomScpExplorerForm::DoSynchronizeBrowse(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  5998. {
  5999. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  6000. if (Side == osLocal)
  6001. {
  6002. if (Action == TSynchronizeChecklist::saDownloadNew)
  6003. {
  6004. OpenFolderInExplorer(LocalPath);
  6005. }
  6006. else
  6007. {
  6008. OpenFileInExplorer(CombinePaths(LocalPath, Item->GetFileName()));
  6009. }
  6010. }
  6011. else if (DebugAlwaysTrue(Side == osRemote))
  6012. {
  6013. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  6014. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  6015. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  6016. if (!LocalPath.IsEmpty())
  6017. {
  6018. SessionData->LocalDirectory = LocalPath;
  6019. }
  6020. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  6021. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(BROWSE_SWITCH), Item->GetFileName())));
  6022. }
  6023. }
  6024. //---------------------------------------------------------------------------
  6025. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  6026. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6027. const TCopyParamType * CopyParams)
  6028. {
  6029. UnicodeString SessionName = CreateHiddenDuplicateSession();
  6030. UnicodeString AdditionalParams =
  6031. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  6032. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  6033. SerializeCopyParamForCommandLine(CopyParams),
  6034. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  6035. LocalDirectory, RemoteDirectory, Mode, Params));
  6036. ExecuteNewInstance(SessionName, AdditionalParams);
  6037. }
  6038. //---------------------------------------------------------------------------
  6039. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  6040. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  6041. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  6042. {
  6043. int Result;
  6044. bool SaveSettings = false;
  6045. int Options =
  6046. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6047. FLAGMASK(!CanCalculateChecksum(), fsoDisableByChecksum) |
  6048. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  6049. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  6050. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  6051. bool Continue =
  6052. ((UseDefaults == 0) ||
  6053. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  6054. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults)) &&
  6055. (FLAGCLEAR(Params, TTerminal::spByChecksum) || EnsureCommandSessionFallback(fcCalculatingChecksum));
  6056. if (Continue)
  6057. {
  6058. Configuration->Usage->Inc(L"Synchronizations");
  6059. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  6060. UpdateCopyParamCounters(CopyParam);
  6061. TSynchronizeOptions SynchronizeOptions;
  6062. GetSynchronizeOptions(Params, SynchronizeOptions);
  6063. if (SaveSettings)
  6064. {
  6065. GUIConfiguration->SynchronizeParams = Params;
  6066. }
  6067. else
  6068. {
  6069. SaveMode = false;
  6070. }
  6071. TDateTime StartTime = Now();
  6072. TSynchronizeChecklist * Checklist = NULL;
  6073. try
  6074. {
  6075. DebugAssert(!FAutoOperation);
  6076. FAutoOperation = true;
  6077. try
  6078. {
  6079. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6080. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6081. int Files = -1;
  6082. if (DataList->Count >= 1)
  6083. {
  6084. Files = StrToIntDef(DataList->Strings[0], Files);
  6085. }
  6086. else
  6087. {
  6088. DataList->Add(UnicodeString());
  6089. }
  6090. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6091. FSynchronizeProgressForm->Start();
  6092. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6093. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6094. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6095. &SynchronizeOptions);
  6096. if (Terminal->SessionData->CacheDirectories)
  6097. {
  6098. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6099. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6100. }
  6101. }
  6102. __finally
  6103. {
  6104. FAutoOperation = false;
  6105. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6106. SAFE_DESTROY(FSynchronizeProgressForm);
  6107. }
  6108. TSynchronizeParams SynchronizeParams;
  6109. SynchronizeParams.LocalDirectory = LocalDirectory;
  6110. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  6111. SynchronizeParams.Mode = Mode;
  6112. SynchronizeParams.CopyParam = &CopyParam;
  6113. SynchronizeParams.Params = Params;
  6114. SynchronizeParams.Checklist = Checklist;
  6115. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6116. SynchronizeParams.StartTime = &StartTime;
  6117. SynchronizeParams.OnProcessedItem = NULL;
  6118. Result = Checklist->Count;
  6119. if (Checklist->Count > 0)
  6120. {
  6121. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6122. {
  6123. if (!DoSynchronizeChecklistDialog(
  6124. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6125. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeBrowse, &SynchronizeParams))
  6126. {
  6127. Result = -1;
  6128. }
  6129. }
  6130. else
  6131. {
  6132. FullSynchronize(SynchronizeParams, NULL, NULL);
  6133. }
  6134. }
  6135. else
  6136. {
  6137. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6138. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6139. }
  6140. }
  6141. __finally
  6142. {
  6143. delete Checklist;
  6144. }
  6145. OperationComplete(StartTime);
  6146. }
  6147. else
  6148. {
  6149. Result = -1;
  6150. }
  6151. return Result;
  6152. }
  6153. //---------------------------------------------------------------------------
  6154. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6155. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6156. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6157. {
  6158. if (Collect)
  6159. {
  6160. DebugAssert(FSynchronizeProgressForm != NULL);
  6161. if (!FSynchronizeProgressForm->Started)
  6162. {
  6163. FSynchronizeProgressForm->Start();
  6164. }
  6165. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6166. SetTaskbarListProgressValue(CompareProgress);
  6167. }
  6168. else
  6169. {
  6170. DebugAssert(FSynchronizeProgressForm == NULL);
  6171. DebugAssert(FProgressForm != NULL);
  6172. }
  6173. }
  6174. //---------------------------------------------------------------------------
  6175. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6176. {
  6177. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6178. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6179. if (File.get() != NULL)
  6180. {
  6181. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6182. Application->ShowMainForm = false;
  6183. Application->Run();
  6184. }
  6185. }
  6186. //---------------------------------------------------------------------------
  6187. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6188. {
  6189. DebugFail();
  6190. }
  6191. //---------------------------------------------------------------------------
  6192. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6193. {
  6194. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6195. SessionData->Assign(ManagedSession->SessionData);
  6196. UpdateSessionData(SessionData.get());
  6197. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6198. if (IsActiveTerminal(ManagedSession))
  6199. {
  6200. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6201. }
  6202. if (!ManagedSession->SessionData->HasSessionName())
  6203. {
  6204. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6205. // once IsWorkspace is cleared
  6206. SessionData->Name = UnicodeString();
  6207. }
  6208. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6209. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6210. SessionData->IsWorkspace = false;
  6211. return SessionData.release();
  6212. }
  6213. //---------------------------------------------------------------------------
  6214. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6215. {
  6216. TSessionData * SessionData = CloneCurrentSessionData();
  6217. try
  6218. {
  6219. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6220. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6221. }
  6222. __finally
  6223. {
  6224. delete SessionData;
  6225. }
  6226. }
  6227. //---------------------------------------------------------------------------
  6228. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6229. {
  6230. TTerminalManager * Manager = TTerminalManager::Instance();
  6231. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6232. if (DebugAlwaysTrue(ManagedSession != NULL))
  6233. {
  6234. // Update ManagedSession->StateData
  6235. UpdateSession(ManagedSession);
  6236. }
  6237. Manager->SaveWorkspace(DataList.get());
  6238. return DataList.release();
  6239. }
  6240. //---------------------------------------------------------------------------
  6241. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6242. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6243. {
  6244. WinConfiguration->LastWorkspace = Name;
  6245. if (!SavePasswords)
  6246. {
  6247. for (int Index = 0; Index < DataList->Count; Index++)
  6248. {
  6249. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6250. if (SessionData->Link.IsEmpty())
  6251. {
  6252. SessionData->ClearSessionPasswords();
  6253. }
  6254. }
  6255. }
  6256. StoredSessions->NewWorkspace(Name, DataList);
  6257. // modified only
  6258. StoredSessions->Save(false, Explicit);
  6259. }
  6260. //---------------------------------------------------------------------------
  6261. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6262. {
  6263. return
  6264. DefaultStr(WinConfiguration->LastWorkspace,
  6265. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6266. }
  6267. //---------------------------------------------------------------------------
  6268. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6269. {
  6270. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6271. bool AnyNonStoredSessionWithPassword = false;
  6272. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6273. bool AllNonStoredSessionsAnonymous = true;
  6274. TTerminalManager * Manager = TTerminalManager::Instance();
  6275. for (int Index = 0; Index < DataList->Count; Index++)
  6276. {
  6277. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6278. if (SessionData->Link.IsEmpty())
  6279. {
  6280. if (SessionData->HasAnySessionPassword())
  6281. {
  6282. AnyNonStoredSessionWithPassword = true;
  6283. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6284. {
  6285. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6286. }
  6287. }
  6288. if (!SameText(SessionData->UserName, AnonymousUserName))
  6289. {
  6290. AllNonStoredSessionsAnonymous = false;
  6291. }
  6292. }
  6293. }
  6294. bool SavePasswords;
  6295. bool * PSavePasswords;
  6296. bool NotRecommendedSavingPasswords =
  6297. !CustomWinConfiguration->UseMasterPassword &&
  6298. !AllNonStoredSessionsAnonymous;
  6299. if (Configuration->DisablePasswordStoring ||
  6300. !AnyNonStoredSessionWithPassword)
  6301. {
  6302. PSavePasswords = NULL;
  6303. SavePasswords = false;
  6304. }
  6305. else
  6306. {
  6307. PSavePasswords = &SavePasswords;
  6308. SavePasswords =
  6309. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6310. !NotRecommendedSavingPasswords;
  6311. }
  6312. UnicodeString Name = WorkspaceName();
  6313. bool CreateShortcut = false;
  6314. bool Result =
  6315. DoSaveWorkspaceDialog(
  6316. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6317. EnableAutoSave);
  6318. if (Result)
  6319. {
  6320. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6321. if (CreateShortcut)
  6322. {
  6323. TOperationVisualizer Visualizer;
  6324. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6325. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6326. }
  6327. if (EnableAutoSave)
  6328. {
  6329. WinConfiguration->AutoSaveWorkspace = true;
  6330. WinConfiguration->AutoWorkspace = Name;
  6331. if (PSavePasswords != NULL)
  6332. {
  6333. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6334. }
  6335. }
  6336. }
  6337. return Result;
  6338. }
  6339. //---------------------------------------------------------------------------
  6340. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6341. {
  6342. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6343. DebugAssert(Session == ManagedSession);
  6344. if (!IsLocalBrowserMode())
  6345. {
  6346. SAFE_DESTROY(Session->RemoteExplorerState);
  6347. if (WinConfiguration->PreservePanelState)
  6348. {
  6349. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6350. }
  6351. }
  6352. UpdateSessionData(Session->StateData);
  6353. }
  6354. //---------------------------------------------------------------------------
  6355. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6356. {
  6357. // Keep in sync with TSessionData::CopyStateData
  6358. DebugAssert(Data != NULL);
  6359. // This is inconsistent with how color (for example) is handled.
  6360. Data->Name = ManagedSession->SessionData->Name;
  6361. if (!IsLocalBrowserMode())
  6362. {
  6363. // cannot use RemoteDirView->Path, because it is empty if connection
  6364. // was already closed
  6365. // also only peek, we may not be connected at all atm
  6366. // so make sure we do not try retrieving current directory from the server
  6367. // (particularly with FTP)
  6368. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6369. if (!ACurrentDirectory.IsEmpty())
  6370. {
  6371. Data->RemoteDirectory = ACurrentDirectory;
  6372. }
  6373. }
  6374. Data->Color = SessionColor;
  6375. }
  6376. //---------------------------------------------------------------------------
  6377. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6378. {
  6379. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6380. DebugAssert(Toolbar != NULL);
  6381. for (int i = 0; i < Toolbar->Items->Count; i++)
  6382. {
  6383. TTBXCustomDropDownItem * DropDownItem;
  6384. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6385. if (DropDownItem != NULL)
  6386. {
  6387. ToolbarItemResize(DropDownItem,
  6388. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6389. Toolbar->NonClientWidth);
  6390. break;
  6391. }
  6392. }
  6393. }
  6394. //---------------------------------------------------------------------------
  6395. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6396. {
  6397. Item->EditWidth = Width;
  6398. }
  6399. //---------------------------------------------------------------------------
  6400. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6401. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6402. {
  6403. for (int i = 0; i < Toolbar->Items->Count; i++)
  6404. {
  6405. TTBXCustomDropDownItem * DropDownItem;
  6406. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6407. if (DropDownItem != NULL)
  6408. {
  6409. ASize.x -= DropDownItem->EditWidth;
  6410. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  6411. }
  6412. }
  6413. }
  6414. //---------------------------------------------------------------------------
  6415. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6416. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6417. {
  6418. if (WinConfiguration->DDWarnLackOfTempSpace)
  6419. {
  6420. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6421. if (!ADrive.IsEmpty())
  6422. {
  6423. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6424. DebugAssert(RequiredSpace >= 0);
  6425. __int64 RequiredWithReserve;
  6426. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6427. if (FreeSpace < RequiredWithReserve)
  6428. {
  6429. unsigned int Result;
  6430. TMessageParams Params(mpNeverAskAgainCheck);
  6431. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6432. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6433. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6434. if (Result == qaNeverAskAgain)
  6435. {
  6436. WinConfiguration->DDWarnLackOfTempSpace = false;
  6437. }
  6438. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6439. }
  6440. }
  6441. }
  6442. }
  6443. //---------------------------------------------------------------------------
  6444. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6445. {
  6446. DoOpenDirectoryDialog(odAddBookmark, Side);
  6447. }
  6448. //---------------------------------------------------------------------------
  6449. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6450. {
  6451. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6452. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6453. try
  6454. {
  6455. TCustomDirView * DView = DirView(Side);
  6456. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6457. {
  6458. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6459. }
  6460. }
  6461. catch (...)
  6462. {
  6463. delete VisitedDirectories;
  6464. throw;
  6465. }
  6466. return VisitedDirectories;
  6467. }
  6468. //---------------------------------------------------------------------------
  6469. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6470. TOpenDirectoryMode Mode, TOperationSide Side)
  6471. {
  6472. bool Continue = true;
  6473. if (Mode == odAddBookmark)
  6474. {
  6475. TMessageParams Params(mpNeverAskAgainCheck);
  6476. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6477. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6478. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6479. unsigned int Answer =
  6480. MessageDialog(Message,
  6481. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6482. if (Answer == qaNeverAskAgain)
  6483. {
  6484. Continue = true;
  6485. WinConfiguration->UseSharedBookmarks = true;
  6486. }
  6487. else if (Answer == qaOK)
  6488. {
  6489. Continue = true;
  6490. WinConfiguration->UseSharedBookmarks = false;
  6491. }
  6492. else
  6493. {
  6494. Continue = false;
  6495. }
  6496. }
  6497. if (Continue)
  6498. {
  6499. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6500. try
  6501. {
  6502. UnicodeString Name = DirView(Side)->PathName;
  6503. bool Repeat;
  6504. do
  6505. {
  6506. Repeat = false;
  6507. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6508. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6509. // do not allow switching to location profiles,
  6510. // if we are not connected
  6511. HasDirView[osLocal] && (Terminal != NULL)))
  6512. {
  6513. TWindowLock Lock(this);
  6514. if (!TryOpenDirectory(Side, Name))
  6515. {
  6516. Repeat = true;
  6517. Mode = odBrowse;
  6518. }
  6519. }
  6520. }
  6521. while (Repeat);
  6522. }
  6523. __finally
  6524. {
  6525. delete VisitedDirectories;
  6526. }
  6527. }
  6528. }
  6529. //---------------------------------------------------------------------------
  6530. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6531. {
  6532. DebugAssert(!Terminal->CommandSessionOpened);
  6533. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6534. }
  6535. //---------------------------------------------------------------------------
  6536. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6537. {
  6538. bool Result = Terminal->IsCapable[Capability] ||
  6539. Terminal->CommandSessionOpened;
  6540. if (!Result)
  6541. {
  6542. // We might get here for example when "checksum" synchronization is requested from command-line
  6543. // on server that supports neither checksum nor shell
  6544. if (!Terminal->IsCapable[fcSecondaryShell])
  6545. {
  6546. NotSupported();
  6547. }
  6548. else if (!GUIConfiguration->ConfirmCommandSession)
  6549. {
  6550. Result = true;
  6551. }
  6552. else
  6553. {
  6554. TMessageParams Params(mpNeverAskAgainCheck);
  6555. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6556. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6557. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6558. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6559. if (Answer == qaNeverAskAgain)
  6560. {
  6561. GUIConfiguration->ConfirmCommandSession = false;
  6562. Result = true;
  6563. }
  6564. else if (Answer == qaOK)
  6565. {
  6566. Result = true;
  6567. }
  6568. }
  6569. if (Result)
  6570. {
  6571. Result = CommandSessionFallback();
  6572. }
  6573. }
  6574. return Result;
  6575. }
  6576. //---------------------------------------------------------------------------
  6577. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6578. {
  6579. if (EnsureCommandSessionFallback(fcAnyCommand))
  6580. {
  6581. DoConsoleDialog(Terminal, Command);
  6582. }
  6583. }
  6584. //---------------------------------------------------------------------------
  6585. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6586. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6587. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6588. {
  6589. if (!IsSideLocalBrowser(osRemote) &&
  6590. IsFileControl(DropSourceControl, osRemote) &&
  6591. (FDDExtMapFile != NULL))
  6592. {
  6593. Accept = true;
  6594. }
  6595. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6596. DebugAssert(FDDTargetControl != NULL);
  6597. }
  6598. //---------------------------------------------------------------------------
  6599. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6600. _di_IDataObject DataObj, int KeyState,
  6601. const TPoint & Point, int & Effect, bool & Accept)
  6602. {
  6603. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6604. }
  6605. //---------------------------------------------------------------------------
  6606. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6607. _di_IDataObject DataObj, int KeyState,
  6608. const TPoint & Point, int & Effect, bool & Accept)
  6609. {
  6610. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6611. }
  6612. //---------------------------------------------------------------------------
  6613. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6614. TObject * Sender)
  6615. {
  6616. DebugUsedParam(Sender);
  6617. DebugAssert(FDDTargetControl == Sender);
  6618. FDDTargetControl = NULL;
  6619. }
  6620. //---------------------------------------------------------------------------
  6621. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  6622. {
  6623. FileControlDDDragLeave(SessionsPageControl);
  6624. }
  6625. //---------------------------------------------------------------------------
  6626. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  6627. {
  6628. FileControlDDDragLeave(QueueView3);
  6629. }
  6630. //---------------------------------------------------------------------------
  6631. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6632. {
  6633. DebugAssert(!IsSideLocalBrowser(Side));
  6634. DebugUsedParam(Side);
  6635. bool Edit = false;
  6636. TRemoteFile * File = NULL;
  6637. UnicodeString FileName;
  6638. UnicodeString PointTo;
  6639. bool SymbolicLink = true;
  6640. if (RemoteDirView->ItemFocused)
  6641. {
  6642. DebugAssert(RemoteDirView->ItemFocused->Data);
  6643. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6644. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6645. if (Edit)
  6646. {
  6647. FileName = File->FileName;
  6648. PointTo = File->LinkTo;
  6649. }
  6650. else if (!File->IsParentDirectory)
  6651. {
  6652. PointTo = File->FileName;
  6653. }
  6654. }
  6655. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6656. Terminal->IsCapable[fcHardLink]))
  6657. {
  6658. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6659. if (Edit)
  6660. {
  6661. DebugAssert(File->FileName == FileName);
  6662. int Params = dfNoRecursive;
  6663. Terminal->ExceptionOnFail = true;
  6664. try
  6665. {
  6666. Terminal->DeleteFile(L"", File, &Params);
  6667. }
  6668. __finally
  6669. {
  6670. Terminal->ExceptionOnFail = false;
  6671. }
  6672. }
  6673. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6674. }
  6675. }
  6676. //---------------------------------------------------------------------------
  6677. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6678. {
  6679. return
  6680. (IsSideLocalBrowser(Side) ||
  6681. (HasActiveTerminal() &&
  6682. Terminal->ResolvingSymlinks &&
  6683. Terminal->IsCapable[fcSymbolicLink]));
  6684. }
  6685. //---------------------------------------------------------------------------
  6686. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6687. {
  6688. return
  6689. !IsSideLocalBrowser(FCurrentSide) &&
  6690. (RemoteDirView->ItemFocused != NULL) &&
  6691. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6692. Terminal->SessionData->ResolveSymlinks;
  6693. }
  6694. //---------------------------------------------------------------------------
  6695. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6696. {
  6697. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6698. FForceExecution = true;
  6699. try
  6700. {
  6701. DirView(osCurrent)->ExecuteCurrentFile();
  6702. }
  6703. __finally
  6704. {
  6705. FForceExecution = false;
  6706. }
  6707. }
  6708. //---------------------------------------------------------------------------
  6709. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6710. {
  6711. TEditorData ExternalEditor;
  6712. ExternalEditor.Editor = edExternal;
  6713. bool Remember = false;
  6714. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6715. {
  6716. if (Remember)
  6717. {
  6718. TEditorList * EditorList = new TEditorList;
  6719. try
  6720. {
  6721. *EditorList = *WinConfiguration->EditorList;
  6722. bool Found = false;
  6723. int i = 0;
  6724. while (!Found && (i < EditorList->Count))
  6725. {
  6726. const TEditorPreferences * Editor = EditorList->Editors[i];
  6727. if ((Editor->Data->Editor == edExternal) &&
  6728. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6729. {
  6730. Found = true;
  6731. }
  6732. i++;
  6733. }
  6734. if (!Found)
  6735. {
  6736. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6737. WinConfiguration->EditorList = EditorList;
  6738. }
  6739. }
  6740. __finally
  6741. {
  6742. delete EditorList;
  6743. }
  6744. }
  6745. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6746. }
  6747. }
  6748. //---------------------------------------------------------------------------
  6749. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6750. {
  6751. if (FFileFindTerminal == ATerminal)
  6752. {
  6753. FFileFindTerminal = NULL;
  6754. HideFileFindDialog();
  6755. }
  6756. if (FClipboardTerminal == ATerminal)
  6757. {
  6758. ClipboardClear(); // implies ClipboardStop
  6759. }
  6760. if ((FOnSynchronizeAbort != NULL) &&
  6761. (ATerminal == FManagedSession))
  6762. {
  6763. FOnSynchronizeAbort(NULL);
  6764. }
  6765. }
  6766. //---------------------------------------------------------------------------
  6767. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6768. {
  6769. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6770. DetachTerminal(Sender);
  6771. }
  6772. //---------------------------------------------------------------------------
  6773. void __fastcall TCustomScpExplorerForm::FileTerminalReplaced(
  6774. const UnicodeString FileName, TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6775. {
  6776. TManagedTerminal * ATerminal = static_cast<TManagedTerminal *>(Arg);
  6777. if (Data->Terminal == Terminal)
  6778. {
  6779. Data->Terminal = ATerminal;
  6780. }
  6781. }
  6782. //---------------------------------------------------------------------------
  6783. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6784. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6785. {
  6786. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6787. DebugAssert(Terminal != NULL);
  6788. if (Data->Terminal == Terminal)
  6789. {
  6790. Data->Terminal = NULL;
  6791. }
  6792. }
  6793. //---------------------------------------------------------------------------
  6794. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6795. {
  6796. return NULL;
  6797. }
  6798. //---------------------------------------------------------------------------
  6799. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6800. {
  6801. UpdateControls();
  6802. SessionColor = TColor(0);
  6803. UpdateRemotePathComboBox(false);
  6804. NeedSession(false);
  6805. }
  6806. //---------------------------------------------------------------------------
  6807. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6808. {
  6809. try
  6810. {
  6811. // Cache, as the login dialog can change its value.
  6812. // See also DoShow. Also see TTerminalManager::NewSession.
  6813. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6814. try
  6815. {
  6816. if (ShowLogin)
  6817. {
  6818. bool ReloadSessions = !Startup;
  6819. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6820. }
  6821. }
  6822. __finally
  6823. {
  6824. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6825. // (so there was no chance for the user to open any session yet)
  6826. if ((ShowLogin || !Startup) &&
  6827. !WinConfiguration->KeepOpenWhenNoSession &&
  6828. // this rules out the implicit Commander's local-local browser
  6829. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6830. {
  6831. TerminateApplication();
  6832. }
  6833. }
  6834. }
  6835. catch (EAbort &)
  6836. {
  6837. // swallow
  6838. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6839. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6840. }
  6841. }
  6842. //---------------------------------------------------------------------------
  6843. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6844. {
  6845. TTerminalManager * Manager = TTerminalManager::Instance();
  6846. DebugAssert(!Manager->Updating);
  6847. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6848. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6849. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6850. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6851. try
  6852. {
  6853. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6854. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6855. {
  6856. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6857. }
  6858. for (int Index = 0; Index <= Manager->Count; Index++)
  6859. {
  6860. TThemeTabSheet * TabSheet;
  6861. if (Index >= SessionsPageControl->PageCount)
  6862. {
  6863. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6864. TabSheet->PageControl = SessionsPageControl;
  6865. }
  6866. else
  6867. {
  6868. TabSheet = SessionsPageControl->Pages[Index];
  6869. }
  6870. bool IsSessionTab = (Index < Manager->Count);
  6871. if (IsSessionTab)
  6872. {
  6873. TTerminal * Terminal = Manager->Sessions[Index];
  6874. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6875. TabSheet->CaptionTruncation = WinConfiguration->SessionTabCaptionTruncation ? tttEllipsis : tttNone;
  6876. UpdateSessionTab(TabSheet);
  6877. }
  6878. else
  6879. {
  6880. TabSheet->Tag = 0; // not really needed
  6881. TabSheet->Shadowed = false;
  6882. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6883. TabSheet->CaptionTruncation = GetNewTabTabCaptionTruncation();
  6884. // 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)
  6885. UpdateNewTabTab();
  6886. }
  6887. }
  6888. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6889. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6890. {
  6891. SessionsPageControl->UpdateTabsCaptionTruncation();
  6892. }
  6893. }
  6894. __finally
  6895. {
  6896. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6897. }
  6898. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6899. }
  6900. //---------------------------------------------------------------------------
  6901. TThemeTabCaptionTruncation TCustomScpExplorerForm::GetNewTabTabCaptionTruncation()
  6902. {
  6903. return WinConfiguration->SessionTabCaptionTruncation ? tttNoText : tttNone;
  6904. }
  6905. //---------------------------------------------------------------------------
  6906. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6907. {
  6908. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6909. }
  6910. //---------------------------------------------------------------------------
  6911. TThemeTabSheet * TCustomScpExplorerForm::GetNewTabTab()
  6912. {
  6913. return SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6914. }
  6915. //---------------------------------------------------------------------------
  6916. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  6917. {
  6918. TThemeTabSheet * TabSheet = GetNewTabTab();
  6919. UnicodeString TabCaption;
  6920. if (WinConfiguration->SelectiveToolbarText)
  6921. {
  6922. TabCaption = GetNewTabTabCaption();
  6923. }
  6924. TabSheet->BaseCaption = TabCaption;
  6925. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  6926. }
  6927. //---------------------------------------------------------------------------
  6928. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  6929. {
  6930. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  6931. }
  6932. //---------------------------------------------------------------------------
  6933. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  6934. {
  6935. DebugFail();
  6936. return UnicodeString();
  6937. }
  6938. //---------------------------------------------------------------------------
  6939. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  6940. {
  6941. if (DebugAlwaysTrue(TabSheet != NULL))
  6942. {
  6943. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  6944. if (DebugAlwaysTrue(ASession != NULL))
  6945. {
  6946. TColor Color = (ASession == Terminal) ? FSessionColor : ASession->StateData->Color;
  6947. if (ASession->LocalBrowser)
  6948. {
  6949. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  6950. }
  6951. else
  6952. {
  6953. TabSheet->ImageIndex = AddSessionColor(Color);
  6954. }
  6955. TTerminalManager * Manager = TTerminalManager::Instance();
  6956. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  6957. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  6958. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  6959. }
  6960. }
  6961. }
  6962. //---------------------------------------------------------------------------
  6963. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  6964. {
  6965. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  6966. }
  6967. //---------------------------------------------------------------------------
  6968. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6969. {
  6970. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6971. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  6972. bool Result = (Session != NULL);
  6973. if (Result)
  6974. {
  6975. TTerminalManager::Instance()->ActiveSession = Session;
  6976. }
  6977. else
  6978. {
  6979. try
  6980. {
  6981. NewTab();
  6982. }
  6983. __finally
  6984. {
  6985. SessionListChanged();
  6986. }
  6987. FSessionsPageControlNewTabTime = Now();
  6988. }
  6989. return Result;
  6990. }
  6991. //---------------------------------------------------------------------------
  6992. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  6993. {
  6994. TWindowLock Lock(this);
  6995. SessionTabSwitched();
  6996. }
  6997. //---------------------------------------------------------------------------
  6998. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  6999. {
  7000. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  7001. DebugAssert(TransferList != NULL);
  7002. UnicodeString Name;
  7003. if (TransferList->ItemIndex <= 0)
  7004. {
  7005. Name = L"";
  7006. }
  7007. else
  7008. {
  7009. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  7010. }
  7011. if (FCopyParamAutoSelected.IsEmpty())
  7012. {
  7013. // if previous preset was not autoselected, make new preset the "default"
  7014. FCopyParamDefault = Name;
  7015. }
  7016. GUIConfiguration->CopyParamCurrent = Name;
  7017. }
  7018. //---------------------------------------------------------------------------
  7019. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  7020. {
  7021. // sanity check
  7022. bool ExistingPreset =
  7023. (FTransferListHoverIndex >= 0) &&
  7024. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  7025. DebugAssert(ExistingPreset);
  7026. if (ExistingPreset)
  7027. {
  7028. HDC DC = GetDC(0);
  7029. TCanvas * Canvas = new TCanvas();
  7030. try
  7031. {
  7032. Canvas->Handle = DC;
  7033. Canvas->Font = GetToolbarFont(this);
  7034. UnicodeString Name;
  7035. if (FTransferListHoverIndex == 0)
  7036. {
  7037. Name = L"";
  7038. }
  7039. else
  7040. {
  7041. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  7042. }
  7043. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  7044. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  7045. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  7046. static_cast<TObject*>(GetComponent(fcTransferList)));
  7047. UnicodeString InfoStr =
  7048. GUIConfiguration->CopyParamPreset[Name].
  7049. GetInfoStr(L"; ",
  7050. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  7051. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  7052. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  7053. {
  7054. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  7055. {
  7056. InfoStr.SetLength(InfoStr.Length() - 1);
  7057. }
  7058. InfoStr += Ellipsis;
  7059. }
  7060. // UpdateCaption does not cause invalidation of whole submenu, while
  7061. // setting Caption property does.
  7062. // also it probably does not resize the label, even if necessary
  7063. // (we do not want that anyway)
  7064. TransferLabel->UpdateCaption(InfoStr);
  7065. }
  7066. __finally
  7067. {
  7068. Canvas->Handle = NULL;
  7069. ReleaseDC(0, DC);
  7070. delete Canvas;
  7071. }
  7072. }
  7073. }
  7074. //---------------------------------------------------------------------------
  7075. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7076. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7077. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7078. {
  7079. if (FTransferListHoverIndex != AHoverIndex)
  7080. {
  7081. FTransferListHoverIndex = AHoverIndex;
  7082. UpdateTransferLabel();
  7083. }
  7084. }
  7085. //---------------------------------------------------------------------------
  7086. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7087. {
  7088. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7089. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7090. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7091. {
  7092. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7093. {
  7094. if (!NonVisualDataModule->Busy)
  7095. {
  7096. OpenDirectory(GetSide(osCurrent));
  7097. }
  7098. Message.Result = 1;
  7099. }
  7100. else
  7101. {
  7102. TForm::Dispatch(&Message);
  7103. }
  7104. }
  7105. else
  7106. {
  7107. TForm::Dispatch(&Message);
  7108. }
  7109. }
  7110. //---------------------------------------------------------------------------
  7111. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7112. {
  7113. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7114. if ((FIgnoreNextDialogChar != 0) &&
  7115. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7116. {
  7117. Message.Result = 1;
  7118. }
  7119. else
  7120. {
  7121. TForm::Dispatch(&Message);
  7122. }
  7123. FIgnoreNextDialogChar = 0;
  7124. }
  7125. //---------------------------------------------------------------------------
  7126. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7127. {
  7128. // The four low-order bits are used internally by Windows
  7129. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7130. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7131. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7132. // 61730 - restore thru double click - undocumented
  7133. // 61490 - maximize thru double click - undocumented
  7134. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7135. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7136. {
  7137. SysResizing(Cmd);
  7138. }
  7139. TForm::Dispatch(&Message);
  7140. }
  7141. //---------------------------------------------------------------------------
  7142. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7143. {
  7144. AppLog(L"Windows session end query");
  7145. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7146. // Also there no point returning TRUE as we are not able to
  7147. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7148. // Hence the process termination might be safer :)
  7149. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7150. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7151. {
  7152. Message.Result = FALSE;
  7153. }
  7154. else
  7155. {
  7156. Message.Result = TRUE;
  7157. }
  7158. // Do not call default handling as that triggers OnCloseQuery,
  7159. // where our implementation will popup confirmation dialogs, what we do not want,
  7160. // as per Vista guidelines:
  7161. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7162. }
  7163. //---------------------------------------------------------------------------
  7164. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7165. {
  7166. AppLog(L"Windows session end");
  7167. if (Message.EndSession && IsApplicationMinimized())
  7168. {
  7169. // WORKAROUND
  7170. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7171. // when it receives WM_ENDSESSION,
  7172. // but that sometimes (particularly when application is minimized) cause crashes.
  7173. // Crash popups message that blocks log off.
  7174. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7175. // so we call ExitProcess() immediately, not even trying to cleanup.
  7176. // It still causes beep, so there's likely some popup, but it does not block
  7177. // log off.
  7178. ExitProcess(0);
  7179. }
  7180. TForm::Dispatch(&Message);
  7181. }
  7182. #ifdef _DEBUG
  7183. //---------------------------------------------------------------------------
  7184. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  7185. {
  7186. TForm::Dispatch(&Message);
  7187. }
  7188. #endif
  7189. //---------------------------------------------------------------------------
  7190. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7191. {
  7192. }
  7193. //---------------------------------------------------------------------------
  7194. void __fastcall TCustomScpExplorerForm::DoShow()
  7195. {
  7196. // Called from TCustomScpExplorerForm::CMShowingChanged
  7197. // only now are the controls resized finally, so the size constraints
  7198. // will not conflict with possibly very small window size
  7199. RestoreFormParams();
  7200. // This indicates that the form was rescaled after parameters were loaded and
  7201. // as most probably the parameters were actually saved with the current form scaling
  7202. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7203. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7204. // and no rounding problems will occur.
  7205. // See also RestoreForm.
  7206. // (we should be safe to call RestoreParams unconditionally)
  7207. if (PixelsPerInch != Screen->PixelsPerInch)
  7208. {
  7209. RestoreParams();
  7210. }
  7211. FixControlsPlacement();
  7212. if (Position == poDefaultPosOnly)
  7213. {
  7214. CutFormToDesktop(this);
  7215. }
  7216. TForm::DoShow();
  7217. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7218. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7219. // This was previously in NeedSession, where other related code is.
  7220. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7221. // unpleasantly shows briefly.
  7222. if ((ManagedSession == NULL) &&
  7223. !WinConfiguration->ShowLoginWhenNoSession &&
  7224. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7225. // This detects if workspace was saved the last time the main widow was closed
  7226. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7227. {
  7228. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7229. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7230. }
  7231. // Before main window displays
  7232. if (ManagedSession == NULL)
  7233. {
  7234. StartingWithoutSession();
  7235. }
  7236. UpdatePixelsPerInchMainWindowCounter();
  7237. FShowing = true;
  7238. }
  7239. //---------------------------------------------------------------------------
  7240. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7241. {
  7242. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7243. }
  7244. //---------------------------------------------------------------------------
  7245. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7246. {
  7247. SessionListChanged();
  7248. InitStatusBar();
  7249. UpdateControls();
  7250. }
  7251. //---------------------------------------------------------------------------
  7252. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7253. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7254. TNotifyEvent OnBalloonClick, TObject * UserData)
  7255. {
  7256. bool Do;
  7257. UnicodeString Message;
  7258. if (E == NULL)
  7259. {
  7260. Message = Str;
  7261. Do = true;
  7262. }
  7263. else
  7264. {
  7265. Do = ExceptionMessage(E, Message);
  7266. }
  7267. if (Do && WinConfiguration->BalloonNotifications)
  7268. {
  7269. UnicodeString Title;
  7270. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7271. {
  7272. Message = TrimLeft(Message);
  7273. }
  7274. else
  7275. {
  7276. Message = UnformatMessage(Message);
  7277. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7278. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7279. Title = LoadResourceString(Captions[Type]);
  7280. if (Terminal != NULL)
  7281. {
  7282. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal->PrimaryTerminal));
  7283. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7284. }
  7285. }
  7286. if (Seconds == 0)
  7287. {
  7288. Seconds = WinConfiguration->NotificationsTimeout;
  7289. }
  7290. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7291. }
  7292. }
  7293. //---------------------------------------------------------------------------
  7294. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7295. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7296. UnicodeString HelpKeyword, const TMessageParams * Params,
  7297. TTerminal * Terminal)
  7298. {
  7299. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7300. (FOnFeedSynchronizeError != NULL)) &&
  7301. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7302. {
  7303. if (FOnFeedSynchronizeError != NULL)
  7304. {
  7305. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7306. }
  7307. else
  7308. {
  7309. DebugAssert(FErrorList != NULL);
  7310. TStringList * MoreMessagesCopy = NULL;
  7311. if (MoreMessages)
  7312. {
  7313. MoreMessagesCopy = new TStringList();
  7314. MoreMessagesCopy->Assign(MoreMessages);
  7315. }
  7316. FErrorList->AddObject(Message, MoreMessagesCopy);
  7317. }
  7318. PopupTrayBalloon(Terminal, Message, Type);
  7319. return ContinueAnswer(Answers);
  7320. }
  7321. else
  7322. {
  7323. bool UseBalloon = FTrayIcon->Visible;
  7324. if (UseBalloon)
  7325. {
  7326. PopupTrayBalloon(Terminal, Message, Type);
  7327. }
  7328. unsigned int Result;
  7329. try
  7330. {
  7331. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7332. }
  7333. __finally
  7334. {
  7335. // cancel only balloon we popped up, otherwise we may cancel notification
  7336. // balloon that was there before the message dialog
  7337. // (such as "dd confirmation opt in balloon)
  7338. if (UseBalloon)
  7339. {
  7340. FTrayIcon->CancelBalloon();
  7341. }
  7342. }
  7343. return Result;
  7344. }
  7345. }
  7346. //---------------------------------------------------------------------------
  7347. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7348. TTerminal * Terminal, Exception * E)
  7349. {
  7350. if (FTrayIcon->Visible)
  7351. {
  7352. PopupTrayBalloon(Terminal, L"", qtError, E);
  7353. }
  7354. // particularly prevent opening new session from jump list,
  7355. // while exception is shown
  7356. NonVisualDataModule->StartBusy();
  7357. try
  7358. {
  7359. ShowExtendedExceptionEx(Terminal, E);
  7360. }
  7361. __finally
  7362. {
  7363. NonVisualDataModule->EndBusy();
  7364. FTrayIcon->CancelBalloon();
  7365. }
  7366. }
  7367. //---------------------------------------------------------------------------
  7368. void __fastcall TCustomScpExplorerForm::SessionReady()
  7369. {
  7370. InitStatusBar();
  7371. // cannot rely on active page being page for active terminal,
  7372. // as it can happen that active page is the "new session" page
  7373. // (e.g. when reconnecting active terminal, while login dialog
  7374. // invoked from "new session" page is modal)
  7375. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7376. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7377. }
  7378. //---------------------------------------------------------------------------
  7379. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  7380. TTerminal * Terminal, Exception * E)
  7381. {
  7382. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  7383. if (!Terminal->Active)
  7384. {
  7385. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7386. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7387. {
  7388. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7389. }
  7390. }
  7391. }
  7392. //---------------------------------------------------------------------------
  7393. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  7394. UnicodeString Message, TQueryType Type,
  7395. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7396. {
  7397. if ((E == NULL) ||
  7398. ExceptionMessage(E, Message))
  7399. {
  7400. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7401. if (Important)
  7402. {
  7403. Seconds *= 5;
  7404. }
  7405. UnicodeString NoteMessage(UnformatMessage(Message));
  7406. if (Terminal != NULL)
  7407. {
  7408. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7409. NoteMessage = FORMAT(L"%s: %s",
  7410. (TTerminalManager::Instance()->GetSessionTitle(Session, true), NoteMessage));
  7411. }
  7412. if (WinConfiguration->BalloonNotifications)
  7413. {
  7414. AddNote(NoteMessage);
  7415. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7416. }
  7417. else
  7418. {
  7419. FlashOnBackground();
  7420. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7421. }
  7422. }
  7423. }
  7424. //---------------------------------------------------------------------------
  7425. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7426. {
  7427. RestoreApp();
  7428. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7429. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7430. !NonVisualDataModule->Busy)
  7431. {
  7432. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7433. TTerminalManager::Instance()->ActiveSession = Terminal;
  7434. if (!ComponentVisible[fcQueueView])
  7435. {
  7436. ToggleQueueVisibility();
  7437. GoToQueue();
  7438. }
  7439. }
  7440. }
  7441. //---------------------------------------------------------------------------
  7442. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7443. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7444. {
  7445. UnicodeString Message;
  7446. TNotifyEvent OnClick = NULL;
  7447. TObject * UserData = NULL;
  7448. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7449. switch (Event)
  7450. {
  7451. case qeEmptyButMonitored:
  7452. if ((ATerminal != Terminal) || QueueInvisible)
  7453. {
  7454. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7455. OnClick = QueueEmptyNoteClicked;
  7456. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7457. TerminalNoteData->Terminal = ATerminal;
  7458. UserData = TerminalNoteData;
  7459. }
  7460. break;
  7461. case qeEmpty:
  7462. OperationComplete(ATerminal->QueueOperationStart);
  7463. break;
  7464. case qePendingUserAction:
  7465. if ((ATerminal != Terminal) ||
  7466. (QueueInvisible && !IsQueueAutoPopup()))
  7467. {
  7468. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7469. }
  7470. break;
  7471. default:
  7472. DebugFail();
  7473. }
  7474. if (!Message.IsEmpty())
  7475. {
  7476. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7477. }
  7478. }
  7479. //---------------------------------------------------------------------------
  7480. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7481. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7482. {
  7483. if (FDDExtMapFile != NULL)
  7484. {
  7485. CloseHandle(FDDExtMapFile);
  7486. FDDExtMapFile = NULL;
  7487. }
  7488. if (WinConfiguration->DDFakeFile)
  7489. {
  7490. DDFakeFileInitDrag(FileList, Created);
  7491. }
  7492. }
  7493. //---------------------------------------------------------------------------
  7494. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7495. {
  7496. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7497. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7498. {
  7499. FFakeFileDropTarget = FileName;
  7500. }
  7501. }
  7502. //---------------------------------------------------------------------------
  7503. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7504. {
  7505. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7506. if (!ForceDirectories(ApiPath(Result)))
  7507. {
  7508. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7509. }
  7510. FileSetAttr(ApiPath(Result), faHidden);
  7511. return Result;
  7512. }
  7513. //---------------------------------------------------------------------------
  7514. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7515. bool & Created)
  7516. {
  7517. FFakeFileDropTarget = UnicodeString();
  7518. FDragFakeDirectory = CreateFakeTransferDirectory();
  7519. FileList->AddItem(NULL, FDragFakeDirectory);
  7520. Created = true;
  7521. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7522. {
  7523. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7524. }
  7525. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7526. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7527. {
  7528. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7529. TDragExtCommStruct* CommStruct;
  7530. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7531. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7532. DebugAssert(CommStruct != NULL);
  7533. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7534. CommStruct->Dragging = true;
  7535. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7536. LENOF(CommStruct->DropDest));
  7537. NULL_TERMINATE(CommStruct->DropDest);
  7538. UnmapViewOfFile(CommStruct);
  7539. }
  7540. }
  7541. //---------------------------------------------------------------------------
  7542. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7543. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7544. {
  7545. bool Result;
  7546. DebugAssert(!IsLocalBrowserMode());
  7547. if (Sender == RemoteDirView)
  7548. {
  7549. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7550. }
  7551. else
  7552. {
  7553. DebugAssert(Sender == RemoteDriveView);
  7554. TStrings * FileList = RemoteDriveView->DragFileList();
  7555. try
  7556. {
  7557. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7558. }
  7559. __finally
  7560. {
  7561. delete FileList;
  7562. }
  7563. }
  7564. if (FDDTargetControl == RemoteDriveView)
  7565. {
  7566. RemoteDriveView->UpdateDropTarget();
  7567. }
  7568. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7569. // or from tree view to dir view.
  7570. // foMove happens when file/dir is dragged from remote tree view outside of
  7571. // application via dragex
  7572. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7573. (DropSourceControl == RemoteDriveView))
  7574. {
  7575. RemoteDriveView->UpdateDropSource();
  7576. }
  7577. return Result;
  7578. }
  7579. //---------------------------------------------------------------------------
  7580. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7581. {
  7582. DebugAssert(!IsLocalBrowserMode());
  7583. // This also handles drops of remote files to queue.
  7584. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7585. SAFE_DESTROY(FDDFileList);
  7586. if (!FFakeFileDropTarget.IsEmpty())
  7587. {
  7588. RemoveDir(ApiPath(FFakeFileDropTarget));
  7589. }
  7590. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7591. {
  7592. try
  7593. {
  7594. TDragResult DDResult = (Sender == RemoteDirView) ?
  7595. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7596. // Focus is moved to the target application,
  7597. // but as we are going to present the UI, we need to steal the focus back.
  7598. // This most likely won't work though (windows does not allow application
  7599. // to steal focus most of the time)
  7600. Application->BringToFront();
  7601. // On older version of Windows we never got drMove here, see also comment below.
  7602. // On Windows 10, we get the "move".
  7603. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7604. {
  7605. UnicodeString TargetDirectory;
  7606. TFileOperation Operation;
  7607. // drInvalid may mean drMove, see comment below
  7608. switch (DDResult)
  7609. {
  7610. case drCopy:
  7611. Operation = foCopy;
  7612. break;
  7613. case drMove:
  7614. Operation = foMove;
  7615. break;
  7616. default:
  7617. DebugFail();
  7618. case drInvalid:
  7619. // prefer "copy" for safety
  7620. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7621. break;
  7622. }
  7623. TTransferOperationParam Param;
  7624. UnicodeString CounterName;
  7625. bool ForceQueue;
  7626. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7627. {
  7628. // we get drInvalid both if d&d was intercepted by ddext,
  7629. // and when users drops on no-drop location.
  7630. // we tell the difference by existence of response from ddext,
  7631. // so we ignore absence of response in this case
  7632. if (DDResult != drInvalid)
  7633. {
  7634. // here we know that the extension is installed,
  7635. // as it is checked as soon as drag&drop starts from
  7636. // RemoteFileControlDDCreateDragFileList
  7637. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7638. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7639. {
  7640. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7641. }
  7642. else
  7643. {
  7644. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7645. }
  7646. }
  7647. }
  7648. else
  7649. {
  7650. // download using fake file
  7651. Param.Temp = false;
  7652. Param.DragDrop = true;
  7653. if (ForceQueue)
  7654. {
  7655. Param.Queue = asOn;
  7656. }
  7657. if (Sender == RemoteDirView)
  7658. {
  7659. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7660. }
  7661. if (RemoteFileControlFileOperation(Sender, Operation,
  7662. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7663. {
  7664. Configuration->Usage->Inc(CounterName);
  7665. }
  7666. }
  7667. }
  7668. }
  7669. __finally
  7670. {
  7671. CloseHandle(FDDExtMapFile);
  7672. FDDExtMapFile = NULL;
  7673. delete FDragFakeMonitors;
  7674. FDragFakeMonitors = NULL;
  7675. RemoveDir(ApiPath(FDragFakeDirectory));
  7676. FDragFakeDirectory = L"";
  7677. FFakeFileDropTarget = UnicodeString();
  7678. }
  7679. }
  7680. if (FDragDropSshTerminate.get() != NULL)
  7681. {
  7682. FDragDropSshTerminate->Rethrow();
  7683. }
  7684. }
  7685. //---------------------------------------------------------------------------
  7686. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7687. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7688. {
  7689. // Remember drop effect so we know (when user drops files), if we copy or move
  7690. FLastDropEffect = dwEffect;
  7691. }
  7692. //---------------------------------------------------------------------------
  7693. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7694. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7695. {
  7696. bool Result;
  7697. if (FDDTargetControl == QueueView3)
  7698. {
  7699. Directory = DefaultDownloadTargetDirectory();
  7700. Result = true;
  7701. CounterName = L"DownloadsDragDropQueue";
  7702. ForceQueue = true;
  7703. }
  7704. else if (!FFakeFileDropTarget.IsEmpty())
  7705. {
  7706. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7707. Result = true;
  7708. ForceQueue = false;
  7709. CounterName = L"DownloadsDragDropFakeFile";
  7710. }
  7711. else
  7712. {
  7713. ForceQueue = false;
  7714. Enabled = false;
  7715. try
  7716. {
  7717. int Timer = 0;
  7718. Result = false;
  7719. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7720. {
  7721. {
  7722. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7723. TDragExtCommStruct* CommStruct;
  7724. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7725. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7726. DebugAssert(CommStruct != NULL);
  7727. Result = !CommStruct->Dragging;
  7728. if (Result)
  7729. {
  7730. Directory = ExtractFilePath(CommStruct->DropDest);
  7731. CounterName = L"DownloadsDragDropExternalExt";
  7732. }
  7733. UnmapViewOfFile(CommStruct);
  7734. }
  7735. if (!Result)
  7736. {
  7737. Sleep(50);
  7738. Timer += 50;
  7739. Application->ProcessMessages();
  7740. }
  7741. }
  7742. }
  7743. __finally
  7744. {
  7745. Enabled = true;
  7746. }
  7747. }
  7748. return Result;
  7749. }
  7750. //---------------------------------------------------------------------------
  7751. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7752. const UnicodeString TempDir, int SecDelay)
  7753. {
  7754. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7755. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7756. if (FDelayedDeletionTimer == NULL)
  7757. {
  7758. DebugAssert(HandleAllocated());
  7759. FDelayedDeletionTimer = new TTimer(this);
  7760. FDelayedDeletionTimer->Interval = 10000;
  7761. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7762. }
  7763. else
  7764. {
  7765. FDelayedDeletionTimer->Enabled = true;
  7766. }
  7767. }
  7768. //---------------------------------------------------------------------------
  7769. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7770. {
  7771. DebugAssert(FDelayedDeletionList != NULL);
  7772. TDateTime N = Now();
  7773. TDateTime Alert;
  7774. UnicodeString Directory;
  7775. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7776. {
  7777. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7778. if ((N >= Alert) || (Sender == NULL))
  7779. {
  7780. Directory = FDelayedDeletionList->Strings[Index];
  7781. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7782. {
  7783. FDelayedDeletionList->Delete(Index);
  7784. }
  7785. }
  7786. }
  7787. if (FDelayedDeletionList->Count == 0)
  7788. {
  7789. FDelayedDeletionTimer->Enabled = false;
  7790. }
  7791. }
  7792. //---------------------------------------------------------------------------
  7793. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7794. {
  7795. DebugAssert(!IsLocalBrowserMode());
  7796. if (IsFileControl(FDDTargetControl, osRemote) ||
  7797. (FDDTargetControl == SessionsPageControl))
  7798. {
  7799. TManagedTerminal * TargetTerminal = NULL;
  7800. TFileOperation Operation = foNone;
  7801. if (FDDTargetControl == SessionsPageControl)
  7802. {
  7803. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7804. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7805. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7806. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7807. if (IsActiveTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7808. {
  7809. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7810. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7811. {
  7812. Operation = foRemoteMove;
  7813. }
  7814. else
  7815. {
  7816. Operation = foRemoteCopy;
  7817. }
  7818. }
  7819. }
  7820. else
  7821. {
  7822. if (FLastDropEffect == DROPEFFECT_MOVE)
  7823. {
  7824. Operation = foRemoteMove;
  7825. }
  7826. else if (FLastDropEffect == DROPEFFECT_COPY)
  7827. {
  7828. Operation = foRemoteCopy;
  7829. }
  7830. }
  7831. if (Operation != foNone)
  7832. {
  7833. RemoteFileControlFileOperation(DropSourceControl,
  7834. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7835. }
  7836. // abort drag&drop
  7837. Abort();
  7838. }
  7839. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7840. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7841. (FDDTargetControl != QueueView3))
  7842. {
  7843. DebugAssert(!FDragTempDir.IsEmpty());
  7844. TTransferType Type;
  7845. UnicodeString TempDir = FDragTempDir;
  7846. // We clear FDragTempDir before calling
  7847. // just in case it fail (raises exception)
  7848. FDragTempDir = L"";
  7849. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7850. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7851. // empty directory parameter means temp directory -> don't display it!
  7852. UnicodeString TargetDir = L"";
  7853. int Options = 0;
  7854. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7855. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7856. {
  7857. Abort();
  7858. }
  7859. // TargetDir is set when dropped on local file control
  7860. // (this was workaround for legacy dirview event handling, now it should be
  7861. // made prettier)
  7862. if (TargetDir.IsEmpty())
  7863. {
  7864. TargetDir = TempDir;
  7865. if (ForceDirectories(ApiPath(TargetDir)))
  7866. {
  7867. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7868. FPendingTempSpaceWarn = true;
  7869. try
  7870. {
  7871. FDragDropOperation = true;
  7872. int Params = cpTemporary |
  7873. (Type == ttMove ? cpDelete : 0);
  7874. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7875. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7876. }
  7877. __finally
  7878. {
  7879. FDragDropOperation = false;
  7880. FPendingTempSpaceWarn = false;
  7881. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7882. }
  7883. }
  7884. else
  7885. {
  7886. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7887. }
  7888. }
  7889. }
  7890. }
  7891. //---------------------------------------------------------------------------
  7892. void __fastcall TCustomScpExplorerForm::DDDownload(
  7893. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7894. {
  7895. DebugAssert(!IsLocalBrowserMode());
  7896. TAutoBatch AutoBatch(this);
  7897. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7898. UpdateCopyParamCounters(*CopyParam);
  7899. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7900. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7901. {
  7902. RemoteDriveView->UpdateDropSource();
  7903. }
  7904. }
  7905. //---------------------------------------------------------------------------
  7906. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7907. {
  7908. public:
  7909. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7910. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7911. {
  7912. }
  7913. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7914. {
  7915. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7916. TDataObjectFilesEx::AllowData(FormatEtc);
  7917. }
  7918. };
  7919. //---------------------------------------------------------------------------
  7920. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7921. TObject * Sender, TDataObject *& DataObject)
  7922. {
  7923. if (FDDExtMapFile != NULL)
  7924. {
  7925. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7926. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7927. {
  7928. Abort();
  7929. }
  7930. if (FileList->Count > 0)
  7931. {
  7932. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7933. if (!FilesObject->IsValid(true, true))
  7934. {
  7935. FilesObject->_Release();
  7936. }
  7937. else
  7938. {
  7939. DataObject = FilesObject;
  7940. }
  7941. }
  7942. }
  7943. }
  7944. //---------------------------------------------------------------------------
  7945. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7946. {
  7947. DebugFail();
  7948. }
  7949. //---------------------------------------------------------------------------
  7950. void __fastcall TCustomScpExplorerForm::GoToTree()
  7951. {
  7952. ComponentVisible[fcRemoteTree] = true;
  7953. DriveView(osRemote)->SetFocus();
  7954. }
  7955. //---------------------------------------------------------------------------
  7956. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7957. TPanelExport Export)
  7958. {
  7959. TCustomDirView * DirView = this->DirView(Side);
  7960. std::unique_ptr<TStrings> ExportData(new TStringList());
  7961. switch (Export)
  7962. {
  7963. case pePath:
  7964. ExportData->Add(DirView->PathName);
  7965. break;
  7966. case peFileList:
  7967. case peFullFileList:
  7968. {
  7969. bool FullPath = (Export == peFullFileList);
  7970. DirView->CreateFileList(false, FullPath, ExportData.get());
  7971. for (int Index = 0; Index < ExportData->Count; Index++)
  7972. {
  7973. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7974. {
  7975. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7976. }
  7977. }
  7978. }
  7979. break;
  7980. default:
  7981. DebugFail();
  7982. }
  7983. return ExportData.release();
  7984. }
  7985. //---------------------------------------------------------------------------
  7986. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7987. TPanelExport Export, TPanelExportDestination Destination)
  7988. {
  7989. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7990. PanelExportStore(Side, Export, Destination, ExportData.get());
  7991. }
  7992. //---------------------------------------------------------------------------
  7993. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  7994. TPanelExport /*Export*/, TPanelExportDestination Destination,
  7995. TStrings * ExportData)
  7996. {
  7997. if (Destination == pedClipboard)
  7998. {
  7999. TInstantOperationVisualizer Visualizer;
  8000. CopyToClipboard(ExportData);
  8001. }
  8002. else
  8003. {
  8004. DebugFail();
  8005. }
  8006. }
  8007. //---------------------------------------------------------------------------
  8008. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  8009. {
  8010. TCustomDirView * DirView = this->DirView(Side);
  8011. UnicodeString Mask = DirView->Mask;
  8012. if (DoFilterMaskDialog(DirView, Mask))
  8013. {
  8014. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  8015. Configuration->Usage->Inc(L"Filters");
  8016. }
  8017. }
  8018. //---------------------------------------------------------------------------
  8019. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  8020. {
  8021. return FQueueController->DefaultOperation();
  8022. }
  8023. //---------------------------------------------------------------------------
  8024. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  8025. TQueueOperation Operation, void ** Param)
  8026. {
  8027. switch (Operation)
  8028. {
  8029. case qoPreferences:
  8030. return true;
  8031. case qoGoTo:
  8032. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  8033. case qoOnceEmpty:
  8034. return IsAnythingQueued();
  8035. default:
  8036. return FQueueController->AllowOperation(Operation, Param);
  8037. }
  8038. }
  8039. //---------------------------------------------------------------------------
  8040. void __fastcall TCustomScpExplorerForm::GoToQueue()
  8041. {
  8042. if (DebugAlwaysTrue(QueueView3->Visible))
  8043. {
  8044. QueueView3->SetFocus();
  8045. }
  8046. }
  8047. //---------------------------------------------------------------------------
  8048. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  8049. TQueueOperation Operation, void * Param)
  8050. {
  8051. if (Operation == qoGoTo)
  8052. {
  8053. GoToQueue();
  8054. }
  8055. else if (Operation == qoPreferences)
  8056. {
  8057. PreferencesDialog(pmQueue);
  8058. }
  8059. else
  8060. {
  8061. FQueueController->ExecuteOperation(Operation, Param);
  8062. }
  8063. }
  8064. //---------------------------------------------------------------------------
  8065. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  8066. {
  8067. return (Queue != NULL) && Queue->Enabled;
  8068. }
  8069. //---------------------------------------------------------------------------
  8070. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8071. {
  8072. DebugAssert(Queue != NULL);
  8073. if (Queue != NULL)
  8074. {
  8075. Queue->Enabled = !Queue->Enabled;
  8076. }
  8077. }
  8078. //---------------------------------------------------------------------------
  8079. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8080. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8081. {
  8082. FQueueActedItem = QueueView3->ItemFocused;
  8083. }
  8084. //---------------------------------------------------------------------------
  8085. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8086. {
  8087. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8088. }
  8089. //---------------------------------------------------------------------------
  8090. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8091. {
  8092. return
  8093. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8094. (QueueDock->Visible ? QueueDock->Height : 0) +
  8095. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8096. }
  8097. //---------------------------------------------------------------------------
  8098. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8099. {
  8100. return ScaleByTextHeight(this, 48);
  8101. }
  8102. //---------------------------------------------------------------------------
  8103. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8104. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8105. {
  8106. // when queue is hidden by double-clicking splitter, stray attempt to
  8107. // resize the panel with strange value arrives, make sure it is ignored
  8108. if (ComponentVisible[fcQueueView])
  8109. {
  8110. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8111. if (NewSize > MaxHeightLimit)
  8112. {
  8113. NewSize = MaxHeightLimit;
  8114. }
  8115. int MinHeightLimit =
  8116. GetStaticQueuePanelComponentsHeight() +
  8117. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8118. GetMinQueueViewHeight();
  8119. if (NewSize < MinHeightLimit)
  8120. {
  8121. NewSize = MinHeightLimit;
  8122. }
  8123. }
  8124. else
  8125. {
  8126. Accept = false;
  8127. }
  8128. }
  8129. //---------------------------------------------------------------------------
  8130. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8131. {
  8132. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8133. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8134. if (QueueViewHeight < GetMinQueueViewHeight())
  8135. {
  8136. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8137. }
  8138. }
  8139. //---------------------------------------------------------------------------
  8140. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8141. TDragObject *& /*DragObject*/)
  8142. {
  8143. FQueueActedItem = QueueView3->ItemFocused;
  8144. FQueueScrollOnDragOver->StartDrag();
  8145. }
  8146. //---------------------------------------------------------------------------
  8147. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8148. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8149. {
  8150. FQueueScrollOnDragOver->EndDrag();
  8151. }
  8152. //---------------------------------------------------------------------------
  8153. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8154. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8155. {
  8156. Accept = true;
  8157. if (Source == QueueView3)
  8158. {
  8159. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8160. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8161. if (Accept)
  8162. {
  8163. TQueueItemProxy * QueueItem;
  8164. TQueueItemProxy * DestQueueItem;
  8165. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8166. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8167. Accept = (QueueItem != DestQueueItem) &&
  8168. (QueueItem->Status == TQueueItem::qsPending) &&
  8169. (DestQueueItem->Status == TQueueItem::qsPending);
  8170. }
  8171. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8172. }
  8173. }
  8174. //---------------------------------------------------------------------------
  8175. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8176. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8177. {
  8178. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8179. {
  8180. TQueueItemProxy * QueueItem;
  8181. TQueueItemProxy * DestQueueItem;
  8182. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8183. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8184. QueueItem->Move(DestQueueItem);
  8185. }
  8186. }
  8187. //---------------------------------------------------------------------------
  8188. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8189. {
  8190. if ((QueueView3->ItemFocused == NULL) &&
  8191. (QueueView3->Items->Count > 0))
  8192. {
  8193. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8194. }
  8195. QueueLabelUpdateStatus();
  8196. }
  8197. //---------------------------------------------------------------------------
  8198. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8199. {
  8200. QueueLabelUpdateStatus();
  8201. }
  8202. //---------------------------------------------------------------------------
  8203. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8204. {
  8205. QueueLabel->UpdateStatus();
  8206. }
  8207. //---------------------------------------------------------------------------
  8208. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8209. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8210. {
  8211. if (Selected)
  8212. {
  8213. NonVisualDataModule->UpdateNonVisibleActions();
  8214. }
  8215. }
  8216. //---------------------------------------------------------------------------
  8217. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8218. {
  8219. TDragDropFilesEx * Result = NULL;
  8220. if (Sender == SessionsPageControl)
  8221. {
  8222. Result = FSessionsDragDropFilesEx;
  8223. }
  8224. else if (Sender == QueueView3)
  8225. {
  8226. Result = FQueueDragDropFilesEx;
  8227. }
  8228. else
  8229. {
  8230. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8231. if (DirView != NULL)
  8232. {
  8233. Result = DirView->DragDropFilesEx;
  8234. }
  8235. else
  8236. {
  8237. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8238. if (DriveView != NULL)
  8239. {
  8240. Result = DriveView->DragDropFilesEx;
  8241. }
  8242. }
  8243. }
  8244. DebugAssert(Result != NULL);
  8245. return Result;
  8246. }
  8247. //---------------------------------------------------------------------------
  8248. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8249. {
  8250. return (DView->SelCount == DView->FilesCount);
  8251. }
  8252. //---------------------------------------------------------------------------
  8253. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8254. {
  8255. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8256. }
  8257. //---------------------------------------------------------------------------
  8258. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8259. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8260. {
  8261. DebugAssert(!IsLocalBrowserMode());
  8262. TFileOperation Operation;
  8263. switch (Effect)
  8264. {
  8265. case DROPEFFECT_MOVE:
  8266. Operation = foMove;
  8267. break;
  8268. case DROPEFFECT_COPY:
  8269. // occures on WinXP (reported by user)
  8270. default:
  8271. Operation = foCopy;
  8272. break;
  8273. };
  8274. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8275. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8276. if (DragDropFilesEx->FileList->Count > 0)
  8277. {
  8278. TStrings * FileList = new TStringList();
  8279. try
  8280. {
  8281. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8282. {
  8283. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8284. }
  8285. FDragDropOperation = true;
  8286. TTransferOperationParam Param;
  8287. Param.TargetDirectory = TargetPath;
  8288. // upload, no temp dirs
  8289. Param.Temp = false;
  8290. Param.DragDrop = DragDrop;
  8291. Param.Options =
  8292. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8293. if (ForceQueue)
  8294. {
  8295. Param.Queue = asOn;
  8296. }
  8297. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8298. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8299. {
  8300. if (IsFileControl(DropSourceControl, osLocal))
  8301. {
  8302. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8303. }
  8304. else
  8305. {
  8306. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8307. }
  8308. }
  8309. }
  8310. __finally
  8311. {
  8312. FDragDropOperation = false;
  8313. delete FileList;
  8314. }
  8315. }
  8316. }
  8317. //---------------------------------------------------------------------------
  8318. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8319. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8320. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8321. {
  8322. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8323. }
  8324. //---------------------------------------------------------------------------
  8325. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8326. TObject * Sender, int grfKeyState, int & dwEffect)
  8327. {
  8328. DebugAssert(!IsLocalBrowserMode());
  8329. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8330. if ((dwEffect != DROPEFFECT_NONE) &&
  8331. IsFileControl(DropSourceControl, osRemote))
  8332. {
  8333. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8334. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8335. (RemoteDirView->DropTarget == NULL))
  8336. {
  8337. dwEffect = DROPEFFECT_NONE;
  8338. }
  8339. else
  8340. {
  8341. if (dwEffect == DROPEFFECT_COPY)
  8342. {
  8343. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8344. // currently we support copying always (at least via temporary directory);
  8345. // remove associated checks once this all proves stable and working
  8346. bool CopyCapable = true;
  8347. // if we do not support neither of operations, there's no discussion
  8348. if (!MoveCapable && !CopyCapable)
  8349. {
  8350. dwEffect = DROPEFFECT_NONE;
  8351. }
  8352. else
  8353. {
  8354. // The default effect inside remote panel is move,
  8355. // unless we do not support it, but support copy
  8356. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8357. {
  8358. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8359. }
  8360. else
  8361. {
  8362. // with ctrl-down, we want copy unless it is not supported
  8363. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8364. }
  8365. }
  8366. }
  8367. }
  8368. }
  8369. }
  8370. //---------------------------------------------------------------------------
  8371. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8372. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8373. {
  8374. DebugAssert(!IsLocalBrowserMode());
  8375. if (FDDTotalSize >= 0)
  8376. {
  8377. if (File->IsDirectory)
  8378. {
  8379. FDDTotalSize = -1;
  8380. }
  8381. else
  8382. {
  8383. FDDTotalSize += File->Size;
  8384. }
  8385. }
  8386. DebugAssert(!FDragTempDir.IsEmpty());
  8387. // TODO: this is quite ineffective
  8388. // TODO: what if invalid character replacement is disabled?
  8389. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8390. UnicodeString TransferFileName;
  8391. if (Sender == RemoteDriveView)
  8392. {
  8393. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8394. }
  8395. else
  8396. {
  8397. TransferFileName = File->FileName;
  8398. }
  8399. FDDFileList->AddObject(TransferFileName, File);
  8400. }
  8401. //---------------------------------------------------------------------------
  8402. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8403. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8404. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8405. {
  8406. // sometimes we do not get DDEnd so the list is not released
  8407. SAFE_DESTROY(FDDFileList);
  8408. FDDFileList = new TStringList();
  8409. FDragTempDir = WinConfiguration->TemporaryDir();
  8410. FDDTotalSize = 0;
  8411. FDragDropSshTerminate.reset(NULL);
  8412. }
  8413. //---------------------------------------------------------------------------
  8414. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8415. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  8416. HRESULT & Result)
  8417. {
  8418. if (Result == DRAGDROP_S_DROP)
  8419. {
  8420. try
  8421. {
  8422. GlobalDragImageList->HideDragImage();
  8423. try
  8424. {
  8425. RemoteFileControlDDTargetDrop();
  8426. }
  8427. catch(ESshTerminate & E)
  8428. {
  8429. FDragDropSshTerminate.reset(E.Clone());
  8430. }
  8431. }
  8432. catch (Exception &E)
  8433. {
  8434. // If downloading fails we need to cancel drag&drop, otherwise
  8435. // Explorer shows error
  8436. // But by the way exception probably never reach this point as
  8437. // it's catched on way.
  8438. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8439. Result = DRAGDROP_S_CANCEL;
  8440. ShowExtendedException(Terminal, &E);
  8441. }
  8442. }
  8443. }
  8444. //---------------------------------------------------------------------------
  8445. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8446. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8447. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8448. {
  8449. TFileMasks::TParams MaskParams;
  8450. MaskParams.Size = Size;
  8451. MaskParams.Modification = Modification;
  8452. // this does not re-parse the mask if it is the same as the last time
  8453. FDirViewMatchMask = Masks;
  8454. bool ImplicitMatch;
  8455. Matches =
  8456. // Local and RecurseInclude parameters have no effect as there's no path.
  8457. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8458. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8459. (AllowImplicitMatches || !ImplicitMatch);
  8460. }
  8461. //---------------------------------------------------------------------------
  8462. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8463. TObject * Sender, TListItem * Item, WORD & Indexes)
  8464. {
  8465. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8466. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8467. {
  8468. Indexes |= oiPartial;
  8469. }
  8470. }
  8471. //---------------------------------------------------------------------------
  8472. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8473. {
  8474. return
  8475. DirViewEnabled(osCurrent) &&
  8476. DirView(osCurrent)->CanPasteFromClipBoard();
  8477. }
  8478. //---------------------------------------------------------------------------
  8479. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8480. {
  8481. bool Result = false;
  8482. if (CanPasteToDirViewFromClipBoard())
  8483. {
  8484. Result = true;
  8485. }
  8486. else
  8487. {
  8488. UnicodeString ClipboardText;
  8489. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8490. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8491. {
  8492. if (StoredSessions->IsUrl(ClipboardText))
  8493. {
  8494. Result = true;
  8495. }
  8496. else
  8497. {
  8498. Result = DirViewEnabled(osCurrent);
  8499. }
  8500. }
  8501. }
  8502. return Result;
  8503. }
  8504. //---------------------------------------------------------------------------
  8505. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8506. {
  8507. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8508. if (DoesClipboardContainOurFiles())
  8509. {
  8510. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8511. {
  8512. DebugAssert(!IsLocalBrowserMode());
  8513. TTerminalManager * Manager = TTerminalManager::Instance();
  8514. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8515. Manager->ActiveSession = FClipboardTerminal;
  8516. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8517. }
  8518. }
  8519. else if (CanPasteToDirViewFromClipBoard())
  8520. {
  8521. DirView(osCurrent)->PasteFromClipBoard();
  8522. }
  8523. else
  8524. {
  8525. UnicodeString ClipboardText;
  8526. if (NonEmptyTextFromClipboard(ClipboardText))
  8527. {
  8528. if (StoredSessions->IsUrl(ClipboardText))
  8529. {
  8530. NewSession(ClipboardText);
  8531. }
  8532. else
  8533. {
  8534. DirView(osCurrent)->Path = ClipboardText;
  8535. }
  8536. }
  8537. }
  8538. }
  8539. //---------------------------------------------------------------------------
  8540. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8541. {
  8542. // TBD
  8543. }
  8544. //---------------------------------------------------------------------------
  8545. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8546. {
  8547. TCustomDirView * ADirView = DirView(Side);
  8548. ADirView->SelectAll(Mode);
  8549. ADirView->SetFocus();
  8550. }
  8551. //---------------------------------------------------------------------------
  8552. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8553. {
  8554. TCustomDirView * ADirView = DirView(Side);
  8555. TFileFilter Filter;
  8556. DefaultFileFilter(Filter);
  8557. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8558. {
  8559. Configuration->Usage->Inc(L"MaskSelections");
  8560. ADirView->SelectFiles(Filter, Select);
  8561. ADirView->SetFocus();
  8562. }
  8563. }
  8564. //---------------------------------------------------------------------------
  8565. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8566. {
  8567. TCustomDirView * ADirView = DirView(Side);
  8568. ADirView->RestoreSelectedNames();
  8569. ADirView->SetFocus();
  8570. }
  8571. //---------------------------------------------------------------------------
  8572. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8573. {
  8574. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8575. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8576. {
  8577. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8578. UnicodeString Ext;
  8579. if (!IsSideLocalBrowser(osCurrent))
  8580. {
  8581. Ext = UnixExtractFileExt(FileName);
  8582. }
  8583. else
  8584. {
  8585. Ext = ExtractFileExt(FileName);
  8586. }
  8587. if (Ext.IsEmpty())
  8588. {
  8589. Ext = L".";
  8590. }
  8591. TFileFilter Filter;
  8592. Filter.Masks = FORMAT(L"*%s", (Ext));
  8593. Filter.Directories = false;
  8594. CurrentDirView->SelectFiles(Filter, Select);
  8595. }
  8596. }
  8597. //---------------------------------------------------------------------------
  8598. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8599. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8600. {
  8601. UnicodeString Result;
  8602. if (FIncrementalSearchState.Searching && (Side == GetSide(osCurrent)))
  8603. {
  8604. Result = FormatIncrementalSearchStatus(FIncrementalSearchState);
  8605. }
  8606. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8607. {
  8608. // noop
  8609. }
  8610. else
  8611. {
  8612. Result =
  8613. FMTLOAD(FILE_INFO_FORMAT,
  8614. (FormatBytes(FileInfo.SelectedSize),
  8615. FormatBytes(FileInfo.FilesSize),
  8616. FormatNumber(FileInfo.SelectedCount),
  8617. FormatNumber(FileInfo.FilesCount)));
  8618. }
  8619. return Result;
  8620. }
  8621. //---------------------------------------------------------------------------
  8622. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8623. TTBXStatusPanel * Panel, TOperationSide Side)
  8624. {
  8625. if (Panel->Index == 1)
  8626. {
  8627. ToggleShowHiddenFiles();
  8628. }
  8629. else if (Panel->Index == 2)
  8630. {
  8631. Filter(Side);
  8632. }
  8633. }
  8634. //---------------------------------------------------------------------------
  8635. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8636. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8637. {
  8638. DebugAssert(!StatusBar->SimplePanel);
  8639. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8640. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8641. }
  8642. //---------------------------------------------------------------------------
  8643. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8644. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8645. {
  8646. DebugAssert(StatusBar->Panels->Count >= 3);
  8647. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8648. if (FileInfo.HiddenCount > 0)
  8649. {
  8650. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8651. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8652. }
  8653. else
  8654. {
  8655. HiddenFilesPanel->ViewPriority = 0;
  8656. // not really necessary, just to cleanup no-longer-valid data
  8657. HiddenFilesPanel->Caption = L"";
  8658. }
  8659. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8660. if (FileInfo.FilteredCount > 0)
  8661. {
  8662. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8663. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8664. }
  8665. else
  8666. {
  8667. FilteredFilesPanel->ViewPriority = 0;
  8668. // not really necessary, just to cleanup no-longer-valid data
  8669. FilteredFilesPanel->Caption = L"";
  8670. }
  8671. }
  8672. //---------------------------------------------------------------------------
  8673. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8674. TObject * /*Sender*/)
  8675. {
  8676. if (DirView(osOther)->Enabled)
  8677. {
  8678. DirView(osOther)->SetFocus();
  8679. }
  8680. }
  8681. //---------------------------------------------------------------------------
  8682. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8683. {
  8684. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8685. switch (Config.Show)
  8686. {
  8687. case qvShow:
  8688. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8689. {
  8690. Config.Show = qvHide;
  8691. }
  8692. else
  8693. {
  8694. Config.Show = Config.LastHideShow;
  8695. }
  8696. break;
  8697. case qvHideWhenEmpty:
  8698. if (ComponentVisible[fcQueueView])
  8699. {
  8700. Config.Show = qvHide;
  8701. }
  8702. else
  8703. {
  8704. Config.LastHideShow = Config.Show;
  8705. Config.Show = qvShow;
  8706. }
  8707. break;
  8708. case qvHide:
  8709. Config.LastHideShow = Config.Show;
  8710. Config.Show = qvShow;
  8711. break;
  8712. }
  8713. WinConfiguration->QueueView = Config;
  8714. }
  8715. //---------------------------------------------------------------------------
  8716. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8717. {
  8718. UnicodeString Result;
  8719. if (Terminal != NULL)
  8720. {
  8721. switch (WinConfiguration->PathInCaption)
  8722. {
  8723. case picShort:
  8724. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8725. break;
  8726. case picFull:
  8727. Result = Terminal->CurrentDirectory;
  8728. break;
  8729. }
  8730. }
  8731. return Result;
  8732. }
  8733. //---------------------------------------------------------------------------
  8734. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8735. {
  8736. TColor Result = GetWindowColor(FSessionColor);
  8737. return Result;
  8738. }
  8739. //---------------------------------------------------------------------------
  8740. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8741. {
  8742. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8743. return Result;
  8744. }
  8745. //---------------------------------------------------------------------------
  8746. void TCustomScpExplorerForm::UpdatePanelControls(TCustomDirView * ADirView, TCustomDriveView * ADriveView)
  8747. {
  8748. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8749. ADirView->DarkMode = UseDarkTheme;
  8750. ADriveView->DarkMode = UseDarkTheme;
  8751. }
  8752. //---------------------------------------------------------------------------
  8753. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8754. {
  8755. if (!FSessionChanging)
  8756. {
  8757. TTerminalManager::Instance()->UpdateAppTitle();
  8758. }
  8759. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8760. // background to gray on Windows 7 (works on Windows 10).
  8761. // See also EnableControl
  8762. if (Showing)
  8763. {
  8764. if (ManagedSession != NULL)
  8765. {
  8766. // Update path when it changes
  8767. if ((SessionsPageControl->ActivePage != NULL) &&
  8768. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8769. {
  8770. UpdateSessionTab(SessionsPageControl->ActivePage);
  8771. }
  8772. }
  8773. NonVisualDataModule->ReconnectSessionAction->Update();
  8774. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8775. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8776. CenterReconnectToolbar();
  8777. bool HasTerminal = HasActiveTerminal();
  8778. RemoteDirView->Enabled = HasTerminal;
  8779. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8780. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8781. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8782. RemoteDriveView->Color = RemoteDirView->Color;
  8783. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8784. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8785. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8786. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8787. QueueFileList->Enabled = QueueView3->Enabled;
  8788. QueueFileList->Color = QueueView3->Color;
  8789. QueueFileList->Font->Color = QueueView3->Font->Color;
  8790. QueueLabelUpdateStatus();
  8791. UpdatePanelControls(RemoteDirView, RemoteDriveView);
  8792. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8793. if (FImmersiveDarkMode != UseDarkTheme)
  8794. {
  8795. UpdateDarkMode();
  8796. }
  8797. SessionsPageControl->TabTheme = UseDarkTheme ? CurrentTheme : NULL;
  8798. UnicodeString CurrentHiContrastThemeName = (FHiContrastTheme != NULL) ? FHiContrastTheme->Name : EmptyStr;
  8799. bool HiContrast = WinConfiguration->HiContrast;
  8800. UnicodeString NewHiContrastThemeName = HiContrast ? GetThemeName(!UseDarkTheme) : EmptyStr;
  8801. if (CurrentHiContrastThemeName != NewHiContrastThemeName)
  8802. {
  8803. ReleaseHiContrastTheme();
  8804. if (!NewHiContrastThemeName.IsEmpty())
  8805. {
  8806. FHiContrastTheme = GetTBXTheme(NewHiContrastThemeName);
  8807. }
  8808. }
  8809. SessionsPageControl->ActiveTabTheme = HiContrast ? DebugNotNull(FHiContrastTheme) : NULL;
  8810. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8811. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8812. }
  8813. }
  8814. //---------------------------------------------------------------------------
  8815. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8816. {
  8817. UpdateControls();
  8818. }
  8819. //---------------------------------------------------------------------------
  8820. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8821. TObject * Sender)
  8822. {
  8823. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8824. DebugAssert(DirView != NULL);
  8825. DoDirViewLoaded(DirView);
  8826. TransferPresetAutoSelect();
  8827. }
  8828. //---------------------------------------------------------------------------
  8829. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8830. {
  8831. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8832. // first run after installation
  8833. if (double(Updates.LastCheck) == 0)
  8834. {
  8835. AppLog(L"First run, scheduling updates check for the next run");
  8836. // make sure next time there will be an update (if enabled)
  8837. Updates.LastCheck = TDateTime(1);
  8838. WinConfiguration->Updates = Updates;
  8839. }
  8840. else
  8841. {
  8842. TDateTime Period;
  8843. if (IsUWP() && !IsOfficialPackage())
  8844. {
  8845. Period = DefaultUpdatesPeriod;
  8846. AppLog(L"Thirdparty UWP package, using default updates check period");
  8847. }
  8848. else
  8849. {
  8850. Period = Updates.Period;
  8851. }
  8852. AppLogFmt(L"Updates check period: %.2f", (double(Period)));
  8853. if (double(Period) > 0)
  8854. {
  8855. TDateTime Interval = Now() - Updates.LastCheck;
  8856. AppLogFmt(L"Interval since the last updates check: %.2f", (double(Interval)));
  8857. if (Interval >= Period)
  8858. {
  8859. StartUpdateThread(UpdatesChecked);
  8860. }
  8861. }
  8862. }
  8863. }
  8864. //---------------------------------------------------------------------------
  8865. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8866. {
  8867. AppLog(L"Updates check done");
  8868. UnicodeString Message;
  8869. bool New;
  8870. TQueryType Type;
  8871. GetUpdatesMessage(Message, New, Type, false);
  8872. if (!Message.IsEmpty())
  8873. {
  8874. AppLogFmt(L"Updates check message: %s", (Message));
  8875. if (New)
  8876. {
  8877. AppLog(L"New version detected");
  8878. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8879. }
  8880. if (!New && (Type != qtWarning))
  8881. {
  8882. AppLog(L"Posting non-critical updates note");
  8883. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  8884. }
  8885. else
  8886. {
  8887. AppLog(L"Posting new version or critical message notification");
  8888. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8889. }
  8890. if (New)
  8891. {
  8892. Configuration->Usage->Inc(L"UpdateNotifications");
  8893. }
  8894. }
  8895. }
  8896. //---------------------------------------------------------------------------
  8897. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8898. {
  8899. RestoreApp();
  8900. bool CanDisplay = !NonVisualDataModule->Busy;
  8901. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8902. {
  8903. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8904. }
  8905. if (CanDisplay)
  8906. {
  8907. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8908. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  8909. NonVisualDataModule->StartBusy();
  8910. try
  8911. {
  8912. CheckForUpdates(true);
  8913. }
  8914. __finally
  8915. {
  8916. NonVisualDataModule->EndBusy();
  8917. }
  8918. }
  8919. else
  8920. {
  8921. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  8922. }
  8923. }
  8924. //---------------------------------------------------------------------------
  8925. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  8926. TCopyParamRuleData & Data)
  8927. {
  8928. DebugAssert(Terminal != NULL);
  8929. Data.HostName = Terminal->SessionData->HostNameExpanded;
  8930. Data.UserName = Terminal->SessionData->UserNameExpanded;
  8931. Data.RemoteDirectory = RemoteDirView->PathName;
  8932. }
  8933. //---------------------------------------------------------------------------
  8934. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  8935. {
  8936. // Terminal can be null when we are changing local directory implicitly,
  8937. // because it has been deleted, while no session is connected
  8938. // (Login dialog is open)
  8939. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  8940. {
  8941. DebugAssert(!IsLocalBrowserMode());
  8942. TCopyParamRuleData Data;
  8943. GetTransferPresetAutoSelectData(Data);
  8944. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  8945. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  8946. if (CopyParamIndex < 0)
  8947. {
  8948. // there is no preset that matches autoselection
  8949. // set preset that we consider "default"
  8950. FCopyParamAutoSelected = L""; // forget last autoselected preset
  8951. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  8952. }
  8953. else
  8954. {
  8955. // there is preset matching autoselection
  8956. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  8957. if (CopyParamName == FCopyParamAutoSelected)
  8958. {
  8959. // autoselected the same preset as the last time
  8960. // make no change (i.e. preserve custom user preset, if any)
  8961. }
  8962. else
  8963. {
  8964. // autoselected the different preset then the last time (or there
  8965. // was default preset set)
  8966. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  8967. GUIConfiguration->CopyParamCurrent = CopyParamName;
  8968. }
  8969. }
  8970. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  8971. {
  8972. if (CopyParamIndex >= 0)
  8973. {
  8974. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  8975. }
  8976. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  8977. try
  8978. {
  8979. int Fmt =
  8980. (CopyParamIndex < 0) ?
  8981. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8982. COPY_PARAM_AUTOSELECTED;
  8983. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  8984. Data->Message = MainInstructions(Message);
  8985. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  8986. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  8987. CopyParamAttrs);
  8988. if (CopyParamIndex >= 0)
  8989. {
  8990. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  8991. Info = FORMAT(L"%s\n \n%s", (Info,
  8992. FMTLOAD(COPY_PARAM_RULE,
  8993. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  8994. }
  8995. Data->Message += L"\n\n" + Info;
  8996. if (WinConfiguration->CopyParamAutoSelectNotice)
  8997. {
  8998. TransferPresetNoteMessage(Data, true);
  8999. }
  9000. else
  9001. {
  9002. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  9003. Data = NULL; // ownership passed
  9004. }
  9005. }
  9006. __finally
  9007. {
  9008. delete Data;
  9009. }
  9010. }
  9011. }
  9012. }
  9013. //---------------------------------------------------------------------------
  9014. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  9015. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  9016. {
  9017. DebugAssert(NoteData != NULL);
  9018. DebugAssert(!IsLocalBrowserMode());
  9019. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  9020. TQueryButtonAlias Aliases[1];
  9021. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  9022. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  9023. Params.Aliases = Aliases;
  9024. Params.AliasesCount = LENOF(Aliases);
  9025. unsigned int Result =
  9026. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  9027. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  9028. switch (Result)
  9029. {
  9030. case qaNeverAskAgain:
  9031. DebugAssert(AllowNeverAskAgain);
  9032. WinConfiguration->CopyParamAutoSelectNotice = false;
  9033. break;
  9034. case qaIgnore:
  9035. PreferencesDialog(pmPresets);
  9036. break;
  9037. }
  9038. }
  9039. //---------------------------------------------------------------------------
  9040. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  9041. {
  9042. // as of now useless, as this is used for notes only, never for balloons, ...
  9043. RestoreApp();
  9044. // .. and we should never be busy here
  9045. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  9046. {
  9047. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  9048. }
  9049. }
  9050. //---------------------------------------------------------------------------
  9051. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  9052. TPreferencesMode APreferencesMode)
  9053. {
  9054. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  9055. TCopyParamRuleData Data;
  9056. if (Terminal != NULL)
  9057. {
  9058. PreferencesData.reset(new TPreferencesDialogData());
  9059. GetTransferPresetAutoSelectData(Data);
  9060. PreferencesData->CopyParamRuleData = &Data;
  9061. }
  9062. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  9063. }
  9064. //---------------------------------------------------------------------------
  9065. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  9066. const TCustomCommandType & Command)
  9067. {
  9068. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  9069. {
  9070. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  9071. }
  9072. }
  9073. //---------------------------------------------------------------------------
  9074. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  9075. {
  9076. bool RemoteAllowed = CustomCommandRemoteAllowed();
  9077. TCustomCommandType Command;
  9078. // make sure we use local custom command when remote are not supported
  9079. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  9080. {
  9081. Command = FLastCustomCommand;
  9082. }
  9083. else
  9084. {
  9085. Command.Params = Command.Params | ccLocal;
  9086. }
  9087. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  9088. FEditingFocusedAdHocCommand = OnFocused;
  9089. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9090. int Options =
  9091. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9092. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9093. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9094. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9095. {
  9096. FLastCustomCommand = Command;
  9097. UpdateCustomCommandsToolbar();
  9098. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9099. }
  9100. }
  9101. //---------------------------------------------------------------------------
  9102. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9103. {
  9104. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9105. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9106. DebugAssert(State > 0);
  9107. if (State <= 0)
  9108. {
  9109. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9110. }
  9111. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9112. }
  9113. //---------------------------------------------------------------------------
  9114. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9115. TCustomCommandType & Command, int & State)
  9116. {
  9117. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9118. if (Result)
  9119. {
  9120. Command = FLastCustomCommand;
  9121. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9122. }
  9123. return Result;
  9124. }
  9125. //---------------------------------------------------------------------------
  9126. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9127. {
  9128. ResetIncrementalSearch();
  9129. }
  9130. //---------------------------------------------------------------------------
  9131. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9132. {
  9133. DebugAssert(ComponentVisible[Component]);
  9134. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9135. }
  9136. //---------------------------------------------------------------------------
  9137. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9138. {
  9139. // when queue panel is resized here directly, the status bar is stretched
  9140. // over whole space the panel occupied
  9141. PostComponentHide(fcQueueView);
  9142. }
  9143. //---------------------------------------------------------------------------
  9144. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9145. {
  9146. ComponentVisible[fcQueueFileList] = false;
  9147. }
  9148. //---------------------------------------------------------------------------
  9149. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9150. {
  9151. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9152. RefreshColorMode();
  9153. ResetSysDarkTheme();
  9154. ConfigurationChanged();
  9155. ConfigureInterface();
  9156. // Should be called for all controls
  9157. RemoteDirView->Perform(WM_THEMECHANGED, 0, 0);
  9158. }
  9159. //---------------------------------------------------------------------------
  9160. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9161. {
  9162. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9163. if (!FInvalid &&
  9164. (Message.LParam != 0) &&
  9165. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9166. {
  9167. ThemeChanged();
  9168. }
  9169. TForm::Dispatch(&Message);
  9170. }
  9171. //---------------------------------------------------------------------------
  9172. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9173. {
  9174. TMessage * M = static_cast<TMessage*>(Message);
  9175. switch (M->Msg)
  9176. {
  9177. case CM_DIALOGCHAR:
  9178. CMDialogChar(*M);
  9179. break;
  9180. case WM_APPCOMMAND:
  9181. WMAppCommand(*M);
  9182. break;
  9183. case WM_SYSCOMMAND:
  9184. WMSysCommand(*M);
  9185. break;
  9186. case WM_QUERYENDSESSION:
  9187. WMQueryEndSession(*M);
  9188. break;
  9189. case WM_ENDSESSION:
  9190. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9191. break;
  9192. #ifdef _DEBUG
  9193. case WM_WINDOWPOSCHANGED:
  9194. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  9195. break;
  9196. case CM_CUSTOMSTYLECHANGED:
  9197. TForm::Dispatch(Message);
  9198. break;
  9199. #endif
  9200. case WM_COMPONENT_HIDE:
  9201. {
  9202. Byte Component = static_cast<Byte>(M->WParam);
  9203. // sanity check
  9204. if (ComponentVisible[Component])
  9205. {
  9206. // special treatment
  9207. if (Component == fcQueueView)
  9208. {
  9209. ToggleQueueVisibility();
  9210. DebugAssert(!ComponentVisible[fcQueueView]);
  9211. }
  9212. else
  9213. {
  9214. ComponentVisible[Component] = false;
  9215. }
  9216. }
  9217. }
  9218. break;
  9219. case WM_COPYDATA:
  9220. WMCopyData(*M);
  9221. break;
  9222. case WM_MANAGES_CAPTION:
  9223. // caption managed in TTerminalManager::UpdateAppTitle()
  9224. M->Result = 1;
  9225. break;
  9226. case WM_WANTS_MOUSEWHEEL:
  9227. M->Result = 1;
  9228. break;
  9229. case CM_SHOWINGCHANGED:
  9230. CMShowingChanged(*M);
  9231. break;
  9232. case WM_CLOSE:
  9233. WMClose(*M);
  9234. break;
  9235. case WM_DPICHANGED:
  9236. WMDpiChanged(*M);
  9237. break;
  9238. case CM_DPICHANGED:
  9239. CMDpiChanged(*M);
  9240. break;
  9241. case WM_SETTINGCHANGE:
  9242. WMSettingChange(*M);
  9243. break;
  9244. case CM_DIALOGKEY:
  9245. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9246. break;
  9247. case WM_PASTE_FILES:
  9248. PasteFiles();
  9249. break;
  9250. case WM_IS_HIDDEN:
  9251. // To treat master password prompt as a main window while showing it when workspace is loading while
  9252. // the exporer is showing up (Visible is true already)
  9253. M->Result = !FShowing;
  9254. break;
  9255. case WM_SHOWWINDOW:
  9256. if (M->WParam)
  9257. {
  9258. AddStartupSequence(L"J");
  9259. }
  9260. TForm::Dispatch(Message);
  9261. break;
  9262. default:
  9263. TForm::Dispatch(Message);
  9264. break;
  9265. }
  9266. }
  9267. //---------------------------------------------------------------------------
  9268. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9269. {
  9270. // noop
  9271. }
  9272. //---------------------------------------------------------------------------
  9273. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  9274. {
  9275. TForm::Dispatch(&Message);
  9276. FSessionColors->Clear();
  9277. AddFixedSessionImages();
  9278. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9279. UpdateImages();
  9280. }
  9281. //---------------------------------------------------------------------------
  9282. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9283. {
  9284. TForm::Dispatch(&Message);
  9285. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9286. UpdatePixelsPerInchMainWindowCounter();
  9287. }
  9288. //---------------------------------------------------------------------------
  9289. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9290. {
  9291. AppLog(L"Main window WM_CLOSE");
  9292. // Cannot close window while we are busy.
  9293. // We cannot test this in FormCloseQuery as that is called also from
  9294. // Close(), which is called by CloseApplicationAction. So we can be busy
  9295. // there already even, when it is legitimate to close the application.
  9296. // Possibly a better place to handle this would be WMSysCommand.
  9297. if (NonVisualDataModule->Busy)
  9298. {
  9299. Message.Result = 1;
  9300. }
  9301. else
  9302. {
  9303. TForm::Dispatch(&Message);
  9304. }
  9305. }
  9306. //---------------------------------------------------------------------------
  9307. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9308. {
  9309. if (!FShowingChanged)
  9310. {
  9311. AddStartupSequence(L"D");
  9312. FShowingChanged = true;
  9313. }
  9314. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9315. bool NoSession = (ManagedSession == NULL);
  9316. // This calls TCustomScpExplorerForm::DoShow
  9317. TForm::Dispatch(&Message);
  9318. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9319. if (Showing && !FStarted)
  9320. {
  9321. FStarted = true;
  9322. InterfaceStarted();
  9323. }
  9324. if (Showing && NoSession)
  9325. {
  9326. // When we are starting minimized (i.e. from an installer),
  9327. // postpone showing Login dialog until we get restored.
  9328. // Otherwise the Login dialog (and Authentication window) show restored
  9329. // over invisible (minimized) main window.
  9330. if (WindowState == wsMinimized)
  9331. {
  9332. FNeedSession = true;
  9333. }
  9334. else
  9335. {
  9336. // This happens before application ever goes idle, so the toolbars would
  9337. // stay enabled (initial state) until the Login dialog is dismissed.
  9338. UpdateActions();
  9339. NonVisualDataModule->StartBusy();
  9340. try
  9341. {
  9342. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9343. // otherwise the dialog does not receive focus.
  9344. // With Commander interface the ProcessMessages is called already
  9345. // by TDriveView, but with Explorer interface, we need to call it explicily
  9346. Application->ProcessMessages();
  9347. // do not reload sessions, they have been loaded just now (optimization)
  9348. NeedSession(true);
  9349. }
  9350. __finally
  9351. {
  9352. NonVisualDataModule->EndBusy();
  9353. }
  9354. }
  9355. }
  9356. }
  9357. //---------------------------------------------------------------------------
  9358. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9359. {
  9360. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9361. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9362. }
  9363. //---------------------------------------------------------------------------
  9364. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9365. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9366. int & MaxHeight)
  9367. {
  9368. // workaround for bug in TWinControl.CalcConstraints
  9369. // Check for empty rect (restore from iconic state) is done there only after
  9370. // call to AdjustClientRect, which enlarges the rect (for forms).
  9371. TRect R = GetClientRect();
  9372. // when restoring from iconic state, place no restrictions
  9373. if (IsRectEmpty(R))
  9374. {
  9375. MinWidth = 0;
  9376. MinHeight = 0;
  9377. MaxWidth = 32000;
  9378. MaxHeight = 32000;
  9379. }
  9380. }
  9381. //---------------------------------------------------------------------------
  9382. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9383. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9384. {
  9385. // terminal can be already closed (e.g. dropped connection)
  9386. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9387. {
  9388. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9389. try
  9390. {
  9391. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9392. }
  9393. catch(...)
  9394. {
  9395. if (!Terminal->Active)
  9396. {
  9397. Close = true;
  9398. }
  9399. throw;
  9400. }
  9401. }
  9402. }
  9403. //---------------------------------------------------------------------------
  9404. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9405. {
  9406. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9407. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9408. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9409. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9410. {
  9411. OnGetSpaceAvailable = GetSpaceAvailable;
  9412. }
  9413. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9414. OnGetSpaceAvailable);
  9415. }
  9416. //---------------------------------------------------------------------------
  9417. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9418. {
  9419. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9420. Terminal->FillSessionDataForCode(Data.get());
  9421. return Data.release();
  9422. }
  9423. //---------------------------------------------------------------------------
  9424. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9425. {
  9426. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9427. DoGenerateUrlDialog(Data.get(), Paths);
  9428. }
  9429. //---------------------------------------------------------------------------
  9430. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9431. {
  9432. GenerateUrl(NULL);
  9433. }
  9434. //---------------------------------------------------------------------------
  9435. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9436. {
  9437. std::unique_ptr<TStrings> Paths(new TStringList());
  9438. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9439. GenerateUrl(Paths.get());
  9440. }
  9441. //---------------------------------------------------------------------------
  9442. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9443. {
  9444. FSessionColor = value;
  9445. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9446. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9447. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9448. DebugAssert(ColorItem != NULL);
  9449. ColorItem->Color = C;
  9450. NonVisualDataModule->ColorMenuItem->Color = C;
  9451. UpdateControls();
  9452. }
  9453. //---------------------------------------------------------------------------
  9454. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9455. {
  9456. if (value != FSessionColor)
  9457. {
  9458. UpdateSessionColor(value);
  9459. // Is null when called from LastTerminalClosed
  9460. if (Terminal != NULL)
  9461. {
  9462. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9463. }
  9464. }
  9465. }
  9466. //---------------------------------------------------------------------------
  9467. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9468. {
  9469. bool Result = FNoteTimer->Enabled;
  9470. if (Result)
  9471. {
  9472. // cannot cancel note too early
  9473. bool NotEarly =
  9474. (Now() - FNoteShown >
  9475. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9476. if (Force || NotEarly)
  9477. {
  9478. FNoteTimer->Enabled = false;
  9479. FNote = L"";
  9480. SAFE_DESTROY(FNoteData);
  9481. FOnNoteClick = NULL;
  9482. FNoteHints = FNotes->Text;
  9483. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9484. UpdateStatusBar();
  9485. }
  9486. }
  9487. return Result;
  9488. }
  9489. //---------------------------------------------------------------------------
  9490. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9491. {
  9492. DebugAssert(FNoteTimer->Enabled);
  9493. CancelNote(true);
  9494. }
  9495. //---------------------------------------------------------------------------
  9496. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9497. {
  9498. FNoteHints = FNotes->Text.TrimRight();
  9499. }
  9500. //---------------------------------------------------------------------------
  9501. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9502. {
  9503. int P = Note.Pos(L"\n");
  9504. if (P > 0)
  9505. {
  9506. Note.SetLength(P - 1);
  9507. }
  9508. FNotes->Add(FORMAT(L"[%s] %s",
  9509. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9510. while (FNotes->Count > 10)
  9511. {
  9512. FNotes->Delete(0);
  9513. }
  9514. if (UpdateNow)
  9515. {
  9516. UpdateNoteHints();
  9517. UpdateStatusBar();
  9518. }
  9519. }
  9520. //---------------------------------------------------------------------------
  9521. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  9522. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9523. {
  9524. int P = Note.Pos(L"\n");
  9525. if (P > 0)
  9526. {
  9527. Note.SetLength(P - 1);
  9528. }
  9529. UpdateNoteHints();
  9530. FNote = Note;
  9531. SAFE_DESTROY(FNoteData);
  9532. FNoteData = NoteData;
  9533. FOnNoteClick = OnNoteClick;
  9534. AddNote(Note, false);
  9535. UpdateStatusBar();
  9536. FNoteShown = Now();
  9537. FNoteTimer->Enabled = false;
  9538. if (Seconds == 0)
  9539. {
  9540. Seconds = WinConfiguration->NotificationsTimeout;
  9541. }
  9542. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9543. FNoteTimer->Enabled = true;
  9544. }
  9545. //---------------------------------------------------------------------------
  9546. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9547. {
  9548. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  9549. }
  9550. //---------------------------------------------------------------------------
  9551. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9552. {
  9553. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9554. {
  9555. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9556. }
  9557. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9558. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9559. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))),
  9560. 0, NULL, NULL);
  9561. }
  9562. //---------------------------------------------------------------------------
  9563. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9564. {
  9565. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9566. UnicodeString Note =
  9567. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9568. PostNote(Note, 0, NULL, NULL);
  9569. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9570. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9571. }
  9572. //---------------------------------------------------------------------------
  9573. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9574. {
  9575. WinConfiguration->FormatSizeBytes = Style;
  9576. }
  9577. //---------------------------------------------------------------------------
  9578. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9579. {
  9580. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9581. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9582. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9583. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  9584. }
  9585. //---------------------------------------------------------------------------
  9586. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9587. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9588. {
  9589. if (Panel->Index == 0)
  9590. {
  9591. if (FOnNoteClick != NULL)
  9592. {
  9593. // prevent the user data from being freed by possible call
  9594. // to CancelNote or PostNote during call to OnNoteClick
  9595. std::unique_ptr<TObject> NoteData(FNoteData);
  9596. TNotifyEvent OnNoteClick = FOnNoteClick;
  9597. FNoteData = NULL;
  9598. // need to cancel the note as we are going to delete its user data
  9599. CancelNote(true);
  9600. OnNoteClick(NoteData.get());
  9601. }
  9602. }
  9603. if (HasActiveTerminal() &&
  9604. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9605. {
  9606. FileSystemInfo();
  9607. }
  9608. }
  9609. //---------------------------------------------------------------------------
  9610. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9611. {
  9612. // workaround:
  9613. // 1) for unknown reason, disabling window, while minimized,
  9614. // prevents it from restoring, even if it was enabled again meanwhile
  9615. // 2) when disabling the main window, while another has focus
  9616. // minimize is no longer possible
  9617. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9618. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9619. // Shouldn't we use IsApplicationMinimized() here?
  9620. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9621. {
  9622. Enabled = false;
  9623. }
  9624. FLockLevel++;
  9625. }
  9626. //---------------------------------------------------------------------------
  9627. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9628. {
  9629. DebugAssert(FLockLevel > 0);
  9630. FLockLevel--;
  9631. if (FLockLevel == 0)
  9632. {
  9633. DebugAssert(FLockSuspendLevel == 0);
  9634. Enabled = true;
  9635. // VCL_COPY (TCustomForm.SetWindowFocus)
  9636. if (Active && (ActiveControl != NULL))
  9637. {
  9638. ::SetFocus(ActiveControl->Handle);
  9639. if (GetFocus() == ActiveControl->Handle)
  9640. {
  9641. ActiveControl->Perform(CM_UIACTIVATE, 0, 0);
  9642. }
  9643. }
  9644. }
  9645. }
  9646. //---------------------------------------------------------------------------
  9647. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9648. {
  9649. // We need to make sure that window is enabled when the last modal window closes
  9650. // otherwise focus is not restored correctly.
  9651. // So we re-enable the window when modal window opens and
  9652. // disable it back after is closes
  9653. if (FLockLevel > 0)
  9654. {
  9655. // while we have nesting counter, we know that we never be called
  9656. // recursivelly as Application->OnModalBegin is called only
  9657. // for the top-level modal window
  9658. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9659. {
  9660. // won't be disabled when conditions in LockWindow() were not satisfied
  9661. FDisabledOnLockSuspend = !Enabled;
  9662. // When minimized to tray (or actually when set to SW_HIDE),
  9663. // setting Enabled makes the window focusable even when there's
  9664. // modal window over it
  9665. if (!FTrayIcon->Visible)
  9666. {
  9667. Enabled = true;
  9668. }
  9669. }
  9670. FLockSuspendLevel++;
  9671. }
  9672. }
  9673. //---------------------------------------------------------------------------
  9674. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9675. {
  9676. if (FLockSuspendLevel > 0)
  9677. {
  9678. DebugAssert(FLockLevel > 0);
  9679. FLockSuspendLevel--;
  9680. // see comment in SuspendWindowLock
  9681. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9682. {
  9683. // Note that window can be enabled here, when we were minized to tray when
  9684. // was SuspendWindowLock() called.
  9685. // We should possibly do the same check as in LockWindow(),
  9686. // if it is ever possible that the consitions change between
  9687. // SuspendWindowLock() and ResumeWindowLock()
  9688. Enabled = !FDisabledOnLockSuspend;
  9689. }
  9690. }
  9691. }
  9692. //---------------------------------------------------------------------------
  9693. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9694. {
  9695. TTBXComboBoxItem * RemotePathComboBox =
  9696. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9697. if (!TextOnly)
  9698. {
  9699. TStrings * Items = RemotePathComboBox->Strings;
  9700. Items->BeginUpdate();
  9701. try
  9702. {
  9703. Items->Clear();
  9704. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9705. {
  9706. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9707. while (!IsUnixRootPath(APath))
  9708. {
  9709. int P = APath.LastDelimiter(L'/');
  9710. DebugAssert(P >= 0);
  9711. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9712. APath.SetLength(P - 1);
  9713. }
  9714. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9715. }
  9716. }
  9717. __finally
  9718. {
  9719. Items->EndUpdate();
  9720. }
  9721. }
  9722. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9723. // Setting ItemIndex to -1 does not reset its text
  9724. if (RemotePathComboBox->Strings->Count == 0)
  9725. {
  9726. RemotePathComboBox->Text = L"";
  9727. }
  9728. }
  9729. //---------------------------------------------------------------------------
  9730. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9731. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9732. {
  9733. if (AIndex < 0)
  9734. {
  9735. AIndex = Sender->ItemIndex;
  9736. }
  9737. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9738. }
  9739. //---------------------------------------------------------------------------
  9740. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9741. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9742. int & ImageIndex)
  9743. {
  9744. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9745. }
  9746. //---------------------------------------------------------------------------
  9747. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9748. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9749. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9750. {
  9751. if (!IsLocalBrowserMode())
  9752. {
  9753. ARect.Left += (10 * AIndex);
  9754. }
  9755. }
  9756. //---------------------------------------------------------------------------
  9757. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9758. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9759. {
  9760. AWidth += (10 * AIndex);
  9761. }
  9762. //---------------------------------------------------------------------------
  9763. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9764. {
  9765. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9766. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9767. int Index = RemotePathComboBox->ItemIndex;
  9768. while (Index < RemotePathComboBox->Strings->Count - 1)
  9769. {
  9770. APath = UnixExtractFileDir(APath);
  9771. Index++;
  9772. }
  9773. // VanDyke style paths
  9774. if (APath.IsEmpty())
  9775. {
  9776. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9777. APath = ROOTDIRECTORY;
  9778. }
  9779. if (RemoteDirView->Path != APath)
  9780. {
  9781. RemoteDirView->Path = APath;
  9782. }
  9783. }
  9784. //---------------------------------------------------------------------------
  9785. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9786. {
  9787. DoRemotePathComboBoxItemClick(Sender);
  9788. }
  9789. //---------------------------------------------------------------------------
  9790. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9791. {
  9792. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9793. DebugUsedParam(Sender);
  9794. UpdateRemotePathComboBox(true);
  9795. }
  9796. //---------------------------------------------------------------------------
  9797. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9798. {
  9799. DoRemotePathComboBoxCancel(Sender);
  9800. }
  9801. //---------------------------------------------------------------------------
  9802. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9803. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9804. {
  9805. ResetIncrementalSearch();
  9806. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9807. DebugAssert(DirView != NULL);
  9808. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9809. {
  9810. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9811. // OnEditing is called also from TCustomListView::CanEdit
  9812. if (Edit != NULL)
  9813. {
  9814. EditSelectBaseName(Edit);
  9815. }
  9816. }
  9817. }
  9818. //---------------------------------------------------------------------------
  9819. //---------------------------------------------------------------------------
  9820. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9821. {
  9822. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9823. Result->AutoDetectDnD = false;
  9824. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9825. Result->RenderDataOn = rdoEnterAndDropSync;
  9826. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9827. return Result;
  9828. }
  9829. //---------------------------------------------------------------------------
  9830. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9831. {
  9832. if (IsWin10Build(19041))
  9833. {
  9834. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9835. BOOL DarkMode = FImmersiveDarkMode ? TRUE : FALSE;
  9836. const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
  9837. DwmSetWindowAttribute(Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, &DarkMode, sizeof(DarkMode));
  9838. }
  9839. }
  9840. //---------------------------------------------------------------------------
  9841. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9842. {
  9843. TForm::CreateWnd();
  9844. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9845. UpdateDarkMode();
  9846. if (FSessionsDragDropFilesEx == NULL)
  9847. {
  9848. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9849. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9850. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9851. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9852. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9853. }
  9854. if (FQueueDragDropFilesEx == NULL)
  9855. {
  9856. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9857. // No need to set OnDragOver as we do not have any restrictions
  9858. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9859. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9860. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9861. }
  9862. }
  9863. //---------------------------------------------------------------------------
  9864. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9865. {
  9866. TForm::DestroyWnd();
  9867. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9868. FQueueDragDropFilesEx->DragDropControl = NULL;
  9869. }
  9870. //---------------------------------------------------------------------------
  9871. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9872. {
  9873. SideEnter(FCurrentSide);
  9874. FEverShown = true;
  9875. }
  9876. //---------------------------------------------------------------------------
  9877. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9878. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9879. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9880. {
  9881. if (!NonVisualDataModule->Busy)
  9882. {
  9883. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9884. Configuration->Usage->Inc(L"FileFinds");
  9885. LockWindow(true);
  9886. NonVisualDataModule->StartBusy();
  9887. WinConfiguration->LockedInterface = true;
  9888. try
  9889. {
  9890. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9891. }
  9892. __finally
  9893. {
  9894. WinConfiguration->LockedInterface = false;
  9895. NonVisualDataModule->EndBusy();
  9896. UnlockWindow();
  9897. }
  9898. }
  9899. }
  9900. //---------------------------------------------------------------------------
  9901. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9902. {
  9903. if (!NonVisualDataModule->Busy)
  9904. {
  9905. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9906. SetFocus();
  9907. RemoteDirView->Path = UnixExtractFilePath(Path);
  9908. UnicodeString FileName = UnixExtractFileName(Path);
  9909. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9910. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9911. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  9912. if (Item == NULL)
  9913. {
  9914. ReloadDirectory(osRemote);
  9915. Item = RemoteDirView->FindFileItem(FileName);
  9916. }
  9917. if (Item != NULL)
  9918. {
  9919. RemoteDirView->ItemFocused = Item;
  9920. RemoteDirView->ItemFocused->MakeVisible(false);
  9921. RemoteDirView->SetFocus();
  9922. }
  9923. }
  9924. }
  9925. //---------------------------------------------------------------------------
  9926. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  9927. {
  9928. bool Result = !NonVisualDataModule->Busy;
  9929. if (Result)
  9930. {
  9931. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9932. }
  9933. return Result;
  9934. }
  9935. //---------------------------------------------------------------------------
  9936. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  9937. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9938. {
  9939. if (CanOperateOnFoundFiles(ATerminal))
  9940. {
  9941. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished, OnFileOperationFinished);
  9942. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  9943. }
  9944. }
  9945. //---------------------------------------------------------------------------
  9946. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  9947. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9948. {
  9949. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  9950. }
  9951. //---------------------------------------------------------------------------
  9952. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  9953. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9954. {
  9955. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  9956. }
  9957. //---------------------------------------------------------------------------
  9958. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  9959. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9960. {
  9961. if (CanOperateOnFoundFiles(ATerminal))
  9962. {
  9963. for (int Index = 0; Index < FileList->Count; Index++)
  9964. {
  9965. UnicodeString FileName = FileList->Strings[Index];
  9966. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  9967. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  9968. OnFileOperationFinished(osRemote, FileName, true);
  9969. }
  9970. }
  9971. }
  9972. //---------------------------------------------------------------------------
  9973. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  9974. {
  9975. FFileFindTerminal = Terminal;
  9976. ShowFileFindDialog(
  9977. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  9978. DoDownloadFoundFiles, DoEditFoundFiles);
  9979. }
  9980. //---------------------------------------------------------------------------
  9981. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  9982. {
  9983. FTaskbarList = TaskbarList;
  9984. }
  9985. //---------------------------------------------------------------------------
  9986. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  9987. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  9988. {
  9989. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9990. if (Index >= 0)
  9991. {
  9992. if (Button == mbLeft)
  9993. {
  9994. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  9995. // If switching tab (switching session) takes long enough for user
  9996. // to actually release the button, "mouse down" is still raised,
  9997. // but we do not get "mouse up" event, so dragging is not cancelled,
  9998. // prevent that by not beginning dragging in the first place.
  9999. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  10000. if (IsKeyPressed(Key))
  10001. {
  10002. // when user clicks the "+", we get mouse down only after the session
  10003. // is closed, when new session tab is already on X:Y, so dragging
  10004. // starts, prevent that
  10005. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  10006. {
  10007. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10008. if (Terminal != NULL)
  10009. {
  10010. SessionsPageControl->BeginDrag(false);
  10011. }
  10012. }
  10013. }
  10014. }
  10015. else if (Button == mbMiddle)
  10016. {
  10017. // ignore middle-click for "New session tab" and the last local-local tab
  10018. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10019. if ((Session != NULL) && CanCloseSession(Session))
  10020. {
  10021. CloseSessionTab(Index);
  10022. }
  10023. }
  10024. }
  10025. }
  10026. //---------------------------------------------------------------------------
  10027. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  10028. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  10029. {
  10030. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10031. // do not allow dropping on the "+" tab
  10032. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10033. if ((TargetTerminal != NULL) &&
  10034. (SessionsPageControl->ActivePage->PageIndex != Index))
  10035. {
  10036. Configuration->Usage->Inc(L"SessionTabMoves");
  10037. // this is almost redundant as we would recreate tabs in SessionListChanged,
  10038. // but we want to actually prevent that to avoid flicker
  10039. SessionsPageControl->ActivePage->PageIndex = Index;
  10040. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  10041. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  10042. }
  10043. }
  10044. //---------------------------------------------------------------------------
  10045. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  10046. TObject * Sender, TObject * Source, int X, int Y,
  10047. TDragState /*State*/, bool & Accept)
  10048. {
  10049. Accept = (Sender == Source);
  10050. if (Accept)
  10051. {
  10052. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10053. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10054. // do not allow dragging to the "+" tab
  10055. Accept = (Terminal != NULL);
  10056. }
  10057. }
  10058. //---------------------------------------------------------------------------
  10059. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  10060. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  10061. {
  10062. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10063. if (Index < 0)
  10064. {
  10065. Effect = DROPEFFECT_NONE;
  10066. }
  10067. else
  10068. {
  10069. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10070. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  10071. if (!IsActiveTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  10072. {
  10073. Effect = DROPEFFECT_NONE;
  10074. }
  10075. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  10076. {
  10077. Effect = DROPEFFECT_COPY;
  10078. }
  10079. }
  10080. }
  10081. //---------------------------------------------------------------------------
  10082. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  10083. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  10084. {
  10085. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10086. // do not allow dropping on local-local, disconnected and the "+" tab
  10087. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  10088. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10089. if (DebugAlwaysTrue(IsActiveTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  10090. {
  10091. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  10092. if (!IsFileControl(DropSourceControl, osRemote))
  10093. {
  10094. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  10095. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  10096. // Why don't we use Terminal->CurrentDirectory directly?
  10097. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10098. // do not force queue, drag drop
  10099. false, true);
  10100. }
  10101. }
  10102. }
  10103. //---------------------------------------------------------------------------
  10104. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10105. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10106. {
  10107. // Downloads are handled in RemoteFileControlDDEnd
  10108. if (!IsFileControl(DropSourceControl, osRemote))
  10109. {
  10110. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10111. Terminal->CurrentDirectory,
  10112. // force queue, drag drop
  10113. true, true);
  10114. }
  10115. }
  10116. //---------------------------------------------------------------------------
  10117. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10118. {
  10119. FShowing = false;
  10120. // Do not save empty workspace
  10121. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10122. {
  10123. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10124. UnicodeString Name = WorkspaceName();
  10125. DoSaveWorkspace(
  10126. Name, DataList.get(),
  10127. !Configuration->DisablePasswordStoring &&
  10128. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10129. WinConfiguration->LastStoredSession = Name;
  10130. }
  10131. AppLog(L"Closing main window");
  10132. }
  10133. //---------------------------------------------------------------------------
  10134. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10135. {
  10136. TManagedTerminal * ManagedTerminal =
  10137. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10138. if (ManagedTerminal != NULL)
  10139. {
  10140. ManagedTerminal->DirectoryLoaded = Now();
  10141. }
  10142. }
  10143. //---------------------------------------------------------------------------
  10144. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10145. TListItem * /*Item*/, bool /*Selected*/)
  10146. {
  10147. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10148. switch (DirView->LastSelectMethod)
  10149. {
  10150. case smKeyboard:
  10151. Configuration->Usage->Inc(L"KeyboardSelections");
  10152. break;
  10153. case smMouse:
  10154. Configuration->Usage->Inc(L"MouseSelections");
  10155. break;
  10156. }
  10157. }
  10158. //---------------------------------------------------------------------------
  10159. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10160. {
  10161. if (Color != 0)
  10162. {
  10163. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10164. }
  10165. else
  10166. {
  10167. return FSessionTabImageIndex;
  10168. }
  10169. }
  10170. //---------------------------------------------------------------------------
  10171. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10172. {
  10173. TPngImageCollectionItem * Item =
  10174. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10175. FSessionColors->AddPng(Item->PngImage);
  10176. return FSessionColors->Count - 1;
  10177. }
  10178. //---------------------------------------------------------------------------
  10179. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10180. {
  10181. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10182. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10183. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10184. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10185. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10186. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10187. }
  10188. //---------------------------------------------------------------------------
  10189. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10190. {
  10191. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10192. }
  10193. //---------------------------------------------------------------------------
  10194. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10195. {
  10196. switch (Side)
  10197. {
  10198. case osLocal:
  10199. return FNewLocalTabTabImageIndex;
  10200. case osRemote:
  10201. case osCurrent:
  10202. return FNewRemoteTabTabImageIndex;
  10203. default:
  10204. DebugFail();
  10205. return -1;
  10206. }
  10207. }
  10208. //---------------------------------------------------------------------------
  10209. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10210. {
  10211. for (int Index = 0; Index < Control->ControlCount; Index++)
  10212. {
  10213. TControl * AControl = Control->Controls[Index];
  10214. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10215. if (WinControl != NULL)
  10216. {
  10217. CollectItemsWithTextDisplayMode(WinControl);
  10218. }
  10219. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10220. if (Toolbar != NULL)
  10221. {
  10222. // we care for top-level items only
  10223. TTBCustomItem * Items = Toolbar->Items;
  10224. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10225. {
  10226. TTBCustomItem * Item = Items->Items[ItemIndex];
  10227. if (((Item->DisplayMode == nbdmImageAndText) ||
  10228. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10229. EligibleForImageDisplayMode(Item))
  10230. {
  10231. FItemsWithTextDisplayMode.insert(Item);
  10232. }
  10233. }
  10234. }
  10235. }
  10236. }
  10237. //---------------------------------------------------------------------------
  10238. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10239. {
  10240. return true;
  10241. }
  10242. //---------------------------------------------------------------------------
  10243. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10244. {
  10245. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10246. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10247. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10248. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10249. bool Result = true;
  10250. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10251. {
  10252. TTBCustomItem * Item = *i;
  10253. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10254. if (Label != NULL)
  10255. {
  10256. // optimization
  10257. if (Label->Visible == SelectiveToolbarText)
  10258. {
  10259. Result = false;
  10260. }
  10261. else
  10262. {
  10263. Label->Visible = SelectiveToolbarText;
  10264. }
  10265. }
  10266. else
  10267. {
  10268. // optimization
  10269. if (Item->DisplayMode == DisplayMode)
  10270. {
  10271. Result = false;
  10272. }
  10273. else
  10274. {
  10275. Item->DisplayMode = DisplayMode;
  10276. }
  10277. }
  10278. ++i;
  10279. }
  10280. UpdateNewTabTab();
  10281. return Result;
  10282. }
  10283. //---------------------------------------------------------------------------
  10284. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10285. {
  10286. DebugFail();
  10287. }
  10288. //---------------------------------------------------------------------------
  10289. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10290. {
  10291. // Among other, a lock level is non zero, while directory is being loaded,
  10292. // even when it happens as a result of dirview navigation,
  10293. // i.e. when TNonVisualDataModule is NOT FBusy.
  10294. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10295. // Among other this prevents a panel auto update to occur while
  10296. // directory is changing.
  10297. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10298. }
  10299. //---------------------------------------------------------------------------
  10300. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10301. {
  10302. // While the window is disabled, we still seem to process menu shortcuts at least,
  10303. // so stop it at least here.
  10304. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10305. bool Result;
  10306. if (Allowed == aaUpdate)
  10307. {
  10308. Result = true;
  10309. }
  10310. else
  10311. {
  10312. Result = !NonVisualDataModule->Busy;
  10313. if (Result && (Allowed == aaShortCut))
  10314. {
  10315. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10316. Action->Update();
  10317. Result = Action->Enabled;
  10318. }
  10319. }
  10320. return Result;
  10321. }
  10322. //---------------------------------------------------------------------------
  10323. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10324. {
  10325. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10326. }
  10327. //---------------------------------------------------------------------------
  10328. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10329. {
  10330. // This is somewhat redundant to LockWindow() call from
  10331. // TTerminalManager::TerminalReadDirectoryProgress.
  10332. // But disabling window is known not to block keyboard shorcuts
  10333. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10334. if (Busy > 0)
  10335. {
  10336. if (NonVisualDataModule->Busy)
  10337. {
  10338. State = false;
  10339. }
  10340. else
  10341. {
  10342. NonVisualDataModule->StartBusy();
  10343. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10344. LockWindow();
  10345. }
  10346. }
  10347. else if (Busy < 0)
  10348. {
  10349. UnlockWindow();
  10350. NonVisualDataModule->EndBusy();
  10351. }
  10352. else
  10353. {
  10354. State = NonVisualDataModule->Busy;
  10355. }
  10356. }
  10357. //---------------------------------------------------------------------------
  10358. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10359. {
  10360. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10361. if (Index >= 0)
  10362. {
  10363. TPopupMenu * PopupMenu = NULL;
  10364. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10365. if (Session != NULL)
  10366. {
  10367. SessionsPageControl->ActivePageIndex = Index;
  10368. if (DebugAlwaysTrue(SessionTabSwitched()))
  10369. {
  10370. // copied from TControl.WMContextMenu
  10371. SendCancelMode(SessionsPageControl);
  10372. // explicit popup instead of using PopupMenu property
  10373. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10374. // while connecting yet not-connected session and hence
  10375. // allowing an access to commands over not-completely connected session
  10376. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10377. }
  10378. }
  10379. else
  10380. {
  10381. if (SupportsLocalBrowser())
  10382. {
  10383. PopupMenu = NonVisualDataModule->NewTabPopup;
  10384. }
  10385. }
  10386. if (PopupMenu != NULL)
  10387. {
  10388. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10389. PopupMenu->PopupComponent = SessionsPageControl;
  10390. PopupMenu->Popup(Point.x, Point.y);
  10391. }
  10392. }
  10393. Handled = true;
  10394. }
  10395. //---------------------------------------------------------------------------
  10396. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10397. {
  10398. return HasActiveTerminal() && Terminal->IsCapable[fcChangePassword];
  10399. }
  10400. //---------------------------------------------------------------------------
  10401. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10402. {
  10403. Configuration->Usage->Inc(L"PasswordChanges");
  10404. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10405. ChangePasswordData->DisableAuthentationsExceptPassword();
  10406. ChangePasswordData->ChangePassword = true;
  10407. std::unique_ptr<TTerminal> ChangePasswordSession(
  10408. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10409. ChangePasswordSession->AutoReadDirectory = false;
  10410. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10411. {
  10412. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10413. }
  10414. else
  10415. {
  10416. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10417. }
  10418. }
  10419. //---------------------------------------------------------------------------
  10420. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10421. {
  10422. // No nice way to assert SSH2
  10423. return HasActiveTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10424. }
  10425. //---------------------------------------------------------------------------
  10426. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10427. {
  10428. TOperationVisualizer OperationVisualizer;
  10429. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10430. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10431. }
  10432. //---------------------------------------------------------------------------
  10433. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  10434. {
  10435. TForm::ChangeScale(M, D);
  10436. int APixelsPerInch = GetControlPixelsPerInch(this);
  10437. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  10438. try
  10439. {
  10440. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  10441. }
  10442. __finally
  10443. {
  10444. GUIConfiguration->ChangeResourceModule(ResourceModule);
  10445. }
  10446. }
  10447. //---------------------------------------------------------------------------
  10448. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10449. {
  10450. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10451. }
  10452. //---------------------------------------------------------------------
  10453. class TPublicControl : public TControl
  10454. {
  10455. friend class TCustomScpExplorerForm;
  10456. };
  10457. //---------------------------------------------------------------------------
  10458. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10459. {
  10460. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10461. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10462. }
  10463. //---------------------------------------------------------------------------
  10464. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10465. {
  10466. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10467. OpenBookmark(Side, Bookmark);
  10468. }
  10469. //---------------------------------------------------------------------------
  10470. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10471. {
  10472. DoBookmarkClick(osLocal, Sender);
  10473. }
  10474. //---------------------------------------------------------------------------
  10475. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10476. {
  10477. DoBookmarkClick(osRemote, Sender);
  10478. }
  10479. //---------------------------------------------------------------------------
  10480. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10481. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10482. {
  10483. if (BookmarkList != NULL)
  10484. {
  10485. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10486. if (IsLocalBrowserMode())
  10487. {
  10488. Side = osLocal;
  10489. }
  10490. if (!WinConfiguration->UseLocationProfiles)
  10491. {
  10492. std::unique_ptr<TStringList> Directories(new TStringList());
  10493. Directories->CaseSensitive = (Side == osRemote);
  10494. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10495. {
  10496. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10497. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10498. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10499. {
  10500. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10501. Item->Caption = EscapeHotkey(Directory);
  10502. Item->ShortCut = Bookmark->ShortCut;
  10503. Item->OnClick = OnBookmarkClick;
  10504. Item->Tag = reinterpret_cast<int>(Bookmark);
  10505. Directories->Add(Directory);
  10506. Menu->Add(Item.release());
  10507. }
  10508. }
  10509. }
  10510. else
  10511. {
  10512. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10513. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10514. {
  10515. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10516. if (!Bookmark->Node.IsEmpty())
  10517. {
  10518. Folders->Add(Bookmark->Node);
  10519. }
  10520. }
  10521. for (int Index = 0; Index < Folders->Count; Index++)
  10522. {
  10523. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10524. Item->Caption = Folders->Strings[Index];
  10525. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10526. Folders->Objects[Index] = Item.get();
  10527. Menu->Add(Item.release());
  10528. }
  10529. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10530. {
  10531. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10532. TTBCustomItem * Parent;
  10533. if (!Bookmark->Node.IsEmpty())
  10534. {
  10535. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10536. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10537. }
  10538. else
  10539. {
  10540. Parent = Menu;
  10541. }
  10542. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10543. Item->Caption = Bookmark->Name;
  10544. Item->ShortCut = Bookmark->ShortCut;
  10545. Item->OnClick = OnBookmarkClick;
  10546. Item->Tag = reinterpret_cast<int>(Bookmark);
  10547. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10548. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10549. {
  10550. // No hint for location profiles that are actually mere "bookmarks"
  10551. }
  10552. else
  10553. {
  10554. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10555. UnicodeString LongHint;
  10556. if (!Bookmark->Local.IsEmpty())
  10557. {
  10558. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10559. }
  10560. if (!Bookmark->Remote.IsEmpty())
  10561. {
  10562. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10563. }
  10564. AddToList(Hint, LongHint, L"|");
  10565. Item->Hint = Hint;
  10566. }
  10567. Parent->Add(Item.release());
  10568. }
  10569. }
  10570. AddMenuSeparator(Menu);
  10571. }
  10572. }
  10573. //---------------------------------------------------------------------------
  10574. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10575. {
  10576. Menu->Clear();
  10577. std::unique_ptr<TTBCustomItem> Item;
  10578. Item.reset(new TTBXItem(Owner));
  10579. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10580. Item->Options = Item->Options << tboDefault;
  10581. Menu->Add(Item.release());
  10582. AddMenuSeparator(Menu);
  10583. if (Terminal != NULL)
  10584. {
  10585. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10586. }
  10587. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10588. Item.reset(new TTBXItem(Owner));
  10589. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10590. Menu->Add(Item.release());
  10591. }
  10592. //---------------------------------------------------------------------------
  10593. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10594. {
  10595. bool Result = true;
  10596. bool Remote = !IsSideLocalBrowser(Side);
  10597. try
  10598. {
  10599. UnicodeString APath = Path;
  10600. if (Remote)
  10601. {
  10602. Terminal->ExceptionOnFail = true;
  10603. }
  10604. else
  10605. {
  10606. APath = ExpandEnvironmentVariables(Path);
  10607. }
  10608. try
  10609. {
  10610. DirView(Side)->Path = APath;
  10611. }
  10612. __finally
  10613. {
  10614. if (Remote)
  10615. {
  10616. Terminal->ExceptionOnFail = false;
  10617. }
  10618. }
  10619. }
  10620. catch (Exception & E)
  10621. {
  10622. if (!Remote || Terminal->Active)
  10623. {
  10624. ShowExtendedExceptionEx(Terminal, &E);
  10625. Result = false;
  10626. }
  10627. else
  10628. {
  10629. throw;
  10630. }
  10631. }
  10632. return Result;
  10633. }
  10634. //---------------------------------------------------------------------------
  10635. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10636. {
  10637. // Make sure there some feedback even when loading tiny local folders
  10638. TInstantOperationVisualizer Visualizer;
  10639. DirView(Side)->ReloadDirectory();
  10640. }
  10641. //---------------------------------------------------------------------------
  10642. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10643. {
  10644. if (Index == SessionsPageControl->TabIndex)
  10645. {
  10646. CloseTab();
  10647. }
  10648. else
  10649. {
  10650. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10651. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10652. TTerminalManager * Manager = TTerminalManager::Instance();
  10653. if (!Terminal->Active)
  10654. {
  10655. Manager->FreeTerminal(Terminal);
  10656. }
  10657. else
  10658. {
  10659. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10660. if (CanCloseQueue(Queue))
  10661. {
  10662. Manager->FreeTerminal(Terminal);
  10663. }
  10664. }
  10665. }
  10666. }
  10667. //---------------------------------------------------------------------------
  10668. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10669. {
  10670. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10671. if (Session == NULL)
  10672. {
  10673. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10674. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10675. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10676. //P = SessionsPageControl->ClientToScreen(P);
  10677. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10678. }
  10679. else
  10680. {
  10681. CloseSessionTab(Index);
  10682. }
  10683. }
  10684. //---------------------------------------------------------------------------
  10685. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10686. {
  10687. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10688. {
  10689. TInstantOperationVisualizer Visualizer;
  10690. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10691. // before we create a new data object
  10692. ClipboardClear();
  10693. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10694. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10695. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10696. // Intermediate variable to WORKAROUND a crash in compiler
  10697. TObjectList * ClipboardFakeMonitors =
  10698. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10699. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10700. if (FClipboardDragDropFilesEx.get() == NULL)
  10701. {
  10702. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10703. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10704. }
  10705. FClipboardDragDropFilesEx->FileList->Clear();
  10706. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10707. FClipboardDragDropFilesEx->CopyToClipboard();
  10708. FClipboardTerminal = Terminal;
  10709. // Need full paths, as cwd can be different once files are pasted
  10710. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10711. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10712. {
  10713. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10714. }
  10715. AppLogFmt(L"Created fake clipboard directory \"%s\" and started drive monitors", (FClipboardFakeDirectory));
  10716. }
  10717. }
  10718. //---------------------------------------------------------------------------
  10719. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10720. {
  10721. if (OpenClipboard(0))
  10722. {
  10723. AppLog(L"Clearing clipboard");
  10724. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10725. CloseClipboard();
  10726. }
  10727. }
  10728. //---------------------------------------------------------------------------
  10729. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10730. {
  10731. return !FClipboardFakeDirectory.IsEmpty();
  10732. }
  10733. //---------------------------------------------------------------------------
  10734. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10735. {
  10736. bool Deleted = RemoveDir(ApiPath(FClipboardFakeDirectory));
  10737. AppLogFmt(L"Clearing clipboard, deleted clipboard temporary folder \"%s\" - %d", (FClipboardFakeDirectory, int(Deleted)));
  10738. FClipboardFakeDirectory = UnicodeString();
  10739. FClipboardTerminal = NULL;
  10740. if (FDownloadingFromClipboard)
  10741. {
  10742. // We are called by the monitor, so attempt to release it would deadlock
  10743. FClipboardFakeMonitorsPendingReset = true;
  10744. }
  10745. else
  10746. {
  10747. FClipboardFakeMonitors.reset(NULL);
  10748. }
  10749. }
  10750. //---------------------------------------------------------------------------
  10751. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10752. {
  10753. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10754. {
  10755. ClipboardStop();
  10756. }
  10757. }
  10758. //---------------------------------------------------------------------------
  10759. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10760. {
  10761. TTerminalManager * Manager = TTerminalManager::Instance();
  10762. Manager->ActiveSession = FClipboardTerminal;
  10763. TTransferOperationParam Params;
  10764. Params.TargetDirectory = TargetDirectory;
  10765. Params.DragDrop = DragDrop;
  10766. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10767. }
  10768. //---------------------------------------------------------------------------
  10769. void TCustomScpExplorerForm::PasteFiles()
  10770. {
  10771. // Guard against possible race conditions
  10772. if (!FClipboardPasteTarget.IsEmpty())
  10773. {
  10774. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10775. UnicodeString Target = FClipboardPasteTarget;
  10776. FClipboardPasteTarget = EmptyStr;
  10777. // Can fail as it can be e.g. locked by AV, so we retry that later
  10778. bool Removed = RemoveDir(ApiPath(Target));
  10779. AppLogFmt(L"First attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10780. try
  10781. {
  10782. if (NonVisualDataModule->Busy)
  10783. {
  10784. AppLog(L"Is busy, cannot paste");
  10785. }
  10786. else
  10787. {
  10788. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10789. FClipboardFakeMonitorsPendingReset = false;
  10790. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10791. TAutoFlag Flag(FDownloadingFromClipboard);
  10792. AppLog(L"Downloading to paste target...");
  10793. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10794. AppLog(L"Downloaded to paste target...");
  10795. }
  10796. }
  10797. __finally
  10798. {
  10799. if (!Removed)
  10800. {
  10801. Removed = RemoveDir(ApiPath(Target));
  10802. AppLogFmt(L"Second attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10803. }
  10804. }
  10805. }
  10806. }
  10807. //---------------------------------------------------------------------------
  10808. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10809. {
  10810. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10811. // (as it pumps a Windows message queue while being shutted down)
  10812. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10813. // Is can happen that creation of our temporary directory is detected (even though we are creating it before starting the monitors).
  10814. // It tent do happen with later copy-pastes, probably because everything is cached already and monitors start quickly.
  10815. !IsPathToSameFile(FClipboardFakeDirectory, FileName) &&
  10816. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10817. {
  10818. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10819. FClipboardPasteTarget = FileName;
  10820. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10821. // Postponing removing (or actually whole pasting operation) seems to help.
  10822. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10823. }
  10824. }
  10825. //---------------------------------------------------------------------------
  10826. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10827. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10828. {
  10829. TFileMasks::TParams MaskParams;
  10830. MaskParams.Size = Size;
  10831. MaskParams.Modification = Modification;
  10832. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10833. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10834. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10835. if (!Local && Directory)
  10836. {
  10837. FileName = UnixExcludeTrailingBackslash(FileName);
  10838. }
  10839. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10840. {
  10841. bool ImplicitMatch;
  10842. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10843. !ImplicitMatch)
  10844. {
  10845. Color = Iter->Color;
  10846. break;
  10847. }
  10848. }
  10849. }
  10850. //---------------------------------------------------------------------------
  10851. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10852. {
  10853. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10854. if (!DirView->IsEditing())
  10855. {
  10856. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10857. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10858. // while searching
  10859. if (Key == VK_BACK)
  10860. {
  10861. if (FIncrementalSearchState.Searching)
  10862. {
  10863. if (FIncrementalSearchState.Text.Length() <= 1)
  10864. {
  10865. ResetIncrementalSearch();
  10866. }
  10867. else
  10868. {
  10869. UnicodeString NewText = LeftStr(FIncrementalSearchState.Text, FIncrementalSearchState.Text.Length() - 1);
  10870. IncrementalSearch(NewText, false, false);
  10871. }
  10872. Key = 0;
  10873. }
  10874. }
  10875. }
  10876. }
  10877. //---------------------------------------------------------------------------
  10878. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10879. {
  10880. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10881. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10882. {
  10883. // Filter control sequences.
  10884. // When not searching yet, prefer use of the space for toggling file selection
  10885. // (so we cannot incrementally search for a string starting with a space).
  10886. if ((Key > VK_SPACE) ||
  10887. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && !FIncrementalSearchState.Searching))
  10888. {
  10889. IncrementalSearch(FIncrementalSearchState.Text + Key, false, false);
  10890. Key = 0;
  10891. }
  10892. }
  10893. }
  10894. //---------------------------------------------------------------------------
  10895. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10896. {
  10897. if (FIncrementalSearchState.Searching)
  10898. {
  10899. FIncrementalSearchState.Reset();
  10900. DirView(osCurrent)->UpdateStatusBar();
  10901. }
  10902. }
  10903. //---------------------------------------------------------------------------
  10904. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10905. {
  10906. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  10907. if (Item == NULL)
  10908. {
  10909. MessageBeep(MB_ICONHAND);
  10910. }
  10911. else
  10912. {
  10913. TCustomDirView * ADirView = DirView(osCurrent);
  10914. {
  10915. TAutoNestingCounter Guard(FIncrementalSearching);
  10916. ADirView->FocusItem(Item);
  10917. if (ADirView->NortonLike == nlOff)
  10918. {
  10919. if ((ADirView->Selected != Item) ||
  10920. (ADirView->SelCount > 1))
  10921. {
  10922. ADirView->ClearSelection();
  10923. ADirView->Selected = Item;
  10924. }
  10925. }
  10926. }
  10927. FIncrementalSearchState.Searching = true;
  10928. FIncrementalSearchState.Text = Text;
  10929. Item->MakeVisible(false);
  10930. TListItem * NextItem = SearchFile(Text, true, Reverse);
  10931. FIncrementalSearchState.HaveNext = (NextItem != NULL) && (NextItem != Item);
  10932. ADirView->UpdateStatusBar();
  10933. }
  10934. }
  10935. //---------------------------------------------------------------------------
  10936. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  10937. {
  10938. int Index = Item->Index;
  10939. if (!Reverse)
  10940. {
  10941. Index++;
  10942. if (Index >= Item->Owner->Count)
  10943. {
  10944. Index = 0;
  10945. }
  10946. }
  10947. else
  10948. {
  10949. Index--;
  10950. if (Index < 0)
  10951. {
  10952. Index = Item->Owner->Count - 1;
  10953. }
  10954. }
  10955. return Item->Owner->Item[Index];
  10956. }
  10957. //---------------------------------------------------------------------------
  10958. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10959. {
  10960. TCustomDirView * ADirView = DirView(osCurrent);
  10961. if (ADirView->Items->Count == 0)
  10962. {
  10963. return NULL;
  10964. }
  10965. else
  10966. {
  10967. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  10968. TListItem * Item = CurrentItem;
  10969. if (SkipCurrent)
  10970. {
  10971. Item = DebugNotNull(GetNextFile(Item, Reverse));
  10972. }
  10973. while (true)
  10974. {
  10975. bool Matches = false;
  10976. switch (WinConfiguration->PanelSearch)
  10977. {
  10978. case isNameStartOnly:
  10979. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  10980. break;
  10981. case isName:
  10982. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  10983. break;
  10984. case isAll:
  10985. int ColCount = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Count : 1;
  10986. int Index = 0;
  10987. while ((Index < ColCount) && !Matches)
  10988. {
  10989. bool Visible = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Visible[Index] : true;
  10990. if (Visible)
  10991. {
  10992. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  10993. }
  10994. Index++;
  10995. }
  10996. break;
  10997. }
  10998. if (Matches)
  10999. {
  11000. return Item;
  11001. }
  11002. Item = GetNextFile(Item, Reverse);
  11003. if (Item == CurrentItem)
  11004. {
  11005. return NULL;
  11006. }
  11007. }
  11008. }
  11009. }
  11010. //---------------------------------------------------------------------------
  11011. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  11012. {
  11013. ResetIncrementalSearch();
  11014. }
  11015. //---------------------------------------------------------------------------
  11016. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  11017. {
  11018. if (Message.CharCode == VK_TAB)
  11019. {
  11020. if (!FIncrementalSearchState.Text.IsEmpty())
  11021. {
  11022. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  11023. bool Reverse = Shift.Contains(ssShift);
  11024. IncrementalSearch(FIncrementalSearchState.Text, true, Reverse);
  11025. Message.Result = 1;
  11026. return;
  11027. }
  11028. }
  11029. else if (Message.CharCode == VK_ESCAPE)
  11030. {
  11031. if (FIncrementalSearchState.Searching)
  11032. {
  11033. ResetIncrementalSearch();
  11034. Message.Result = 1;
  11035. return;
  11036. }
  11037. }
  11038. TForm::Dispatch(&Message);
  11039. }
  11040. //---------------------------------------------------------------------------
  11041. void __fastcall TCustomScpExplorerForm::Deactivate()
  11042. {
  11043. TForm::Deactivate();
  11044. // E.g. when switching to an internal editor window
  11045. ResetIncrementalSearch();
  11046. }
  11047. //---------------------------------------------------------------------------
  11048. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  11049. {
  11050. // When switching to another application
  11051. ResetIncrementalSearch();
  11052. }
  11053. //---------------------------------------------------------------------------
  11054. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  11055. {
  11056. ResetIncrementalSearch();
  11057. }
  11058. //---------------------------------------------------------------------------
  11059. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  11060. {
  11061. if (FIncrementalSearching <= 0)
  11062. {
  11063. ResetIncrementalSearch();
  11064. }
  11065. }
  11066. //---------------------------------------------------------------------------
  11067. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  11068. {
  11069. CountClicksForWindowPrint(this);
  11070. }
  11071. //---------------------------------------------------------------------------
  11072. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  11073. {
  11074. CenterReconnectToolbar();
  11075. }
  11076. //---------------------------------------------------------------------------
  11077. void TCustomScpExplorerForm::DoBrowseFile(TCustomDirView * DirView, const UnicodeString & FileName)
  11078. {
  11079. if (!FileName.IsEmpty())
  11080. {
  11081. DirView->RestoreFocus(FileName);
  11082. if (DirView->ItemFocused != NULL)
  11083. {
  11084. DirView->ItemFocused->Selected = true;
  11085. }
  11086. }
  11087. }
  11088. //---------------------------------------------------------------------------
  11089. void __fastcall TCustomScpExplorerForm::BrowseFile(const UnicodeString & FileName)
  11090. {
  11091. DoBrowseFile(RemoteDirView, FileName);
  11092. }
  11093. //---------------------------------------------------------------------------
  11094. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  11095. {
  11096. if (!FQueueStatusUpdating)
  11097. {
  11098. bool Refresh;
  11099. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  11100. {
  11101. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  11102. }
  11103. else
  11104. {
  11105. if (FQueueFileList->GetCount() > 0)
  11106. {
  11107. FQueueFileList->Clear();
  11108. Refresh = true;
  11109. }
  11110. }
  11111. int Count = FQueueFileList->GetCount();
  11112. if (QueueFileList->Items->Count != Count)
  11113. {
  11114. DebugAssert(Refresh);
  11115. QueueFileList->Items->Count = Count;
  11116. }
  11117. if (Refresh)
  11118. {
  11119. QueueFileList->Invalidate();
  11120. }
  11121. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  11122. }
  11123. }
  11124. //---------------------------------------------------------------------------
  11125. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  11126. {
  11127. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  11128. }
  11129. //---------------------------------------------------------------------------
  11130. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  11131. {
  11132. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  11133. // See TSynchronizeChecklistDialog::UpdateTimer
  11134. if (QueueFileList->Items->Count > 0)
  11135. {
  11136. QueueFileList->Items->Item[0]->MakeVisible(false);
  11137. }
  11138. UpdateQueueFileList();
  11139. }
  11140. //---------------------------------------------------------------------------
  11141. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  11142. {
  11143. Active = QueueView3->Focused() || QueueFileList->Focused();
  11144. }
  11145. //---------------------------------------------------------------------------
  11146. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11147. {
  11148. QueueLabelUpdateStatus();
  11149. }
  11150. //---------------------------------------------------------------------------
  11151. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11152. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11153. {
  11154. int State = FQueueFileList->GetState(Item->Index);
  11155. if (State == qfsProcessed)
  11156. {
  11157. Sender->Canvas->Font->Color = clGrayText;
  11158. }
  11159. }
  11160. //---------------------------------------------------------------------------
  11161. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11162. {
  11163. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11164. QueueFileList->Column[0]->Width =
  11165. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11166. }
  11167. //---------------------------------------------------------------------------
  11168. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11169. {
  11170. QueueFileListColumnAutoSize();
  11171. }
  11172. //---------------------------------------------------------------------------
  11173. void __fastcall TCustomScpExplorerForm::CloseApp()
  11174. {
  11175. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11176. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11177. // So we clear the flag here.
  11178. DebugAssert(NonVisualDataModule->Busy);
  11179. NonVisualDataModule->EndBusy();
  11180. try
  11181. {
  11182. Close();
  11183. }
  11184. __finally
  11185. {
  11186. NonVisualDataModule->StartBusy();
  11187. }
  11188. }
  11189. //---------------------------------------------------------------------------
  11190. bool __fastcall TCustomScpExplorerForm::IsActiveTerminal(TTerminal * Terminal)
  11191. {
  11192. return (Terminal != NULL) && Terminal->Active;
  11193. }
  11194. //---------------------------------------------------------------------------
  11195. bool __fastcall TCustomScpExplorerForm::HasManagedSession()
  11196. {
  11197. return (ManagedSession != NULL);
  11198. }
  11199. //---------------------------------------------------------------------------
  11200. bool __fastcall TCustomScpExplorerForm::HasActiveTerminal()
  11201. {
  11202. return IsActiveTerminal(Terminal);
  11203. }
  11204. //---------------------------------------------------------------------------
  11205. void TCustomScpExplorerForm::LocalLocalCopy(
  11206. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11207. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11208. {
  11209. DebugFail();
  11210. }
  11211. //---------------------------------------------------------------------------
  11212. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11213. {
  11214. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11215. }
  11216. //---------------------------------------------------------------------------
  11217. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11218. {
  11219. // 1) Changing tab list triggers the OnResize.
  11220. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11221. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11222. {
  11223. // UpdateTabsCaptionTruncation should be enough
  11224. SessionListChanged(true);
  11225. }
  11226. }
  11227. //---------------------------------------------------------------------------
  11228. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11229. {
  11230. if (ASession == ManagedSession)
  11231. {
  11232. UpdateSession(ASession);
  11233. }
  11234. TSessionData * Data = ASession->StateData;
  11235. UnicodeString Result;
  11236. if (Side == osLocal)
  11237. {
  11238. Result = Data->LocalDirectory;
  11239. }
  11240. else if (DebugAlwaysTrue(Side == osOther))
  11241. {
  11242. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11243. }
  11244. return Result;
  11245. }
  11246. //---------------------------------------------------------------------------
  11247. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11248. {
  11249. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11250. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11251. if (Title == Result)
  11252. {
  11253. Result = EmptyStr;
  11254. }
  11255. else
  11256. {
  11257. Result += L"\n";
  11258. }
  11259. return Result;
  11260. }
  11261. //---------------------------------------------------------------------------
  11262. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11263. {
  11264. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11265. if (!ASession->Active)
  11266. {
  11267. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11268. }
  11269. else
  11270. {
  11271. Result += GetSessionPath(ASession, osRemote);
  11272. }
  11273. return Result;
  11274. }
  11275. //---------------------------------------------------------------------------
  11276. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11277. {
  11278. return LoadStr(NEW_REMOTE_TAB_HINT);
  11279. }
  11280. //---------------------------------------------------------------------------
  11281. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11282. {
  11283. if (Index >= 0)
  11284. {
  11285. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11286. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11287. if (TabSession == NULL)
  11288. {
  11289. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11290. if (NewTabTabCaption != TabSheet->Caption)
  11291. {
  11292. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11293. }
  11294. }
  11295. else
  11296. {
  11297. TTerminalManager * Manager = TTerminalManager::Instance();
  11298. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11299. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11300. }
  11301. }
  11302. }
  11303. //---------------------------------------------------------------------------
  11304. typedef std::vector<TListItem *> TListItemsVector;
  11305. struct TCalculateSizeOperation
  11306. {
  11307. TCalculateSizeStats Stats;
  11308. TListItemsVector ListItems;
  11309. size_t Index;
  11310. };
  11311. //---------------------------------------------------------------------------
  11312. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11313. {
  11314. TCalculateSizeOperation CalculateSizeOperation;
  11315. Side = GetSide(Side);
  11316. TCustomDirView * ADirView = DirView(Side);
  11317. bool LocalSide = IsSideLocalBrowser(Side);
  11318. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11319. std::unique_ptr<TStrings> FileList(new TStringList());
  11320. for (int Index = 0; Index < AllFileList->Count; Index++)
  11321. {
  11322. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11323. if (ADirView->ItemIsDirectory(Item))
  11324. {
  11325. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11326. CalculateSizeOperation.ListItems.push_back(Item);
  11327. }
  11328. }
  11329. CalculateSizeOperation.Index = 0;
  11330. __int64 Size = 0;
  11331. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation, &CalculateSizeOperation);
  11332. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11333. FOnFileOperationFinished = DirectorySizeCalculated;
  11334. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation, foCalculateSize);
  11335. TCalculatedSizes CalculatedSizes;
  11336. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11337. if (LocalSide)
  11338. {
  11339. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, Side);
  11340. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11341. }
  11342. else
  11343. {
  11344. TCalculateSizeParams Params;
  11345. Params.Stats = &CalculateSizeOperation.Stats;
  11346. Params.UseCache = true;
  11347. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11348. }
  11349. }
  11350. //---------------------------------------------------------------------------
  11351. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(TOperationSide Side, const UnicodeString & FileName, bool Success)
  11352. {
  11353. DebugAlwaysTrue(FCalculateSizeOperation != NULL);
  11354. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11355. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11356. // optimization
  11357. bool GotExpectedItem =
  11358. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11359. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11360. int Index = -1;
  11361. if (DebugAlwaysTrue(GotExpectedItem))
  11362. {
  11363. Index = FCalculateSizeOperation->Index;
  11364. FCalculateSizeOperation->Index++;
  11365. }
  11366. else
  11367. {
  11368. TListItemsVector::iterator I =
  11369. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11370. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11371. {
  11372. Index = I - FCalculateSizeOperation->ListItems.begin();
  11373. }
  11374. }
  11375. if (DebugAlwaysTrue(Index >= 0) && Success)
  11376. {
  11377. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11378. ADirView->SetItemCalculatedSize(Item, Size);
  11379. }
  11380. }
  11381. //---------------------------------------------------------------------------
  11382. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11383. {
  11384. Accept = false;
  11385. }
  11386. //---------------------------------------------------------------------------
  11387. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11388. {
  11389. // Send Ctrl+Gray+ to the list view
  11390. TKeyboardState KeyState;
  11391. GetKeyboardState(KeyState);
  11392. TKeyboardState NewKeyState;
  11393. memset(NewKeyState, 0, sizeof(NewKeyState));
  11394. NewKeyState[VK_CONTROL] = 0x81;
  11395. SetKeyboardState(NewKeyState);
  11396. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11397. SetKeyboardState(KeyState);
  11398. }
  11399. //---------------------------------------------------------------------------
  11400. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11401. {
  11402. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11403. }
  11404. //---------------------------------------------------------------------------
  11405. void * TCustomScpExplorerForm::SaveFocus()
  11406. {
  11407. return NULL;
  11408. }
  11409. //---------------------------------------------------------------------------
  11410. void TCustomScpExplorerForm::RestoreFocus(void * Focus)
  11411. {
  11412. DebugUsedParam(Focus);
  11413. DebugAssert(Focus == NULL);
  11414. }
  11415. //---------------------------------------------------------------------------
  11416. void TCustomScpExplorerForm::IncrementalSearchStart()
  11417. {
  11418. TCustomDirView * ADirView = DirView(osCurrent);
  11419. ADirView->SetFocus();
  11420. if (!FIncrementalSearchState.Searching)
  11421. {
  11422. FIncrementalSearchState.Searching = true;
  11423. FIncrementalSearchState.HaveNext = false;
  11424. DebugAssert(FIncrementalSearchState.Text.IsEmpty());
  11425. ADirView->UpdateStatusBar();
  11426. }
  11427. }