CustomScpExplorer.cpp 405 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include <Common.h>
  6. #include "CustomScpExplorer.h"
  7. #include <algorithm>
  8. #include <Bookmarks.h>
  9. #include <Interface.h>
  10. #include <Exceptions.h>
  11. #include <CoreMain.h>
  12. #include <FileSystems.h>
  13. #include <TextsCore.h>
  14. #include <TextsWin.h>
  15. #include <HelpWin.h>
  16. #include <VCLCommon.h>
  17. #include <Progress.h>
  18. #include <SynchronizeProgress.h>
  19. #include <DragExt.h>
  20. #include <WinApi.h>
  21. #include "GUITools.h"
  22. #include "NonVisual.h"
  23. #include "Glyphs.h"
  24. #include "Tools.h"
  25. #include "WinConfiguration.h"
  26. #include "TerminalManager.h"
  27. #include "EditorManager.h"
  28. #include "ProgParams.h"
  29. #include "Setup.h"
  30. #include <Consts.hpp>
  31. #include <DateUtils.hpp>
  32. #include <TB2Common.hpp>
  33. #include <DirectoryMonitor.hpp>
  34. #include <System.IOUtils.hpp>
  35. //---------------------------------------------------------------------------
  36. #pragma package(smart_init)
  37. #pragma link "CustomDirView"
  38. #pragma link "CustomUnixDirView"
  39. #pragma link "IEListView"
  40. #pragma link "NortonLikeListView"
  41. #pragma link "UnixDirView"
  42. #pragma link "CustomDriveView"
  43. #pragma link "UnixDriveView"
  44. #pragma link "CustomDriveView"
  45. #pragma link "TB2Dock"
  46. #pragma link "TBXStatusBars"
  47. #pragma link "TB2Item"
  48. #pragma link "TB2Toolbar"
  49. #pragma link "ThemePageControl"
  50. #pragma link "PathLabel"
  51. #pragma resource "*.dfm"
  52. //---------------------------------------------------------------------------
  53. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  54. #define WM_PASTE_FILES (WM_WINSCP_USER + 14)
  55. static const int SessionPanelCount = 3;
  56. //---------------------------------------------------------------------------
  57. class TMutexGuard
  58. {
  59. public:
  60. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  61. int Timeout = 5000)
  62. {
  63. FMutex = NULL;
  64. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  65. if (WaitResult == WAIT_TIMEOUT)
  66. {
  67. throw Exception(LoadStr(MUTEX_RELEASE_TIMEOUT));
  68. }
  69. else
  70. {
  71. FMutex = AMutex;
  72. }
  73. }
  74. ~TMutexGuard()
  75. {
  76. if (FMutex != NULL)
  77. {
  78. ReleaseMutex(FMutex);
  79. }
  80. }
  81. private:
  82. HANDLE FMutex;
  83. };
  84. //---------------------------------------------------------------------------
  85. class TWindowLock
  86. {
  87. public:
  88. TWindowLock(TCustomScpExplorerForm * Form) :
  89. FForm(Form)
  90. {
  91. FForm->LockWindow();
  92. }
  93. ~TWindowLock()
  94. {
  95. FForm->UnlockWindow();
  96. }
  97. private:
  98. TCustomScpExplorerForm * FForm;
  99. };
  100. //---------------------------------------------------------------------------
  101. TAutoBatch::TAutoBatch(TCustomScpExplorerForm * Form) :
  102. FForm(Form)
  103. {
  104. FForm->BatchStart(FBatchStorage);
  105. }
  106. //---------------------------------------------------------------------------
  107. TAutoBatch::~TAutoBatch()
  108. {
  109. FForm->BatchEnd(FBatchStorage);
  110. }
  111. //---------------------------------------------------------------------------
  112. struct TTransferOperationParam
  113. {
  114. TTransferOperationParam();
  115. UnicodeString TargetDirectory;
  116. bool Temp;
  117. bool DragDrop;
  118. int Options;
  119. TAutoSwitch Queue;
  120. };
  121. //---------------------------------------------------------------------------
  122. TTransferOperationParam::TTransferOperationParam()
  123. {
  124. Temp = false;
  125. DragDrop = false;
  126. Options = 0;
  127. Queue = asAuto;
  128. }
  129. //---------------------------------------------------------------------------
  130. class TTransferPresetNoteData : public TObject
  131. {
  132. public:
  133. UnicodeString Message;
  134. };
  135. //---------------------------------------------------------------------------
  136. class TTerminalNoteData : public TObject
  137. {
  138. public:
  139. TManagedTerminal * Terminal;
  140. };
  141. //---------------------------------------------------------------------------
  142. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  143. FFormRestored(false),
  144. TForm(Owner)
  145. {
  146. AddStartupSequence(L"F");
  147. FInvalid = false;
  148. FCurrentSide = osRemote;
  149. FEverShown = false;
  150. FDocks = new TList();
  151. InitControls();
  152. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  153. // So that UpdateCustomCommandsToolbar called from RestoreParams works
  154. NonVisualDataModule->ScpExplorer = this;
  155. RestoreParams();
  156. ConfigurationChanged();
  157. RemoteDirView->Invalidate();
  158. FAutoOperation = false;
  159. FOnFileOperationFinished = NULL;
  160. FPrimaryOperation = foNone;
  161. FForceExecution = false;
  162. FIgnoreNextDialogChar = 0;
  163. FErrorList = NULL;
  164. FSynchronizeProgressForm = NULL;
  165. FProgressForm = NULL;
  166. FRefreshLocalDirectory = false;
  167. FRefreshRemoteDirectory = false;
  168. FDDExtMapFile = NULL;
  169. // CreateMutexW keeps failing with ERROR_NOACCESS
  170. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  171. DebugAssert(FDDExtMutex != NULL);
  172. FDDTargetControl = NULL;
  173. FDelayedDeletionTimer = NULL;
  174. FDelayedDeletionList = new TStringList();
  175. FDDFileList = NULL;
  176. FPendingTempSpaceWarn = false;
  177. FCapturedLog = NULL;
  178. FDragDropOperation = false;
  179. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  180. FAllowTransferPresetAutoSelect = true;
  181. FSessionChanging = false;
  182. FCopyParamDefault = L"";
  183. FSynchronizeController = NULL;
  184. FPendingQueueActionItem = NULL;
  185. FLockLevel = 0;
  186. FLockSuspendLevel = 0;
  187. FDisabledOnLockSuspend = false;
  188. FAlternativeDelete = false;
  189. FTrayIcon = new ::TTrayIcon(0);
  190. FTrayIcon->OnClick = TrayIconClick;
  191. FMaxQueueLength = 0;
  192. FLastContextPopupScreenPoint = TPoint(-1, -1);
  193. FTransferResumeList = NULL;
  194. FDeletedFiles = NULL;
  195. FMoveToQueue = false;
  196. StandaloneOperation = false;
  197. FOnFeedSynchronizeError = NULL;
  198. FOnSynchronizeAbort = NULL;
  199. FSynchronizeTerminal = NULL;
  200. FNeedSession = false;
  201. FDoNotIdleCurrentTerminal = 0;
  202. FIncrementalSearching = 0;
  203. FIncrementalSearchHaveNext = false;
  204. FQueueFileList.reset(new TQueueFileList());
  205. FProgressSide = osCurrent;
  206. FCalculateSizeOperation = NULL;
  207. FDownloadingFromClipboard = false;
  208. FClipboardFakeMonitorsPendingReset = false;
  209. FHiContrastTheme = NULL;
  210. FEditorManager = new TEditorManager();
  211. FEditorManager->OnFileChange = ExecutedFileChanged;
  212. FEditorManager->OnFileReload = ExecutedFileReload;
  213. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  214. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  215. FLocalEditors = new TList();
  216. FQueueStatus = NULL;
  217. FQueueStatusSection = new TCriticalSection();
  218. FQueueStatusInvalidated = false;
  219. FQueueItemInvalidated = false;
  220. FQueueStatusUpdating = false;
  221. FQueueActedItem = NULL;
  222. FQueueController = new TQueueController(QueueView3);
  223. FQueueScrollOnDragOver = new TListViewScrollOnDragOver(QueueView3, true);
  224. FUserActionTimer = new TTimer(this);
  225. FUserActionTimer->Enabled = false;
  226. FUserActionTimer->Interval = 10;
  227. FUserActionTimer->OnTimer = UserActionTimer;
  228. FNotes = new TStringList();
  229. FNoteTimer = new TTimer(this);
  230. FNoteTimer->Enabled = false;
  231. FNoteTimer->OnTimer = NoteTimer;
  232. FOnNoteClick = NULL;
  233. FOle32Library = LoadLibrary(L"Ole32.dll");
  234. FDragMoveCursor = FOle32Library != NULL ?
  235. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  236. UseSystemSettings(this);
  237. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  238. static_cast<TObject*>(GetComponent(fcTransferList)));
  239. DebugAssert(TransferList != NULL);
  240. FTransferListHoverIndex = -1;
  241. TransferList->OnChange = TransferListChange;
  242. TransferList->OnDrawItem = TransferListDrawItem;
  243. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))), true);
  244. SetSubmenu(NonVisualDataModule->ColorMenuItem, true);
  245. UseDesktopFont(SessionsPageControl);
  246. UpdateSessionsPageControlHeight();
  247. UseDesktopFont(RemoteDirView);
  248. UseDesktopFont(RemoteDriveView);
  249. UseDesktopFont(QueueView3);
  250. UseDesktopFont(QueueFileList);
  251. UseDesktopFont(QueueLabel);
  252. UseDesktopFont(RemoteStatusBar);
  253. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  254. QueueSplitter->ShowHint = true;
  255. reinterpret_cast<TLabel*>(QueueFileListSplitter)->OnDblClick = QueueFileListSplitterDblClick;
  256. QueueFileListSplitter->ShowHint = true;
  257. RemotePanelSplitter->ShowHint = true;
  258. UpdateImages();
  259. FCustomCommandMenu = CreateTBXPopupMenu(this);
  260. FCustomCommandLocalFileList = NULL;
  261. FCustomCommandRemoteFileList = NULL;
  262. FSessionColors = new TPngImageList(this);
  263. FSessionColors->ColorDepth = cd32Bit;
  264. AddFixedSessionImages();
  265. SessionsPageControl->Images = FSessionColors;
  266. UpdateQueueLabel();
  267. CheckStoreTransition();
  268. CreateHiddenWindow();
  269. StartUpdates();
  270. // Start loading drive data, so that they are ready once we need them for StartCreationDirectoryMonitorsOnEachDrive
  271. // (necessary for "explorer" only, as "commander" loads it for its drive menu)
  272. DriveInfo->NeedData();
  273. }
  274. //---------------------------------------------------------------------------
  275. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  276. {
  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. StoreParams();
  319. }
  320. ManagedSession = NULL;
  321. Queue = NULL;
  322. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  323. NonVisualDataModule->ScpExplorer = NULL;
  324. delete FQueueScrollOnDragOver;
  325. FQueueScrollOnDragOver = NULL;
  326. delete FQueueController;
  327. FQueueController = NULL;
  328. delete FQueueStatusSection;
  329. FQueueStatusSection = NULL;
  330. delete FQueueStatus;
  331. FQueueStatus = NULL;
  332. delete FUserActionTimer;
  333. FUserActionTimer = NULL;
  334. delete FNoteTimer;
  335. delete FNotes;
  336. delete FNoteData;
  337. SAFE_DESTROY(FDocks);
  338. SessionsPageControl->Images = NULL;
  339. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  340. SAFE_DESTROY(FSessionColors);
  341. SAFE_DESTROY(FSessionsDragDropFilesEx);
  342. SAFE_DESTROY(FHistoryMenu[0][0]);
  343. SAFE_DESTROY(FHistoryMenu[0][1]);
  344. SAFE_DESTROY(FHistoryMenu[1][0]);
  345. SAFE_DESTROY(FHistoryMenu[1][1]);
  346. if (FHiddenWindow != NULL)
  347. {
  348. DestroyWindow(FHiddenWindow);
  349. FHiddenWindow = NULL;
  350. }
  351. }
  352. //---------------------------------------------------------------------------
  353. void TCustomScpExplorerForm::ReleaseHiContrastTheme()
  354. {
  355. if (FHiContrastTheme != NULL)
  356. {
  357. ReleaseTBXTheme(FHiContrastTheme);
  358. FHiContrastTheme = NULL;
  359. }
  360. }
  361. //---------------------------------------------------------------------------
  362. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  363. {
  364. std::unique_ptr<TSessionData> Data;
  365. if (!Session.IsEmpty())
  366. {
  367. bool DefaultsOnly;
  368. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  369. }
  370. TTerminalManager * Manager = TTerminalManager::Instance();
  371. for (int Index = 0; Index < Manager->Count; Index++)
  372. {
  373. TTerminal * Terminal = Manager->Sessions[Index];
  374. if (Session.IsEmpty() ||
  375. Manager->IsActiveTerminalForSite(Terminal, Data.get()))
  376. {
  377. if (Path.IsEmpty())
  378. {
  379. Terminal->ClearCaches();
  380. }
  381. else
  382. {
  383. Terminal->DirectoryModified(Path, true);
  384. }
  385. }
  386. }
  387. // We should flag a pending refresh for the background terminals or busy foreground terminals
  388. if (HasActiveTerminal() &&
  389. CanCommandLineFromAnotherInstance() &&
  390. (Session.IsEmpty() || Manager->IsActiveTerminalForSite(Terminal, Data.get())) &&
  391. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  392. {
  393. Terminal->ReloadDirectory();
  394. }
  395. }
  396. //---------------------------------------------------------------------------
  397. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  398. {
  399. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  400. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  401. size_t MessageSize = sizeof(TCopyDataMessage);
  402. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  403. if (Result)
  404. {
  405. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  406. Result = (Message.Version == TCopyDataMessage::Version1);
  407. if (Result)
  408. {
  409. switch (Message.Command)
  410. {
  411. case TCopyDataMessage::CommandCanCommandLine:
  412. Result = CanCommandLineFromAnotherInstance();
  413. if (Result)
  414. {
  415. AppLog(L"Can process command-line from other instance");
  416. }
  417. else
  418. {
  419. AppLog(L"Cannot process command-line from other instance");
  420. }
  421. break;
  422. case TCopyDataMessage::CommandCommandLine:
  423. {
  424. UnicodeString CommandLine(Message.CommandLine);
  425. Result = CommandLineFromAnotherInstance(CommandLine);
  426. }
  427. break;
  428. case TCopyDataMessage::RefreshPanel:
  429. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  430. break;
  431. case TCopyDataMessage::MainWindowCheck:
  432. Result = true;
  433. break;
  434. default:
  435. Result = false;
  436. break;
  437. }
  438. }
  439. }
  440. Message.Result = Result ? 1 : 0;
  441. }
  442. //---------------------------------------------------------------------------
  443. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  444. {
  445. WNDCLASS WindowClass = {0};
  446. WindowClass.lpfnWndProc = DefWindowProc;
  447. WindowClass.hInstance = HInstance;
  448. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  449. FHiddenWindow = NULL;
  450. if (RegisterClass(&WindowClass))
  451. {
  452. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  453. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  454. }
  455. }
  456. //---------------------------------------------------------------------------
  457. bool __fastcall TCustomScpExplorerForm::CanConsole()
  458. {
  459. return
  460. HasActiveTerminal() &&
  461. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  462. }
  463. //---------------------------------------------------------------------------
  464. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  465. {
  466. bool Result = Visible && !NonVisualDataModule->Busy;
  467. return Result;
  468. }
  469. //---------------------------------------------------------------------------
  470. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  471. const UnicodeString & CommandLine)
  472. {
  473. TProgramParams Params(CommandLine);
  474. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  475. if (Result)
  476. {
  477. NonVisualDataModule->StartBusy();
  478. try
  479. {
  480. // this action is initiated from another process,
  481. // so it's likely that our window is not visible,
  482. // and user won't see what is going on
  483. Application->BringToFront();
  484. // reload sessions as we may be asked to open a session
  485. // just stored by another instance
  486. StoredSessions->Reload();
  487. UnicodeString SessionName = Params.Param[1];
  488. std::unique_ptr<TObjectList> DataList(new TObjectList());
  489. try
  490. {
  491. UnicodeString DownloadFile; // unused
  492. int Flags = GetCommandLineParseUrlFlags(&Params);
  493. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  494. }
  495. catch (EAbort &)
  496. {
  497. // Happens when opening session in PuTTY and in other situations,
  498. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  499. // to process the command-line on its own (or to pass it to yet another instance)
  500. }
  501. if (DataList->Count > 0)
  502. {
  503. TTerminalManager * Manager = TTerminalManager::Instance();
  504. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  505. }
  506. }
  507. __finally
  508. {
  509. NonVisualDataModule->EndBusy();
  510. }
  511. }
  512. return Result;
  513. }
  514. //---------------------------------------------------------------------------
  515. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  516. {
  517. TManagedTerminal * Result;
  518. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  519. {
  520. Result = FManagedSession;
  521. }
  522. else
  523. {
  524. Result = NULL;
  525. }
  526. return Result;
  527. }
  528. //---------------------------------------------------------------------------
  529. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  530. {
  531. if (FManagedSession != value)
  532. {
  533. TWindowLock Lock(this);
  534. SessionChanging();
  535. DoSetManagedSession(value, false);
  536. }
  537. }
  538. //---------------------------------------------------------------------------
  539. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  540. {
  541. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  542. FManagedSession = value;
  543. {
  544. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect);
  545. FAllowTransferPresetAutoSelect = false;
  546. TAutoFlag SessionChangingFlag(FSessionChanging);
  547. SessionChanged(Replace);
  548. }
  549. if (Terminal != NULL)
  550. {
  551. TransferPresetAutoSelect();
  552. }
  553. // Update app and tab titles, prevented above by FSessionChanging.
  554. UpdateControls();
  555. }
  556. //---------------------------------------------------------------------------
  557. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  558. {
  559. FEditorManager->ProcessFiles(FileTerminalReplaced, value);
  560. DoSetManagedSession(value, true);
  561. }
  562. //---------------------------------------------------------------------------
  563. void __fastcall TCustomScpExplorerForm::SessionChanging()
  564. {
  565. if (ManagedSession != NULL)
  566. {
  567. UpdateSession(ManagedSession);
  568. }
  569. }
  570. //---------------------------------------------------------------------------
  571. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  572. {
  573. if (ManagedSession != NULL)
  574. {
  575. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  576. }
  577. if (!TTerminalManager::Instance()->Updating)
  578. {
  579. SessionListChanged();
  580. }
  581. if (Terminal != NULL)
  582. {
  583. TObject * State = NULL;
  584. if (WinConfiguration->PreservePanelState)
  585. {
  586. State = Terminal->RemoteExplorerState;
  587. DirView(osRemote)->AnnounceState(State);
  588. }
  589. try
  590. {
  591. if (Replaced)
  592. {
  593. RemoteDirView->ReplaceTerminal(Terminal);
  594. }
  595. else
  596. {
  597. RemoteDirView->Terminal = Terminal;
  598. }
  599. if (Terminal->Active)
  600. {
  601. Terminal->RefreshDirectory();
  602. }
  603. if (State != NULL)
  604. {
  605. DirView(osRemote)->RestoreState(State);
  606. }
  607. }
  608. __finally
  609. {
  610. DirView(osRemote)->AnnounceState(NULL);
  611. }
  612. }
  613. else
  614. {
  615. RemoteDirView->Terminal = NULL;
  616. }
  617. InitStatusBar();
  618. UpdateTransferList();
  619. // Update panels Enable state before refreshing the labels
  620. UpdateControls();
  621. }
  622. //---------------------------------------------------------------------------
  623. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  624. {
  625. if (Queue != value)
  626. {
  627. if (FQueue != NULL)
  628. {
  629. FQueue->OnListUpdate = NULL;
  630. FQueue->OnQueueItemUpdate = NULL;
  631. }
  632. FQueue = value;
  633. if (FQueue != NULL)
  634. {
  635. DebugAssert(FQueue->OnListUpdate == NULL);
  636. FQueue->OnListUpdate = QueueListUpdate;
  637. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  638. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  639. }
  640. QueueChanged();
  641. }
  642. }
  643. //---------------------------------------------------------------------------
  644. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  645. TListItem * Item)
  646. {
  647. if (FQueueActedItem == Item)
  648. {
  649. FQueueActedItem = NULL;
  650. if ((QueueView3->PopupMenu != NULL) &&
  651. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  652. {
  653. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  654. ReleaseCapture();
  655. }
  656. }
  657. if (Item->Data == FPendingQueueActionItem)
  658. {
  659. FPendingQueueActionItem = NULL;
  660. }
  661. }
  662. //---------------------------------------------------------------------------
  663. bool TCustomScpExplorerForm::IsAnythingQueued()
  664. {
  665. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  666. }
  667. //---------------------------------------------------------------------------
  668. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  669. {
  670. {
  671. TGuard Guard(FQueueStatusSection);
  672. FQueueStatusInvalidated = false;
  673. if (FQueue != NULL)
  674. {
  675. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  676. }
  677. }
  678. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  679. {
  680. FMaxQueueLength = FQueueStatus->Count;
  681. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  682. }
  683. {
  684. TAutoFlag Flag(FQueueStatusUpdating);
  685. FQueueController->UpdateQueueStatus(FQueueStatus);
  686. }
  687. UpdateQueueFileList();
  688. SetQueueProgress();
  689. UpdateQueueView();
  690. bool IsEmpty = !IsAnythingQueued();
  691. if (IsEmpty && (Terminal != NULL))
  692. {
  693. TOnceDoneOperation OnceDoneOperation =
  694. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  695. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  696. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  697. {
  698. FQueue->Enabled = false;
  699. }
  700. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  701. {
  702. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  703. }
  704. }
  705. }
  706. //---------------------------------------------------------------------------
  707. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  708. {
  709. UnicodeString Result;
  710. if (FQueueStatus != NULL)
  711. {
  712. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  713. {
  714. TFileOperationProgressType * ProgressData =
  715. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  716. if ((ProgressData != NULL) && ProgressData->InProgress)
  717. {
  718. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  719. }
  720. }
  721. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  722. {
  723. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  724. }
  725. }
  726. return Result;
  727. }
  728. //---------------------------------------------------------------------------
  729. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  730. {
  731. ComponentVisible[fcQueueView] =
  732. !IsLocalBrowserMode() &&
  733. ((WinConfiguration->QueueView.Show == qvShow) ||
  734. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  735. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  736. }
  737. //---------------------------------------------------------------------------
  738. void __fastcall TCustomScpExplorerForm::QueueChanged()
  739. {
  740. if (FQueueStatus != NULL)
  741. {
  742. // UpdateFileList implementation relies on the status being recreated when session changes
  743. delete FQueueStatus;
  744. FQueueStatus = NULL;
  745. }
  746. UpdateQueueStatus(true);
  747. }
  748. //---------------------------------------------------------------------------
  749. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  750. {
  751. if (FQueue == Queue)
  752. {
  753. FQueueStatusInvalidated = true;
  754. }
  755. }
  756. //---------------------------------------------------------------------------
  757. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  758. TQueueItem * Item)
  759. {
  760. if (FQueue == Queue)
  761. {
  762. TGuard Guard(FQueueStatusSection);
  763. // this may be running in parallel with QueueChanged
  764. if (FQueueStatus != NULL)
  765. {
  766. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  767. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  768. {
  769. FRefreshLocalDirectory = (QueueItem == NULL) ||
  770. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  771. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  772. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  773. }
  774. if (QueueItem != NULL)
  775. {
  776. QueueItem->UserData = (void*)true;
  777. FQueueItemInvalidated = true;
  778. }
  779. }
  780. }
  781. }
  782. //---------------------------------------------------------------------------
  783. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  784. {
  785. // during standalone editing, we have no way to see/control queue,
  786. // so we have to always popup prompts automatically
  787. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  788. }
  789. //---------------------------------------------------------------------------
  790. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  791. {
  792. if (FQueueStatus != NULL)
  793. {
  794. bool QueueAutoPopup = IsQueueAutoPopup();
  795. bool NeedRefresh = FQueueController->NeedRefresh();
  796. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  797. FQueueItemInvalidated = false;
  798. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  799. bool Updated = false;
  800. TQueueItemProxy * QueueItem;
  801. bool WasUserAction;
  802. for (int Index = 0; Index < Limit; Index++)
  803. {
  804. bool Update = false;
  805. QueueItem = FQueueStatus->Items[Index];
  806. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  807. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  808. (FPendingQueueActionItem == NULL))
  809. {
  810. FPendingQueueActionItem = QueueItem;
  811. FUserActionTimer->Enabled = true;
  812. }
  813. if ((bool)QueueItem->UserData)
  814. {
  815. QueueItem->UserData = (void*)false;
  816. QueueItem->Update();
  817. Updated = true;
  818. Update = true;
  819. }
  820. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  821. {
  822. Update = true;
  823. }
  824. if (Update)
  825. {
  826. FQueueController->RefreshQueueItem(QueueItem);
  827. }
  828. }
  829. if (Updated)
  830. {
  831. NonVisualDataModule->UpdateNonVisibleActions();
  832. SetQueueProgress();
  833. UpdateQueueFileList();
  834. }
  835. }
  836. }
  837. //---------------------------------------------------------------------------
  838. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  839. {
  840. if (FTaskbarList != NULL)
  841. {
  842. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  843. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  844. }
  845. }
  846. //---------------------------------------------------------------------------
  847. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  848. {
  849. if (Progress >= 0)
  850. {
  851. if (FTaskbarList != NULL)
  852. {
  853. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  854. }
  855. }
  856. else
  857. {
  858. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  859. }
  860. }
  861. //---------------------------------------------------------------------------
  862. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  863. {
  864. int OverallProgress;
  865. // FProgressForm is null when this is called from SetQueueProgress
  866. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  867. {
  868. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  869. }
  870. else if (!ProgressData->IsIndeterminate())
  871. {
  872. OverallProgress = ProgressData->OverallProgress();
  873. }
  874. else
  875. {
  876. OverallProgress = -1;
  877. }
  878. SetTaskbarListProgressValue(OverallProgress);
  879. }
  880. //---------------------------------------------------------------------------
  881. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  882. {
  883. TTerminalManager::Instance()->QueueStatusUpdated();
  884. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  885. {
  886. // Do not animate task bar button, when items are queued, but processing is disabled
  887. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  888. {
  889. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  890. {
  891. TFileOperationProgressType * ProgressData = NULL;
  892. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  893. {
  894. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  895. }
  896. if ((ProgressData != NULL) &&
  897. ProgressData->InProgress)
  898. {
  899. SetTaskbarListProgressValue(ProgressData);
  900. }
  901. else
  902. {
  903. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  904. }
  905. }
  906. else
  907. {
  908. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  909. }
  910. }
  911. else
  912. {
  913. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  914. }
  915. }
  916. UpdateQueueLabel();
  917. }
  918. //---------------------------------------------------------------------------
  919. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  920. {
  921. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  922. if (FQueueStatus != NULL)
  923. {
  924. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  925. if (ActiveAndPendingPrimaryCount > 0)
  926. {
  927. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  928. }
  929. }
  930. QueueLabel->Caption = Caption;
  931. }
  932. //---------------------------------------------------------------------------
  933. void TCustomScpExplorerForm::CheckStoreTransition()
  934. {
  935. if (WinConfiguration->StoreTransition == stInit)
  936. {
  937. if (IsUWP())
  938. {
  939. WinConfiguration->StoreTransition = stStoreFresh;
  940. AppLog(L"Fresh UWP/store installation");
  941. }
  942. else
  943. {
  944. WinConfiguration->StoreTransition = stStandard;
  945. AppLog(L"Fresh standard installation");
  946. }
  947. }
  948. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  949. {
  950. WinConfiguration->StoreTransition = stStoreMigrated;
  951. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  952. AppLog(L"Standard installation migrated to store installation");
  953. }
  954. if (WinConfiguration->StoreTransition == stStoreMigrated)
  955. {
  956. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  957. Toolbar->Parent = MessageDock;
  958. Toolbar->FullSize = true;
  959. Toolbar->Color = Application->HintColor;
  960. TTBXLabelItem * LabelItem;
  961. LabelItem = new TTBXLabelItem(Toolbar);
  962. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  963. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  964. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  965. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  966. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  967. Toolbar->Items->Add(LabelItem);
  968. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  969. LinkItem->FontSettings->Color = LinkColor;
  970. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  971. LinkItem->OnClick = StoreTransitionLinkClick;
  972. Toolbar->Items->Add(LinkItem);
  973. AddMenuSeparator(Toolbar->Items);
  974. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  975. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  976. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  977. CloseItem->OnClick = StoreTransitionCloseClick;
  978. Toolbar->Items->Add(CloseItem);
  979. GiveTBItemPriority(CloseItem);
  980. }
  981. }
  982. //---------------------------------------------------------------------------
  983. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  984. {
  985. ShowHelp(HELP_STORE_TRANSITION);
  986. }
  987. //---------------------------------------------------------------------------
  988. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  989. {
  990. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  991. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  992. delete Toolbar;
  993. WinConfiguration->StoreTransition = stStoreAcknowledged;
  994. UpdateControls();
  995. }
  996. //---------------------------------------------------------------------------
  997. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  998. {
  999. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  1000. static_cast<TComponent*>(GetComponent(fcTransferList)));
  1001. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  1002. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  1003. TransferList->Strings->BeginUpdate();
  1004. try
  1005. {
  1006. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  1007. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  1008. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  1009. if (FTransferDropDownHint.IsEmpty())
  1010. {
  1011. FTransferDropDownHint = TransferDropDown->Hint;
  1012. }
  1013. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1014. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1015. TransferDropDown->Text = StripHotkey(Name);
  1016. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1017. (FTransferDropDownHint, StripHotkey(Name),
  1018. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1019. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1020. // update the label, otherwise when it is updated only on the first draw
  1021. // of the list, it is drawn "bold" for some reason
  1022. FTransferListHoverIndex = TransferList->ItemIndex;
  1023. UpdateTransferLabel();
  1024. }
  1025. __finally
  1026. {
  1027. TransferList->Strings->EndUpdate();
  1028. }
  1029. }
  1030. //---------------------------------------------------------------------------
  1031. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1032. {
  1033. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1034. DebugAssert(Toolbar != NULL);
  1035. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1036. }
  1037. //---------------------------------------------------------------------------
  1038. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1039. {
  1040. TForm::UpdateActions();
  1041. if (ComponentVisible[fcCustomCommandsBand])
  1042. {
  1043. UpdateCustomCommandsToolbar();
  1044. }
  1045. }
  1046. //---------------------------------------------------------------------------
  1047. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1048. {
  1049. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1050. }
  1051. //---------------------------------------------------------------------------
  1052. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1053. {
  1054. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1055. {
  1056. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1057. // Without this, the panel turns gray and unused part of header turns black
  1058. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1059. }
  1060. }
  1061. //---------------------------------------------------------------------------
  1062. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1063. {
  1064. Color = GetBtnFaceColor();
  1065. DebugAssert(Configuration && RemoteDirView);
  1066. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1067. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1068. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1069. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1070. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1071. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1072. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1073. UpdateRowSelect(RemoteDirView);
  1074. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1075. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1076. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1077. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1078. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1079. UpdateSessionsPageControlHeight();
  1080. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1081. UpdateToolbarDisplayMode();
  1082. UpdateTransferList();
  1083. if (Terminal != NULL)
  1084. {
  1085. TransferPresetAutoSelect();
  1086. }
  1087. UpdateQueueView();
  1088. UpdateControls();
  1089. // this can be called even before constuctor finishes.
  1090. if (FEditorManager != NULL)
  1091. {
  1092. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1093. }
  1094. // this can be called even before constuctor finishes.
  1095. if (FLocalEditors != NULL)
  1096. {
  1097. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1098. {
  1099. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1100. }
  1101. }
  1102. if (ComponentVisible[fcCustomCommandsBand])
  1103. {
  1104. UpdateCustomCommandsToolbar();
  1105. }
  1106. // show only when keeping queue items forever,
  1107. // otherwise, it's enough to have it in the context menu
  1108. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1109. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1110. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1111. {
  1112. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1113. FFileColorsCurrent = WinConfiguration->FileColors;
  1114. FileColorsChanged();
  1115. }
  1116. if ((GetNewTabTab()->CaptionTruncation != GetNewTabTabCaptionTruncation()) &&
  1117. (FSessionColors != NULL))
  1118. {
  1119. SessionListChanged();
  1120. }
  1121. }
  1122. //---------------------------------------------------------------------------
  1123. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1124. {
  1125. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1126. DirView->Invalidate();
  1127. }
  1128. //---------------------------------------------------------------------------
  1129. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1130. {
  1131. DoFileColorsChanged(RemoteDirView);
  1132. }
  1133. //---------------------------------------------------------------------------
  1134. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1135. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  1136. void * /*Arg*/)
  1137. {
  1138. if (Token != NULL)
  1139. {
  1140. TForm * Editor = dynamic_cast<TForm*>(Token);
  1141. DebugAssert(Editor != NULL);
  1142. ReconfigureEditorForm(Editor);
  1143. }
  1144. }
  1145. //---------------------------------------------------------------------------
  1146. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1147. {
  1148. WinConfiguration->DDTransferConfirmation = asOn;
  1149. }
  1150. //---------------------------------------------------------------------------
  1151. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1152. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1153. {
  1154. // noop
  1155. }
  1156. //---------------------------------------------------------------------------
  1157. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1158. {
  1159. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1163. {
  1164. if (DoNotShowAgain)
  1165. {
  1166. if (DragDrop)
  1167. {
  1168. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1169. {
  1170. PopupTrayBalloon(
  1171. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1172. }
  1173. WinConfiguration->DDTransferConfirmation = asOff;
  1174. }
  1175. else
  1176. {
  1177. WinConfiguration->ConfirmTransferring = false;
  1178. }
  1179. }
  1180. else
  1181. {
  1182. // User explicitly unchecked "do not show again",
  1183. // so show him the dialog the next time
  1184. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1185. {
  1186. WinConfiguration->DDTransferConfirmation = asOn;
  1187. }
  1188. }
  1189. }
  1190. //---------------------------------------------------------------------------
  1191. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1192. TTransferDirection Direction, TTransferType Type, bool Temp,
  1193. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1194. bool Confirm, bool DragDrop, int Options)
  1195. {
  1196. bool Result = true;
  1197. DebugAssert(HasActiveTerminal());
  1198. // these parameters are known in advance
  1199. int Params =
  1200. FLAGMASK(Type == ttMove, cpDelete);
  1201. bool ToTemp = (Temp && (Direction == tdToLocal));
  1202. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1203. {
  1204. bool DisableNewerOnly =
  1205. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1206. ToTemp;
  1207. Options |=
  1208. FLAGMASK(ToTemp, coTemp) |
  1209. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1210. coDoNotShowAgain;
  1211. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1212. int CopyParamAttrs = (Direction == tdToRemote ?
  1213. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1214. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1215. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1216. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1217. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1218. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1219. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1220. if (Result)
  1221. {
  1222. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1223. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1224. }
  1225. }
  1226. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1227. {
  1228. Configuration->Usage->Inc(L"TransfersOnBackground");
  1229. // these parameter are known only after transfer dialog
  1230. Params |=
  1231. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1232. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1233. Result = false;
  1234. ClearTransferSourceSelection(Direction);
  1235. }
  1236. return Result;
  1237. }
  1238. //---------------------------------------------------------------------------
  1239. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1240. {
  1241. if (FOnFileOperationFinished != NULL)
  1242. {
  1243. FOnFileOperationFinished(Side, UnicodeString(), true);
  1244. }
  1245. else
  1246. {
  1247. if (HasDirView[Side])
  1248. {
  1249. DirView(Side)->SelectAll(smNone);
  1250. }
  1251. }
  1252. }
  1253. //---------------------------------------------------------------------------
  1254. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1255. {
  1256. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1257. ClearOperationSelection(Side);
  1258. }
  1259. //---------------------------------------------------------------------------
  1260. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1261. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1262. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1263. int Params)
  1264. {
  1265. DebugAssert(Queue != NULL);
  1266. bool SingleFile = false;
  1267. if (FileList->Count == 1)
  1268. {
  1269. if (Direction == tdToRemote)
  1270. {
  1271. UnicodeString FileName = FileList->Strings[0];
  1272. SingleFile = FileExists(ApiPath(FileName));
  1273. }
  1274. else
  1275. {
  1276. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1277. SingleFile = !File->IsDirectory;
  1278. }
  1279. }
  1280. TQueueItem * QueueItem;
  1281. if (Direction == tdToRemote)
  1282. {
  1283. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1284. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1285. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1286. }
  1287. else
  1288. {
  1289. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1290. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1291. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1292. }
  1293. AddQueueItem(Queue, QueueItem, Terminal);
  1294. }
  1295. //---------------------------------------------------------------------------
  1296. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1297. {
  1298. if (Queue->IsEmpty)
  1299. {
  1300. Terminal->QueueOperationStart = Now();
  1301. }
  1302. Queue->AddItem(QueueItem);
  1303. }
  1304. //---------------------------------------------------------------------------
  1305. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1306. {
  1307. }
  1308. //---------------------------------------------------------------------------
  1309. void __fastcall TCustomScpExplorerForm::InitControls()
  1310. {
  1311. DebugAssert(FDocks != NULL);
  1312. for (int Index = 0; Index < ComponentCount; Index++)
  1313. {
  1314. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1315. if ((Dock != NULL) && (Dock->Tag == 0))
  1316. {
  1317. FDocks->Add(Dock);
  1318. }
  1319. }
  1320. CollectItemsWithTextDisplayMode(this);
  1321. }
  1322. //---------------------------------------------------------------------------
  1323. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1324. {
  1325. ConfigurationChanged();
  1326. QueuePanel->Height =
  1327. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1328. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1329. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1330. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1331. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1332. QueueFileList->Height =
  1333. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1334. if (QueueFileList->Visible)
  1335. {
  1336. AdjustQueueLayout();
  1337. }
  1338. UpdateCustomCommandsToolbar();
  1339. }
  1340. //---------------------------------------------------------------------------
  1341. void __fastcall TCustomScpExplorerForm::StoreParams()
  1342. {
  1343. int APixelsPerInch = GetControlPixelsPerInch(this);
  1344. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1345. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1346. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1347. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1348. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1349. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1350. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1351. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1352. }
  1353. //---------------------------------------------------------------------------
  1354. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1355. {
  1356. if (!FFormRestored)
  1357. {
  1358. FFormRestored = true;
  1359. RestoreFormParams();
  1360. }
  1361. TForm::CreateParams(Params);
  1362. }
  1363. //---------------------------------------------------------------------------
  1364. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1365. {
  1366. DebugAssert(FDocks != NULL);
  1367. for (int Index = 0; Index < FDocks->Count; Index++)
  1368. {
  1369. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1370. }
  1371. }
  1372. //---------------------------------------------------------------------------
  1373. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1374. {
  1375. SetDockAllowDrag(true);
  1376. while (!ButtonsStr.IsEmpty())
  1377. {
  1378. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1379. UnicodeString Name = CutToChar(S, L'=', true);
  1380. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1381. {
  1382. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1383. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1384. {
  1385. while (!S.IsEmpty())
  1386. {
  1387. UnicodeString S2 = CutToChar(S, L',', true);
  1388. UnicodeString Name = CutToChar(S2, L':', true);
  1389. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1390. {
  1391. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1392. if (SameText(GetToolbarItemName(Item), Name))
  1393. {
  1394. // forward compatibility
  1395. UnicodeString S3 = CutToChar(S2, L':', true);
  1396. bool Visible = StrToIntDef(S3, 0);
  1397. Item->Visible = Visible;
  1398. }
  1399. }
  1400. }
  1401. }
  1402. }
  1403. }
  1404. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1405. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1406. }
  1407. //---------------------------------------------------------------------------
  1408. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1409. {
  1410. UnicodeString Result;
  1411. SetDockAllowDrag(true);
  1412. Result = ::GetToolbarsLayoutStr(this);
  1413. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1414. return Result;
  1415. }
  1416. //---------------------------------------------------------------------------
  1417. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1418. {
  1419. UnicodeString Result;
  1420. if (Item->Action != NULL)
  1421. {
  1422. Result = Item->Action->Name;
  1423. Result = RemoveSuffix(Result, L"Action", true);
  1424. }
  1425. else
  1426. {
  1427. Result = Item->Name;
  1428. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1429. Result = RemoveSuffix(Result, L"Item", true);
  1430. }
  1431. return Result;
  1432. }
  1433. //---------------------------------------------------------------------------
  1434. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1435. {
  1436. UnicodeString Result;
  1437. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1438. {
  1439. UnicodeString ToolbarStr;
  1440. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1441. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1442. {
  1443. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1444. {
  1445. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1446. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1447. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1448. // and save the changes here only.
  1449. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1450. {
  1451. UnicodeString Name = GetToolbarItemName(Item);
  1452. DebugAssert(Name.Pos(L"TBX") == 0);
  1453. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1454. }
  1455. }
  1456. }
  1457. if (!ToolbarStr.IsEmpty())
  1458. {
  1459. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1460. }
  1461. }
  1462. return Result;
  1463. }
  1464. //---------------------------------------------------------------------------
  1465. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1466. {
  1467. DebugAssert(FProgressForm == NULL);
  1468. bool AllowSkip = HasActiveTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1469. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1470. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1471. FProgressForm->DeleteLocalToRecycleBin =
  1472. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1473. FProgressForm->DeleteRemoteToRecycleBin =
  1474. HasActiveTerminal() &&
  1475. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1476. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1477. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1478. LockWindow();
  1479. // Actually, do not know what hides the progress once the operation finishes
  1480. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1481. SetTaskbarListProgressState(TBPF_NORMAL);
  1482. }
  1483. //---------------------------------------------------------------------------
  1484. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1485. {
  1486. UnlockWindow();
  1487. SAFE_DESTROY(FProgressForm);
  1488. SetQueueProgress();
  1489. }
  1490. //---------------------------------------------------------------------------
  1491. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1492. TFileOperationProgressType & ProgressData)
  1493. {
  1494. // Download to temporary local directory
  1495. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1496. {
  1497. bool Continue = true;
  1498. FPendingTempSpaceWarn = false;
  1499. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1500. if (!Continue)
  1501. {
  1502. Abort();
  1503. }
  1504. }
  1505. // operation is being executed and we still didn't show up progress form
  1506. if (ProgressData.InProgress && !FProgressForm)
  1507. {
  1508. CreateProgressForm(NULL);
  1509. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1510. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1511. }
  1512. // operation is finished (or terminated), so we hide progress form
  1513. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1514. {
  1515. DestroyProgressForm();
  1516. if (ProgressData.Operation == foCalculateSize)
  1517. {
  1518. // When calculating size before transfer, the abort caused by
  1519. // cancel flag set due to "MoveToQueue" below,
  1520. // is not propagated back to us in ExecuteFileOperation,
  1521. // as it is silently swallowed.
  1522. // So we explicitly (re)throw it here.
  1523. if (FMoveToQueue)
  1524. {
  1525. Abort();
  1526. }
  1527. }
  1528. else
  1529. {
  1530. if ((ProgressData.Cancel == csContinue) &&
  1531. !FAutoOperation)
  1532. {
  1533. OperationComplete(ProgressData.StartTime);
  1534. }
  1535. }
  1536. }
  1537. if (FProgressForm &&
  1538. // Can happen only during synchronization, when ending one of the operations
  1539. ProgressData.InProgress)
  1540. {
  1541. FProgressForm->SetProgressData(ProgressData);
  1542. DebugAssert(ProgressData.InProgress);
  1543. SetTaskbarListProgressValue(&ProgressData);
  1544. if (FProgressForm->Cancel > csContinue)
  1545. {
  1546. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1547. if (FProgressForm->Cancel == csCancelFile)
  1548. {
  1549. FProgressForm->ClearCancel();
  1550. }
  1551. // cancel cancels even the move
  1552. FMoveToQueue = false;
  1553. }
  1554. else if (FProgressForm->MoveToQueue)
  1555. {
  1556. FMoveToQueue = true;
  1557. ProgressData.SetCancelAtLeast(csCancel);
  1558. }
  1559. if ((FTransferResumeList != NULL) &&
  1560. ProgressData.InProgress &&
  1561. ProgressData.IsTransfer() &&
  1562. !ProgressData.FullFileName.IsEmpty())
  1563. {
  1564. if ((FTransferResumeList->Count == 0) ||
  1565. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1566. {
  1567. // note that we do not recognize directories from files here
  1568. FTransferResumeList->Add(ProgressData.FullFileName);
  1569. }
  1570. }
  1571. }
  1572. }
  1573. //---------------------------------------------------------------------------
  1574. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1575. const TDateTime & StartTime)
  1576. {
  1577. if (GUIConfiguration->BeepOnFinish &&
  1578. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1579. {
  1580. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1581. DWORD Sound;
  1582. if (!ExtractFileExt(BeepSound).IsEmpty())
  1583. {
  1584. Sound = SND_FILENAME;
  1585. }
  1586. else
  1587. {
  1588. Sound = SND_ALIAS;
  1589. }
  1590. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1591. }
  1592. }
  1593. //---------------------------------------------------------------------------
  1594. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1595. TFileOperationProgressType & ProgressData)
  1596. {
  1597. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1598. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1599. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1600. FileOperationProgress(ProgressData);
  1601. }
  1602. //---------------------------------------------------------------------------
  1603. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1604. {
  1605. UnicodeString Result;
  1606. if (FProgressForm != NULL)
  1607. {
  1608. Result = FProgressForm->ProgressStr();
  1609. }
  1610. return Result;
  1611. }
  1612. //---------------------------------------------------------------------------
  1613. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1614. bool DragDrop)
  1615. {
  1616. return (!DragDrop && (DropSourceControl == NULL)) ||
  1617. (DropSourceControl == DirView(osOther));
  1618. }
  1619. //---------------------------------------------------------------------------
  1620. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1621. {
  1622. TCustomDirView * ADirView = DirView(Side);
  1623. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1624. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1625. // this can happen when local drive is unplugged in the middle of the operation
  1626. if (Item != NULL)
  1627. {
  1628. if (Unselect)
  1629. {
  1630. Item->Selected = false;
  1631. }
  1632. ADirView->MakeProgressVisible(Item);
  1633. }
  1634. return Item;
  1635. }
  1636. //---------------------------------------------------------------------------
  1637. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1638. TFileOperation Operation, TOperationSide Side,
  1639. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1640. TOnceDoneOperation & OnceDoneOperation)
  1641. {
  1642. if (!FAutoOperation)
  1643. {
  1644. // no selection on "/upload", form serves only as event handler
  1645. // (it is not displayed)
  1646. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1647. ((Operation == FPrimaryOperation) ||
  1648. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1649. {
  1650. TOperationSide DViewSide;
  1651. if ((FProgressSide != osCurrent) &&
  1652. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1653. {
  1654. // assume the operation is over the focused panel
  1655. DViewSide = FProgressSide;
  1656. }
  1657. else
  1658. {
  1659. DViewSide = Side;
  1660. }
  1661. if (FOnFileOperationFinished != NULL)
  1662. {
  1663. FOnFileOperationFinished(DViewSide, FileName, Success);
  1664. }
  1665. else
  1666. {
  1667. VisualiseOperationFinished(DViewSide, FileName, Success);
  1668. }
  1669. }
  1670. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1671. {
  1672. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1673. {
  1674. if (Side == osLocal)
  1675. {
  1676. Configuration->Usage->Inc(L"UploadedFiles");
  1677. }
  1678. else
  1679. {
  1680. Configuration->Usage->Inc(L"DownloadedFiles");
  1681. }
  1682. }
  1683. }
  1684. }
  1685. if (Success && (FSynchronizeController != NULL))
  1686. {
  1687. DebugAssert(!IsSideLocalBrowser(osRemote));
  1688. if (Operation == foCopy)
  1689. {
  1690. DebugAssert(Side == osLocal);
  1691. FSynchronizeController->LogOperation(soUpload, FileName);
  1692. }
  1693. else if (Operation == foDelete)
  1694. {
  1695. DebugAssert(Side == osRemote);
  1696. FSynchronizeController->LogOperation(soDelete, FileName);
  1697. }
  1698. }
  1699. if (FProgressForm)
  1700. {
  1701. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1702. }
  1703. }
  1704. //---------------------------------------------------------------------------
  1705. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1706. TFileOperation Operation, TOperationSide Side,
  1707. bool Temp, const UnicodeString & FileName, Boolean Success,
  1708. TOnceDoneOperation & OnceDoneOperation)
  1709. {
  1710. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1711. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1712. OnceDoneOperation);
  1713. }
  1714. //---------------------------------------------------------------------------
  1715. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1716. {
  1717. return false;
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1721. {
  1722. return false;
  1723. }
  1724. //---------------------------------------------------------------------------
  1725. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1726. {
  1727. return false;
  1728. }
  1729. //---------------------------------------------------------------------------
  1730. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1731. {
  1732. return NULL;
  1733. }
  1734. //---------------------------------------------------------------------------
  1735. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1736. {
  1737. DebugAssert(GetSide(Side) == osRemote);
  1738. DebugUsedParam(Side);
  1739. return RemoteDirView;
  1740. }
  1741. //---------------------------------------------------------------------------
  1742. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1743. {
  1744. DebugAssert(GetSide(Side) == osRemote);
  1745. DebugUsedParam(Side);
  1746. return RemoteDriveView;
  1747. }
  1748. //---------------------------------------------------------------------------
  1749. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1750. {
  1751. DebugAssert(GetSide(Side) == osRemote);
  1752. DebugUsedParam(Side);
  1753. return HasActiveTerminal();
  1754. }
  1755. //---------------------------------------------------------------------------
  1756. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1757. TOperationSide Side, int FilesOnly)
  1758. {
  1759. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1760. }
  1761. //---------------------------------------------------------------------------
  1762. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1763. TOperationSide Side, int FilesOnly)
  1764. {
  1765. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1766. }
  1767. //---------------------------------------------------------------------------
  1768. struct THistoryItemData
  1769. {
  1770. short int Side;
  1771. short int Index;
  1772. };
  1773. //---------------------------------------------------------------------------
  1774. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1775. {
  1776. DirView(Side)->HistoryGo(Index);
  1777. }
  1778. //---------------------------------------------------------------------------
  1779. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1780. {
  1781. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1782. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1783. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1784. }
  1785. //---------------------------------------------------------------------------
  1786. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1787. bool Back)
  1788. {
  1789. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1790. {
  1791. TCustomDirView * DView = DirView(Side);
  1792. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1793. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1794. if (ICount > 10)
  1795. {
  1796. ICount = 10;
  1797. }
  1798. Menu->Items->Clear();
  1799. THistoryItemData Data;
  1800. Data.Side = Side;
  1801. for (short int i = 1; i <= ICount; i++)
  1802. {
  1803. TTBCustomItem * Item = new TTBXItem(Menu);
  1804. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1805. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1806. Item->Hint = DView->HistoryPath[Data.Index];
  1807. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1808. Item->Tag = *reinterpret_cast<int*>(&Data);
  1809. Item->OnClick = HistoryItemClick;
  1810. Menu->Items->Add(Item);
  1811. }
  1812. }
  1813. }
  1814. //---------------------------------------------------------------------------
  1815. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1816. TOperationSide Side, bool Back)
  1817. {
  1818. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1819. {
  1820. // workaround
  1821. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1822. // operator new allocates memory in Pascal code, but calls inline
  1823. // constructor in C++, leading in problems, the function does
  1824. // both in Pascal code
  1825. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1826. UpdateHistoryMenu(Side, Back);
  1827. }
  1828. return FHistoryMenu[Side == osLocal][Back];
  1829. }
  1830. //---------------------------------------------------------------------------
  1831. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1832. TCustomDirView *Sender)
  1833. {
  1834. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1835. UpdateHistoryMenu(Side, true);
  1836. UpdateHistoryMenu(Side, false);
  1837. }
  1838. //---------------------------------------------------------------------------
  1839. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1840. {
  1841. // remote custom commands can be executed only if the server supports shell commands
  1842. // or have secondary shell
  1843. return HasActiveTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1844. }
  1845. //---------------------------------------------------------------------------
  1846. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1847. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1848. {
  1849. // -1 = hidden, 0 = disabled, 1 = enabled
  1850. int Result;
  1851. TFileCustomCommand RemoteCustomCommand;
  1852. TLocalCustomCommand LocalCustomCommand;
  1853. TFileCustomCommand * NonInteractiveCustomCommand =
  1854. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1855. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1856. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1857. if (FLAGCLEAR(Command.Params, ccLocal))
  1858. {
  1859. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1860. // custom command that does not operate with files can be executed anytime ...
  1861. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1862. {
  1863. // ... but do not show such command in remote file menu
  1864. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1865. {
  1866. Result = AllowedState;
  1867. }
  1868. else
  1869. {
  1870. Result = -1;
  1871. }
  1872. }
  1873. else
  1874. {
  1875. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1876. {
  1877. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1878. }
  1879. else
  1880. {
  1881. Result = -1;
  1882. }
  1883. }
  1884. }
  1885. else
  1886. {
  1887. // custom command that does not operate with files can be executed anytime
  1888. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1889. {
  1890. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1891. }
  1892. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1893. {
  1894. if ((ListType == ccltAll) || (ListType == ccltFile))
  1895. {
  1896. // special case is "diff"-style command that can be executed over any side,
  1897. // if we have both sides
  1898. Result =
  1899. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1900. // directly (instead of EnableSelectedOperation) to pass
  1901. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1902. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1903. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1904. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1905. }
  1906. else if (ListType == ccltBoth)
  1907. {
  1908. DebugAssert(!IsLocalBrowserMode());
  1909. Result = 1;
  1910. }
  1911. else
  1912. {
  1913. Result = -1;
  1914. }
  1915. }
  1916. else
  1917. {
  1918. if ((ListType == ccltAll) ||
  1919. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1920. {
  1921. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1922. }
  1923. else
  1924. {
  1925. Result = -1;
  1926. }
  1927. }
  1928. if ((Result > 0) &&
  1929. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1930. !HasActiveTerminal())
  1931. {
  1932. Result = 0;
  1933. }
  1934. }
  1935. return Result;
  1936. }
  1937. //---------------------------------------------------------------------------
  1938. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1939. TStrings * FileList, const TCustomCommandType & ACommand,
  1940. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1941. {
  1942. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1943. {
  1944. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1945. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1946. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1947. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1948. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1949. bool Capture =
  1950. FLAGSET(ACommand.Params, ccShowResults) ||
  1951. FLAGSET(ACommand.Params, ccCopyResults) ||
  1952. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1953. TCaptureOutputEvent OutputEvent = NULL;
  1954. DebugAssert(FCapturedLog == NULL);
  1955. if (Capture)
  1956. {
  1957. FCapturedLog = new TStringList();
  1958. OutputEvent = TerminalCaptureLog;
  1959. }
  1960. try
  1961. {
  1962. if (!RemoteCustomCommand.IsFileCommand(Command))
  1963. {
  1964. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1965. OutputEvent);
  1966. }
  1967. else
  1968. {
  1969. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1970. }
  1971. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1972. {
  1973. if (FLAGSET(ACommand.Params, ccCopyResults))
  1974. {
  1975. CopyToClipboard(FCapturedLog);
  1976. }
  1977. if (FLAGSET(ACommand.Params, ccShowResults))
  1978. {
  1979. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1980. }
  1981. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1982. {
  1983. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1984. }
  1985. }
  1986. }
  1987. __finally
  1988. {
  1989. SAFE_DESTROY(FCapturedLog);
  1990. }
  1991. }
  1992. }
  1993. //---------------------------------------------------------------------------
  1994. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1995. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1996. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1997. {
  1998. DebugAssert(!IsLocalBrowserMode());
  1999. TStrings * LocalFileList = NULL;
  2000. TStrings * RemoteFileList = NULL;
  2001. TStrings * RemoteFileListFull = NULL;
  2002. try
  2003. {
  2004. if (LocalFileCommand)
  2005. {
  2006. if (ALocalFileList == NULL)
  2007. {
  2008. DebugAssert(HasDirView[osLocal]);
  2009. // Cannot have focus on both panels, so we have to call AnyFileSelected
  2010. // directly (instead of EnableSelectedOperation) to pass
  2011. // false to FocusedFileOnlyWhenFocused
  2012. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  2013. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  2014. }
  2015. else
  2016. {
  2017. LocalFileList = ALocalFileList;
  2018. }
  2019. if (FileListCommand)
  2020. {
  2021. if (LocalFileList->Count != 1)
  2022. {
  2023. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2024. }
  2025. }
  2026. else
  2027. {
  2028. if ((LocalFileList->Count != 1) &&
  2029. (FileList->Count != 1) &&
  2030. (LocalFileList->Count != FileList->Count))
  2031. {
  2032. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2033. }
  2034. }
  2035. }
  2036. UnicodeString RootTempDir;
  2037. UnicodeString TempDir;
  2038. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2039. if (!RemoteFiles)
  2040. {
  2041. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true, true);
  2042. }
  2043. try
  2044. {
  2045. TDateTimes RemoteFileTimes;
  2046. if (RemoteFiles)
  2047. {
  2048. RemoteFileList = FileList;
  2049. }
  2050. else
  2051. {
  2052. RemoteFileList = new TStringList();
  2053. TMakeLocalFileListParams MakeFileListParam;
  2054. MakeFileListParam.FileList = RemoteFileList;
  2055. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2056. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2057. MakeFileListParam.Recursive =
  2058. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2059. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2060. if (!MakeFileListParam.Recursive)
  2061. {
  2062. RemoteFileTimes.clear();
  2063. RemoteFileListFull = new TStringList();
  2064. MakeFileListParam.FileList = RemoteFileListFull;
  2065. MakeFileListParam.Recursive = true;
  2066. MakeFileListParam.IncludeDirs = false;
  2067. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2068. }
  2069. else
  2070. {
  2071. RemoteFileListFull = RemoteFileList;
  2072. }
  2073. }
  2074. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2075. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2076. if (!NonBlocking)
  2077. {
  2078. int Count;
  2079. if (FileListCommand)
  2080. {
  2081. Count = 1;
  2082. }
  2083. else if (LocalFileCommand)
  2084. {
  2085. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2086. }
  2087. else
  2088. {
  2089. Count = RemoteFileList->Count;
  2090. }
  2091. Progress.Start(foCustomCommand, osRemote, Count);
  2092. DebugAssert(FProgressForm != NULL);
  2093. FProgressForm->ReadOnly = true;
  2094. }
  2095. try
  2096. {
  2097. if (FileListCommand)
  2098. {
  2099. UnicodeString LocalFile;
  2100. // MakeFileList does not delimit filenames
  2101. UnicodeString FileList = MakeFileList(RemoteFileList);
  2102. if (LocalFileCommand)
  2103. {
  2104. DebugAssert(LocalFileList->Count == 1);
  2105. LocalFile = LocalFileList->Strings[0];
  2106. }
  2107. TLocalCustomCommand CustomCommand(Data,
  2108. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2109. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2110. if (NonBlocking)
  2111. {
  2112. DebugAssert(!POutput);
  2113. ExecuteShellChecked(ShellCommand);
  2114. }
  2115. else
  2116. {
  2117. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2118. }
  2119. }
  2120. else if (LocalFileCommand)
  2121. {
  2122. if (LocalFileList->Count == 1)
  2123. {
  2124. UnicodeString LocalFile = LocalFileList->Strings[0];
  2125. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2126. {
  2127. UnicodeString FileName = RemoteFileList->Strings[Index];
  2128. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2129. Progress.SetFile(FileNameForProgress);
  2130. TLocalCustomCommand CustomCommand(Data,
  2131. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2132. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2133. TOnceDoneOperation OnceDoneOperation;
  2134. // Do not unselect anything, as it won't work with two panels anyway
  2135. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2136. }
  2137. }
  2138. else if (RemoteFileList->Count == 1)
  2139. {
  2140. UnicodeString FileName = RemoteFileList->Strings[0];
  2141. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2142. {
  2143. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2144. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2145. Progress.SetFile(LocalFileNameOnly);
  2146. TLocalCustomCommand CustomCommand(
  2147. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2148. FileName, LocalFileName, L"");
  2149. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2150. TOnceDoneOperation OnceDoneOperation;
  2151. // Do not unselect anything, as it won't work with two panels anyway
  2152. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2153. }
  2154. }
  2155. else
  2156. {
  2157. if (LocalFileList->Count != RemoteFileList->Count)
  2158. {
  2159. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2160. }
  2161. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2162. {
  2163. UnicodeString FileName = RemoteFileList->Strings[Index];
  2164. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2165. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2166. Progress.SetFile(LocalFileNameOnly); // sic
  2167. TLocalCustomCommand CustomCommand(
  2168. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2169. FileName, LocalFileName, L"");
  2170. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2171. TOnceDoneOperation OnceDoneOperation;
  2172. // Do not unselect anything, as it won't work with two panels anyway
  2173. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2174. }
  2175. }
  2176. }
  2177. else
  2178. {
  2179. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2180. {
  2181. UnicodeString FileName = RemoteFileList->Strings[Index];
  2182. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2183. Progress.SetFile(FileNameForProgress);
  2184. TLocalCustomCommand CustomCommand(Data,
  2185. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2186. FileName, L"", L"");
  2187. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2188. TOnceDoneOperation OnceDoneOperation;
  2189. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2190. }
  2191. }
  2192. }
  2193. __finally
  2194. {
  2195. if (!NonBlocking)
  2196. {
  2197. Progress.Stop();
  2198. }
  2199. }
  2200. DebugAssert(!FAutoOperation);
  2201. if (!RemoteFiles)
  2202. {
  2203. TempDir = IncludeTrailingBackslash(TempDir);
  2204. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2205. {
  2206. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2207. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2208. // Skip directories, process only nested files.
  2209. // The check is redundant as FileAge fails for directories anyway.
  2210. !DirectoryExists(FileName))
  2211. {
  2212. UnicodeString RemoteDir =
  2213. UnixExtractFileDir(
  2214. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2215. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  2216. TDateTime NewTime;
  2217. if (FileAge(FileName, NewTime) &&
  2218. (NewTime != RemoteFileTimes[Index]))
  2219. {
  2220. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2221. TemporaryFileCopyParam(CopyParam);
  2222. CopyParam.FileMask = L"";
  2223. FAutoOperation = true;
  2224. FMoveToQueue = false;
  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);
  2348. FProgressSide = FCurrentSide;
  2349. if (!LocalCustomCommand.IsFileCommand(Command))
  2350. {
  2351. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2352. }
  2353. // remote files?
  2354. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2355. {
  2356. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2357. }
  2358. // local files
  2359. else
  2360. {
  2361. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2362. }
  2363. if (POutput.get() != NULL)
  2364. {
  2365. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2366. int P = POutput->Pos(sLineBreak);
  2367. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2368. {
  2369. POutput->SetLength(P - 1);
  2370. }
  2371. // Copy even empty output to clipboard
  2372. if (FLAGSET(ACommand.Params, ccCopyResults))
  2373. {
  2374. CopyToClipboard(*POutput);
  2375. }
  2376. // But do not show an empty message box.
  2377. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2378. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2379. !POutput->IsEmpty())
  2380. {
  2381. TClipboardHandler ClipboardHandler;
  2382. ClipboardHandler.Text = *POutput;
  2383. TMessageParams Params;
  2384. TQueryButtonAlias Aliases[1];
  2385. Aliases[0].Button = qaRetry;
  2386. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2387. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2388. Params.Aliases = Aliases;
  2389. Params.AliasesCount = LENOF(Aliases);
  2390. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2391. }
  2392. }
  2393. }
  2394. //---------------------------------------------------------------------------
  2395. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2396. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2397. {
  2398. TCustomCommandData Data;
  2399. UnicodeString Site;
  2400. UnicodeString RemotePath;
  2401. if (HasActiveTerminal())
  2402. {
  2403. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2404. Data = TCustomCommandData(SessionData.get());
  2405. Site = Terminal->SessionData->SessionKey;
  2406. RemotePath = Terminal->CurrentDirectory;
  2407. }
  2408. UnicodeString HelpKeyword = ACommand.HomePage;
  2409. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2410. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2411. {
  2412. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2413. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2414. {
  2415. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2416. }
  2417. else
  2418. {
  2419. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2420. }
  2421. if (!DoCustomCommandOptionsDialog(
  2422. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2423. {
  2424. Abort();
  2425. }
  2426. }
  2427. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2428. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2429. {
  2430. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2431. }
  2432. else
  2433. {
  2434. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2435. }
  2436. }
  2437. //---------------------------------------------------------------------------
  2438. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2439. const TCustomCommandType & Command)
  2440. {
  2441. DebugAssert(FCustomCommandLocalFileList != NULL);
  2442. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2443. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2444. TStrings * LocalFileList = new TStringList();
  2445. TStrings * RemoteFileList = new TStringList();
  2446. try
  2447. {
  2448. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2449. {
  2450. LocalFileList->Clear();
  2451. LocalFileList->AddObject(
  2452. FCustomCommandLocalFileList->Strings[Index],
  2453. FCustomCommandLocalFileList->Objects[Index]);
  2454. RemoteFileList->Clear();
  2455. RemoteFileList->AddObject(
  2456. FCustomCommandRemoteFileList->Strings[Index],
  2457. FCustomCommandRemoteFileList->Objects[Index]);
  2458. CustomCommand(RemoteFileList, Command, LocalFileList);
  2459. }
  2460. }
  2461. __finally
  2462. {
  2463. delete LocalFileList;
  2464. delete RemoteFileList;
  2465. }
  2466. }
  2467. //---------------------------------------------------------------------------
  2468. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2469. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2470. {
  2471. delete FCustomCommandLocalFileList;
  2472. delete FCustomCommandRemoteFileList;
  2473. // takeover ownership,
  2474. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2475. FCustomCommandLocalFileList = LocalFileList;
  2476. FCustomCommandRemoteFileList = RemoteFileList;
  2477. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2478. if (Button != NULL)
  2479. {
  2480. FCustomCommandMenu->Items->Clear();
  2481. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2482. MenuPopup(FCustomCommandMenu, Button);
  2483. }
  2484. else
  2485. {
  2486. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2487. }
  2488. }
  2489. //---------------------------------------------------------------------------
  2490. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2491. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2492. {
  2493. DebugAssert(FCapturedLog != NULL);
  2494. if ((OutputType == cotOutput) || (OutputType == cotError))
  2495. {
  2496. FCapturedLog->Add(AddedLine);
  2497. }
  2498. }
  2499. //---------------------------------------------------------------------------
  2500. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2501. TOperationSide Side)
  2502. {
  2503. return
  2504. (Side == osOther) &&
  2505. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2506. }
  2507. //---------------------------------------------------------------------------
  2508. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2509. TOperationSide Side, TTBXCustomItem * Item,
  2510. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2511. {
  2512. TCustomDirView * DView = DirView(Side);
  2513. bool IsDefault = false;
  2514. if (DView->ItemFocused != NULL)
  2515. {
  2516. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2517. TResolvedDoubleClickAction DefaultAction =
  2518. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2519. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2520. }
  2521. TTBItemOptions O = Item->Options;
  2522. if (IsDefault)
  2523. {
  2524. Item->Options = O << tboDefault;
  2525. }
  2526. else
  2527. {
  2528. Item->Options = O >> tboDefault;
  2529. }
  2530. }
  2531. //---------------------------------------------------------------------------
  2532. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2533. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2534. {
  2535. TCustomDirView * DView = DirView(Side);
  2536. TListItem * Item = DView->ItemFocused;
  2537. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2538. EnableFocusedOperation[Side])
  2539. {
  2540. TPoint ClientPoint;
  2541. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2542. TPoint(0, 0) : MousePos;
  2543. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2544. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2545. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2546. }
  2547. }
  2548. //---------------------------------------------------------------------------
  2549. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2550. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2551. {
  2552. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2553. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2554. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2555. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2556. Handled = true;
  2557. }
  2558. //---------------------------------------------------------------------------
  2559. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2560. {
  2561. }
  2562. //---------------------------------------------------------------------------
  2563. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2564. {
  2565. DebugAssert(FErrorList == NULL);
  2566. if (WinConfiguration->ContinueOnError)
  2567. {
  2568. FErrorList = new TStringList();
  2569. Configuration->Usage->Inc(L"ContinuationsOnError");
  2570. }
  2571. NonVisualDataModule->StartBusy();
  2572. }
  2573. //---------------------------------------------------------------------------
  2574. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2575. {
  2576. NonVisualDataModule->EndBusy();
  2577. if (FErrorList)
  2578. {
  2579. HandleErrorList(FErrorList);
  2580. }
  2581. }
  2582. //---------------------------------------------------------------------------
  2583. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2584. const TCopyParamType & CopyParam)
  2585. {
  2586. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2587. {
  2588. Configuration->Usage->Inc(L"FileMaskUses");
  2589. }
  2590. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2591. {
  2592. Configuration->Usage->Inc(L"OperationMaskUses");
  2593. }
  2594. }
  2595. //---------------------------------------------------------------------------
  2596. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2597. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2598. {
  2599. DebugAssert(!IsLocalBrowserMode());
  2600. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2601. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2602. TTransferOperationParam DefaultParam;
  2603. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2604. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2605. switch (Param.Queue)
  2606. {
  2607. case asOn:
  2608. CopyParam.Queue = true;
  2609. break;
  2610. case asOff:
  2611. CopyParam.Queue = false;
  2612. break;
  2613. case asAuto:
  2614. default:
  2615. // keep default
  2616. break;
  2617. }
  2618. bool Result =
  2619. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2620. if (Result)
  2621. {
  2622. DebugAssert(Terminal);
  2623. bool SelectionRestored = false;
  2624. TCustomDirView * DView = NULL;
  2625. if (HasDirView[Side])
  2626. {
  2627. DView = DirView(Side);
  2628. DView->SaveSelection();
  2629. DView->SaveSelectedNames();
  2630. }
  2631. UpdateCopyParamCounters(CopyParam);
  2632. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2633. DebugAssert(FTransferResumeList == NULL);
  2634. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2635. FMoveToQueue = false;
  2636. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2637. try
  2638. {
  2639. TStrings * PermanentFileList;
  2640. std::unique_ptr<TStrings> PermanentFileListOwner;
  2641. try
  2642. {
  2643. if (Side == osLocal)
  2644. {
  2645. PermanentFileList = FileList;
  2646. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2647. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2648. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2649. if (Operation == foMove)
  2650. {
  2651. ReloadLocalDirectory();
  2652. if (DView != NULL)
  2653. {
  2654. DView->RestoreSelection();
  2655. }
  2656. SelectionRestored = true;
  2657. }
  2658. }
  2659. else
  2660. {
  2661. // Clone the file list as it may refer to current directory files,
  2662. // which get destroyed, when the source directory is reloaded after foMove operation.
  2663. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2664. // But for a hotfix, we are not going to do such a big change.
  2665. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2666. PermanentFileList = PermanentFileListOwner.get();
  2667. try
  2668. {
  2669. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2670. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2671. }
  2672. __finally
  2673. {
  2674. if (Operation == foMove)
  2675. {
  2676. if (DView != NULL)
  2677. {
  2678. DView->RestoreSelection();
  2679. }
  2680. SelectionRestored = true;
  2681. }
  2682. ReloadLocalDirectory(Param.TargetDirectory);
  2683. }
  2684. }
  2685. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2686. if (FMoveToQueue)
  2687. {
  2688. Abort();
  2689. }
  2690. }
  2691. catch (EAbort &)
  2692. {
  2693. if (FMoveToQueue)
  2694. {
  2695. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2696. DebugAssert(CopyParam.TransferSkipList == NULL);
  2697. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2698. if (TransferResumeList->Count > 0)
  2699. {
  2700. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2701. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2702. }
  2703. CopyParam.TransferSkipList = TransferResumeList.release();
  2704. // not really needed, just to keep it consistent with TransferResumeList
  2705. FTransferResumeList = NULL;
  2706. FMoveToQueue = false;
  2707. Configuration->Usage->Inc("MovesToBackground");
  2708. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2709. ClearTransferSourceSelection(Direction);
  2710. }
  2711. throw;
  2712. }
  2713. }
  2714. __finally
  2715. {
  2716. if (!SelectionRestored && (DView != NULL))
  2717. {
  2718. DView->DiscardSavedSelection();
  2719. }
  2720. FTransferResumeList = NULL;
  2721. }
  2722. }
  2723. return Result;
  2724. }
  2725. //---------------------------------------------------------------------------
  2726. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2727. TOperationSide Side, TStrings * FileList, void * Param)
  2728. {
  2729. DebugAssert(FileList->Count);
  2730. // We deliberately do not toggle alternative flag (Param), but use OR,
  2731. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2732. // shortcut of CurrentDeleteAlternativeAction
  2733. bool Alternative =
  2734. bool(Param) || UseAlternativeFunction();
  2735. bool Recycle;
  2736. if (IsSideLocalBrowser(Side))
  2737. {
  2738. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2739. }
  2740. else
  2741. {
  2742. Recycle =
  2743. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2744. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2745. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2746. }
  2747. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2748. if (!Result)
  2749. {
  2750. UnicodeString Query;
  2751. if (FileList->Count == 1)
  2752. {
  2753. if (IsSideLocalBrowser(Side))
  2754. {
  2755. Query = ExtractFileName(FileList->Strings[0]);
  2756. }
  2757. else
  2758. {
  2759. Query = UnixExtractFileName(FileList->Strings[0]);
  2760. }
  2761. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2762. }
  2763. else
  2764. {
  2765. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2766. }
  2767. TMessageParams Params(mpNeverAskAgainCheck);
  2768. Params.ImageName = L"Delete file";
  2769. unsigned int Answer =
  2770. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2771. if (Answer == qaNeverAskAgain)
  2772. {
  2773. Result = true;
  2774. if (Recycle)
  2775. {
  2776. WinConfiguration->ConfirmRecycling = false;
  2777. }
  2778. else
  2779. {
  2780. WinConfiguration->ConfirmDeleting = false;
  2781. }
  2782. }
  2783. else
  2784. {
  2785. Result = (Answer == qaOK);
  2786. }
  2787. }
  2788. if (Result)
  2789. {
  2790. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2791. }
  2792. return Result;
  2793. }
  2794. //---------------------------------------------------------------------------
  2795. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2796. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2797. {
  2798. TAutoBatch AutoBatch(this);
  2799. bool Result;
  2800. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2801. {
  2802. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2803. }
  2804. else if (Operation == foRename)
  2805. {
  2806. DebugAssert(DirView(Side)->ItemFocused);
  2807. DirView(Side)->ItemFocused->EditCaption();
  2808. Result = true;
  2809. }
  2810. else if (Operation == foDelete)
  2811. {
  2812. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2813. }
  2814. else if (Operation == foSetProperties)
  2815. {
  2816. DirView(osRemote)->SaveSelectedNames();
  2817. Result = SetProperties(Side, FileList);
  2818. }
  2819. else if (Operation == foCustomCommand)
  2820. {
  2821. DebugAssert(Param);
  2822. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2823. DirView(osRemote)->SaveSelectedNames();
  2824. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2825. CustomCommand(FileList, *Command, NULL);
  2826. Result = true;
  2827. }
  2828. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2829. {
  2830. DebugAssert(!IsSideLocalBrowser(Side));
  2831. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2832. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2833. }
  2834. else if (Operation == foLock)
  2835. {
  2836. DebugAssert(!IsSideLocalBrowser(Side));
  2837. LockFiles(FileList, true);
  2838. Result = true;
  2839. }
  2840. else if (Operation == foUnlock)
  2841. {
  2842. DebugAssert(!IsSideLocalBrowser(Side));
  2843. LockFiles(FileList, false);
  2844. Result = true;
  2845. }
  2846. else
  2847. {
  2848. DebugFail();
  2849. }
  2850. return Result;
  2851. }
  2852. //---------------------------------------------------------------------------
  2853. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2854. {
  2855. if (Side == osCurrent)
  2856. {
  2857. Side = FCurrentSide;
  2858. }
  2859. return Side;
  2860. }
  2861. //---------------------------------------------------------------------------
  2862. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2863. {
  2864. TOperationSide Result;
  2865. switch (GetSide(Side))
  2866. {
  2867. case osLocal:
  2868. Result = osOther;
  2869. break;
  2870. case osOther:
  2871. Result = osLocal;
  2872. break;
  2873. default:
  2874. DebugFail();
  2875. Abort();
  2876. }
  2877. return Result;
  2878. }
  2879. //---------------------------------------------------------------------------
  2880. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2881. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2882. {
  2883. Side = GetSide(Side);
  2884. bool FullPath = IsSideLocalBrowser(Side);
  2885. TCustomDirView * ADirView = DirView(Side);
  2886. std::unique_ptr<TStringList> FileList(new TStringList());
  2887. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2888. bool ReloadProperties =
  2889. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2890. DebugAlwaysTrue(HasActiveTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2891. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2892. if (Result && ReloadProperties)
  2893. {
  2894. std::unique_ptr<TStringList> FileList2(new TStringList());
  2895. FileList->CaseSensitive = true;
  2896. FileList->Sort();
  2897. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2898. {
  2899. TListItem * Item = ADirView->Items->Item[Index];
  2900. UnicodeString FileName = ADirView->ItemFileName(Item);
  2901. int Index2;
  2902. if (FileList->Find(FileName, Index2))
  2903. {
  2904. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2905. }
  2906. }
  2907. LoadFilesProperties(FileList2.get());
  2908. }
  2909. return Result;
  2910. }
  2911. //---------------------------------------------------------------------------
  2912. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2913. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2914. bool NoConfirmation, void * Param)
  2915. {
  2916. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2917. {
  2918. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2919. {
  2920. DebugAssert(!IsLocalBrowserMode());
  2921. if (GetSide(Side) == osLocal)
  2922. {
  2923. Configuration->Usage->Inc(L"UploadsCommand");
  2924. }
  2925. else
  2926. {
  2927. Configuration->Usage->Inc(L"DownloadsCommand");
  2928. }
  2929. }
  2930. }
  2931. }
  2932. //---------------------------------------------------------------------------
  2933. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2934. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2935. {
  2936. TTransferOperationParam Param;
  2937. if ((WinConfiguration->Interface != ifCommander) ||
  2938. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2939. {
  2940. Flags &= ~cocShortCutHint;
  2941. }
  2942. TCustomDirView * DView = DirView(Side);
  2943. Param.Options =
  2944. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2945. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2946. if (FLAGSET(Flags, cocQueue))
  2947. {
  2948. Param.Queue = asOn;
  2949. }
  2950. else if (FLAGSET(Flags, cocNonQueue))
  2951. {
  2952. Param.Queue = asOff;
  2953. }
  2954. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2955. }
  2956. //---------------------------------------------------------------------------
  2957. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2958. {
  2959. int Count = ErrorList->Count;
  2960. try
  2961. {
  2962. if (ErrorList->Count)
  2963. {
  2964. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2965. if (MessageDialog(Message, qtError,
  2966. qaOK | qaCancel, HELP_NONE) == qaOK)
  2967. {
  2968. unsigned int Answer;
  2969. int Index = 0;
  2970. do
  2971. {
  2972. DebugAssert(Index >= 0 && Index < Count);
  2973. TQueryButtonAlias Aliases[2];
  2974. Aliases[0].Button = qaYes;
  2975. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2976. Aliases[1].Button = qaNo;
  2977. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2978. TMessageParams Params;
  2979. Params.Aliases = Aliases;
  2980. Params.AliasesCount = LENOF(Aliases);
  2981. int No = Index + 1;
  2982. UnicodeString Message = ErrorList->Strings[Index];
  2983. UnicodeString AMainInstructions;
  2984. UnicodeString Details;
  2985. if (ExtractMainInstructions(Message, AMainInstructions))
  2986. {
  2987. Details = Message;
  2988. Message = AMainInstructions;
  2989. }
  2990. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2991. Answer = MoreMessageDialog(
  2992. Message,
  2993. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2994. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2995. qaOK, HELP_NONE, &Params);
  2996. if (Answer == qaNo)
  2997. {
  2998. Index++;
  2999. }
  3000. if (Answer == qaYes)
  3001. {
  3002. Index--;
  3003. }
  3004. }
  3005. while (Answer != qaOK);
  3006. }
  3007. }
  3008. }
  3009. __finally
  3010. {
  3011. TStrings * List = ErrorList;
  3012. ErrorList = NULL;
  3013. for (int i = 0; i < Count; i++)
  3014. {
  3015. delete List->Objects[i];
  3016. }
  3017. delete List;
  3018. }
  3019. }
  3020. //---------------------------------------------------------------------------
  3021. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3022. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3023. {
  3024. // needed for checking filemasks, as there's no directory object
  3025. // associated with the file object
  3026. File->FullFileName = FullFileName;
  3027. TFileMasks::TParams MaskParams;
  3028. MaskParams.Size = File->Size;
  3029. MaskParams.Modification = File->Modification;
  3030. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3031. }
  3032. //---------------------------------------------------------------------------
  3033. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3034. {
  3035. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3036. Side = GetSide(Side);
  3037. TCustomDirView * DView = DirView(Side);
  3038. TListItem * FocusedItem = DView->ItemFocused;
  3039. UnicodeString Name;
  3040. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3041. {
  3042. Name = DView->ItemFileName(FocusedItem);
  3043. }
  3044. else
  3045. {
  3046. Name = LoadStr(NEW_FILE);
  3047. }
  3048. UnicodeString Names = Name;
  3049. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3050. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3051. HELP_EDIT_NEW, History.get(), true, NULL, true, 400))
  3052. {
  3053. while (!Names.IsEmpty())
  3054. {
  3055. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3056. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3057. UnicodeString TargetFileName;
  3058. UnicodeString LocalFileName;
  3059. UnicodeString RootTempDir;
  3060. UnicodeString TempDir;
  3061. UnicodeString RemoteDirectory;
  3062. bool ExistingFile = false;
  3063. if (!IsSideLocalBrowser(Side))
  3064. {
  3065. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3066. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3067. if ((File.get() != NULL) &&
  3068. !File->IsDirectory)
  3069. {
  3070. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3071. ExistingFile = true;
  3072. }
  3073. File.reset(NULL);
  3074. if (!ExistingFile)
  3075. {
  3076. RemoteDirectory = UnixExtractFilePath(Name);
  3077. TemporaryDirectoryForRemoteFiles(
  3078. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3079. TargetFileName = UnixExtractFileName(Name);
  3080. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3081. LocalFileName = TempDir +
  3082. // We probably do not want to trim the VMS version here
  3083. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3084. }
  3085. }
  3086. else
  3087. {
  3088. if (ExtractFilePath(Name).IsEmpty())
  3089. {
  3090. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3091. }
  3092. else
  3093. {
  3094. LocalFileName = ExpandFileName(Name);
  3095. }
  3096. TargetFileName = ExtractFileName(Name);
  3097. }
  3098. if (!ExistingFile)
  3099. {
  3100. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3101. if (NewFile)
  3102. {
  3103. int File = FileCreate(ApiPath(LocalFileName));
  3104. if (File < 0)
  3105. {
  3106. if (!RootTempDir.IsEmpty())
  3107. {
  3108. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3109. }
  3110. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3111. }
  3112. else
  3113. {
  3114. FileClose(File);
  3115. }
  3116. }
  3117. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3118. const TEditorData * ExternalEditor = NULL;
  3119. TFileMasks::TParams MaskParams; // size not known
  3120. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3121. false, MaskParams);
  3122. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3123. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3124. }
  3125. }
  3126. }
  3127. }
  3128. //---------------------------------------------------------------------------
  3129. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3130. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3131. {
  3132. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3133. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3134. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3135. return
  3136. ((ExecuteFileBy == efInternalEditor)) ||
  3137. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3138. }
  3139. //---------------------------------------------------------------------------
  3140. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3141. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3142. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3143. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3144. {
  3145. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3146. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3147. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3148. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3149. Side = GetSide(Side);
  3150. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3151. if (!IsSideLocalBrowser(Side))
  3152. {
  3153. Data->Terminal = Terminal;
  3154. Data->SessionData = CloneCurrentSessionData();
  3155. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3156. Data->RemoteDirectory = RemoteDirectory;
  3157. Data->SessionName = Terminal->SessionData->SessionName;
  3158. Data->LocalRootDirectory = LocalRootDirectory;
  3159. Data->OriginalFileName = OriginalFileName;
  3160. Data->Command = L""; // will be changed later for external editor
  3161. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3162. if (WinConfiguration->EditorCheckNotModified)
  3163. {
  3164. Data->SourceTimestamp = SourceTimestamp;
  3165. }
  3166. }
  3167. if (ExecuteFileBy == efInternalEditor)
  3168. {
  3169. if (!IsSideLocalBrowser(Side))
  3170. {
  3171. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3172. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3173. TForm * Editor;
  3174. try
  3175. {
  3176. Editor =
  3177. ShowEditorForm(
  3178. FileName, this,
  3179. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3180. SaveAllInternalEditors, AnyInternalEditorModified,
  3181. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3182. }
  3183. catch(...)
  3184. {
  3185. if (!LocalRootDirectory.IsEmpty())
  3186. {
  3187. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3188. }
  3189. throw;
  3190. }
  3191. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3192. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3193. }
  3194. else
  3195. {
  3196. DebugAssert(!StandaloneOperation);
  3197. TForm * Editor =
  3198. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3199. SaveAllInternalEditors, AnyInternalEditorModified,
  3200. L"", false, SessionColor, -1, NewFile);
  3201. FLocalEditors->Add(Editor);
  3202. }
  3203. }
  3204. else
  3205. {
  3206. HANDLE Process;
  3207. if (ExecuteFileBy == efExternalEditor)
  3208. {
  3209. UnicodeString Program, Params, Dir;
  3210. Data->Command = ExternalEditor->ExternalEditor;
  3211. ReformatFileNameCommand(Data->Command);
  3212. SplitCommand(Data->Command, Program, Params, Dir);
  3213. Params = ExpandFileNameCommand(Params, FileName);
  3214. Program = ExpandEnvironmentVariables(Program);
  3215. if (!ExecuteShell(Program, Params, Process))
  3216. {
  3217. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3218. }
  3219. }
  3220. else
  3221. {
  3222. DebugAssert(!IsSideLocalBrowser(Side));
  3223. if (!ExecuteShell(FileName, L"", Process))
  3224. {
  3225. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3226. }
  3227. }
  3228. if (IsSideLocalBrowser(Side) ||
  3229. ((ExecuteFileBy == efShell) &&
  3230. !WinConfiguration->Editor.SDIShellEditor) ||
  3231. ((ExecuteFileBy == efExternalEditor) &&
  3232. !ExternalEditor->SDIExternalEditor))
  3233. {
  3234. // no need for handle
  3235. if (Process != NULL)
  3236. {
  3237. DebugCheck(CloseHandle(Process));
  3238. }
  3239. Process = INVALID_HANDLE_VALUE;
  3240. }
  3241. else
  3242. {
  3243. if (Process == NULL)
  3244. {
  3245. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3246. }
  3247. }
  3248. if (!IsSideLocalBrowser(Side))
  3249. {
  3250. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3251. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3252. }
  3253. }
  3254. }
  3255. //---------------------------------------------------------------------------
  3256. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3257. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3258. void * /*Arg*/)
  3259. {
  3260. if (Token != NULL)
  3261. {
  3262. EditorFormFileSave(static_cast<TForm *>(Token));
  3263. }
  3264. }
  3265. //---------------------------------------------------------------------------
  3266. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3267. {
  3268. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3269. {
  3270. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3271. }
  3272. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3273. }
  3274. //---------------------------------------------------------------------------
  3275. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3276. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3277. void * Arg)
  3278. {
  3279. if ((Token != NULL) &&
  3280. IsEditorFormModified(static_cast<TForm *>(Token)))
  3281. {
  3282. *static_cast<bool *>(Arg) = true;
  3283. }
  3284. }
  3285. //---------------------------------------------------------------------------
  3286. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3287. TObject * /*Sender*/, bool & Modified)
  3288. {
  3289. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3290. {
  3291. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3292. {
  3293. Modified = true;
  3294. }
  3295. }
  3296. if (!Modified)
  3297. {
  3298. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3299. }
  3300. }
  3301. //---------------------------------------------------------------------------
  3302. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3303. {
  3304. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3305. }
  3306. //---------------------------------------------------------------------------
  3307. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3308. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3309. UnicodeString & Result, UnicodeString & RootDirectory)
  3310. {
  3311. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3312. {
  3313. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3314. Result = RootDirectory;
  3315. }
  3316. else
  3317. {
  3318. RootDirectory = L"";
  3319. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3320. Result = IncludeTrailingBackslash(Result);
  3321. }
  3322. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3323. {
  3324. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3325. }
  3326. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3327. {
  3328. UnicodeString ARemoteDirectory = RemoteDirectory;
  3329. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3330. {
  3331. ARemoteDirectory.Delete(1, 1);
  3332. }
  3333. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3334. }
  3335. if (!ForceDirectories(ApiPath(Result)))
  3336. {
  3337. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3338. }
  3339. }
  3340. //---------------------------------------------------------------------------
  3341. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3342. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3343. bool GetTargetNames, bool AutoOperation, bool SimpleTempDir)
  3344. {
  3345. DebugAssert(!IsLocalBrowserMode());
  3346. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3347. if (ForceText)
  3348. {
  3349. CopyParam.TransferMode = tmAscii;
  3350. }
  3351. TemporaryFileCopyParam(CopyParam);
  3352. if (TempDir.IsEmpty())
  3353. {
  3354. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3355. }
  3356. DebugAssert(!FAutoOperation);
  3357. FAutoOperation = AutoOperation;
  3358. FMoveToQueue = false;
  3359. Terminal->ExceptionOnFail = true;
  3360. try
  3361. {
  3362. try
  3363. {
  3364. // turn off confirmations, as for MDI editors we may possibly download
  3365. // the same file over
  3366. Terminal->CopyToLocal(
  3367. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3368. if (GetTargetNames)
  3369. {
  3370. for (int i = 0; i < FileList->Count; i++)
  3371. {
  3372. FileList->Strings[i] =
  3373. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3374. }
  3375. }
  3376. }
  3377. catch(...)
  3378. {
  3379. if (!RootTempDir.IsEmpty())
  3380. {
  3381. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3382. }
  3383. throw;
  3384. }
  3385. }
  3386. __finally
  3387. {
  3388. FAutoOperation = false;
  3389. Terminal->ExceptionOnFail = false;
  3390. }
  3391. }
  3392. //---------------------------------------------------------------------------
  3393. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3394. {
  3395. // Do not waste time checking for default editor list the next time,
  3396. // or testing if default editor is not notepad.
  3397. bool TryNextTime = false;
  3398. UnicodeString UsageState;
  3399. if (!WinConfiguration->EditorList->IsDefaultList())
  3400. {
  3401. UsageState = "H";
  3402. }
  3403. else
  3404. {
  3405. UnicodeString Executable;
  3406. UnicodeString ExecutableDescription;
  3407. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3408. {
  3409. UnicodeString Message =
  3410. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3411. unsigned int Answer =
  3412. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3413. if (Answer != qaOK)
  3414. {
  3415. UsageState = "R";
  3416. }
  3417. else
  3418. {
  3419. UsageState = "A";
  3420. TEditorData EditorData;
  3421. EditorData.Editor = edExternal;
  3422. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3423. EditorData.ExternalEditorOptionsAutodetect();
  3424. TEditorList EditorList;
  3425. EditorList = *WinConfiguration->EditorList;
  3426. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3427. WinConfiguration->EditorList = &EditorList;
  3428. }
  3429. }
  3430. }
  3431. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3432. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3433. }
  3434. //---------------------------------------------------------------------------
  3435. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3436. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3437. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3438. {
  3439. if (ExecuteFileBy == efDefaultEditor)
  3440. {
  3441. if (!WinConfiguration->OfferedEditorAutoConfig)
  3442. {
  3443. EditorAutoConfig();
  3444. }
  3445. const TEditorPreferences * Editor =
  3446. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3447. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3448. {
  3449. ExecuteFileBy = efInternalEditor;
  3450. ExternalEditor = NULL;
  3451. }
  3452. else if (Editor->Data->Editor == edOpen)
  3453. {
  3454. ExecuteFileBy = efShell;
  3455. ExternalEditor = NULL;
  3456. }
  3457. else
  3458. {
  3459. ExecuteFileBy = efExternalEditor;
  3460. ExternalEditor = Editor->Data;
  3461. }
  3462. }
  3463. }
  3464. //---------------------------------------------------------------------------
  3465. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3466. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3467. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3468. {
  3469. UnicodeString OriginalFileName;
  3470. UnicodeString LocalRootDirectory;
  3471. UnicodeString RemoteDirectory;
  3472. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3473. IsSideLocalBrowser(Side), MaskParams);
  3474. UnicodeString Counter;
  3475. UnicodeString LocalFileName;
  3476. bool Handled = false;
  3477. if (!IsSideLocalBrowser(Side))
  3478. {
  3479. // We need to trim VMS version here, so that we use name without version
  3480. // when uploading back to create a new version of the file
  3481. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3482. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3483. TObject * Token = NULL;
  3484. UnicodeString LocalDirectory;
  3485. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3486. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3487. LocalDirectory))
  3488. {
  3489. if (Token != NULL)
  3490. {
  3491. TForm * Form = dynamic_cast<TForm *>(Token);
  3492. if (Form->WindowState == wsMinimized)
  3493. {
  3494. ShowWindow(Form->Handle, SW_RESTORE);
  3495. }
  3496. else
  3497. {
  3498. Form->SetFocus();
  3499. }
  3500. Handled = true;
  3501. }
  3502. else
  3503. {
  3504. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3505. }
  3506. }
  3507. if (!Handled)
  3508. {
  3509. TStringList * FileList1 = new TStringList();
  3510. try
  3511. {
  3512. FileList1->AddObject(FullFileName, Object);
  3513. TemporarilyDownloadFiles(FileList1,
  3514. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3515. LocalRootDirectory, LocalDirectory, true, true, false);
  3516. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3517. }
  3518. __finally
  3519. {
  3520. delete FileList1;
  3521. }
  3522. switch (ExecuteFileBy)
  3523. {
  3524. case efShell:
  3525. Counter = "RemoteFilesExecuted";
  3526. break;
  3527. case efInternalEditor:
  3528. Counter = "RemoteFilesOpenedInInternalEditor";
  3529. break;
  3530. case efExternalEditor:
  3531. Counter = "RemoteFilesOpenedInExternalEditor";
  3532. break;
  3533. default:
  3534. DebugFail();
  3535. }
  3536. }
  3537. }
  3538. else
  3539. {
  3540. LocalFileName = FullFileName;
  3541. OriginalFileName = ExtractFileName(FullFileName);
  3542. switch (ExecuteFileBy)
  3543. {
  3544. case efShell:
  3545. Counter = "LocalFilesExecuted";
  3546. break;
  3547. case efInternalEditor:
  3548. Counter = "LocalFilesOpenedInInternalEditor";
  3549. break;
  3550. case efExternalEditor:
  3551. Counter = "LocalFilesOpenedInExternalEditor";
  3552. break;
  3553. default:
  3554. DebugFail();
  3555. }
  3556. }
  3557. if (!Handled)
  3558. {
  3559. Configuration->Usage->Inc(Counter);
  3560. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3561. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3562. }
  3563. }
  3564. //---------------------------------------------------------------------------
  3565. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3566. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3567. bool AllSelected, bool OnFocused)
  3568. {
  3569. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3570. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3571. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3572. Side = GetSide(Side);
  3573. TCustomDirView * DView = DirView(Side);
  3574. TStrings * FileList =
  3575. AllSelected ?
  3576. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3577. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3578. try
  3579. {
  3580. DebugAssert(AllSelected || (FileList->Count == 1));
  3581. for (int i = 0; i < FileList->Count; i++)
  3582. {
  3583. UnicodeString ListFileName = FileList->Strings[i];
  3584. UnicodeString FileNameOnly =
  3585. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3586. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3587. if (!DView->ItemIsDirectory(Item))
  3588. {
  3589. UnicodeString FullFileName;
  3590. if (!IsSideLocalBrowser(Side))
  3591. {
  3592. FullFileName = DirView(Side)->Path + ListFileName;
  3593. }
  3594. else
  3595. {
  3596. FullFileName = ListFileName;
  3597. }
  3598. TObject * Object = FileList->Objects[i];
  3599. TFileMasks::TParams MaskParams;
  3600. MaskParams.Size = DView->ItemFileSize(Item);
  3601. TDateTimePrecision Precision;
  3602. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3603. std::unique_ptr<TRemoteFile> File;
  3604. if (!IsSideLocalBrowser(Side))
  3605. {
  3606. File.reset(Terminal->TryReadFile(FullFileName));
  3607. if (File.get() != NULL)
  3608. {
  3609. File->FullFileName = FullFileName;
  3610. Object = File.get();
  3611. MaskParams.Size = File->Size;
  3612. MaskParams.Modification = File->Modification;
  3613. }
  3614. }
  3615. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3616. }
  3617. }
  3618. }
  3619. __finally
  3620. {
  3621. delete FileList;
  3622. }
  3623. }
  3624. //---------------------------------------------------------------------------
  3625. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3626. {
  3627. CopyParam.FileNameCase = ncNoChange;
  3628. CopyParam.PreserveRights = false;
  3629. CopyParam.PreserveReadOnly = false;
  3630. CopyParam.ReplaceInvalidChars = true;
  3631. CopyParam.IncludeFileMask = TFileMasks();
  3632. CopyParam.NewerOnly = false;
  3633. CopyParam.FileMask = L"";
  3634. }
  3635. //---------------------------------------------------------------------------
  3636. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3637. {
  3638. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3639. }
  3640. //---------------------------------------------------------------------------
  3641. class TEditorUploadQueueItem : public TUploadQueueItem
  3642. {
  3643. public:
  3644. __fastcall TEditorUploadQueueItem(
  3645. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3646. const TCopyParamType * CopyParam, int Params) :
  3647. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, true, false)
  3648. {
  3649. }
  3650. protected:
  3651. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3652. {
  3653. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3654. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3655. }
  3656. };
  3657. //---------------------------------------------------------------------------
  3658. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3659. {
  3660. if (WinConfiguration->EditorCheckNotModified) // optimization
  3661. {
  3662. UnicodeString RemoteFilePath;
  3663. {
  3664. TGuard Guard(FEditorManager->Section);
  3665. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3666. if (DebugAlwaysTrue(Data != NULL) &&
  3667. EditorCheckNotModified(Data))
  3668. {
  3669. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3670. }
  3671. }
  3672. if (!RemoteFilePath.IsEmpty())
  3673. {
  3674. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3675. if (File.get() != NULL)
  3676. {
  3677. TGuard Guard(FEditorManager->Section);
  3678. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3679. if (DebugAlwaysTrue(Data != NULL))
  3680. {
  3681. Data->SourceTimestamp = File->Modification;
  3682. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3683. }
  3684. }
  3685. }
  3686. }
  3687. }
  3688. //---------------------------------------------------------------------------
  3689. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3690. const UnicodeString & FileName, TEditedFileData * Data, HANDLE UploadCompleteEvent, bool & Retry)
  3691. {
  3692. TTerminalManager * Manager = TTerminalManager::Instance();
  3693. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3694. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3695. {
  3696. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3697. Retry = true;
  3698. }
  3699. else if (!IsActiveTerminal(Data->Terminal))
  3700. {
  3701. if (!NonVisualDataModule->Busy)
  3702. {
  3703. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3704. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3705. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3706. if (Data->Terminal == NULL)
  3707. {
  3708. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3709. if (SameSiteTerminal != NULL)
  3710. {
  3711. UnicodeString Message =
  3712. FMTLOAD(EDIT_SESSION_REATTACH,
  3713. (FileNameOnly, Data->SessionName, FileNameOnly));
  3714. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3715. {
  3716. Data->Terminal = SameSiteTerminal;
  3717. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3718. // We might also overwrite session data
  3719. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3720. }
  3721. else
  3722. {
  3723. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3724. Abort();
  3725. }
  3726. }
  3727. }
  3728. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3729. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3730. {
  3731. UnicodeString Message =
  3732. MainInstructions(
  3733. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3734. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3735. {
  3736. if (Terminal->Disconnected)
  3737. {
  3738. Manager->ActiveSession = Terminal;
  3739. ReconnectSession();
  3740. // Was it reconnected? (if not, Data->Terminal should be nulled now)
  3741. if (!IsActiveTerminal(Data->Terminal) || (Terminal != Data->Terminal))
  3742. {
  3743. Abort();
  3744. }
  3745. }
  3746. else
  3747. {
  3748. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3749. }
  3750. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3751. }
  3752. else
  3753. {
  3754. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3755. Abort();
  3756. }
  3757. }
  3758. }
  3759. if (!IsActiveTerminal(Data->Terminal))
  3760. {
  3761. Configuration->Usage->Inc(L"EditInactiveSession");
  3762. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3763. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3764. (ExtractFileName(FileName), Data->SessionName)));
  3765. }
  3766. }
  3767. if (!Retry && EditorCheckNotModified(Data))
  3768. {
  3769. if (NonVisualDataModule->Busy)
  3770. {
  3771. Retry = true;
  3772. }
  3773. else
  3774. {
  3775. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3776. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3777. if (File.get() != NULL)
  3778. {
  3779. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3780. if (File->Modification != Data->SourceTimestamp)
  3781. {
  3782. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3783. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3784. {
  3785. Abort();
  3786. }
  3787. }
  3788. }
  3789. }
  3790. }
  3791. if (!Retry)
  3792. {
  3793. TStrings * FileList = new TStringList();
  3794. try
  3795. {
  3796. FileList->Add(FileName);
  3797. // Consider using the same settings (preset) as when the file was downloaded.
  3798. // More over this does not reflect the actual session that will do the upload.
  3799. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3800. TemporaryFileCopyParam(CopyParam);
  3801. if (Data->ForceText)
  3802. {
  3803. CopyParam.TransferMode = tmAscii;
  3804. }
  3805. // so i do not need to worry if masking algorithm works in all cases
  3806. // ("" means "copy file name", no masking is actually done)
  3807. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3808. {
  3809. CopyParam.FileMask = L"";
  3810. }
  3811. else
  3812. {
  3813. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3814. }
  3815. int Params = cpNoConfirmation | cpTemporary;
  3816. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3817. {
  3818. TTerminalQueue * AQueue = Manager->FindQueueForTerminal(Data->Terminal);
  3819. TQueueItem * QueueItem =
  3820. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3821. QueueItem->CompleteEvent = UploadCompleteEvent;
  3822. AddQueueItem(AQueue, QueueItem, Data->Terminal);
  3823. }
  3824. else
  3825. {
  3826. if (NonVisualDataModule->Busy)
  3827. {
  3828. Retry = true;
  3829. }
  3830. else
  3831. {
  3832. FMoveToQueue = false;
  3833. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3834. SetEvent(UploadCompleteEvent);
  3835. }
  3836. }
  3837. }
  3838. __finally
  3839. {
  3840. delete FileList;
  3841. }
  3842. }
  3843. }
  3844. //---------------------------------------------------------------------------
  3845. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3846. const UnicodeString & FileName, TEditedFileData * Data)
  3847. {
  3848. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3849. DebugAssert(!NonVisualDataModule->Busy);
  3850. if (!IsActiveTerminal(Data->Terminal))
  3851. {
  3852. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3853. (ExtractFileName(FileName), Data->SessionName)));
  3854. }
  3855. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3856. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3857. NonVisualDataModule->StartBusy();
  3858. try
  3859. {
  3860. std::unique_ptr<TRemoteFile> File;
  3861. UnicodeString RemoteFileName =
  3862. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3863. Terminal->ExceptionOnFail = true;
  3864. try
  3865. {
  3866. File.reset(Terminal->ReadFile(RemoteFileName));
  3867. if (!File->HaveFullFileName)
  3868. {
  3869. File->FullFileName = RemoteFileName;
  3870. }
  3871. }
  3872. __finally
  3873. {
  3874. Terminal->ExceptionOnFail = false;
  3875. }
  3876. std::unique_ptr<TStrings> FileList(new TStringList());
  3877. FileList->AddObject(RemoteFileName, File.get());
  3878. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3879. UnicodeString TempDir = ExtractFilePath(FileName);
  3880. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, true, false);
  3881. if (EditorCheckNotModified(Data))
  3882. {
  3883. Data->SourceTimestamp = File->Modification;
  3884. }
  3885. // sanity check, the target file name should be still the same
  3886. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3887. }
  3888. __finally
  3889. {
  3890. NonVisualDataModule->EndBusy();
  3891. // it actually may not exist anymore...
  3892. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3893. }
  3894. }
  3895. //---------------------------------------------------------------------------
  3896. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3897. const TEditedFileData * Data, bool & KeepOpen)
  3898. {
  3899. // Command is set for external editors only (not for "shell" open).
  3900. if (!Data->Command.IsEmpty())
  3901. {
  3902. bool AnyFound = false;
  3903. bool AnyMDI = false;
  3904. bool AnyNonMDI = false;
  3905. bool AnyDetect = false;
  3906. TEditorList * EditorList = new TEditorList();
  3907. try
  3908. {
  3909. *EditorList = *WinConfiguration->EditorList;
  3910. for (int i = 0; i < EditorList->Count; i++)
  3911. {
  3912. const TEditorPreferences * Editor = EditorList->Editors[i];
  3913. if ((Editor->Data->Editor == edExternal) &&
  3914. (Editor->Data->ExternalEditor == Data->Command))
  3915. {
  3916. AnyFound = true;
  3917. if (Editor->Data->SDIExternalEditor)
  3918. {
  3919. AnyNonMDI = true;
  3920. if (Editor->Data->DetectMDIExternalEditor)
  3921. {
  3922. AnyDetect = true;
  3923. }
  3924. }
  3925. else
  3926. {
  3927. AnyMDI = true;
  3928. }
  3929. }
  3930. }
  3931. bool EnableMDI = false;
  3932. bool DisableDetect = false;
  3933. if (AnyMDI)
  3934. {
  3935. KeepOpen = true;
  3936. if (AnyNonMDI)
  3937. {
  3938. // there is at least one instance of the editor with MDI support enabled,
  3939. // and one with disabled, enable it for all instances
  3940. EnableMDI = true;
  3941. }
  3942. }
  3943. else if (AnyFound && !AnyDetect)
  3944. {
  3945. // at least once instance found but all have MDI autodetection disabled
  3946. // => close the file (default action)
  3947. }
  3948. else
  3949. {
  3950. // no instance of the editor has MDI support enabled
  3951. TMessageParams Params;
  3952. if (AnyFound)
  3953. {
  3954. // there is at least one instance of the editor
  3955. Params.Params |= mpNeverAskAgainCheck;
  3956. }
  3957. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3958. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3959. switch (Answer)
  3960. {
  3961. case qaNeverAskAgain:
  3962. DisableDetect = true;
  3963. break;
  3964. case qaNo:
  3965. EnableMDI = true;
  3966. KeepOpen = true;
  3967. break;
  3968. }
  3969. }
  3970. if (AnyFound && (EnableMDI || DisableDetect))
  3971. {
  3972. bool Changed = false;
  3973. for (int i = 0; i < EditorList->Count; i++)
  3974. {
  3975. const TEditorPreferences * Editor = EditorList->Editors[i];
  3976. if ((Editor->Data->Editor == edExternal) &&
  3977. (Editor->Data->ExternalEditor == Data->Command) &&
  3978. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3979. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3980. {
  3981. Changed = true;
  3982. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3983. if (EnableMDI)
  3984. {
  3985. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3986. }
  3987. if (DisableDetect)
  3988. {
  3989. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3990. }
  3991. EditorList->Change(i, UpdatedEditor);
  3992. }
  3993. }
  3994. if (Changed)
  3995. {
  3996. WinConfiguration->EditorList = EditorList;
  3997. }
  3998. }
  3999. }
  4000. __finally
  4001. {
  4002. delete EditorList;
  4003. }
  4004. }
  4005. else
  4006. {
  4007. // "open" case
  4008. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  4009. qaOK, HELP_APP_EARLY_CLOSED);
  4010. }
  4011. }
  4012. //---------------------------------------------------------------------------
  4013. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  4014. {
  4015. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  4016. }
  4017. //---------------------------------------------------------------------------
  4018. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  4019. {
  4020. SideEnter(osRemote);
  4021. }
  4022. //---------------------------------------------------------------------------
  4023. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4024. {
  4025. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4026. SideEnter(osRemote);
  4027. }
  4028. //---------------------------------------------------------------------------
  4029. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4030. {
  4031. FCurrentSide = Side;
  4032. if (Visible)
  4033. {
  4034. UpdateControls();
  4035. }
  4036. }
  4037. //---------------------------------------------------------------------------
  4038. void __fastcall TCustomScpExplorerForm::FileDeleted(TOperationSide Side, const UnicodeString & FileName, bool Success)
  4039. {
  4040. VisualiseOperationFinished(Side, FileName, Success);
  4041. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4042. {
  4043. FDeletedFiles->Add(FileName);
  4044. }
  4045. }
  4046. //---------------------------------------------------------------------------
  4047. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4048. TStrings * FileList, bool Alternative)
  4049. {
  4050. TCustomDirView * DView = DirView(Side);
  4051. DView->SaveSelection();
  4052. DView->SaveSelectedNames();
  4053. DebugAssert(!FAlternativeDelete);
  4054. FAlternativeDelete = Alternative;
  4055. try
  4056. {
  4057. if (!IsSideLocalBrowser(Side))
  4058. {
  4059. DebugAssert(Terminal != NULL);
  4060. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4061. std::unique_ptr<TStrings> PermanentFileList(TRemoteFileList::CloneStrings(FileList));
  4062. std::unique_ptr<TStringList> DeletedFiles(new TStringList());
  4063. DeletedFiles->CaseSensitive = DebugAlwaysTrue(!IsSideLocalBrowser(Side));
  4064. int Params = FLAGMASK(Alternative, dfAlternative);
  4065. try
  4066. {
  4067. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles);
  4068. DebugAssert(FDeletedFiles == NULL);
  4069. FDeletedFiles = DeletedFiles.get();
  4070. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4071. FOnFileOperationFinished = FileDeleted;
  4072. FMoveToQueue = false;
  4073. Terminal->DeleteFiles(FileList, Params);
  4074. // Probably not needed for deleting, just for consistency with transfer code
  4075. if (FMoveToQueue)
  4076. {
  4077. Abort();
  4078. }
  4079. }
  4080. catch (EAbort &)
  4081. {
  4082. if (FMoveToQueue)
  4083. {
  4084. DeletedFiles->Sorted = true;
  4085. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4086. {
  4087. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4088. {
  4089. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4090. DebugAssert(Index == 0);
  4091. PermanentFileList->Delete(Index);
  4092. Index--;
  4093. }
  4094. }
  4095. FMoveToQueue = false;
  4096. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4097. TQueueItem * QueueItem = new TDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4098. AddQueueItem(Queue, QueueItem, Terminal);
  4099. ClearOperationSelection(osRemote);
  4100. }
  4101. }
  4102. }
  4103. else
  4104. {
  4105. if (IsLocalBrowserMode())
  4106. {
  4107. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4108. }
  4109. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  4110. FProgressSide = FCurrentSide;
  4111. try
  4112. {
  4113. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  4114. }
  4115. __finally
  4116. {
  4117. ReloadLocalDirectory();
  4118. }
  4119. }
  4120. FAlternativeDelete = false;
  4121. }
  4122. catch(...)
  4123. {
  4124. FAlternativeDelete = false;
  4125. DView->DiscardSavedSelection();
  4126. throw;
  4127. }
  4128. DView->RestoreSelection();
  4129. }
  4130. //---------------------------------------------------------------------------
  4131. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4132. {
  4133. DebugAssert(Terminal);
  4134. DebugAssert(!IsLocalBrowserMode());
  4135. RemoteDirView->SaveSelection();
  4136. RemoteDirView->SaveSelectedNames();
  4137. try
  4138. {
  4139. if (Lock)
  4140. {
  4141. Terminal->LockFiles(FileList);
  4142. }
  4143. else
  4144. {
  4145. Terminal->UnlockFiles(FileList);
  4146. }
  4147. }
  4148. catch(...)
  4149. {
  4150. RemoteDirView->DiscardSavedSelection();
  4151. throw;
  4152. }
  4153. RemoteDirView->RestoreSelection();
  4154. }
  4155. //---------------------------------------------------------------------------
  4156. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4157. {
  4158. bool Result = false;
  4159. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4160. if (IsActiveTerminal(ATerminal))
  4161. {
  4162. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(Directory));
  4163. Result = File && File->IsDirectory;
  4164. }
  4165. return Result;
  4166. }
  4167. //---------------------------------------------------------------------------
  4168. bool TCustomScpExplorerForm::NeedSecondarySessionForRemoteCopy(TStrings * FileList)
  4169. {
  4170. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4171. return
  4172. !Terminal->IsCapable[fcRemoteCopy] ||
  4173. (CopyDirsOnSecondarySession && TRemoteFileList::AnyDirectory(FileList));
  4174. }
  4175. //---------------------------------------------------------------------------
  4176. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4177. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4178. bool NoConfirmation, bool Move)
  4179. {
  4180. DebugAssert(Terminal != NULL);
  4181. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4182. DebugAssert(!IsLocalBrowserMode());
  4183. if (Session == NULL)
  4184. {
  4185. Session = Terminal;
  4186. }
  4187. bool TargetConfirmed = false;
  4188. if (Session == Terminal)
  4189. {
  4190. if (RemoteDriveView->DropTarget != NULL)
  4191. {
  4192. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4193. TargetConfirmed = true;
  4194. }
  4195. else if (RemoteDirView->DropTarget != NULL)
  4196. {
  4197. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4198. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4199. TargetConfirmed = true;
  4200. }
  4201. else
  4202. {
  4203. Target = RemoteDirView->Path;
  4204. }
  4205. }
  4206. else
  4207. {
  4208. Target = GetSessionPath(Session, osRemote);
  4209. }
  4210. Target = UnixIncludeTrailingBackslash(Target);
  4211. if (FileList->Count == 1)
  4212. {
  4213. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4214. }
  4215. else
  4216. {
  4217. FileMask = AnyMask;
  4218. }
  4219. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4220. bool Result = true;
  4221. if (!NoConfirmation)
  4222. {
  4223. bool Multi = (FileList->Count > 1);
  4224. if (Move)
  4225. {
  4226. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4227. }
  4228. else
  4229. {
  4230. std::unique_ptr<TStrings> Sessions(new TStringList);
  4231. std::unique_ptr<TStrings> Directories(new TStringList);
  4232. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4233. for (int Index = 0; Index < SessionList->Count; Index++)
  4234. {
  4235. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4236. if (IsActiveTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4237. {
  4238. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4239. Directories->Add(GetSessionPath(ASession, osRemote));
  4240. }
  4241. }
  4242. bool AnyDirectory = false;
  4243. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4244. if (CopyDirsOnSecondarySession && !Terminal->CommandSessionOpened) // optimization
  4245. {
  4246. for (int Index = 0; !AnyDirectory && (Index < FileList->Count); Index++)
  4247. {
  4248. AnyDirectory = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]))->IsDirectory;
  4249. }
  4250. }
  4251. TDirectRemoteCopy AllowDirectCopy;
  4252. if (Terminal->CommandSessionOpened || !NeedSecondarySessionForRemoteCopy(FileList))
  4253. {
  4254. DebugAssert(DirectCopy);
  4255. AllowDirectCopy = drcAllow;
  4256. }
  4257. else if (Terminal->IsCapable[fcSecondaryShell])
  4258. {
  4259. DebugAssert(DirectCopy);
  4260. AllowDirectCopy = Terminal->IsCapable[fcRemoteCopy] ? drcConfirmCommandSessionDirs : drcConfirmCommandSession;
  4261. }
  4262. else
  4263. {
  4264. DebugAssert(!DirectCopy);
  4265. AllowDirectCopy = drcDisallow;
  4266. }
  4267. void * ASession = Session;
  4268. Result = DoRemoteCopyDialog(
  4269. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4270. DoDirectoryExists, TargetConfirmed);
  4271. Session = static_cast<TManagedTerminal *>(ASession);
  4272. }
  4273. }
  4274. return Result;
  4275. }
  4276. //---------------------------------------------------------------------------
  4277. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4278. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4279. {
  4280. DebugAssert(!IsLocalBrowserMode());
  4281. bool DirectCopy;
  4282. UnicodeString Target, FileMask;
  4283. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4284. if (Result)
  4285. {
  4286. if (!Move && !DirectCopy)
  4287. {
  4288. Configuration->Usage->Inc("RemoteCopyTemp");
  4289. UnicodeString RootTempDir;
  4290. UnicodeString TempDir;
  4291. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  4292. TStrings * TemporaryFilesList = new TStringList();
  4293. try
  4294. {
  4295. TMakeLocalFileListParams MakeFileListParam;
  4296. MakeFileListParam.FileList = TemporaryFilesList;
  4297. MakeFileListParam.FileTimes = NULL;
  4298. MakeFileListParam.IncludeDirs = true;
  4299. MakeFileListParam.Recursive = false;
  4300. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4301. TTerminalManager::Instance()->ActiveSession = Session;
  4302. if (TemporaryFilesList->Count > 0)
  4303. {
  4304. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4305. CopyParam.FileMask = FileMask;
  4306. DebugAssert(!FAutoOperation);
  4307. FAutoOperation = true;
  4308. FMoveToQueue = false;
  4309. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4310. }
  4311. }
  4312. __finally
  4313. {
  4314. delete TemporaryFilesList;
  4315. FAutoOperation = false;
  4316. if (!RootTempDir.IsEmpty())
  4317. {
  4318. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4319. }
  4320. }
  4321. }
  4322. else
  4323. {
  4324. RemoteDirView->SaveSelection();
  4325. RemoteDirView->SaveSelectedNames();
  4326. try
  4327. {
  4328. if (Move)
  4329. {
  4330. Configuration->Usage->Inc("RemoteMove");
  4331. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4332. }
  4333. else
  4334. {
  4335. Configuration->Usage->Inc("RemoteCopyDirect");
  4336. DebugAssert(DirectCopy);
  4337. DebugAssert(Session == Terminal);
  4338. if (!NeedSecondarySessionForRemoteCopy(FileList) ||
  4339. Terminal->CommandSessionOpened ||
  4340. CommandSessionFallback())
  4341. {
  4342. Terminal->CopyFiles(FileList, Target, FileMask, false);
  4343. }
  4344. }
  4345. }
  4346. catch(...)
  4347. {
  4348. RemoteDirView->DiscardSavedSelection();
  4349. throw;
  4350. }
  4351. RemoteDirView->RestoreSelection();
  4352. }
  4353. }
  4354. return Result;
  4355. }
  4356. //---------------------------------------------------------------------------
  4357. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4358. const UnicodeString & Path, TRemoteProperties & Properties)
  4359. {
  4360. DebugAssert(!IsLocalBrowserMode());
  4361. Properties.Valid = Properties.Valid << vpEncrypt;
  4362. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4363. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4364. }
  4365. //---------------------------------------------------------------------------
  4366. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4367. {
  4368. Side = GetSide(Side);
  4369. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4370. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4371. UnicodeString Name = LoadStr(NEW_FOLDER);
  4372. int AllowedChanges =
  4373. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4374. bool SaveSettings = false;
  4375. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4376. {
  4377. TWindowLock Lock(this);
  4378. if (!IsSideLocalBrowser(Side))
  4379. {
  4380. if (SaveSettings)
  4381. {
  4382. GUIConfiguration->NewDirectoryProperties = Properties;
  4383. }
  4384. CreateRemoteDirectory(Name, Properties);
  4385. }
  4386. else
  4387. {
  4388. DirView(Side)->CreateDirectory(Name);
  4389. }
  4390. }
  4391. }
  4392. //---------------------------------------------------------------------------
  4393. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4394. {
  4395. TWindowLock Lock(this);
  4396. DirView(Side)->ExecuteHomeDirectory();
  4397. }
  4398. //---------------------------------------------------------------------------
  4399. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4400. {
  4401. DoOpenDirectoryDialog(odBrowse, Side);
  4402. }
  4403. //---------------------------------------------------------------------------
  4404. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4405. {
  4406. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4407. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4408. bool Result = !Path.IsEmpty();
  4409. if (Result)
  4410. {
  4411. TryOpenDirectory(Side, Path);
  4412. }
  4413. return Result;
  4414. }
  4415. //---------------------------------------------------------------------------
  4416. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4417. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4418. bool & Close)
  4419. {
  4420. // terminal can be already closed (e.g. dropped connection)
  4421. if (Terminal != NULL)
  4422. {
  4423. try
  4424. {
  4425. TCalculateSizeParams Params;
  4426. Params.Stats = &Stats;
  4427. Terminal->CalculateFilesSize(FileList, Size, Params);
  4428. }
  4429. catch(...)
  4430. {
  4431. if (!Terminal->Active)
  4432. {
  4433. Close = true;
  4434. }
  4435. throw;
  4436. }
  4437. }
  4438. }
  4439. //---------------------------------------------------------------------------
  4440. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4441. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4442. bool & Close)
  4443. {
  4444. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4445. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4446. {
  4447. Configuration->Usage->Inc(L"ChecksumCalculated");
  4448. try
  4449. {
  4450. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4451. }
  4452. catch(...)
  4453. {
  4454. if (!Terminal->Active)
  4455. {
  4456. Close = true;
  4457. }
  4458. throw;
  4459. }
  4460. }
  4461. }
  4462. //---------------------------------------------------------------------------
  4463. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4464. {
  4465. if (Terminal->LoadFilesProperties(FileList))
  4466. {
  4467. RemoteDirView->Invalidate();
  4468. }
  4469. }
  4470. //---------------------------------------------------------------------------
  4471. bool TCustomScpExplorerForm::CanCalculateChecksum()
  4472. {
  4473. return
  4474. Terminal->IsCapable[fcCalculatingChecksum] ||
  4475. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles());
  4476. }
  4477. //---------------------------------------------------------------------------
  4478. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4479. {
  4480. bool Result;
  4481. if (!IsSideLocalBrowser(Side))
  4482. {
  4483. TRemoteTokenList * GroupList = NULL;
  4484. TRemoteTokenList * UserList = NULL;
  4485. try
  4486. {
  4487. TRemoteProperties CurrentProperties;
  4488. LoadFilesProperties(FileList);
  4489. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4490. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4491. if (CapableGroupChanging || CapableOwnerChanging)
  4492. {
  4493. if (CapableGroupChanging)
  4494. {
  4495. GroupList = Terminal->Groups->Duplicate();
  4496. }
  4497. if (CapableOwnerChanging)
  4498. {
  4499. UserList = Terminal->Users->Duplicate();
  4500. }
  4501. TRemoteDirectory * Files = Terminal->Files;
  4502. int Count = Files->Count;
  4503. if (Count > 100)
  4504. {
  4505. Count = 100;
  4506. }
  4507. for (int Index = 0; Index < Count; Index++)
  4508. {
  4509. TRemoteFile * File = Files->Files[Index];
  4510. if (CapableGroupChanging)
  4511. {
  4512. GroupList->AddUnique(File->Group);
  4513. }
  4514. if (CapableOwnerChanging)
  4515. {
  4516. UserList->AddUnique(File->Owner);
  4517. }
  4518. }
  4519. // if we haven't collected tokens for all files in current directory,
  4520. // make sure we collect them at least for all selected files.
  4521. // (note that so far the files in FileList has to be from current direcotry)
  4522. if (Count < Files->Count)
  4523. {
  4524. for (int Index = 0; Index < FileList->Count; Index++)
  4525. {
  4526. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4527. if (CapableGroupChanging)
  4528. {
  4529. GroupList->AddUnique(File->Group);
  4530. }
  4531. if (CapableOwnerChanging)
  4532. {
  4533. UserList->AddUnique(File->Owner);
  4534. }
  4535. }
  4536. }
  4537. }
  4538. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4539. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4540. if (CapableAclChanging && TRemoteFileList::AnyDirectory(FileList))
  4541. {
  4542. CapableAclChanging = false;
  4543. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4544. }
  4545. int Flags = 0;
  4546. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4547. if (CapableAclChanging) Flags |= cpAcl;
  4548. if (CapableOwnerChanging) Flags |= cpOwner;
  4549. if (CapableGroupChanging) Flags |= cpGroup;
  4550. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4551. if (CanCalculateChecksum())
  4552. {
  4553. CalculateChecksumEvent = CalculateChecksum;
  4554. }
  4555. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4556. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4557. TRemoteProperties NewProperties = CurrentProperties;
  4558. Result =
  4559. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4560. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4561. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4562. CalculateSize, CalculateChecksumEvent);
  4563. if (Result)
  4564. {
  4565. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4566. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4567. }
  4568. }
  4569. __finally
  4570. {
  4571. delete GroupList;
  4572. delete UserList;
  4573. }
  4574. }
  4575. else
  4576. {
  4577. DirView(Side)->DisplayPropertiesMenu();
  4578. Result = true;
  4579. }
  4580. return Result;
  4581. }
  4582. //---------------------------------------------------------------------------
  4583. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4584. {
  4585. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4586. {
  4587. FIgnoreNextDialogChar = Key;
  4588. }
  4589. Key = 0;
  4590. }
  4591. //---------------------------------------------------------------------------
  4592. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4593. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4594. {
  4595. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4596. if (Command != NULL)
  4597. {
  4598. KeyProcessed(Key, Shift);
  4599. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4600. {
  4601. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4602. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4603. false, false, const_cast<TCustomCommandType *>(Command));
  4604. }
  4605. }
  4606. }
  4607. //---------------------------------------------------------------------------
  4608. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4609. {
  4610. if (!NonVisualDataModule->Busy)
  4611. {
  4612. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4613. {
  4614. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4615. }
  4616. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4617. {
  4618. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4619. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4620. {
  4621. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4622. // But so far it's not a problem, as it does what we want.
  4623. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4624. if (((Action->ShortCut == KeyShortCut) ||
  4625. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4626. AllowedAction(Action, aaShortCut))
  4627. {
  4628. // Has to be called before the action as the dialog char is already in queue.
  4629. // So when the action consumes message queue, we already need to have the
  4630. // FIgnoreNextDialogChar set
  4631. KeyProcessed(Key, Shift);
  4632. // Reset reference to previous component (when menu/toolbar was clicked).
  4633. // Needed to detect that action was invoked by keyboard shortcut
  4634. // in TNonVisualDataModule::ExplorerActionsExecute
  4635. Action->ActionComponent = NULL;
  4636. Action->Execute();
  4637. return;
  4638. }
  4639. }
  4640. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4641. {
  4642. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4643. {
  4644. KeyProcessed(Key, Shift);
  4645. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4646. return;
  4647. }
  4648. }
  4649. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4650. {
  4651. KeyProcessed(Key, Shift);
  4652. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4653. }
  4654. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4655. if (IsCustomShortCut(CustomShortCut))
  4656. {
  4657. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4658. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4659. if (WinConfiguration->SharedBookmarks != NULL)
  4660. {
  4661. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4662. if ((Bookmark != NULL) &&
  4663. OpenBookmark(FCurrentSide, Bookmark))
  4664. {
  4665. KeyProcessed(Key, Shift);
  4666. }
  4667. }
  4668. }
  4669. }
  4670. }
  4671. TForm::KeyDown(Key, Shift);
  4672. }
  4673. //---------------------------------------------------------------------------
  4674. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4675. {
  4676. bool OpenedTerminal = false;
  4677. UnicodeString ProtocolName;
  4678. UnicodeString ProtocolNameHint;
  4679. UnicodeString SecurityProtocolName;
  4680. UnicodeString DurationHint;
  4681. // See the comment in TScpCommanderForm::UpdateControls()
  4682. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4683. if (ActiveTerminal != NULL)
  4684. {
  4685. // Active is not enough here
  4686. if (ActiveTerminal->Status == ssOpened)
  4687. {
  4688. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4689. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4690. if (FileSystemInfo.ProtocolName.IsEmpty())
  4691. {
  4692. ProtocolName = SessionInfo.ProtocolName;
  4693. }
  4694. else
  4695. {
  4696. ProtocolName = FileSystemInfo.ProtocolName;
  4697. }
  4698. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4699. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4700. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4701. OpenedTerminal = true;
  4702. }
  4703. else if (ActiveTerminal->Status > ssClosed)
  4704. {
  4705. ProtocolName = LoadStr(STATUS_CONNECTING);
  4706. }
  4707. else
  4708. {
  4709. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4710. }
  4711. }
  4712. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4713. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4714. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4715. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4716. if (ProtocolStatusPanel->Caption != ProtocolName)
  4717. {
  4718. ProtocolStatusPanel->Caption = ProtocolName;
  4719. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4720. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4721. }
  4722. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4723. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4724. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4725. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4726. SecurityStatusPanel->Enabled = SecurityEnabled;
  4727. UnicodeString SecurityProtocolHint;
  4728. if (SecurityEnabled)
  4729. {
  4730. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4731. }
  4732. else
  4733. {
  4734. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4735. }
  4736. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4737. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4738. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4739. DurationStatusPanel->Hint = DurationHint;
  4740. UpdateStatusBar();
  4741. }
  4742. //---------------------------------------------------------------------------
  4743. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4744. {
  4745. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4746. DebugAssert(SessionStatusBar != NULL);
  4747. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4748. if (!FNote.IsEmpty())
  4749. {
  4750. NoteStatusPanel->Caption = FNote;
  4751. }
  4752. else
  4753. {
  4754. UpdateStatusPanelText(NoteStatusPanel);
  4755. }
  4756. NoteStatusPanel->Hint = FNoteHints;
  4757. UnicodeString LoginTime;
  4758. // See the comment in TScpCommanderForm::UpdateControls()
  4759. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4760. // Active is not enough here
  4761. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4762. {
  4763. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4764. LoginTime = FormatDateTimeSpan(Now() - SessionInfo.LoginTime);
  4765. }
  4766. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4767. DurationStatusPanel->Caption = LoginTime;
  4768. }
  4769. //---------------------------------------------------------------------------
  4770. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4771. {
  4772. Panel->Caption = L"";
  4773. }
  4774. //---------------------------------------------------------------------------
  4775. void __fastcall TCustomScpExplorerForm::Idle()
  4776. {
  4777. if (FShowing ||
  4778. // Particularly for
  4779. // - Standalone editing
  4780. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4781. // while "keeping remote directory up to date".
  4782. StandaloneOperation)
  4783. {
  4784. FEditorManager->Check();
  4785. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4786. // that needs to know if queue view is visible (and it may be closed after queue update)
  4787. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4788. }
  4789. if (FShowing)
  4790. {
  4791. if (!NonVisualDataModule->Busy &&
  4792. // Menu is opened or drag&drop is going on
  4793. (Mouse->Capture == NULL))
  4794. {
  4795. if (FRefreshRemoteDirectory)
  4796. {
  4797. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4798. {
  4799. Terminal->RefreshDirectory();
  4800. }
  4801. FRefreshRemoteDirectory = false;
  4802. }
  4803. if (FRefreshLocalDirectory)
  4804. {
  4805. ReloadLocalDirectory();
  4806. FRefreshLocalDirectory = false;
  4807. }
  4808. if (WinConfiguration->RefreshRemotePanel)
  4809. {
  4810. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4811. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4812. {
  4813. RemoteDirView->ReloadDirectory();
  4814. }
  4815. }
  4816. }
  4817. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4818. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4819. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4820. // 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.
  4821. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4822. MenuToolbar->Idle();
  4823. }
  4824. if (FShowing || StandaloneOperation)
  4825. {
  4826. if (FQueueStatusInvalidated)
  4827. {
  4828. UpdateQueueStatus(false);
  4829. }
  4830. RefreshQueueItems();
  4831. }
  4832. if (FShowing)
  4833. {
  4834. UpdateStatusBar();
  4835. }
  4836. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4837. {
  4838. FClipboardFakeMonitorsPendingReset = false;
  4839. FClipboardFakeMonitors.reset(NULL);
  4840. }
  4841. FIgnoreNextDialogChar = 0;
  4842. }
  4843. //---------------------------------------------------------------------------
  4844. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4845. {
  4846. try
  4847. {
  4848. FUserActionTimer->Enabled = false;
  4849. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4850. {
  4851. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4852. {
  4853. FPendingQueueActionItem->ProcessUserAction();
  4854. }
  4855. }
  4856. }
  4857. __finally
  4858. {
  4859. FPendingQueueActionItem = NULL;
  4860. }
  4861. }
  4862. //---------------------------------------------------------------------------
  4863. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4864. {
  4865. if (WinConfiguration->MinimizeToTray)
  4866. {
  4867. UpdateTrayIcon();
  4868. FTrayIcon->Visible = true;
  4869. if (Visible)
  4870. {
  4871. ShowWindow(Handle, SW_HIDE);
  4872. }
  4873. }
  4874. }
  4875. //---------------------------------------------------------------------------
  4876. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4877. {
  4878. // WORKAROUND
  4879. // When restoring maximized window from minimization,
  4880. // rarely some controls do not align properly.
  4881. // Two instances seen (both for Commander):
  4882. // - When restoring, window is temporarily narrower (not maximized),
  4883. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4884. // Once maximized already, top dock shinks back, but the session PageControl,
  4885. // do not align up, leaving space between TopDock and PageControl.
  4886. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4887. for (int Index = 0; Index < ControlCount; Index++)
  4888. {
  4889. RealignControl(Controls[Index]);
  4890. }
  4891. if (FTrayIcon->Visible)
  4892. {
  4893. FTrayIcon->Visible = false;
  4894. if (Visible)
  4895. {
  4896. ShowWindow(Handle, SW_SHOW);
  4897. }
  4898. }
  4899. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4900. {
  4901. FNeedSession = false;
  4902. NonVisualDataModule->StartBusy();
  4903. try
  4904. {
  4905. NeedSession(true);
  4906. }
  4907. __finally
  4908. {
  4909. NonVisualDataModule->EndBusy();
  4910. }
  4911. }
  4912. }
  4913. //---------------------------------------------------------------------------
  4914. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4915. {
  4916. FTrayIcon->Hint = GetMainForm()->Caption;
  4917. }
  4918. //---------------------------------------------------------------------------
  4919. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4920. {
  4921. UpdateTrayIcon();
  4922. }
  4923. //---------------------------------------------------------------------------
  4924. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4925. {
  4926. // workaround
  4927. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4928. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4929. // But WM_ACTIVATEAPP message can be received even when
  4930. // the main window is minimized to the tray and internal editor window is focused
  4931. // (after another application was previously active)
  4932. if (::IsIconic(Handle))
  4933. {
  4934. if (!IsAppIconic())
  4935. {
  4936. SetAppIconic(true);
  4937. }
  4938. }
  4939. ::ApplicationRestore();
  4940. Application->BringToFront();
  4941. }
  4942. //---------------------------------------------------------------------------
  4943. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4944. {
  4945. RestoreApp();
  4946. }
  4947. //---------------------------------------------------------------------------
  4948. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4949. {
  4950. if (OpenInNewWindow())
  4951. {
  4952. ExecuteNewInstance(SessionUrl);
  4953. }
  4954. else
  4955. {
  4956. TTerminalManager::Instance()->NewSession(SessionUrl);
  4957. }
  4958. }
  4959. //---------------------------------------------------------------------------
  4960. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4961. {
  4962. NewSession();
  4963. }
  4964. //---------------------------------------------------------------------------
  4965. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4966. {
  4967. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4968. StoredSessions->NewSession(SessionName, SessionData);
  4969. // modified only, explicit
  4970. StoredSessions->Save(false, true);
  4971. // encode session name because of slashes in hierarchical sessions
  4972. return EncodeUrlString(SessionName);
  4973. }
  4974. //---------------------------------------------------------------------------
  4975. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4976. {
  4977. // current working directories become defaults here, what is not right
  4978. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4979. return SaveHiddenDuplicateSession(SessionData.get());
  4980. }
  4981. //---------------------------------------------------------------------------
  4982. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  4983. {
  4984. if (OpenInNewWindow())
  4985. {
  4986. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4987. }
  4988. else
  4989. {
  4990. // current working directories become defaults here, what is not right
  4991. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4992. TTerminalManager * Manager = TTerminalManager::Instance();
  4993. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  4994. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  4995. // We definitely want these
  4996. ASession->Disconnected = ManagedSession->Disconnected;
  4997. // Not sure about these two
  4998. ASession->Permanent = ManagedSession->Permanent;
  4999. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  5000. Manager->ActiveSession = ASession;
  5001. }
  5002. }
  5003. //---------------------------------------------------------------------------
  5004. void __fastcall TCustomScpExplorerForm::RenameTab()
  5005. {
  5006. UnicodeString Name = ManagedSession->SessionData->SessionName;
  5007. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  5008. // When submitting the default name, do not fix it
  5009. (Name != ManagedSession->SessionData->SessionName))
  5010. {
  5011. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  5012. TSessionData::ValidateName(Name);
  5013. // This is inconsistent with how color (for example) is handled.
  5014. ManagedSession->SessionData->Name = Name;
  5015. UpdateControls();
  5016. // Add/Remove distinguishing paths from sessions of the same name.
  5017. SessionListChanged();
  5018. }
  5019. }
  5020. //---------------------------------------------------------------------------
  5021. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  5022. {
  5023. DebugAssert(Queue != NULL);
  5024. bool Result = Queue->IsEmpty;
  5025. if (!Result)
  5026. {
  5027. SetFocus();
  5028. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  5029. }
  5030. return Result;
  5031. }
  5032. //---------------------------------------------------------------------------
  5033. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  5034. {
  5035. return CanCloseQueue(FQueue);
  5036. }
  5037. //---------------------------------------------------------------------------
  5038. void __fastcall TCustomScpExplorerForm::CloseTab()
  5039. {
  5040. if (CanCloseQueue())
  5041. {
  5042. TTerminalManager::Instance()->FreeActiveTerminal();
  5043. }
  5044. }
  5045. //---------------------------------------------------------------------------
  5046. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5047. {
  5048. if (CanCloseQueue())
  5049. {
  5050. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5051. }
  5052. }
  5053. //---------------------------------------------------------------------------
  5054. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5055. {
  5056. DetachTerminal(Terminal);
  5057. RemoteDirView->Terminal = Terminal;
  5058. UpdateRemotePathComboBox(false);
  5059. InitStatusBar();
  5060. UpdateControls();
  5061. }
  5062. //---------------------------------------------------------------------------
  5063. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5064. {
  5065. InitStatusBar();
  5066. }
  5067. //---------------------------------------------------------------------------
  5068. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5069. {
  5070. if (DebugAlwaysTrue(!Terminal->Active))
  5071. {
  5072. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5073. }
  5074. }
  5075. //---------------------------------------------------------------------------
  5076. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5077. {
  5078. if (OpenInNewWindow())
  5079. {
  5080. // encode session name because of slashes in hierarchical sessions
  5081. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5082. }
  5083. else
  5084. {
  5085. TTerminalManager * Manager = TTerminalManager::Instance();
  5086. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5087. Manager->ActiveSession = Terminal;
  5088. }
  5089. }
  5090. //---------------------------------------------------------------------------
  5091. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5092. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5093. {
  5094. TTerminalManager * Manager = TTerminalManager::Instance();
  5095. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5096. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5097. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5098. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5099. {
  5100. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5101. // FirstSession can be null, if none of the workspace sites exist anymore
  5102. // or if all workspace sessions are not suported by the interface
  5103. // (when trying to open all local-local workspace in "explorer" interface)
  5104. if (FirstSession != NULL)
  5105. {
  5106. if (!ConnectFirstTerminal)
  5107. {
  5108. FirstSession->Disconnected = true;
  5109. FirstSession->DisconnectedTemporarily = true;
  5110. }
  5111. Manager->ActiveSession = FirstSession;
  5112. }
  5113. }
  5114. }
  5115. //---------------------------------------------------------------------------
  5116. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5117. {
  5118. if (OpenInNewWindow())
  5119. {
  5120. ExecuteNewInstance(Name);
  5121. }
  5122. else
  5123. {
  5124. DoOpenFolderOrWorkspace(Name, true, false);
  5125. }
  5126. }
  5127. //---------------------------------------------------------------------------
  5128. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5129. bool &CanClose)
  5130. {
  5131. AppLog(L"Windows close query");
  5132. // See the comment in CloseApp()
  5133. if (NonVisualDataModule->Busy)
  5134. {
  5135. CanClose = false;
  5136. }
  5137. else
  5138. {
  5139. TTerminalManager * Manager = TTerminalManager::Instance();
  5140. int ActiveSessions = 0;
  5141. for (int Index = 0; Index < Manager->Count; Index++)
  5142. {
  5143. if (Manager->Sessions[Index]->Active)
  5144. {
  5145. ActiveSessions++;
  5146. }
  5147. }
  5148. // Confirm, when there's at least one active remote session or
  5149. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5150. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5151. WinConfiguration->ConfirmClosingSession)
  5152. {
  5153. unsigned int Result;
  5154. TMessageParams Params(mpNeverAskAgainCheck);
  5155. UnicodeString Message;
  5156. int Answers = qaOK | qaCancel;
  5157. // The current session is the only active session
  5158. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5159. {
  5160. if (!WinConfiguration->AutoSaveWorkspace)
  5161. {
  5162. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5163. }
  5164. else
  5165. {
  5166. Message = LoadStr(CLOSE_SESSION);
  5167. }
  5168. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5169. }
  5170. // Multiple active sessions or one active session, but it's not the current one
  5171. else if (ActiveSessions > 0)
  5172. {
  5173. if (!WinConfiguration->AutoSaveWorkspace)
  5174. {
  5175. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5176. }
  5177. else
  5178. {
  5179. Message = LoadStr(CLOSE_SESSIONS);
  5180. }
  5181. }
  5182. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5183. else
  5184. {
  5185. DebugAlwaysTrue(Manager->Count > 1);
  5186. DebugAlwaysTrue(!WinConfiguration->AutoSaveWorkspace);
  5187. Message = LoadStr(CLOSE_WORKSPACE);
  5188. }
  5189. UnicodeString Note;
  5190. if (WinConfiguration->AutoSaveWorkspace)
  5191. {
  5192. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5193. }
  5194. else
  5195. {
  5196. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5197. Answers = qaYes | qaNo | qaCancel;
  5198. }
  5199. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5200. SetFocus();
  5201. Result = MessageDialog(Message, qtConfirmation,
  5202. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5203. if (Result == qaNeverAskAgain)
  5204. {
  5205. WinConfiguration->ConfirmClosingSession = false;
  5206. }
  5207. if (Result == qaNo)
  5208. {
  5209. CanClose = SaveWorkspace(true);
  5210. // note that the workspace will be saved redundatly again from FormClose
  5211. }
  5212. else
  5213. {
  5214. CanClose =
  5215. (Result == qaOK) ||
  5216. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5217. (Result == qaNeverAskAgain);
  5218. }
  5219. }
  5220. if (CanClose && HasActiveTerminal())
  5221. {
  5222. CanClose = CanCloseQueue();
  5223. }
  5224. }
  5225. if (CanClose)
  5226. {
  5227. CanClose =
  5228. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5229. FEditorManager->CloseExternalFilesWithoutProcess();
  5230. if (CanClose)
  5231. {
  5232. while (CanClose && (FLocalEditors->Count > 0))
  5233. {
  5234. int PrevCount = FLocalEditors->Count;
  5235. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5236. CanClose = (FLocalEditors->Count < PrevCount);
  5237. }
  5238. if (CanClose)
  5239. {
  5240. CanClose = FEditorManager->Empty(true);
  5241. if (!CanClose)
  5242. {
  5243. SetFocus();
  5244. CanClose =
  5245. (MessageDialog(
  5246. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5247. }
  5248. }
  5249. }
  5250. }
  5251. }
  5252. //---------------------------------------------------------------------------
  5253. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5254. {
  5255. TForm * Form = dynamic_cast<TForm *>(Sender);
  5256. DebugAssert(Form != NULL);
  5257. Form->Close();
  5258. }
  5259. //---------------------------------------------------------------------------
  5260. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5261. {
  5262. TForm * Form = dynamic_cast<TForm *>(Sender);
  5263. delete Form;
  5264. }
  5265. //---------------------------------------------------------------------------
  5266. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5267. {
  5268. while (FLocalEditors->Count > 0)
  5269. {
  5270. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5271. }
  5272. }
  5273. //---------------------------------------------------------------------------
  5274. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5275. TObject *Sender)
  5276. {
  5277. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5278. try
  5279. {
  5280. SetProperties(osRemote, FileList);
  5281. }
  5282. __finally
  5283. {
  5284. delete FileList;
  5285. }
  5286. }
  5287. //---------------------------------------------------------------------------
  5288. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5289. {
  5290. if (value)
  5291. {
  5292. if (Component == fcCustomCommandsBand)
  5293. {
  5294. UpdateCustomCommandsToolbar();
  5295. }
  5296. if (Component == fcQueueFileList)
  5297. {
  5298. DebugAssert(!QueueFileListSplitter->Visible);
  5299. AdjustQueueLayout();
  5300. UpdateQueueFileList();
  5301. }
  5302. }
  5303. }
  5304. //---------------------------------------------------------------------------
  5305. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5306. {
  5307. int MinHeightLimit =
  5308. GetStaticQueuePanelComponentsHeight() +
  5309. QueueFileListSplitter->Height +
  5310. QueueFileList->Height +
  5311. GetMinQueueViewHeight();
  5312. if (QueuePanel->ClientHeight < MinHeightLimit)
  5313. {
  5314. QueuePanel->ClientHeight = MinHeightLimit;
  5315. }
  5316. }
  5317. //---------------------------------------------------------------------------
  5318. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5319. {
  5320. TControl * Control = GetComponent(Component);
  5321. DebugAssert(Control);
  5322. bool Changed = (Control->Visible != value);
  5323. if (Changed)
  5324. {
  5325. ComponentShowing(Component, value);
  5326. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5327. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5328. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5329. if (value)
  5330. {
  5331. int RemainingHeight = Control->Parent->ClientHeight;
  5332. int RemainingWidth = Control->Parent->ClientWidth;
  5333. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5334. {
  5335. TControl * ChildControl = Control->Parent->Controls[i];
  5336. if (ChildControl->Visible)
  5337. {
  5338. switch (ChildControl->Align)
  5339. {
  5340. case alTop:
  5341. case alBottom:
  5342. RemainingHeight -= ChildControl->Height;
  5343. break;
  5344. case alLeft:
  5345. case alRight:
  5346. RemainingWidth -= ChildControl->Width;
  5347. break;
  5348. }
  5349. }
  5350. }
  5351. int Reserve = ScaleByTextHeight(this, 32);
  5352. // queue in explorer, trees in commander
  5353. if (Control->Height > RemainingHeight - Reserve)
  5354. {
  5355. Control->Height = RemainingHeight / 2;
  5356. }
  5357. if (Control->Width > RemainingWidth - Reserve)
  5358. {
  5359. Control->Width = RemainingWidth / 2;
  5360. }
  5361. }
  5362. Control->Visible = value;
  5363. if (WasFocused && Visible)
  5364. {
  5365. DirView(osCurrent)->SetFocus();
  5366. }
  5367. FixControlsPlacement();
  5368. }
  5369. }
  5370. //---------------------------------------------------------------------------
  5371. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5372. {
  5373. TControl * Control = GetComponent(Component);
  5374. if (Control == NULL)
  5375. {
  5376. return false;
  5377. }
  5378. else
  5379. {
  5380. return Control->Visible;
  5381. }
  5382. }
  5383. //---------------------------------------------------------------------------
  5384. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5385. {
  5386. bool Result;
  5387. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5388. {
  5389. Result = !IsUWP();
  5390. }
  5391. else
  5392. {
  5393. Result = true;
  5394. }
  5395. return Result;
  5396. }
  5397. //---------------------------------------------------------------------------
  5398. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5399. {
  5400. if (DirView->ItemFocused != NULL)
  5401. {
  5402. DirView->ItemFocused->MakeVisible(false);
  5403. }
  5404. }
  5405. //---------------------------------------------------------------------------
  5406. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5407. {
  5408. MakeFocusedItemVisible(RemoteDirView);
  5409. QueueSplitter->Visible = QueuePanel->Visible;
  5410. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5411. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5412. TControl * TopControlsOrder[] =
  5413. { TopDock, MessageDock, SessionsPageControl };
  5414. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5415. TControl * QueueControlsOrder[] =
  5416. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5417. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5418. }
  5419. //---------------------------------------------------------------------------
  5420. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5421. {
  5422. switch (Component) {
  5423. case fcStatusBar: return RemoteStatusBar;
  5424. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5425. case fcQueueView: return QueuePanel;
  5426. case fcQueueToolbar: return QueueDock;
  5427. case fcRemoteTree: return RemoteDrivePanel;
  5428. case fcSessionsTabs: return SessionsPageControl;
  5429. case fcQueueFileList: return QueueFileList;
  5430. default: return NULL;
  5431. }
  5432. }
  5433. //---------------------------------------------------------------------------
  5434. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5435. TObject *Sender, TListColumn *Column, TPoint &Point)
  5436. {
  5437. DebugAssert(NonVisualDataModule && Column && Sender);
  5438. NonVisualDataModule->ListColumn = Column;
  5439. TPopupMenu * DirViewColumnMenu;
  5440. if (Sender == DirView(osOther))
  5441. {
  5442. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5443. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5444. bool SizeColumn = (Column->Index == uvSize);
  5445. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5446. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5447. }
  5448. else
  5449. {
  5450. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5451. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5452. bool SizeColumn = (Column->Index == dvSize);
  5453. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5454. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5455. }
  5456. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5457. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5458. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5459. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5460. }
  5461. //---------------------------------------------------------------------------
  5462. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5463. TObject *Sender, TListItem *Item, bool &AllowExec)
  5464. {
  5465. DoDirViewExecFile(Sender, Item, AllowExec);
  5466. }
  5467. //---------------------------------------------------------------------------
  5468. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5469. TListItem * Item, bool & AllowExec)
  5470. {
  5471. DebugAssert(Sender && Item && Configuration);
  5472. DebugAssert(AllowExec);
  5473. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5474. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5475. bool Remote = !IsSideLocalBrowser(Side);
  5476. DebugAssert(Item == ADirView->ItemFocused);
  5477. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5478. TResolvedDoubleClickAction Action;
  5479. if (FForceExecution)
  5480. {
  5481. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5482. }
  5483. else
  5484. {
  5485. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5486. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5487. }
  5488. if (Action == rdcaCopy)
  5489. {
  5490. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5491. UnlockWindow();
  5492. try
  5493. {
  5494. if (IsLocalBrowserMode())
  5495. {
  5496. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5497. }
  5498. else
  5499. {
  5500. if (HasActiveTerminal())
  5501. {
  5502. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5503. }
  5504. }
  5505. }
  5506. __finally
  5507. {
  5508. LockWindow();
  5509. }
  5510. AllowExec = false;
  5511. }
  5512. else if (Action == rdcaEdit)
  5513. {
  5514. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5515. {
  5516. ExecuteFile(Side, efDefaultEditor);
  5517. AllowExec = false;
  5518. }
  5519. }
  5520. else if (Action == rdcaOpen)
  5521. {
  5522. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5523. {
  5524. ExecuteFile(osRemote, efShell);
  5525. AllowExec = false;
  5526. }
  5527. }
  5528. }
  5529. //---------------------------------------------------------------------------
  5530. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5531. {
  5532. return ((Side == osRemote) || (Side == osCurrent));
  5533. }
  5534. //---------------------------------------------------------------------------
  5535. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5536. {
  5537. DebugFail();
  5538. }
  5539. //---------------------------------------------------------------------------
  5540. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5541. {
  5542. DebugFail();
  5543. }
  5544. //---------------------------------------------------------------------------
  5545. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5546. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5547. {
  5548. TSynchronizeParamType Params;
  5549. Params.LocalDirectory = LocalDirectory;
  5550. Params.RemoteDirectory = RemoteDirectory;
  5551. int UnusedParams =
  5552. (GUIConfiguration->SynchronizeParams &
  5553. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5554. TTerminal::spCaseSensitive | TTerminal::spMirror | TTerminal::spByChecksum));
  5555. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5556. Params.Options = GUIConfiguration->SynchronizeOptions;
  5557. bool SaveSettings = false;
  5558. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5559. &DoSynchronizeTooManyDirectories);
  5560. DebugAssert(FSynchronizeController == NULL);
  5561. FSynchronizeController = &Controller;
  5562. bool Result;
  5563. try
  5564. {
  5565. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5566. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5567. int Options =
  5568. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5569. DebugAssert(FOnFeedSynchronizeError == NULL);
  5570. DebugAssert(FOnSynchronizeAbort == NULL);
  5571. DebugAssert(FSynchronizeTerminal == NULL);
  5572. FSynchronizeTerminal = Terminal;
  5573. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5574. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5575. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5576. if (Result)
  5577. {
  5578. if (SaveSettings)
  5579. {
  5580. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5581. GUIConfiguration->SynchronizeOptions = Params.Options;
  5582. }
  5583. else
  5584. {
  5585. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5586. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5587. FLAGSET(Params.Options, soSynchronize))
  5588. {
  5589. GUIConfiguration->SynchronizeOptions =
  5590. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5591. soSynchronize;
  5592. }
  5593. }
  5594. LocalDirectory = Params.LocalDirectory;
  5595. RemoteDirectory = Params.RemoteDirectory;
  5596. }
  5597. }
  5598. __finally
  5599. {
  5600. FSynchronizeController = NULL;
  5601. DebugAssert(FOnFeedSynchronizeError == NULL);
  5602. FOnFeedSynchronizeError = NULL;
  5603. DebugAssert(FOnSynchronizeAbort == NULL);
  5604. FOnSynchronizeAbort = NULL;
  5605. FSynchronizeTerminal = NULL;
  5606. }
  5607. return Result;
  5608. }
  5609. //---------------------------------------------------------------------------
  5610. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5611. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5612. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5613. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5614. TSynchronizeOptions * Options, bool Full)
  5615. {
  5616. // Keep-up-to-date mode
  5617. if (Terminal->Status == ssOpened)
  5618. {
  5619. try
  5620. {
  5621. int PParams = Params.Params;
  5622. if (!Full)
  5623. {
  5624. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5625. if (FLAGSET(Params.Options, soRecurse))
  5626. {
  5627. PParams |= TTerminal::spSubDirs;
  5628. }
  5629. }
  5630. else
  5631. {
  5632. // if keepuptodate is non-recursive,
  5633. // full sync before has to be non-recursive as well
  5634. if (FLAGCLEAR(Params.Options, soRecurse))
  5635. {
  5636. PParams |= TTerminal::spNoRecurse;
  5637. }
  5638. }
  5639. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5640. PParams, Checklist, Options);
  5641. }
  5642. catch (Exception & E)
  5643. {
  5644. if (!Terminal->Active)
  5645. {
  5646. ShowExtendedExceptionEx(Terminal, &E);
  5647. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5648. if (!Terminal->Active)
  5649. {
  5650. throw;
  5651. }
  5652. }
  5653. else
  5654. {
  5655. if (FLAGSET(Params.Options, soContinueOnError) &&
  5656. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5657. {
  5658. // noop, already logged in MoreMessageDialog
  5659. }
  5660. else
  5661. {
  5662. // We get mostly EAbort here, so this is noop.
  5663. // Exception is an error when listing directories while looking for differences.
  5664. ShowExtendedExceptionEx(Terminal, &E);
  5665. throw;
  5666. }
  5667. }
  5668. }
  5669. }
  5670. }
  5671. //---------------------------------------------------------------------------
  5672. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5673. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5674. const UnicodeString ErrorStr)
  5675. {
  5676. if (!Directory.IsEmpty())
  5677. {
  5678. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5679. }
  5680. else
  5681. {
  5682. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5683. }
  5684. }
  5685. //---------------------------------------------------------------------------
  5686. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5687. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5688. {
  5689. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5690. {
  5691. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5692. }
  5693. else
  5694. {
  5695. TMessageParams Params(mpNeverAskAgainCheck);
  5696. unsigned int Result = MessageDialog(
  5697. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5698. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5699. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5700. {
  5701. MaxDirectories *= 2;
  5702. if (Result == qaNeverAskAgain)
  5703. {
  5704. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5705. }
  5706. }
  5707. else
  5708. {
  5709. Abort();
  5710. }
  5711. }
  5712. }
  5713. //---------------------------------------------------------------------------
  5714. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5715. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5716. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5717. TSynchronizeOptions * Options)
  5718. {
  5719. // Keep-up-to-date mode
  5720. DebugAssert(!FAutoOperation);
  5721. void * BatchStorage;
  5722. BatchStart(BatchStorage);
  5723. FAutoOperation = true;
  5724. bool AnyOperation = false;
  5725. TDateTime StartTime = Now();
  5726. TSynchronizeChecklist * AChecklist = NULL;
  5727. try
  5728. {
  5729. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, -1);
  5730. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5731. {
  5732. FSynchronizeProgressForm->Start();
  5733. }
  5734. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5735. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5736. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5737. Options);
  5738. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5739. SAFE_DESTROY(FSynchronizeProgressForm);
  5740. AnyOperation = (AChecklist->CheckedCount > 0);
  5741. if (AnyOperation)
  5742. {
  5743. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5744. CreateProgressForm(&SynchronizeProgress);
  5745. try
  5746. {
  5747. Terminal->SynchronizeApply(
  5748. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5749. SynchronizeProcessedItem, NULL, NULL, NULL);
  5750. }
  5751. __finally
  5752. {
  5753. DestroyProgressForm();
  5754. }
  5755. }
  5756. }
  5757. __finally
  5758. {
  5759. if (Checklist == NULL)
  5760. {
  5761. delete AChecklist;
  5762. }
  5763. else
  5764. {
  5765. *Checklist = AChecklist;
  5766. }
  5767. FAutoOperation = false;
  5768. SAFE_DESTROY(FSynchronizeProgressForm);
  5769. BatchEnd(BatchStorage);
  5770. ReloadLocalDirectory();
  5771. if (AnyOperation)
  5772. {
  5773. OperationComplete(StartTime);
  5774. }
  5775. }
  5776. }
  5777. //---------------------------------------------------------------------------
  5778. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5779. {
  5780. // can be called from command line
  5781. return Visible &&
  5782. ((DirView(osRemote)->SelCount > 0) ||
  5783. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5784. }
  5785. //---------------------------------------------------------------------------
  5786. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5787. {
  5788. LogSynchronizeEvent(Terminal, Message);
  5789. }
  5790. //---------------------------------------------------------------------------
  5791. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5792. int Params, TSynchronizeOptions & Options)
  5793. {
  5794. DebugAssert(!IsLocalBrowserMode());
  5795. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5796. {
  5797. Options.Filter = new TStringList();
  5798. Options.Filter->CaseSensitive = false;
  5799. Options.Filter->Duplicates = Types::dupAccept;
  5800. if (DirView(osRemote)->SelCount > 0)
  5801. {
  5802. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5803. }
  5804. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5805. {
  5806. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5807. }
  5808. Options.Filter->Sort();
  5809. }
  5810. }
  5811. //---------------------------------------------------------------------------
  5812. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5813. {
  5814. TCopyParamType Defaults;
  5815. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5816. ConfigStorage->AccessMode = smRead;
  5817. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5818. {
  5819. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5820. }
  5821. ConfigStorage.reset(NULL);
  5822. std::unique_ptr<TStringList> Options(new TStringList());
  5823. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5824. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5825. UnicodeString Result;
  5826. if (Options->Count > 0)
  5827. {
  5828. Result =
  5829. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5830. }
  5831. return Result;
  5832. }
  5833. //---------------------------------------------------------------------------
  5834. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5835. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5836. {
  5837. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5838. UnicodeString AdditionalParams =
  5839. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5840. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5841. SerializeCopyParamForCommandLine(CopyParams),
  5842. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5843. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5844. ExecuteNewInstance(SessionName, AdditionalParams);
  5845. }
  5846. //---------------------------------------------------------------------------
  5847. struct TSynchronizeParams
  5848. {
  5849. UnicodeString LocalDirectory;
  5850. UnicodeString RemoteDirectory;
  5851. TSynchronizeMode Mode;
  5852. TSynchronizeChecklist * Checklist;
  5853. int Params;
  5854. TCopyParamType * CopyParam;
  5855. TDateTime CollectElapsed;
  5856. TDateTime * StartTime;
  5857. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5858. };
  5859. //---------------------------------------------------------------------------
  5860. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5861. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5862. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5863. {
  5864. DebugAssert(!FAutoOperation);
  5865. void * BatchStorage;
  5866. BatchStart(BatchStorage);
  5867. FAutoOperation = true;
  5868. TFileOperationStatistics Statistics;
  5869. TDateTime Start = Now();
  5870. try
  5871. {
  5872. Params.OnProcessedItem = OnProcessedItem;
  5873. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5874. CreateProgressForm(&SynchronizeProgress);
  5875. Terminal->SynchronizeApply(
  5876. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5877. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5878. &Statistics);
  5879. }
  5880. __finally
  5881. {
  5882. Params.OnProcessedItem = NULL;
  5883. FAutoOperation = false;
  5884. DestroyProgressForm();
  5885. BatchEnd(BatchStorage);
  5886. ReloadLocalDirectory();
  5887. }
  5888. if (WinConfiguration->SynchronizeSummary)
  5889. {
  5890. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5891. // The statistics should be 0 anyway in this case
  5892. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5893. {
  5894. Message += L"\n";
  5895. if (Statistics.FilesUploaded > 0)
  5896. {
  5897. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5898. }
  5899. if (Statistics.FilesDownloaded > 0)
  5900. {
  5901. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5902. }
  5903. if (Statistics.FilesDeletedLocal > 0)
  5904. {
  5905. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5906. }
  5907. if (Statistics.FilesDeletedRemote > 0)
  5908. {
  5909. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5910. }
  5911. }
  5912. TDateTime Elapsed = (Now() - Start);
  5913. Message +=
  5914. L"\n" +
  5915. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Params.CollectElapsed))) + L"\n" +
  5916. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Elapsed)));
  5917. TMessageParams Params(mpNeverAskAgainCheck);
  5918. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5919. if (Result == qaNeverAskAgain)
  5920. {
  5921. WinConfiguration->SynchronizeSummary = false;
  5922. }
  5923. }
  5924. }
  5925. //---------------------------------------------------------------------------
  5926. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5927. {
  5928. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5929. {
  5930. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5931. }
  5932. // Not set in keep-up-to-date mode - Synchronize() method
  5933. if (Token != NULL)
  5934. {
  5935. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5936. if (Params.OnProcessedItem != NULL)
  5937. {
  5938. Params.OnProcessedItem(NULL, ChecklistItem);
  5939. }
  5940. }
  5941. }
  5942. //---------------------------------------------------------------------------
  5943. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5944. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5945. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5946. {
  5947. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5948. *Params.StartTime = Now();
  5949. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5950. }
  5951. //---------------------------------------------------------------------------
  5952. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5953. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5954. {
  5955. // terminal can be already closed (e.g. dropped connection)
  5956. if (Terminal != NULL)
  5957. {
  5958. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5959. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5960. }
  5961. }
  5962. //---------------------------------------------------------------------------
  5963. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5964. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5965. {
  5966. DebugAssert(!IsLocalBrowserMode());
  5967. TAutoBatch AutoBatch(this);
  5968. TAutoFlag AutoOperationFlag(FAutoOperation);
  5969. if (Side == osRemote)
  5970. {
  5971. std::unique_ptr<TStrings> FileList(new TStringList());
  5972. FileList->AddObject(FileName, RemoteFile);
  5973. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5974. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5975. RemoteDirView->SaveSelection();
  5976. RemoteDirView->SaveSelectedNames();
  5977. try
  5978. {
  5979. Terminal->MoveFiles(FileList.get(), Target, FileMask, false);
  5980. }
  5981. catch(...)
  5982. {
  5983. RemoteDirView->DiscardSavedSelection();
  5984. throw;
  5985. }
  5986. RemoteDirView->RestoreSelection();
  5987. }
  5988. else if (DebugAlwaysTrue(Side == osLocal))
  5989. {
  5990. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5991. {
  5992. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5993. }
  5994. UnicodeString Directory = ExtractFileDir(FileName);
  5995. ReloadLocalDirectory(Directory);
  5996. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5997. if (!SamePaths(Directory, NewDirectory))
  5998. {
  5999. ReloadLocalDirectory(NewDirectory);
  6000. }
  6001. }
  6002. }
  6003. //---------------------------------------------------------------------------
  6004. void __fastcall TCustomScpExplorerForm::DoSynchronizeBrowse(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  6005. {
  6006. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  6007. if (Side == osLocal)
  6008. {
  6009. if (Action == TSynchronizeChecklist::saDownloadNew)
  6010. {
  6011. OpenFolderInExplorer(LocalPath);
  6012. }
  6013. else
  6014. {
  6015. OpenFileInExplorer(TPath::Combine(LocalPath, Item->GetFileName()));
  6016. }
  6017. }
  6018. else if (DebugAlwaysTrue(Side == osRemote))
  6019. {
  6020. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  6021. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  6022. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  6023. if (!LocalPath.IsEmpty())
  6024. {
  6025. SessionData->LocalDirectory = LocalPath;
  6026. }
  6027. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  6028. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(BROWSE_SWITCH), Item->GetFileName())));
  6029. }
  6030. }
  6031. //---------------------------------------------------------------------------
  6032. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  6033. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6034. const TCopyParamType * CopyParams)
  6035. {
  6036. UnicodeString SessionName = CreateHiddenDuplicateSession();
  6037. UnicodeString AdditionalParams =
  6038. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  6039. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  6040. SerializeCopyParamForCommandLine(CopyParams),
  6041. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  6042. LocalDirectory, RemoteDirectory, Mode, Params));
  6043. ExecuteNewInstance(SessionName, AdditionalParams);
  6044. }
  6045. //---------------------------------------------------------------------------
  6046. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  6047. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  6048. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  6049. {
  6050. int Result;
  6051. bool SaveSettings = false;
  6052. int Options =
  6053. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6054. FLAGMASK(!CanCalculateChecksum(), fsoDisableByChecksum) |
  6055. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  6056. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  6057. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  6058. bool Continue =
  6059. ((UseDefaults == 0) ||
  6060. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  6061. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults)) &&
  6062. (FLAGCLEAR(Params, TTerminal::spByChecksum) || EnsureCommandSessionFallback(fcCalculatingChecksum));
  6063. if (Continue)
  6064. {
  6065. Configuration->Usage->Inc(L"Synchronizations");
  6066. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  6067. UpdateCopyParamCounters(CopyParam);
  6068. TSynchronizeOptions SynchronizeOptions;
  6069. GetSynchronizeOptions(Params, SynchronizeOptions);
  6070. if (SaveSettings)
  6071. {
  6072. GUIConfiguration->SynchronizeParams = Params;
  6073. }
  6074. else
  6075. {
  6076. SaveMode = false;
  6077. }
  6078. TDateTime StartTime = Now();
  6079. TSynchronizeChecklist * Checklist = NULL;
  6080. try
  6081. {
  6082. DebugAssert(!FAutoOperation);
  6083. FAutoOperation = true;
  6084. try
  6085. {
  6086. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6087. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6088. int Files = -1;
  6089. if (DataList->Count >= 1)
  6090. {
  6091. Files = StrToIntDef(DataList->Strings[0], Files);
  6092. }
  6093. else
  6094. {
  6095. DataList->Add(UnicodeString());
  6096. }
  6097. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6098. FSynchronizeProgressForm->Start();
  6099. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6100. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6101. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6102. &SynchronizeOptions);
  6103. if (Terminal->SessionData->CacheDirectories)
  6104. {
  6105. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6106. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6107. }
  6108. }
  6109. __finally
  6110. {
  6111. FAutoOperation = false;
  6112. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6113. SAFE_DESTROY(FSynchronizeProgressForm);
  6114. }
  6115. TSynchronizeParams SynchronizeParams;
  6116. SynchronizeParams.LocalDirectory = LocalDirectory;
  6117. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  6118. SynchronizeParams.Mode = Mode;
  6119. SynchronizeParams.CopyParam = &CopyParam;
  6120. SynchronizeParams.Params = Params;
  6121. SynchronizeParams.Checklist = Checklist;
  6122. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6123. SynchronizeParams.StartTime = &StartTime;
  6124. SynchronizeParams.OnProcessedItem = NULL;
  6125. Result = Checklist->Count;
  6126. if (Checklist->Count > 0)
  6127. {
  6128. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6129. {
  6130. if (!DoSynchronizeChecklistDialog(
  6131. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6132. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeBrowse, &SynchronizeParams))
  6133. {
  6134. Result = -1;
  6135. }
  6136. }
  6137. else
  6138. {
  6139. FullSynchronize(SynchronizeParams, NULL, NULL);
  6140. }
  6141. }
  6142. else
  6143. {
  6144. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6145. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6146. }
  6147. }
  6148. __finally
  6149. {
  6150. delete Checklist;
  6151. }
  6152. OperationComplete(StartTime);
  6153. }
  6154. else
  6155. {
  6156. Result = -1;
  6157. }
  6158. return Result;
  6159. }
  6160. //---------------------------------------------------------------------------
  6161. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6162. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6163. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6164. {
  6165. if (Collect)
  6166. {
  6167. DebugAssert(FSynchronizeProgressForm != NULL);
  6168. if (!FSynchronizeProgressForm->Started)
  6169. {
  6170. FSynchronizeProgressForm->Start();
  6171. }
  6172. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6173. SetTaskbarListProgressValue(CompareProgress);
  6174. }
  6175. else
  6176. {
  6177. DebugAssert(FSynchronizeProgressForm == NULL);
  6178. DebugAssert(FProgressForm != NULL);
  6179. }
  6180. }
  6181. //---------------------------------------------------------------------------
  6182. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6183. {
  6184. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6185. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6186. if (File.get() != NULL)
  6187. {
  6188. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6189. Application->ShowMainForm = false;
  6190. Application->Run();
  6191. }
  6192. }
  6193. //---------------------------------------------------------------------------
  6194. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6195. {
  6196. DebugFail();
  6197. }
  6198. //---------------------------------------------------------------------------
  6199. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6200. {
  6201. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6202. SessionData->Assign(ManagedSession->SessionData);
  6203. UpdateSessionData(SessionData.get());
  6204. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6205. if (IsActiveTerminal(ManagedSession))
  6206. {
  6207. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6208. }
  6209. if (!ManagedSession->SessionData->HasSessionName())
  6210. {
  6211. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6212. // once IsWorkspace is cleared
  6213. SessionData->Name = UnicodeString();
  6214. }
  6215. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6216. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6217. SessionData->IsWorkspace = false;
  6218. return SessionData.release();
  6219. }
  6220. //---------------------------------------------------------------------------
  6221. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6222. {
  6223. TSessionData * SessionData = CloneCurrentSessionData();
  6224. try
  6225. {
  6226. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6227. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6228. }
  6229. __finally
  6230. {
  6231. delete SessionData;
  6232. }
  6233. }
  6234. //---------------------------------------------------------------------------
  6235. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6236. {
  6237. TTerminalManager * Manager = TTerminalManager::Instance();
  6238. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6239. if (DebugAlwaysTrue(ManagedSession != NULL))
  6240. {
  6241. // Update ManagedSession->StateData
  6242. UpdateSession(ManagedSession);
  6243. }
  6244. Manager->SaveWorkspace(DataList.get());
  6245. return DataList.release();
  6246. }
  6247. //---------------------------------------------------------------------------
  6248. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6249. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6250. {
  6251. WinConfiguration->LastWorkspace = Name;
  6252. if (!SavePasswords)
  6253. {
  6254. for (int Index = 0; Index < DataList->Count; Index++)
  6255. {
  6256. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6257. if (SessionData->Link.IsEmpty())
  6258. {
  6259. SessionData->ClearSessionPasswords();
  6260. }
  6261. }
  6262. }
  6263. StoredSessions->NewWorkspace(Name, DataList);
  6264. // modified only
  6265. StoredSessions->Save(false, Explicit);
  6266. }
  6267. //---------------------------------------------------------------------------
  6268. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6269. {
  6270. return
  6271. DefaultStr(WinConfiguration->LastWorkspace,
  6272. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6273. }
  6274. //---------------------------------------------------------------------------
  6275. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6276. {
  6277. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6278. bool AnyNonStoredSessionWithPassword = false;
  6279. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6280. bool AllNonStoredSessionsAnonymous = true;
  6281. TTerminalManager * Manager = TTerminalManager::Instance();
  6282. for (int Index = 0; Index < DataList->Count; Index++)
  6283. {
  6284. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6285. if (SessionData->Link.IsEmpty())
  6286. {
  6287. if (SessionData->HasAnySessionPassword())
  6288. {
  6289. AnyNonStoredSessionWithPassword = true;
  6290. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6291. {
  6292. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6293. }
  6294. }
  6295. if (!SameText(SessionData->UserName, AnonymousUserName))
  6296. {
  6297. AllNonStoredSessionsAnonymous = false;
  6298. }
  6299. }
  6300. }
  6301. bool SavePasswords;
  6302. bool * PSavePasswords;
  6303. bool NotRecommendedSavingPasswords =
  6304. !CustomWinConfiguration->UseMasterPassword &&
  6305. !AllNonStoredSessionsAnonymous;
  6306. if (Configuration->DisablePasswordStoring ||
  6307. !AnyNonStoredSessionWithPassword)
  6308. {
  6309. PSavePasswords = NULL;
  6310. SavePasswords = false;
  6311. }
  6312. else
  6313. {
  6314. PSavePasswords = &SavePasswords;
  6315. SavePasswords =
  6316. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6317. !NotRecommendedSavingPasswords;
  6318. }
  6319. UnicodeString Name = WorkspaceName();
  6320. bool CreateShortcut = false;
  6321. bool Result =
  6322. DoSaveWorkspaceDialog(
  6323. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6324. EnableAutoSave);
  6325. if (Result)
  6326. {
  6327. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6328. if (CreateShortcut)
  6329. {
  6330. TOperationVisualizer Visualizer;
  6331. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6332. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6333. }
  6334. if (EnableAutoSave)
  6335. {
  6336. WinConfiguration->AutoSaveWorkspace = true;
  6337. WinConfiguration->AutoWorkspace = Name;
  6338. if (PSavePasswords != NULL)
  6339. {
  6340. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6341. }
  6342. }
  6343. }
  6344. return Result;
  6345. }
  6346. //---------------------------------------------------------------------------
  6347. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6348. {
  6349. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6350. DebugAssert(Session == ManagedSession);
  6351. if (!IsLocalBrowserMode())
  6352. {
  6353. SAFE_DESTROY(Session->RemoteExplorerState);
  6354. if (WinConfiguration->PreservePanelState)
  6355. {
  6356. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6357. }
  6358. }
  6359. UpdateSessionData(Session->StateData);
  6360. }
  6361. //---------------------------------------------------------------------------
  6362. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6363. {
  6364. // Keep in sync with TSessionData::CopyStateData
  6365. DebugAssert(Data != NULL);
  6366. // This is inconsistent with how color (for example) is handled.
  6367. Data->Name = ManagedSession->SessionData->Name;
  6368. if (!IsLocalBrowserMode())
  6369. {
  6370. // cannot use RemoteDirView->Path, because it is empty if connection
  6371. // was already closed
  6372. // also only peek, we may not be connected at all atm
  6373. // so make sure we do not try retrieving current directory from the server
  6374. // (particularly with FTP)
  6375. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6376. if (!ACurrentDirectory.IsEmpty())
  6377. {
  6378. Data->RemoteDirectory = ACurrentDirectory;
  6379. }
  6380. }
  6381. Data->Color = SessionColor;
  6382. }
  6383. //---------------------------------------------------------------------------
  6384. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6385. {
  6386. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6387. DebugAssert(Toolbar != NULL);
  6388. for (int i = 0; i < Toolbar->Items->Count; i++)
  6389. {
  6390. TTBXCustomDropDownItem * DropDownItem;
  6391. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6392. if (DropDownItem != NULL)
  6393. {
  6394. ToolbarItemResize(DropDownItem,
  6395. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6396. Toolbar->NonClientWidth);
  6397. break;
  6398. }
  6399. }
  6400. }
  6401. //---------------------------------------------------------------------------
  6402. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6403. {
  6404. Item->EditWidth = Width;
  6405. }
  6406. //---------------------------------------------------------------------------
  6407. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6408. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6409. {
  6410. for (int i = 0; i < Toolbar->Items->Count; i++)
  6411. {
  6412. TTBXCustomDropDownItem * DropDownItem;
  6413. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6414. if (DropDownItem != NULL)
  6415. {
  6416. ASize.x -= DropDownItem->EditWidth;
  6417. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  6418. }
  6419. }
  6420. }
  6421. //---------------------------------------------------------------------------
  6422. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6423. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6424. {
  6425. if (WinConfiguration->DDWarnLackOfTempSpace)
  6426. {
  6427. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6428. if (!ADrive.IsEmpty())
  6429. {
  6430. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6431. DebugAssert(RequiredSpace >= 0);
  6432. __int64 RequiredWithReserve;
  6433. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6434. if (FreeSpace < RequiredWithReserve)
  6435. {
  6436. unsigned int Result;
  6437. TMessageParams Params(mpNeverAskAgainCheck);
  6438. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6439. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6440. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6441. if (Result == qaNeverAskAgain)
  6442. {
  6443. WinConfiguration->DDWarnLackOfTempSpace = false;
  6444. }
  6445. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6446. }
  6447. }
  6448. }
  6449. }
  6450. //---------------------------------------------------------------------------
  6451. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6452. {
  6453. DoOpenDirectoryDialog(odAddBookmark, Side);
  6454. }
  6455. //---------------------------------------------------------------------------
  6456. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6457. {
  6458. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6459. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6460. try
  6461. {
  6462. TCustomDirView * DView = DirView(Side);
  6463. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6464. {
  6465. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6466. }
  6467. }
  6468. catch (...)
  6469. {
  6470. delete VisitedDirectories;
  6471. throw;
  6472. }
  6473. return VisitedDirectories;
  6474. }
  6475. //---------------------------------------------------------------------------
  6476. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6477. TOpenDirectoryMode Mode, TOperationSide Side)
  6478. {
  6479. bool Continue = true;
  6480. if (Mode == odAddBookmark)
  6481. {
  6482. TMessageParams Params(mpNeverAskAgainCheck);
  6483. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6484. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6485. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6486. unsigned int Answer =
  6487. MessageDialog(Message,
  6488. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6489. if (Answer == qaNeverAskAgain)
  6490. {
  6491. Continue = true;
  6492. WinConfiguration->UseSharedBookmarks = true;
  6493. }
  6494. else if (Answer == qaOK)
  6495. {
  6496. Continue = true;
  6497. WinConfiguration->UseSharedBookmarks = false;
  6498. }
  6499. else
  6500. {
  6501. Continue = false;
  6502. }
  6503. }
  6504. if (Continue)
  6505. {
  6506. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6507. try
  6508. {
  6509. UnicodeString Name = DirView(Side)->PathName;
  6510. bool Repeat;
  6511. do
  6512. {
  6513. Repeat = false;
  6514. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6515. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6516. // do not allow switching to location profiles,
  6517. // if we are not connected
  6518. HasDirView[osLocal] && (Terminal != NULL)))
  6519. {
  6520. TWindowLock Lock(this);
  6521. if (!TryOpenDirectory(Side, Name))
  6522. {
  6523. Repeat = true;
  6524. Mode = odBrowse;
  6525. }
  6526. }
  6527. }
  6528. while (Repeat);
  6529. }
  6530. __finally
  6531. {
  6532. delete VisitedDirectories;
  6533. }
  6534. }
  6535. }
  6536. //---------------------------------------------------------------------------
  6537. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6538. {
  6539. DebugAssert(!Terminal->CommandSessionOpened);
  6540. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6541. }
  6542. //---------------------------------------------------------------------------
  6543. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6544. {
  6545. bool Result = Terminal->IsCapable[Capability] ||
  6546. Terminal->CommandSessionOpened;
  6547. if (!Result)
  6548. {
  6549. // We might get here for example when "checksum" synchronization is requested from command-line
  6550. // on server that supports neither checksum nor shell
  6551. if (!Terminal->IsCapable[fcSecondaryShell])
  6552. {
  6553. NotSupported();
  6554. }
  6555. else if (!GUIConfiguration->ConfirmCommandSession)
  6556. {
  6557. Result = true;
  6558. }
  6559. else
  6560. {
  6561. TMessageParams Params(mpNeverAskAgainCheck);
  6562. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6563. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6564. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6565. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6566. if (Answer == qaNeverAskAgain)
  6567. {
  6568. GUIConfiguration->ConfirmCommandSession = false;
  6569. Result = true;
  6570. }
  6571. else if (Answer == qaOK)
  6572. {
  6573. Result = true;
  6574. }
  6575. }
  6576. if (Result)
  6577. {
  6578. Result = CommandSessionFallback();
  6579. }
  6580. }
  6581. return Result;
  6582. }
  6583. //---------------------------------------------------------------------------
  6584. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6585. {
  6586. if (EnsureCommandSessionFallback(fcAnyCommand))
  6587. {
  6588. DoConsoleDialog(Terminal, Command);
  6589. }
  6590. }
  6591. //---------------------------------------------------------------------------
  6592. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6593. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6594. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6595. {
  6596. if (!IsSideLocalBrowser(osRemote) &&
  6597. IsFileControl(DropSourceControl, osRemote) &&
  6598. (FDDExtMapFile != NULL))
  6599. {
  6600. Accept = true;
  6601. }
  6602. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6603. DebugAssert(FDDTargetControl != NULL);
  6604. }
  6605. //---------------------------------------------------------------------------
  6606. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6607. _di_IDataObject DataObj, int KeyState,
  6608. const TPoint & Point, int & Effect, bool & Accept)
  6609. {
  6610. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6611. }
  6612. //---------------------------------------------------------------------------
  6613. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6614. _di_IDataObject DataObj, int KeyState,
  6615. const TPoint & Point, int & Effect, bool & Accept)
  6616. {
  6617. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6618. }
  6619. //---------------------------------------------------------------------------
  6620. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6621. TObject * Sender)
  6622. {
  6623. DebugUsedParam(Sender);
  6624. DebugAssert(FDDTargetControl == Sender);
  6625. FDDTargetControl = NULL;
  6626. }
  6627. //---------------------------------------------------------------------------
  6628. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  6629. {
  6630. FileControlDDDragLeave(SessionsPageControl);
  6631. }
  6632. //---------------------------------------------------------------------------
  6633. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  6634. {
  6635. FileControlDDDragLeave(QueueView3);
  6636. }
  6637. //---------------------------------------------------------------------------
  6638. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6639. {
  6640. DebugAssert(!IsSideLocalBrowser(Side));
  6641. DebugUsedParam(Side);
  6642. bool Edit = false;
  6643. TRemoteFile * File = NULL;
  6644. UnicodeString FileName;
  6645. UnicodeString PointTo;
  6646. bool SymbolicLink = true;
  6647. if (RemoteDirView->ItemFocused)
  6648. {
  6649. DebugAssert(RemoteDirView->ItemFocused->Data);
  6650. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6651. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6652. if (Edit)
  6653. {
  6654. FileName = File->FileName;
  6655. PointTo = File->LinkTo;
  6656. }
  6657. else if (!File->IsParentDirectory)
  6658. {
  6659. PointTo = File->FileName;
  6660. }
  6661. }
  6662. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6663. Terminal->IsCapable[fcHardLink]))
  6664. {
  6665. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6666. if (Edit)
  6667. {
  6668. DebugAssert(File->FileName == FileName);
  6669. int Params = dfNoRecursive;
  6670. Terminal->ExceptionOnFail = true;
  6671. try
  6672. {
  6673. Terminal->DeleteFile(L"", File, &Params);
  6674. }
  6675. __finally
  6676. {
  6677. Terminal->ExceptionOnFail = false;
  6678. }
  6679. }
  6680. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6681. }
  6682. }
  6683. //---------------------------------------------------------------------------
  6684. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6685. {
  6686. return
  6687. (IsSideLocalBrowser(Side) ||
  6688. (HasActiveTerminal() &&
  6689. Terminal->ResolvingSymlinks &&
  6690. Terminal->IsCapable[fcSymbolicLink]));
  6691. }
  6692. //---------------------------------------------------------------------------
  6693. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6694. {
  6695. return
  6696. !IsSideLocalBrowser(FCurrentSide) &&
  6697. (RemoteDirView->ItemFocused != NULL) &&
  6698. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6699. Terminal->SessionData->ResolveSymlinks;
  6700. }
  6701. //---------------------------------------------------------------------------
  6702. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6703. {
  6704. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6705. FForceExecution = true;
  6706. try
  6707. {
  6708. DirView(osCurrent)->ExecuteCurrentFile();
  6709. }
  6710. __finally
  6711. {
  6712. FForceExecution = false;
  6713. }
  6714. }
  6715. //---------------------------------------------------------------------------
  6716. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6717. {
  6718. TEditorData ExternalEditor;
  6719. ExternalEditor.Editor = edExternal;
  6720. bool Remember = false;
  6721. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6722. {
  6723. if (Remember)
  6724. {
  6725. TEditorList * EditorList = new TEditorList;
  6726. try
  6727. {
  6728. *EditorList = *WinConfiguration->EditorList;
  6729. bool Found = false;
  6730. int i = 0;
  6731. while (!Found && (i < EditorList->Count))
  6732. {
  6733. const TEditorPreferences * Editor = EditorList->Editors[i];
  6734. if ((Editor->Data->Editor == edExternal) &&
  6735. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6736. {
  6737. Found = true;
  6738. }
  6739. i++;
  6740. }
  6741. if (!Found)
  6742. {
  6743. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6744. WinConfiguration->EditorList = EditorList;
  6745. }
  6746. }
  6747. __finally
  6748. {
  6749. delete EditorList;
  6750. }
  6751. }
  6752. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6753. }
  6754. }
  6755. //---------------------------------------------------------------------------
  6756. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6757. {
  6758. if (FFileFindTerminal == ATerminal)
  6759. {
  6760. FFileFindTerminal = NULL;
  6761. HideFileFindDialog();
  6762. }
  6763. if (FClipboardTerminal == ATerminal)
  6764. {
  6765. ClipboardClear(); // implies ClipboardStop
  6766. }
  6767. if ((FOnSynchronizeAbort != NULL) &&
  6768. (ATerminal == FManagedSession))
  6769. {
  6770. FOnSynchronizeAbort(NULL);
  6771. }
  6772. }
  6773. //---------------------------------------------------------------------------
  6774. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6775. {
  6776. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6777. DetachTerminal(Sender);
  6778. }
  6779. //---------------------------------------------------------------------------
  6780. void __fastcall TCustomScpExplorerForm::FileTerminalReplaced(
  6781. const UnicodeString FileName, TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6782. {
  6783. TManagedTerminal * ATerminal = static_cast<TManagedTerminal *>(Arg);
  6784. if (Data->Terminal == Terminal)
  6785. {
  6786. Data->Terminal = ATerminal;
  6787. }
  6788. }
  6789. //---------------------------------------------------------------------------
  6790. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6791. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6792. {
  6793. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6794. DebugAssert(Terminal != NULL);
  6795. if (Data->Terminal == Terminal)
  6796. {
  6797. Data->Terminal = NULL;
  6798. }
  6799. }
  6800. //---------------------------------------------------------------------------
  6801. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6802. {
  6803. return NULL;
  6804. }
  6805. //---------------------------------------------------------------------------
  6806. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6807. {
  6808. UpdateControls();
  6809. SessionColor = TColor(0);
  6810. UpdateRemotePathComboBox(false);
  6811. NeedSession(false);
  6812. }
  6813. //---------------------------------------------------------------------------
  6814. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6815. {
  6816. try
  6817. {
  6818. // Cache, as the login dialog can change its value.
  6819. // See also DoShow. Also see TTerminalManager::NewSession.
  6820. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6821. try
  6822. {
  6823. if (ShowLogin)
  6824. {
  6825. bool ReloadSessions = !Startup;
  6826. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6827. }
  6828. }
  6829. __finally
  6830. {
  6831. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6832. // (so there was no chance for the user to open any session yet)
  6833. if ((ShowLogin || !Startup) &&
  6834. !WinConfiguration->KeepOpenWhenNoSession &&
  6835. // this rules out the implicit Commander's local-local browser
  6836. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6837. {
  6838. TerminateApplication();
  6839. }
  6840. }
  6841. }
  6842. catch (EAbort &)
  6843. {
  6844. // swallow
  6845. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6846. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6847. }
  6848. }
  6849. //---------------------------------------------------------------------------
  6850. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6851. {
  6852. TTerminalManager * Manager = TTerminalManager::Instance();
  6853. DebugAssert(!Manager->Updating);
  6854. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6855. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6856. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6857. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6858. try
  6859. {
  6860. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6861. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6862. {
  6863. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6864. }
  6865. for (int Index = 0; Index <= Manager->Count; Index++)
  6866. {
  6867. TThemeTabSheet * TabSheet;
  6868. if (Index >= SessionsPageControl->PageCount)
  6869. {
  6870. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6871. TabSheet->PageControl = SessionsPageControl;
  6872. }
  6873. else
  6874. {
  6875. TabSheet = SessionsPageControl->Pages[Index];
  6876. }
  6877. bool IsSessionTab = (Index < Manager->Count);
  6878. if (IsSessionTab)
  6879. {
  6880. TTerminal * Terminal = Manager->Sessions[Index];
  6881. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6882. TabSheet->CaptionTruncation = WinConfiguration->SessionTabCaptionTruncation ? tttEllipsis : tttNone;
  6883. UpdateSessionTab(TabSheet);
  6884. }
  6885. else
  6886. {
  6887. TabSheet->Tag = 0; // not really needed
  6888. TabSheet->Shadowed = false;
  6889. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6890. TabSheet->CaptionTruncation = GetNewTabTabCaptionTruncation();
  6891. // 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)
  6892. UpdateNewTabTab();
  6893. }
  6894. }
  6895. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6896. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6897. {
  6898. SessionsPageControl->UpdateTabsCaptionTruncation();
  6899. }
  6900. }
  6901. __finally
  6902. {
  6903. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6904. }
  6905. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6906. }
  6907. //---------------------------------------------------------------------------
  6908. TThemeTabCaptionTruncation TCustomScpExplorerForm::GetNewTabTabCaptionTruncation()
  6909. {
  6910. return WinConfiguration->SessionTabCaptionTruncation ? tttNoText : tttNone;
  6911. }
  6912. //---------------------------------------------------------------------------
  6913. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6914. {
  6915. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6916. }
  6917. //---------------------------------------------------------------------------
  6918. TThemeTabSheet * TCustomScpExplorerForm::GetNewTabTab()
  6919. {
  6920. return SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6921. }
  6922. //---------------------------------------------------------------------------
  6923. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  6924. {
  6925. TThemeTabSheet * TabSheet = GetNewTabTab();
  6926. UnicodeString TabCaption;
  6927. if (WinConfiguration->SelectiveToolbarText)
  6928. {
  6929. TabCaption = GetNewTabTabCaption();
  6930. }
  6931. TabSheet->BaseCaption = TabCaption;
  6932. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  6933. }
  6934. //---------------------------------------------------------------------------
  6935. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  6936. {
  6937. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  6938. }
  6939. //---------------------------------------------------------------------------
  6940. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  6941. {
  6942. DebugFail();
  6943. return UnicodeString();
  6944. }
  6945. //---------------------------------------------------------------------------
  6946. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  6947. {
  6948. if (DebugAlwaysTrue(TabSheet != NULL))
  6949. {
  6950. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  6951. if (DebugAlwaysTrue(ASession != NULL))
  6952. {
  6953. TColor Color = (ASession == Terminal) ? FSessionColor : ASession->StateData->Color;
  6954. if (ASession->LocalBrowser)
  6955. {
  6956. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  6957. }
  6958. else
  6959. {
  6960. TabSheet->ImageIndex = AddSessionColor(Color);
  6961. }
  6962. TTerminalManager * Manager = TTerminalManager::Instance();
  6963. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  6964. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  6965. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  6966. }
  6967. }
  6968. }
  6969. //---------------------------------------------------------------------------
  6970. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  6971. {
  6972. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  6973. }
  6974. //---------------------------------------------------------------------------
  6975. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6976. {
  6977. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6978. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  6979. bool Result = (Session != NULL);
  6980. if (Result)
  6981. {
  6982. TTerminalManager::Instance()->ActiveSession = Session;
  6983. }
  6984. else
  6985. {
  6986. try
  6987. {
  6988. NewTab();
  6989. }
  6990. __finally
  6991. {
  6992. SessionListChanged();
  6993. }
  6994. FSessionsPageControlNewTabTime = Now();
  6995. }
  6996. return Result;
  6997. }
  6998. //---------------------------------------------------------------------------
  6999. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  7000. {
  7001. TWindowLock Lock(this);
  7002. SessionTabSwitched();
  7003. }
  7004. //---------------------------------------------------------------------------
  7005. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  7006. {
  7007. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  7008. DebugAssert(TransferList != NULL);
  7009. UnicodeString Name;
  7010. if (TransferList->ItemIndex <= 0)
  7011. {
  7012. Name = L"";
  7013. }
  7014. else
  7015. {
  7016. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  7017. }
  7018. if (FCopyParamAutoSelected.IsEmpty())
  7019. {
  7020. // if previous preset was not autoselected, make new preset the "default"
  7021. FCopyParamDefault = Name;
  7022. }
  7023. GUIConfiguration->CopyParamCurrent = Name;
  7024. }
  7025. //---------------------------------------------------------------------------
  7026. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  7027. {
  7028. // sanity check
  7029. bool ExistingPreset =
  7030. (FTransferListHoverIndex >= 0) &&
  7031. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  7032. DebugAssert(ExistingPreset);
  7033. if (ExistingPreset)
  7034. {
  7035. HDC DC = GetDC(0);
  7036. TCanvas * Canvas = new TCanvas();
  7037. try
  7038. {
  7039. Canvas->Handle = DC;
  7040. Canvas->Font = GetToolbarFont(this);
  7041. UnicodeString Name;
  7042. if (FTransferListHoverIndex == 0)
  7043. {
  7044. Name = L"";
  7045. }
  7046. else
  7047. {
  7048. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  7049. }
  7050. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  7051. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  7052. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  7053. static_cast<TObject*>(GetComponent(fcTransferList)));
  7054. UnicodeString InfoStr =
  7055. GUIConfiguration->CopyParamPreset[Name].
  7056. GetInfoStr(L"; ",
  7057. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  7058. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  7059. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  7060. {
  7061. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  7062. {
  7063. InfoStr.SetLength(InfoStr.Length() - 1);
  7064. }
  7065. InfoStr += Ellipsis;
  7066. }
  7067. // UpdateCaption does not cause invalidation of whole submenu, while
  7068. // setting Caption property does.
  7069. // also it probably does not resize the label, even if necessary
  7070. // (we do not want that anyway)
  7071. TransferLabel->UpdateCaption(InfoStr);
  7072. }
  7073. __finally
  7074. {
  7075. Canvas->Handle = NULL;
  7076. ReleaseDC(0, DC);
  7077. delete Canvas;
  7078. }
  7079. }
  7080. }
  7081. //---------------------------------------------------------------------------
  7082. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7083. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7084. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7085. {
  7086. if (FTransferListHoverIndex != AHoverIndex)
  7087. {
  7088. FTransferListHoverIndex = AHoverIndex;
  7089. UpdateTransferLabel();
  7090. }
  7091. }
  7092. //---------------------------------------------------------------------------
  7093. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7094. {
  7095. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7096. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7097. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7098. {
  7099. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7100. {
  7101. if (!NonVisualDataModule->Busy)
  7102. {
  7103. OpenDirectory(GetSide(osCurrent));
  7104. }
  7105. Message.Result = 1;
  7106. }
  7107. else
  7108. {
  7109. TForm::Dispatch(&Message);
  7110. }
  7111. }
  7112. else
  7113. {
  7114. TForm::Dispatch(&Message);
  7115. }
  7116. }
  7117. //---------------------------------------------------------------------------
  7118. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7119. {
  7120. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7121. if ((FIgnoreNextDialogChar != 0) &&
  7122. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7123. {
  7124. Message.Result = 1;
  7125. }
  7126. else
  7127. {
  7128. TForm::Dispatch(&Message);
  7129. }
  7130. FIgnoreNextDialogChar = 0;
  7131. }
  7132. //---------------------------------------------------------------------------
  7133. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7134. {
  7135. // The four low-order bits are used internally by Windows
  7136. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7137. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7138. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7139. // 61730 - restore thru double click - undocumented
  7140. // 61490 - maximize thru double click - undocumented
  7141. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7142. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7143. {
  7144. SysResizing(Cmd);
  7145. }
  7146. TForm::Dispatch(&Message);
  7147. }
  7148. //---------------------------------------------------------------------------
  7149. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7150. {
  7151. AppLog(L"Windows session end query");
  7152. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7153. // Also there no point returning TRUE as we are not able to
  7154. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7155. // Hence the process termination might be safer :)
  7156. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7157. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7158. {
  7159. Message.Result = FALSE;
  7160. }
  7161. else
  7162. {
  7163. Message.Result = TRUE;
  7164. }
  7165. // Do not call default handling as that triggers OnCloseQuery,
  7166. // where our implementation will popup confirmation dialogs, what we do not want,
  7167. // as per Vista guidelines:
  7168. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7169. }
  7170. //---------------------------------------------------------------------------
  7171. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7172. {
  7173. AppLog(L"Windows session end");
  7174. if (Message.EndSession && IsApplicationMinimized())
  7175. {
  7176. // WORKAROUND
  7177. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7178. // when it receives WM_ENDSESSION,
  7179. // but that sometimes (particularly when application is minimized) cause crashes.
  7180. // Crash popups message that blocks log off.
  7181. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7182. // so we call ExitProcess() immediately, not even trying to cleanup.
  7183. // It still causes beep, so there's likely some popup, but it does not block
  7184. // log off.
  7185. ExitProcess(0);
  7186. }
  7187. TForm::Dispatch(&Message);
  7188. }
  7189. #ifdef _DEBUG
  7190. //---------------------------------------------------------------------------
  7191. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  7192. {
  7193. TForm::Dispatch(&Message);
  7194. }
  7195. #endif
  7196. //---------------------------------------------------------------------------
  7197. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7198. {
  7199. }
  7200. //---------------------------------------------------------------------------
  7201. void __fastcall TCustomScpExplorerForm::DoShow()
  7202. {
  7203. // Called from TCustomScpExplorerForm::CMShowingChanged
  7204. // only now are the controls resized finally, so the size constraints
  7205. // will not conflict with possibly very small window size
  7206. RestoreFormParams();
  7207. // This indicates that the form was rescaled after parameters were loaded and
  7208. // as most probably the parameters were actually saved with the current form scaling
  7209. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7210. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7211. // and no rounding problems will occur.
  7212. // See also RestoreForm.
  7213. // (we should be safe to call RestoreParams unconditionally)
  7214. if (PixelsPerInch != Screen->PixelsPerInch)
  7215. {
  7216. RestoreParams();
  7217. }
  7218. FixControlsPlacement();
  7219. if (Position == poDefaultPosOnly)
  7220. {
  7221. CutFormToDesktop(this);
  7222. }
  7223. TForm::DoShow();
  7224. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7225. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7226. // This was previously in NeedSession, where other related code is.
  7227. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7228. // unpleasantly shows briefly.
  7229. if ((ManagedSession == NULL) &&
  7230. !WinConfiguration->ShowLoginWhenNoSession &&
  7231. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7232. // This detects if workspace was saved the last time the main widow was closed
  7233. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7234. {
  7235. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7236. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7237. }
  7238. // Before main window displays
  7239. if (ManagedSession == NULL)
  7240. {
  7241. StartingWithoutSession();
  7242. }
  7243. UpdatePixelsPerInchMainWindowCounter();
  7244. FShowing = true;
  7245. }
  7246. //---------------------------------------------------------------------------
  7247. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7248. {
  7249. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7250. }
  7251. //---------------------------------------------------------------------------
  7252. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7253. {
  7254. SessionListChanged();
  7255. InitStatusBar();
  7256. UpdateControls();
  7257. }
  7258. //---------------------------------------------------------------------------
  7259. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7260. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7261. TNotifyEvent OnBalloonClick, TObject * UserData)
  7262. {
  7263. bool Do;
  7264. UnicodeString Message;
  7265. if (E == NULL)
  7266. {
  7267. Message = Str;
  7268. Do = true;
  7269. }
  7270. else
  7271. {
  7272. Do = ExceptionMessage(E, Message);
  7273. }
  7274. if (Do && WinConfiguration->BalloonNotifications)
  7275. {
  7276. UnicodeString Title;
  7277. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7278. {
  7279. Message = TrimLeft(Message);
  7280. }
  7281. else
  7282. {
  7283. Message = UnformatMessage(Message);
  7284. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7285. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7286. Title = LoadResourceString(Captions[Type]);
  7287. if (Terminal != NULL)
  7288. {
  7289. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal->PrimaryTerminal));
  7290. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7291. }
  7292. }
  7293. if (Seconds == 0)
  7294. {
  7295. Seconds = WinConfiguration->NotificationsTimeout;
  7296. }
  7297. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7298. }
  7299. }
  7300. //---------------------------------------------------------------------------
  7301. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7302. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7303. UnicodeString HelpKeyword, const TMessageParams * Params,
  7304. TTerminal * Terminal)
  7305. {
  7306. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7307. (FOnFeedSynchronizeError != NULL)) &&
  7308. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7309. {
  7310. if (FOnFeedSynchronizeError != NULL)
  7311. {
  7312. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7313. }
  7314. else
  7315. {
  7316. DebugAssert(FErrorList != NULL);
  7317. TStringList * MoreMessagesCopy = NULL;
  7318. if (MoreMessages)
  7319. {
  7320. MoreMessagesCopy = new TStringList();
  7321. MoreMessagesCopy->Assign(MoreMessages);
  7322. }
  7323. FErrorList->AddObject(Message, MoreMessagesCopy);
  7324. }
  7325. PopupTrayBalloon(Terminal, Message, Type);
  7326. return ContinueAnswer(Answers);
  7327. }
  7328. else
  7329. {
  7330. bool UseBalloon = FTrayIcon->Visible;
  7331. if (UseBalloon)
  7332. {
  7333. PopupTrayBalloon(Terminal, Message, Type);
  7334. }
  7335. unsigned int Result;
  7336. try
  7337. {
  7338. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7339. }
  7340. __finally
  7341. {
  7342. // cancel only balloon we popped up, otherwise we may cancel notification
  7343. // balloon that was there before the message dialog
  7344. // (such as "dd confirmation opt in balloon)
  7345. if (UseBalloon)
  7346. {
  7347. FTrayIcon->CancelBalloon();
  7348. }
  7349. }
  7350. return Result;
  7351. }
  7352. }
  7353. //---------------------------------------------------------------------------
  7354. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7355. TTerminal * Terminal, Exception * E)
  7356. {
  7357. if (FTrayIcon->Visible)
  7358. {
  7359. PopupTrayBalloon(Terminal, L"", qtError, E);
  7360. }
  7361. // particularly prevent opening new session from jump list,
  7362. // while exception is shown
  7363. NonVisualDataModule->StartBusy();
  7364. try
  7365. {
  7366. ShowExtendedExceptionEx(Terminal, E);
  7367. }
  7368. __finally
  7369. {
  7370. NonVisualDataModule->EndBusy();
  7371. FTrayIcon->CancelBalloon();
  7372. }
  7373. }
  7374. //---------------------------------------------------------------------------
  7375. void __fastcall TCustomScpExplorerForm::SessionReady()
  7376. {
  7377. InitStatusBar();
  7378. // cannot rely on active page being page for active terminal,
  7379. // as it can happen that active page is the "new session" page
  7380. // (e.g. when reconnecting active terminal, while login dialog
  7381. // invoked from "new session" page is modal)
  7382. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7383. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7384. }
  7385. //---------------------------------------------------------------------------
  7386. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  7387. TTerminal * Terminal, Exception * E)
  7388. {
  7389. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  7390. if (!Terminal->Active)
  7391. {
  7392. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7393. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7394. {
  7395. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7396. }
  7397. }
  7398. }
  7399. //---------------------------------------------------------------------------
  7400. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  7401. UnicodeString Message, TQueryType Type,
  7402. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7403. {
  7404. if ((E == NULL) ||
  7405. ExceptionMessage(E, Message))
  7406. {
  7407. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7408. if (Important)
  7409. {
  7410. Seconds *= 5;
  7411. }
  7412. UnicodeString NoteMessage(UnformatMessage(Message));
  7413. if (Terminal != NULL)
  7414. {
  7415. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7416. NoteMessage = FORMAT(L"%s: %s",
  7417. (TTerminalManager::Instance()->GetSessionTitle(Session, true), NoteMessage));
  7418. }
  7419. if (WinConfiguration->BalloonNotifications)
  7420. {
  7421. AddNote(NoteMessage);
  7422. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7423. }
  7424. else
  7425. {
  7426. FlashOnBackground();
  7427. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7428. }
  7429. }
  7430. }
  7431. //---------------------------------------------------------------------------
  7432. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7433. {
  7434. RestoreApp();
  7435. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7436. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7437. !NonVisualDataModule->Busy)
  7438. {
  7439. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7440. TTerminalManager::Instance()->ActiveSession = Terminal;
  7441. if (!ComponentVisible[fcQueueView])
  7442. {
  7443. ToggleQueueVisibility();
  7444. GoToQueue();
  7445. }
  7446. }
  7447. }
  7448. //---------------------------------------------------------------------------
  7449. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7450. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7451. {
  7452. UnicodeString Message;
  7453. TNotifyEvent OnClick = NULL;
  7454. TObject * UserData = NULL;
  7455. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7456. switch (Event)
  7457. {
  7458. case qeEmptyButMonitored:
  7459. if ((ATerminal != Terminal) || QueueInvisible)
  7460. {
  7461. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7462. OnClick = QueueEmptyNoteClicked;
  7463. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7464. TerminalNoteData->Terminal = ATerminal;
  7465. UserData = TerminalNoteData;
  7466. }
  7467. break;
  7468. case qeEmpty:
  7469. OperationComplete(ATerminal->QueueOperationStart);
  7470. break;
  7471. case qePendingUserAction:
  7472. if ((ATerminal != Terminal) ||
  7473. (QueueInvisible && !IsQueueAutoPopup()))
  7474. {
  7475. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7476. }
  7477. break;
  7478. default:
  7479. DebugFail();
  7480. }
  7481. if (!Message.IsEmpty())
  7482. {
  7483. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7484. }
  7485. }
  7486. //---------------------------------------------------------------------------
  7487. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7488. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7489. {
  7490. if (FDDExtMapFile != NULL)
  7491. {
  7492. CloseHandle(FDDExtMapFile);
  7493. FDDExtMapFile = NULL;
  7494. }
  7495. if (WinConfiguration->DDFakeFile)
  7496. {
  7497. DDFakeFileInitDrag(FileList, Created);
  7498. }
  7499. }
  7500. //---------------------------------------------------------------------------
  7501. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7502. {
  7503. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7504. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7505. {
  7506. FFakeFileDropTarget = FileName;
  7507. }
  7508. }
  7509. //---------------------------------------------------------------------------
  7510. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7511. {
  7512. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7513. if (!ForceDirectories(ApiPath(Result)))
  7514. {
  7515. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7516. }
  7517. FileSetAttr(ApiPath(Result), faHidden);
  7518. return Result;
  7519. }
  7520. //---------------------------------------------------------------------------
  7521. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7522. bool & Created)
  7523. {
  7524. FFakeFileDropTarget = UnicodeString();
  7525. FDragFakeDirectory = CreateFakeTransferDirectory();
  7526. FileList->AddItem(NULL, FDragFakeDirectory);
  7527. Created = true;
  7528. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7529. {
  7530. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7531. }
  7532. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7533. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7534. {
  7535. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7536. TDragExtCommStruct* CommStruct;
  7537. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7538. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7539. DebugAssert(CommStruct != NULL);
  7540. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7541. CommStruct->Dragging = true;
  7542. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7543. LENOF(CommStruct->DropDest));
  7544. NULL_TERMINATE(CommStruct->DropDest);
  7545. UnmapViewOfFile(CommStruct);
  7546. }
  7547. }
  7548. //---------------------------------------------------------------------------
  7549. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7550. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7551. {
  7552. bool Result;
  7553. DebugAssert(!IsLocalBrowserMode());
  7554. if (Sender == RemoteDirView)
  7555. {
  7556. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7557. }
  7558. else
  7559. {
  7560. DebugAssert(Sender == RemoteDriveView);
  7561. TStrings * FileList = RemoteDriveView->DragFileList();
  7562. try
  7563. {
  7564. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7565. }
  7566. __finally
  7567. {
  7568. delete FileList;
  7569. }
  7570. }
  7571. if (FDDTargetControl == RemoteDriveView)
  7572. {
  7573. RemoteDriveView->UpdateDropTarget();
  7574. }
  7575. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7576. // or from tree view to dir view.
  7577. // foMove happens when file/dir is dragged from remote tree view outside of
  7578. // application via dragex
  7579. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7580. (DropSourceControl == RemoteDriveView))
  7581. {
  7582. RemoteDriveView->UpdateDropSource();
  7583. }
  7584. return Result;
  7585. }
  7586. //---------------------------------------------------------------------------
  7587. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7588. {
  7589. DebugAssert(!IsLocalBrowserMode());
  7590. // This also handles drops of remote files to queue.
  7591. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7592. SAFE_DESTROY(FDDFileList);
  7593. if (!FFakeFileDropTarget.IsEmpty())
  7594. {
  7595. RemoveDir(ApiPath(FFakeFileDropTarget));
  7596. }
  7597. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7598. {
  7599. try
  7600. {
  7601. TDragResult DDResult = (Sender == RemoteDirView) ?
  7602. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7603. // Focus is moved to the target application,
  7604. // but as we are going to present the UI, we need to steal the focus back.
  7605. // This most likely won't work though (windows does not allow application
  7606. // to steal focus most of the time)
  7607. Application->BringToFront();
  7608. // On older version of Windows we never got drMove here, see also comment below.
  7609. // On Windows 10, we get the "move".
  7610. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7611. {
  7612. UnicodeString TargetDirectory;
  7613. TFileOperation Operation;
  7614. // drInvalid may mean drMove, see comment below
  7615. switch (DDResult)
  7616. {
  7617. case drCopy:
  7618. Operation = foCopy;
  7619. break;
  7620. case drMove:
  7621. Operation = foMove;
  7622. break;
  7623. default:
  7624. DebugFail();
  7625. case drInvalid:
  7626. // prefer "copy" for safety
  7627. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7628. break;
  7629. }
  7630. TTransferOperationParam Param;
  7631. UnicodeString CounterName;
  7632. bool ForceQueue;
  7633. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7634. {
  7635. // we get drInvalid both if d&d was intercepted by ddext,
  7636. // and when users drops on no-drop location.
  7637. // we tell the difference by existence of response from ddext,
  7638. // so we ignore absence of response in this case
  7639. if (DDResult != drInvalid)
  7640. {
  7641. // here we know that the extension is installed,
  7642. // as it is checked as soon as drag&drop starts from
  7643. // RemoteFileControlDDCreateDragFileList
  7644. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7645. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7646. {
  7647. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7648. }
  7649. else
  7650. {
  7651. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7652. }
  7653. }
  7654. }
  7655. else
  7656. {
  7657. // download using fake file
  7658. Param.Temp = false;
  7659. Param.DragDrop = true;
  7660. if (ForceQueue)
  7661. {
  7662. Param.Queue = asOn;
  7663. }
  7664. if (Sender == RemoteDirView)
  7665. {
  7666. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7667. }
  7668. if (RemoteFileControlFileOperation(Sender, Operation,
  7669. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7670. {
  7671. Configuration->Usage->Inc(CounterName);
  7672. }
  7673. }
  7674. }
  7675. }
  7676. __finally
  7677. {
  7678. CloseHandle(FDDExtMapFile);
  7679. FDDExtMapFile = NULL;
  7680. delete FDragFakeMonitors;
  7681. FDragFakeMonitors = NULL;
  7682. RemoveDir(ApiPath(FDragFakeDirectory));
  7683. FDragFakeDirectory = L"";
  7684. FFakeFileDropTarget = UnicodeString();
  7685. }
  7686. }
  7687. if (FDragDropSshTerminate.get() != NULL)
  7688. {
  7689. FDragDropSshTerminate->Rethrow();
  7690. }
  7691. }
  7692. //---------------------------------------------------------------------------
  7693. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7694. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7695. {
  7696. // Remember drop effect so we know (when user drops files), if we copy or move
  7697. FLastDropEffect = dwEffect;
  7698. }
  7699. //---------------------------------------------------------------------------
  7700. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7701. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7702. {
  7703. bool Result;
  7704. if (FDDTargetControl == QueueView3)
  7705. {
  7706. Directory = DefaultDownloadTargetDirectory();
  7707. Result = true;
  7708. CounterName = L"DownloadsDragDropQueue";
  7709. ForceQueue = true;
  7710. }
  7711. else if (!FFakeFileDropTarget.IsEmpty())
  7712. {
  7713. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7714. Result = true;
  7715. ForceQueue = false;
  7716. CounterName = L"DownloadsDragDropFakeFile";
  7717. }
  7718. else
  7719. {
  7720. ForceQueue = false;
  7721. Enabled = false;
  7722. try
  7723. {
  7724. int Timer = 0;
  7725. Result = false;
  7726. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7727. {
  7728. {
  7729. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7730. TDragExtCommStruct* CommStruct;
  7731. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7732. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7733. DebugAssert(CommStruct != NULL);
  7734. Result = !CommStruct->Dragging;
  7735. if (Result)
  7736. {
  7737. Directory = ExtractFilePath(CommStruct->DropDest);
  7738. CounterName = L"DownloadsDragDropExternalExt";
  7739. }
  7740. UnmapViewOfFile(CommStruct);
  7741. }
  7742. if (!Result)
  7743. {
  7744. Sleep(50);
  7745. Timer += 50;
  7746. Application->ProcessMessages();
  7747. }
  7748. }
  7749. }
  7750. __finally
  7751. {
  7752. Enabled = true;
  7753. }
  7754. }
  7755. return Result;
  7756. }
  7757. //---------------------------------------------------------------------------
  7758. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7759. const UnicodeString TempDir, int SecDelay)
  7760. {
  7761. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7762. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7763. if (FDelayedDeletionTimer == NULL)
  7764. {
  7765. DebugAssert(HandleAllocated());
  7766. FDelayedDeletionTimer = new TTimer(this);
  7767. FDelayedDeletionTimer->Interval = 10000;
  7768. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7769. }
  7770. else
  7771. {
  7772. FDelayedDeletionTimer->Enabled = true;
  7773. }
  7774. }
  7775. //---------------------------------------------------------------------------
  7776. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7777. {
  7778. DebugAssert(FDelayedDeletionList != NULL);
  7779. TDateTime N = Now();
  7780. TDateTime Alert;
  7781. UnicodeString Directory;
  7782. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7783. {
  7784. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7785. if ((N >= Alert) || (Sender == NULL))
  7786. {
  7787. Directory = FDelayedDeletionList->Strings[Index];
  7788. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7789. {
  7790. FDelayedDeletionList->Delete(Index);
  7791. }
  7792. }
  7793. }
  7794. if (FDelayedDeletionList->Count == 0)
  7795. {
  7796. FDelayedDeletionTimer->Enabled = false;
  7797. }
  7798. }
  7799. //---------------------------------------------------------------------------
  7800. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7801. {
  7802. DebugAssert(!IsLocalBrowserMode());
  7803. if (IsFileControl(FDDTargetControl, osRemote) ||
  7804. (FDDTargetControl == SessionsPageControl))
  7805. {
  7806. TManagedTerminal * TargetTerminal = NULL;
  7807. TFileOperation Operation = foNone;
  7808. if (FDDTargetControl == SessionsPageControl)
  7809. {
  7810. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7811. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7812. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7813. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7814. if (IsActiveTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7815. {
  7816. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7817. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7818. {
  7819. Operation = foRemoteMove;
  7820. }
  7821. else
  7822. {
  7823. Operation = foRemoteCopy;
  7824. }
  7825. }
  7826. }
  7827. else
  7828. {
  7829. if (FLastDropEffect == DROPEFFECT_MOVE)
  7830. {
  7831. Operation = foRemoteMove;
  7832. }
  7833. else if (FLastDropEffect == DROPEFFECT_COPY)
  7834. {
  7835. Operation = foRemoteCopy;
  7836. }
  7837. }
  7838. if (Operation != foNone)
  7839. {
  7840. RemoteFileControlFileOperation(DropSourceControl,
  7841. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7842. }
  7843. // abort drag&drop
  7844. Abort();
  7845. }
  7846. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7847. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7848. (FDDTargetControl != QueueView3))
  7849. {
  7850. DebugAssert(!FDragTempDir.IsEmpty());
  7851. TTransferType Type;
  7852. UnicodeString TempDir = FDragTempDir;
  7853. // We clear FDragTempDir before calling
  7854. // just in case it fail (raises exception)
  7855. FDragTempDir = L"";
  7856. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7857. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7858. // empty directory parameter means temp directory -> don't display it!
  7859. UnicodeString TargetDir = L"";
  7860. int Options = 0;
  7861. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7862. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7863. {
  7864. Abort();
  7865. }
  7866. // TargetDir is set when dropped on local file control
  7867. // (this was workaround for legacy dirview event handling, now it should be
  7868. // made prettier)
  7869. if (TargetDir.IsEmpty())
  7870. {
  7871. TargetDir = TempDir;
  7872. if (ForceDirectories(ApiPath(TargetDir)))
  7873. {
  7874. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7875. FPendingTempSpaceWarn = true;
  7876. try
  7877. {
  7878. FDragDropOperation = true;
  7879. int Params = cpTemporary |
  7880. (Type == ttMove ? cpDelete : 0);
  7881. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7882. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7883. }
  7884. __finally
  7885. {
  7886. FDragDropOperation = false;
  7887. FPendingTempSpaceWarn = false;
  7888. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7889. }
  7890. }
  7891. else
  7892. {
  7893. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7894. }
  7895. }
  7896. }
  7897. }
  7898. //---------------------------------------------------------------------------
  7899. void __fastcall TCustomScpExplorerForm::DDDownload(
  7900. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7901. {
  7902. DebugAssert(!IsLocalBrowserMode());
  7903. TAutoBatch AutoBatch(this);
  7904. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7905. UpdateCopyParamCounters(*CopyParam);
  7906. FMoveToQueue = false;
  7907. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7908. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7909. {
  7910. RemoteDriveView->UpdateDropSource();
  7911. }
  7912. }
  7913. //---------------------------------------------------------------------------
  7914. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7915. {
  7916. public:
  7917. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7918. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7919. {
  7920. }
  7921. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7922. {
  7923. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7924. TDataObjectFilesEx::AllowData(FormatEtc);
  7925. }
  7926. };
  7927. //---------------------------------------------------------------------------
  7928. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7929. TObject * Sender, TDataObject *& DataObject)
  7930. {
  7931. if (FDDExtMapFile != NULL)
  7932. {
  7933. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7934. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7935. {
  7936. Abort();
  7937. }
  7938. if (FileList->Count > 0)
  7939. {
  7940. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7941. if (!FilesObject->IsValid(true, true))
  7942. {
  7943. FilesObject->_Release();
  7944. }
  7945. else
  7946. {
  7947. DataObject = FilesObject;
  7948. }
  7949. }
  7950. }
  7951. }
  7952. //---------------------------------------------------------------------------
  7953. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7954. {
  7955. DebugFail();
  7956. }
  7957. //---------------------------------------------------------------------------
  7958. void __fastcall TCustomScpExplorerForm::GoToTree()
  7959. {
  7960. ComponentVisible[fcRemoteTree] = true;
  7961. DriveView(osRemote)->SetFocus();
  7962. }
  7963. //---------------------------------------------------------------------------
  7964. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7965. TPanelExport Export)
  7966. {
  7967. TCustomDirView * DirView = this->DirView(Side);
  7968. std::unique_ptr<TStrings> ExportData(new TStringList());
  7969. switch (Export)
  7970. {
  7971. case pePath:
  7972. ExportData->Add(DirView->PathName);
  7973. break;
  7974. case peFileList:
  7975. case peFullFileList:
  7976. {
  7977. bool FullPath = (Export == peFullFileList);
  7978. DirView->CreateFileList(false, FullPath, ExportData.get());
  7979. for (int Index = 0; Index < ExportData->Count; Index++)
  7980. {
  7981. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7982. {
  7983. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7984. }
  7985. }
  7986. }
  7987. break;
  7988. default:
  7989. DebugFail();
  7990. }
  7991. return ExportData.release();
  7992. }
  7993. //---------------------------------------------------------------------------
  7994. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7995. TPanelExport Export, TPanelExportDestination Destination)
  7996. {
  7997. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7998. PanelExportStore(Side, Export, Destination, ExportData.get());
  7999. }
  8000. //---------------------------------------------------------------------------
  8001. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  8002. TPanelExport /*Export*/, TPanelExportDestination Destination,
  8003. TStrings * ExportData)
  8004. {
  8005. if (Destination == pedClipboard)
  8006. {
  8007. TInstantOperationVisualizer Visualizer;
  8008. CopyToClipboard(ExportData);
  8009. }
  8010. else
  8011. {
  8012. DebugFail();
  8013. }
  8014. }
  8015. //---------------------------------------------------------------------------
  8016. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  8017. {
  8018. TCustomDirView * DirView = this->DirView(Side);
  8019. UnicodeString Mask = DirView->Mask;
  8020. if (DoFilterMaskDialog(DirView, Mask))
  8021. {
  8022. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  8023. Configuration->Usage->Inc(L"Filters");
  8024. }
  8025. }
  8026. //---------------------------------------------------------------------------
  8027. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  8028. {
  8029. return FQueueController->DefaultOperation();
  8030. }
  8031. //---------------------------------------------------------------------------
  8032. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  8033. TQueueOperation Operation, void ** Param)
  8034. {
  8035. switch (Operation)
  8036. {
  8037. case qoPreferences:
  8038. return true;
  8039. case qoGoTo:
  8040. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  8041. case qoOnceEmpty:
  8042. return IsAnythingQueued();
  8043. default:
  8044. return FQueueController->AllowOperation(Operation, Param);
  8045. }
  8046. }
  8047. //---------------------------------------------------------------------------
  8048. void __fastcall TCustomScpExplorerForm::GoToQueue()
  8049. {
  8050. if (DebugAlwaysTrue(QueueView3->Visible))
  8051. {
  8052. QueueView3->SetFocus();
  8053. }
  8054. }
  8055. //---------------------------------------------------------------------------
  8056. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  8057. TQueueOperation Operation, void * Param)
  8058. {
  8059. if (Operation == qoGoTo)
  8060. {
  8061. GoToQueue();
  8062. }
  8063. else if (Operation == qoPreferences)
  8064. {
  8065. PreferencesDialog(pmQueue);
  8066. }
  8067. else
  8068. {
  8069. FQueueController->ExecuteOperation(Operation, Param);
  8070. }
  8071. }
  8072. //---------------------------------------------------------------------------
  8073. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  8074. {
  8075. return (Queue != NULL) && Queue->Enabled;
  8076. }
  8077. //---------------------------------------------------------------------------
  8078. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8079. {
  8080. DebugAssert(Queue != NULL);
  8081. if (Queue != NULL)
  8082. {
  8083. Queue->Enabled = !Queue->Enabled;
  8084. }
  8085. }
  8086. //---------------------------------------------------------------------------
  8087. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8088. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8089. {
  8090. FQueueActedItem = QueueView3->ItemFocused;
  8091. }
  8092. //---------------------------------------------------------------------------
  8093. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8094. {
  8095. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8096. }
  8097. //---------------------------------------------------------------------------
  8098. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8099. {
  8100. return
  8101. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8102. (QueueDock->Visible ? QueueDock->Height : 0) +
  8103. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8104. }
  8105. //---------------------------------------------------------------------------
  8106. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8107. {
  8108. return ScaleByTextHeight(this, 48);
  8109. }
  8110. //---------------------------------------------------------------------------
  8111. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8112. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8113. {
  8114. // when queue is hidden by double-clicking splitter, stray attempt to
  8115. // resize the panel with strange value arrives, make sure it is ignored
  8116. if (ComponentVisible[fcQueueView])
  8117. {
  8118. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8119. if (NewSize > MaxHeightLimit)
  8120. {
  8121. NewSize = MaxHeightLimit;
  8122. }
  8123. int MinHeightLimit =
  8124. GetStaticQueuePanelComponentsHeight() +
  8125. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8126. GetMinQueueViewHeight();
  8127. if (NewSize < MinHeightLimit)
  8128. {
  8129. NewSize = MinHeightLimit;
  8130. }
  8131. }
  8132. else
  8133. {
  8134. Accept = false;
  8135. }
  8136. }
  8137. //---------------------------------------------------------------------------
  8138. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8139. {
  8140. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8141. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8142. if (QueueViewHeight < GetMinQueueViewHeight())
  8143. {
  8144. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8145. }
  8146. }
  8147. //---------------------------------------------------------------------------
  8148. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8149. TDragObject *& /*DragObject*/)
  8150. {
  8151. FQueueActedItem = QueueView3->ItemFocused;
  8152. FQueueScrollOnDragOver->StartDrag();
  8153. }
  8154. //---------------------------------------------------------------------------
  8155. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8156. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8157. {
  8158. FQueueScrollOnDragOver->EndDrag();
  8159. }
  8160. //---------------------------------------------------------------------------
  8161. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8162. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8163. {
  8164. Accept = true;
  8165. if (Source == QueueView3)
  8166. {
  8167. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8168. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8169. if (Accept)
  8170. {
  8171. TQueueItemProxy * QueueItem;
  8172. TQueueItemProxy * DestQueueItem;
  8173. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8174. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8175. Accept = (QueueItem != DestQueueItem) &&
  8176. (QueueItem->Status == TQueueItem::qsPending) &&
  8177. (DestQueueItem->Status == TQueueItem::qsPending);
  8178. }
  8179. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8180. }
  8181. }
  8182. //---------------------------------------------------------------------------
  8183. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8184. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8185. {
  8186. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8187. {
  8188. TQueueItemProxy * QueueItem;
  8189. TQueueItemProxy * DestQueueItem;
  8190. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8191. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8192. QueueItem->Move(DestQueueItem);
  8193. }
  8194. }
  8195. //---------------------------------------------------------------------------
  8196. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8197. {
  8198. if ((QueueView3->ItemFocused == NULL) &&
  8199. (QueueView3->Items->Count > 0))
  8200. {
  8201. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8202. }
  8203. QueueLabelUpdateStatus();
  8204. }
  8205. //---------------------------------------------------------------------------
  8206. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8207. {
  8208. QueueLabelUpdateStatus();
  8209. }
  8210. //---------------------------------------------------------------------------
  8211. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8212. {
  8213. QueueLabel->UpdateStatus();
  8214. }
  8215. //---------------------------------------------------------------------------
  8216. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8217. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8218. {
  8219. if (Selected)
  8220. {
  8221. NonVisualDataModule->UpdateNonVisibleActions();
  8222. }
  8223. }
  8224. //---------------------------------------------------------------------------
  8225. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8226. {
  8227. TDragDropFilesEx * Result = NULL;
  8228. if (Sender == SessionsPageControl)
  8229. {
  8230. Result = FSessionsDragDropFilesEx;
  8231. }
  8232. else if (Sender == QueueView3)
  8233. {
  8234. Result = FQueueDragDropFilesEx;
  8235. }
  8236. else
  8237. {
  8238. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8239. if (DirView != NULL)
  8240. {
  8241. Result = DirView->DragDropFilesEx;
  8242. }
  8243. else
  8244. {
  8245. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8246. if (DriveView != NULL)
  8247. {
  8248. Result = DriveView->DragDropFilesEx;
  8249. }
  8250. }
  8251. }
  8252. DebugAssert(Result != NULL);
  8253. return Result;
  8254. }
  8255. //---------------------------------------------------------------------------
  8256. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8257. {
  8258. return (DView->SelCount == DView->FilesCount);
  8259. }
  8260. //---------------------------------------------------------------------------
  8261. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8262. {
  8263. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8264. }
  8265. //---------------------------------------------------------------------------
  8266. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8267. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8268. {
  8269. DebugAssert(!IsLocalBrowserMode());
  8270. TFileOperation Operation;
  8271. switch (Effect)
  8272. {
  8273. case DROPEFFECT_MOVE:
  8274. Operation = foMove;
  8275. break;
  8276. case DROPEFFECT_COPY:
  8277. // occures on WinXP (reported by user)
  8278. default:
  8279. Operation = foCopy;
  8280. break;
  8281. };
  8282. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8283. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8284. if (DragDropFilesEx->FileList->Count > 0)
  8285. {
  8286. TStrings * FileList = new TStringList();
  8287. try
  8288. {
  8289. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8290. {
  8291. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8292. }
  8293. FDragDropOperation = true;
  8294. TTransferOperationParam Param;
  8295. Param.TargetDirectory = TargetPath;
  8296. // upload, no temp dirs
  8297. Param.Temp = false;
  8298. Param.DragDrop = DragDrop;
  8299. Param.Options =
  8300. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8301. if (ForceQueue)
  8302. {
  8303. Param.Queue = asOn;
  8304. }
  8305. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8306. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8307. {
  8308. if (IsFileControl(DropSourceControl, osLocal))
  8309. {
  8310. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8311. }
  8312. else
  8313. {
  8314. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8315. }
  8316. }
  8317. }
  8318. __finally
  8319. {
  8320. FDragDropOperation = false;
  8321. delete FileList;
  8322. }
  8323. }
  8324. }
  8325. //---------------------------------------------------------------------------
  8326. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8327. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8328. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8329. {
  8330. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8331. }
  8332. //---------------------------------------------------------------------------
  8333. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8334. TObject * Sender, int grfKeyState, int & dwEffect)
  8335. {
  8336. DebugAssert(!IsLocalBrowserMode());
  8337. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8338. if ((dwEffect != DROPEFFECT_NONE) &&
  8339. IsFileControl(DropSourceControl, osRemote))
  8340. {
  8341. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8342. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8343. (RemoteDirView->DropTarget == NULL))
  8344. {
  8345. dwEffect = DROPEFFECT_NONE;
  8346. }
  8347. else
  8348. {
  8349. if (dwEffect == DROPEFFECT_COPY)
  8350. {
  8351. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8352. // currently we support copying always (at least via temporary directory);
  8353. // remove associated checks once this all proves stable and working
  8354. bool CopyCapable = true;
  8355. // if we do not support neither of operations, there's no discussion
  8356. if (!MoveCapable && !CopyCapable)
  8357. {
  8358. dwEffect = DROPEFFECT_NONE;
  8359. }
  8360. else
  8361. {
  8362. // The default effect inside remote panel is move,
  8363. // unless we do not support it, but support copy
  8364. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8365. {
  8366. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8367. }
  8368. else
  8369. {
  8370. // with ctrl-down, we want copy unless it is not supported
  8371. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8372. }
  8373. }
  8374. }
  8375. }
  8376. }
  8377. }
  8378. //---------------------------------------------------------------------------
  8379. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8380. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8381. {
  8382. DebugAssert(!IsLocalBrowserMode());
  8383. if (FDDTotalSize >= 0)
  8384. {
  8385. if (File->IsDirectory)
  8386. {
  8387. FDDTotalSize = -1;
  8388. }
  8389. else
  8390. {
  8391. FDDTotalSize += File->Size;
  8392. }
  8393. }
  8394. DebugAssert(!FDragTempDir.IsEmpty());
  8395. // TODO: this is quite ineffective
  8396. // TODO: what if invalid character replacement is disabled?
  8397. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8398. UnicodeString TransferFileName;
  8399. if (Sender == RemoteDriveView)
  8400. {
  8401. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8402. }
  8403. else
  8404. {
  8405. TransferFileName = File->FileName;
  8406. }
  8407. FDDFileList->AddObject(TransferFileName, File);
  8408. }
  8409. //---------------------------------------------------------------------------
  8410. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8411. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8412. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8413. {
  8414. // sometimes we do not get DDEnd so the list is not released
  8415. SAFE_DESTROY(FDDFileList);
  8416. FDDFileList = new TStringList();
  8417. FDragTempDir = WinConfiguration->TemporaryDir();
  8418. FDDTotalSize = 0;
  8419. FDragDropSshTerminate.reset(NULL);
  8420. }
  8421. //---------------------------------------------------------------------------
  8422. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8423. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  8424. HRESULT & Result)
  8425. {
  8426. if (Result == DRAGDROP_S_DROP)
  8427. {
  8428. try
  8429. {
  8430. GlobalDragImageList->HideDragImage();
  8431. try
  8432. {
  8433. RemoteFileControlDDTargetDrop();
  8434. }
  8435. catch(ESshTerminate & E)
  8436. {
  8437. FDragDropSshTerminate.reset(E.Clone());
  8438. }
  8439. }
  8440. catch (Exception &E)
  8441. {
  8442. // If downloading fails we need to cancel drag&drop, otherwise
  8443. // Explorer shows error
  8444. // But by the way exception probably never reach this point as
  8445. // it's catched on way.
  8446. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8447. Result = DRAGDROP_S_CANCEL;
  8448. ShowExtendedException(Terminal, &E);
  8449. }
  8450. }
  8451. }
  8452. //---------------------------------------------------------------------------
  8453. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8454. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8455. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8456. {
  8457. TFileMasks::TParams MaskParams;
  8458. MaskParams.Size = Size;
  8459. MaskParams.Modification = Modification;
  8460. // this does not re-parse the mask if it is the same as the last time
  8461. FDirViewMatchMask = Masks;
  8462. bool ImplicitMatch;
  8463. Matches =
  8464. // Local and RecurseInclude parameters have no effect as there's no path.
  8465. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8466. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8467. (AllowImplicitMatches || !ImplicitMatch);
  8468. }
  8469. //---------------------------------------------------------------------------
  8470. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8471. TObject * Sender, TListItem * Item, WORD & Indexes)
  8472. {
  8473. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8474. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8475. {
  8476. Indexes |= oiPartial;
  8477. }
  8478. }
  8479. //---------------------------------------------------------------------------
  8480. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8481. {
  8482. return
  8483. DirViewEnabled(osCurrent) &&
  8484. DirView(osCurrent)->CanPasteFromClipBoard();
  8485. }
  8486. //---------------------------------------------------------------------------
  8487. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8488. {
  8489. bool Result = false;
  8490. if (CanPasteToDirViewFromClipBoard())
  8491. {
  8492. Result = true;
  8493. }
  8494. else
  8495. {
  8496. UnicodeString ClipboardText;
  8497. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8498. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8499. {
  8500. if (StoredSessions->IsUrl(ClipboardText))
  8501. {
  8502. Result = true;
  8503. }
  8504. else
  8505. {
  8506. Result = DirViewEnabled(osCurrent);
  8507. }
  8508. }
  8509. }
  8510. return Result;
  8511. }
  8512. //---------------------------------------------------------------------------
  8513. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8514. {
  8515. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8516. if (DoesClipboardContainOurFiles())
  8517. {
  8518. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8519. {
  8520. DebugAssert(!IsLocalBrowserMode());
  8521. TTerminalManager * Manager = TTerminalManager::Instance();
  8522. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8523. Manager->ActiveSession = FClipboardTerminal;
  8524. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8525. }
  8526. }
  8527. else if (CanPasteToDirViewFromClipBoard())
  8528. {
  8529. DirView(osCurrent)->PasteFromClipBoard();
  8530. }
  8531. else
  8532. {
  8533. UnicodeString ClipboardText;
  8534. if (NonEmptyTextFromClipboard(ClipboardText))
  8535. {
  8536. if (StoredSessions->IsUrl(ClipboardText))
  8537. {
  8538. NewSession(ClipboardText);
  8539. }
  8540. else
  8541. {
  8542. DirView(osCurrent)->Path = ClipboardText;
  8543. }
  8544. }
  8545. }
  8546. }
  8547. //---------------------------------------------------------------------------
  8548. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8549. {
  8550. // TBD
  8551. }
  8552. //---------------------------------------------------------------------------
  8553. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8554. {
  8555. TCustomDirView * ADirView = DirView(Side);
  8556. ADirView->SelectAll(Mode);
  8557. ADirView->SetFocus();
  8558. }
  8559. //---------------------------------------------------------------------------
  8560. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8561. {
  8562. TCustomDirView * ADirView = DirView(Side);
  8563. TFileFilter Filter;
  8564. DefaultFileFilter(Filter);
  8565. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8566. {
  8567. Configuration->Usage->Inc(L"MaskSelections");
  8568. ADirView->SelectFiles(Filter, Select);
  8569. ADirView->SetFocus();
  8570. }
  8571. }
  8572. //---------------------------------------------------------------------------
  8573. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8574. {
  8575. TCustomDirView * ADirView = DirView(Side);
  8576. ADirView->RestoreSelectedNames();
  8577. ADirView->SetFocus();
  8578. }
  8579. //---------------------------------------------------------------------------
  8580. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8581. {
  8582. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8583. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8584. {
  8585. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8586. UnicodeString Ext;
  8587. if (!IsSideLocalBrowser(osCurrent))
  8588. {
  8589. Ext = UnixExtractFileExt(FileName);
  8590. }
  8591. else
  8592. {
  8593. Ext = ExtractFileExt(FileName);
  8594. }
  8595. if (Ext.IsEmpty())
  8596. {
  8597. Ext = L".";
  8598. }
  8599. TFileFilter Filter;
  8600. Filter.Masks = FORMAT(L"*%s", (Ext));
  8601. Filter.Directories = false;
  8602. CurrentDirView->SelectFiles(Filter, Select);
  8603. }
  8604. }
  8605. //---------------------------------------------------------------------------
  8606. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8607. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8608. {
  8609. UnicodeString Result;
  8610. if (!FIncrementalSearch.IsEmpty() && (Side == GetSide(osCurrent)))
  8611. {
  8612. Result = FormatIncrementalSearchStatus(FIncrementalSearch, FIncrementalSearchHaveNext);
  8613. }
  8614. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8615. {
  8616. // noop
  8617. }
  8618. else
  8619. {
  8620. Result =
  8621. FMTLOAD(FILE_INFO_FORMAT,
  8622. (FormatBytes(FileInfo.SelectedSize),
  8623. FormatBytes(FileInfo.FilesSize),
  8624. FormatNumber(FileInfo.SelectedCount),
  8625. FormatNumber(FileInfo.FilesCount)));
  8626. }
  8627. return Result;
  8628. }
  8629. //---------------------------------------------------------------------------
  8630. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8631. TTBXStatusPanel * Panel, TOperationSide Side)
  8632. {
  8633. if (Panel->Index == 1)
  8634. {
  8635. ToggleShowHiddenFiles();
  8636. }
  8637. else if (Panel->Index == 2)
  8638. {
  8639. Filter(Side);
  8640. }
  8641. }
  8642. //---------------------------------------------------------------------------
  8643. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8644. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8645. {
  8646. DebugAssert(!StatusBar->SimplePanel);
  8647. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8648. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8649. }
  8650. //---------------------------------------------------------------------------
  8651. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8652. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8653. {
  8654. DebugAssert(StatusBar->Panels->Count >= 3);
  8655. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8656. if (FileInfo.HiddenCount > 0)
  8657. {
  8658. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8659. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8660. }
  8661. else
  8662. {
  8663. HiddenFilesPanel->ViewPriority = 0;
  8664. // not really necessary, just to cleanup no-longer-valid data
  8665. HiddenFilesPanel->Caption = L"";
  8666. }
  8667. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8668. if (FileInfo.FilteredCount > 0)
  8669. {
  8670. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8671. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8672. }
  8673. else
  8674. {
  8675. FilteredFilesPanel->ViewPriority = 0;
  8676. // not really necessary, just to cleanup no-longer-valid data
  8677. FilteredFilesPanel->Caption = L"";
  8678. }
  8679. }
  8680. //---------------------------------------------------------------------------
  8681. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8682. TObject * /*Sender*/)
  8683. {
  8684. if (DirView(osOther)->Enabled)
  8685. {
  8686. DirView(osOther)->SetFocus();
  8687. }
  8688. }
  8689. //---------------------------------------------------------------------------
  8690. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8691. {
  8692. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8693. switch (Config.Show)
  8694. {
  8695. case qvShow:
  8696. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8697. {
  8698. Config.Show = qvHide;
  8699. }
  8700. else
  8701. {
  8702. Config.Show = Config.LastHideShow;
  8703. }
  8704. break;
  8705. case qvHideWhenEmpty:
  8706. if (ComponentVisible[fcQueueView])
  8707. {
  8708. Config.Show = qvHide;
  8709. }
  8710. else
  8711. {
  8712. Config.LastHideShow = Config.Show;
  8713. Config.Show = qvShow;
  8714. }
  8715. break;
  8716. case qvHide:
  8717. Config.LastHideShow = Config.Show;
  8718. Config.Show = qvShow;
  8719. break;
  8720. }
  8721. WinConfiguration->QueueView = Config;
  8722. }
  8723. //---------------------------------------------------------------------------
  8724. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8725. {
  8726. UnicodeString Result;
  8727. if (Terminal != NULL)
  8728. {
  8729. switch (WinConfiguration->PathInCaption)
  8730. {
  8731. case picShort:
  8732. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8733. break;
  8734. case picFull:
  8735. Result = Terminal->CurrentDirectory;
  8736. break;
  8737. }
  8738. }
  8739. return Result;
  8740. }
  8741. //---------------------------------------------------------------------------
  8742. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8743. {
  8744. TColor Result = GetWindowColor(FSessionColor);
  8745. return Result;
  8746. }
  8747. //---------------------------------------------------------------------------
  8748. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8749. {
  8750. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8751. return Result;
  8752. }
  8753. //---------------------------------------------------------------------------
  8754. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8755. {
  8756. if (!FSessionChanging)
  8757. {
  8758. TTerminalManager::Instance()->UpdateAppTitle();
  8759. }
  8760. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8761. // background to gray on Windows 7 (works on Windows 10).
  8762. // See also EnableControl
  8763. if (Showing)
  8764. {
  8765. if (ManagedSession != NULL)
  8766. {
  8767. // Update path when it changes
  8768. if ((SessionsPageControl->ActivePage != NULL) &&
  8769. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8770. {
  8771. UpdateSessionTab(SessionsPageControl->ActivePage);
  8772. }
  8773. }
  8774. NonVisualDataModule->ReconnectSessionAction->Update();
  8775. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8776. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8777. CenterReconnectToolbar();
  8778. bool HasTerminal = HasActiveTerminal();
  8779. RemoteDirView->Enabled = HasTerminal;
  8780. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8781. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8782. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8783. RemoteDriveView->Color = RemoteDirView->Color;
  8784. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8785. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8786. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8787. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8788. QueueFileList->Enabled = QueueView3->Enabled;
  8789. QueueFileList->Color = QueueView3->Color;
  8790. QueueFileList->Font->Color = QueueView3->Font->Color;
  8791. QueueLabelUpdateStatus();
  8792. RemoteDirView->DarkMode = WinConfiguration->UseDarkTheme();
  8793. RemoteDriveView->DarkMode = RemoteDirView->DarkMode;
  8794. if (FImmersiveDarkMode != WinConfiguration->UseDarkTheme())
  8795. {
  8796. UpdateDarkMode();
  8797. }
  8798. // As the hi-contrast theme is currently used for session tabs only, which currently do not support dark mode,
  8799. // we always use dark theme. But ultimatelly, we should use an opposite theme to the main one.
  8800. UnicodeString CurrentHiContrastThemeName = (FHiContrastTheme != NULL) ? FHiContrastTheme->Name : EmptyStr;
  8801. UnicodeString NewHiContrastThemeName = WinConfiguration->HiContrast ? GetThemeName(true) : EmptyStr;
  8802. if (CurrentHiContrastThemeName != NewHiContrastThemeName)
  8803. {
  8804. ReleaseHiContrastTheme();
  8805. if (!NewHiContrastThemeName.IsEmpty())
  8806. {
  8807. FHiContrastTheme = GetTBXTheme(NewHiContrastThemeName);
  8808. }
  8809. SessionsPageControl->ActiveTabTheme = FHiContrastTheme;
  8810. }
  8811. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8812. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8813. }
  8814. }
  8815. //---------------------------------------------------------------------------
  8816. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8817. {
  8818. UpdateControls();
  8819. }
  8820. //---------------------------------------------------------------------------
  8821. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8822. TObject * Sender)
  8823. {
  8824. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8825. DebugAssert(DirView != NULL);
  8826. DoDirViewLoaded(DirView);
  8827. TransferPresetAutoSelect();
  8828. }
  8829. //---------------------------------------------------------------------------
  8830. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8831. {
  8832. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8833. // first run after installation
  8834. if (double(Updates.LastCheck) == 0)
  8835. {
  8836. AppLog(L"First run, scheduling updates check for the next run");
  8837. // make sure next time there will be an update (if enabled)
  8838. Updates.LastCheck = TDateTime(1);
  8839. WinConfiguration->Updates = Updates;
  8840. }
  8841. else
  8842. {
  8843. TDateTime Period;
  8844. if (IsUWP() && !IsOfficialPackage())
  8845. {
  8846. Period = DefaultUpdatesPeriod;
  8847. AppLog(L"Thirdparty UWP package, using default updates check period");
  8848. }
  8849. else
  8850. {
  8851. Period = Updates.Period;
  8852. }
  8853. AppLogFmt(L"Updates check period: %.2f", (double(Period)));
  8854. if (double(Period) > 0)
  8855. {
  8856. TDateTime Interval = Now() - Updates.LastCheck;
  8857. AppLogFmt(L"Interval since the last updates check: %.2f", (double(Interval)));
  8858. if (Interval >= Period)
  8859. {
  8860. StartUpdateThread(UpdatesChecked);
  8861. }
  8862. }
  8863. }
  8864. }
  8865. //---------------------------------------------------------------------------
  8866. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8867. {
  8868. AppLog(L"Updates check done");
  8869. UnicodeString Message;
  8870. bool New;
  8871. TQueryType Type;
  8872. GetUpdatesMessage(Message, New, Type, false);
  8873. if (!Message.IsEmpty())
  8874. {
  8875. AppLogFmt(L"Updates check message: %s", (Message));
  8876. if (New)
  8877. {
  8878. AppLog(L"New version detected");
  8879. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8880. }
  8881. if (!New && (Type != qtWarning))
  8882. {
  8883. AppLog(L"Posting non-critical updates note");
  8884. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  8885. }
  8886. else
  8887. {
  8888. AppLog(L"Posting new version or critical message notification");
  8889. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8890. }
  8891. if (New)
  8892. {
  8893. Configuration->Usage->Inc(L"UpdateNotifications");
  8894. }
  8895. }
  8896. }
  8897. //---------------------------------------------------------------------------
  8898. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8899. {
  8900. RestoreApp();
  8901. bool CanDisplay = !NonVisualDataModule->Busy;
  8902. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8903. {
  8904. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8905. }
  8906. if (CanDisplay)
  8907. {
  8908. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8909. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  8910. NonVisualDataModule->StartBusy();
  8911. try
  8912. {
  8913. CheckForUpdates(true);
  8914. }
  8915. __finally
  8916. {
  8917. NonVisualDataModule->EndBusy();
  8918. }
  8919. }
  8920. else
  8921. {
  8922. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  8923. }
  8924. }
  8925. //---------------------------------------------------------------------------
  8926. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  8927. TCopyParamRuleData & Data)
  8928. {
  8929. DebugAssert(Terminal != NULL);
  8930. Data.HostName = Terminal->SessionData->HostNameExpanded;
  8931. Data.UserName = Terminal->SessionData->UserNameExpanded;
  8932. Data.RemoteDirectory = RemoteDirView->PathName;
  8933. }
  8934. //---------------------------------------------------------------------------
  8935. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  8936. {
  8937. // Terminal can be null when we are changing local directory implicitly,
  8938. // because it has been deleted, while no session is connected
  8939. // (Login dialog is open)
  8940. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  8941. {
  8942. DebugAssert(!IsLocalBrowserMode());
  8943. TCopyParamRuleData Data;
  8944. GetTransferPresetAutoSelectData(Data);
  8945. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  8946. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  8947. if (CopyParamIndex < 0)
  8948. {
  8949. // there is no preset that matches autoselection
  8950. // set preset that we consider "default"
  8951. FCopyParamAutoSelected = L""; // forget last autoselected preset
  8952. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  8953. }
  8954. else
  8955. {
  8956. // there is preset matching autoselection
  8957. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  8958. if (CopyParamName == FCopyParamAutoSelected)
  8959. {
  8960. // autoselected the same preset as the last time
  8961. // make no change (i.e. preserve custom user preset, if any)
  8962. }
  8963. else
  8964. {
  8965. // autoselected the different preset then the last time (or there
  8966. // was default preset set)
  8967. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  8968. GUIConfiguration->CopyParamCurrent = CopyParamName;
  8969. }
  8970. }
  8971. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  8972. {
  8973. if (CopyParamIndex >= 0)
  8974. {
  8975. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  8976. }
  8977. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  8978. try
  8979. {
  8980. int Fmt =
  8981. (CopyParamIndex < 0) ?
  8982. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8983. COPY_PARAM_AUTOSELECTED;
  8984. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  8985. Data->Message = MainInstructions(Message);
  8986. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  8987. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  8988. CopyParamAttrs);
  8989. if (CopyParamIndex >= 0)
  8990. {
  8991. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  8992. Info = FORMAT(L"%s\n \n%s", (Info,
  8993. FMTLOAD(COPY_PARAM_RULE,
  8994. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  8995. }
  8996. Data->Message += L"\n\n" + Info;
  8997. if (WinConfiguration->CopyParamAutoSelectNotice)
  8998. {
  8999. TransferPresetNoteMessage(Data, true);
  9000. }
  9001. else
  9002. {
  9003. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  9004. Data = NULL; // ownership passed
  9005. }
  9006. }
  9007. __finally
  9008. {
  9009. delete Data;
  9010. }
  9011. }
  9012. }
  9013. }
  9014. //---------------------------------------------------------------------------
  9015. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  9016. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  9017. {
  9018. DebugAssert(NoteData != NULL);
  9019. DebugAssert(!IsLocalBrowserMode());
  9020. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  9021. TQueryButtonAlias Aliases[1];
  9022. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  9023. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  9024. Params.Aliases = Aliases;
  9025. Params.AliasesCount = LENOF(Aliases);
  9026. unsigned int Result =
  9027. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  9028. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  9029. switch (Result)
  9030. {
  9031. case qaNeverAskAgain:
  9032. DebugAssert(AllowNeverAskAgain);
  9033. WinConfiguration->CopyParamAutoSelectNotice = false;
  9034. break;
  9035. case qaIgnore:
  9036. PreferencesDialog(pmPresets);
  9037. break;
  9038. }
  9039. }
  9040. //---------------------------------------------------------------------------
  9041. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  9042. {
  9043. // as of now useless, as this is used for notes only, never for balloons, ...
  9044. RestoreApp();
  9045. // .. and we should never be busy here
  9046. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  9047. {
  9048. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  9049. }
  9050. }
  9051. //---------------------------------------------------------------------------
  9052. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  9053. TPreferencesMode APreferencesMode)
  9054. {
  9055. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  9056. TCopyParamRuleData Data;
  9057. if (Terminal != NULL)
  9058. {
  9059. PreferencesData.reset(new TPreferencesDialogData());
  9060. GetTransferPresetAutoSelectData(Data);
  9061. PreferencesData->CopyParamRuleData = &Data;
  9062. }
  9063. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  9064. }
  9065. //---------------------------------------------------------------------------
  9066. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  9067. const TCustomCommandType & Command)
  9068. {
  9069. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  9070. {
  9071. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  9072. }
  9073. }
  9074. //---------------------------------------------------------------------------
  9075. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  9076. {
  9077. bool RemoteAllowed = CustomCommandRemoteAllowed();
  9078. TCustomCommandType Command;
  9079. // make sure we use local custom command when remote are not supported
  9080. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  9081. {
  9082. Command = FLastCustomCommand;
  9083. }
  9084. else
  9085. {
  9086. Command.Params = Command.Params | ccLocal;
  9087. }
  9088. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  9089. FEditingFocusedAdHocCommand = OnFocused;
  9090. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9091. int Options =
  9092. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9093. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9094. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9095. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9096. {
  9097. FLastCustomCommand = Command;
  9098. UpdateCustomCommandsToolbar();
  9099. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9100. }
  9101. }
  9102. //---------------------------------------------------------------------------
  9103. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9104. {
  9105. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9106. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9107. DebugAssert(State > 0);
  9108. if (State <= 0)
  9109. {
  9110. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9111. }
  9112. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9113. }
  9114. //---------------------------------------------------------------------------
  9115. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9116. TCustomCommandType & Command, int & State)
  9117. {
  9118. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9119. if (Result)
  9120. {
  9121. Command = FLastCustomCommand;
  9122. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9123. }
  9124. return Result;
  9125. }
  9126. //---------------------------------------------------------------------------
  9127. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9128. {
  9129. ResetIncrementalSearch();
  9130. }
  9131. //---------------------------------------------------------------------------
  9132. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9133. {
  9134. DebugAssert(ComponentVisible[Component]);
  9135. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9136. }
  9137. //---------------------------------------------------------------------------
  9138. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9139. {
  9140. // when queue panel is resized here directly, the status bar is stretched
  9141. // over whole space the panel occupied
  9142. PostComponentHide(fcQueueView);
  9143. }
  9144. //---------------------------------------------------------------------------
  9145. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9146. {
  9147. ComponentVisible[fcQueueFileList] = false;
  9148. }
  9149. //---------------------------------------------------------------------------
  9150. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9151. {
  9152. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9153. RefreshColorMode();
  9154. ResetSysDarkTheme();
  9155. ConfigurationChanged();
  9156. ConfigureInterface();
  9157. // Should be called for all controls
  9158. RemoteDirView->Perform(WM_THEMECHANGED, 0, 0);
  9159. }
  9160. //---------------------------------------------------------------------------
  9161. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9162. {
  9163. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9164. if (!FInvalid &&
  9165. (Message.LParam != 0) &&
  9166. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9167. {
  9168. ThemeChanged();
  9169. }
  9170. TForm::Dispatch(&Message);
  9171. }
  9172. //---------------------------------------------------------------------------
  9173. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9174. {
  9175. TMessage * M = static_cast<TMessage*>(Message);
  9176. switch (M->Msg)
  9177. {
  9178. case CM_DIALOGCHAR:
  9179. CMDialogChar(*M);
  9180. break;
  9181. case WM_APPCOMMAND:
  9182. WMAppCommand(*M);
  9183. break;
  9184. case WM_SYSCOMMAND:
  9185. WMSysCommand(*M);
  9186. break;
  9187. case WM_QUERYENDSESSION:
  9188. WMQueryEndSession(*M);
  9189. break;
  9190. case WM_ENDSESSION:
  9191. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9192. break;
  9193. #ifdef _DEBUG
  9194. case WM_WINDOWPOSCHANGED:
  9195. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  9196. break;
  9197. case CM_CUSTOMSTYLECHANGED:
  9198. TForm::Dispatch(Message);
  9199. break;
  9200. #endif
  9201. case WM_COMPONENT_HIDE:
  9202. {
  9203. Byte Component = static_cast<Byte>(M->WParam);
  9204. // sanity check
  9205. if (ComponentVisible[Component])
  9206. {
  9207. // special treatment
  9208. if (Component == fcQueueView)
  9209. {
  9210. ToggleQueueVisibility();
  9211. DebugAssert(!ComponentVisible[fcQueueView]);
  9212. }
  9213. else
  9214. {
  9215. ComponentVisible[Component] = false;
  9216. }
  9217. }
  9218. }
  9219. break;
  9220. case WM_COPYDATA:
  9221. WMCopyData(*M);
  9222. break;
  9223. case WM_MANAGES_CAPTION:
  9224. // caption managed in TTerminalManager::UpdateAppTitle()
  9225. M->Result = 1;
  9226. break;
  9227. case WM_WANTS_MOUSEWHEEL:
  9228. M->Result = 1;
  9229. break;
  9230. case CM_SHOWINGCHANGED:
  9231. CMShowingChanged(*M);
  9232. break;
  9233. case WM_CLOSE:
  9234. WMClose(*M);
  9235. break;
  9236. case WM_DPICHANGED:
  9237. WMDpiChanged(*M);
  9238. break;
  9239. case CM_DPICHANGED:
  9240. CMDpiChanged(*M);
  9241. break;
  9242. case WM_SETTINGCHANGE:
  9243. WMSettingChange(*M);
  9244. break;
  9245. case CM_DIALOGKEY:
  9246. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9247. break;
  9248. case WM_PASTE_FILES:
  9249. PasteFiles();
  9250. break;
  9251. case WM_IS_HIDDEN:
  9252. // To treat master password prompt as a main window while showing it when workspace is loading while
  9253. // the exporer is showing up (Visible is true already)
  9254. M->Result = !FShowing;
  9255. break;
  9256. case WM_SHOWWINDOW:
  9257. if (M->WParam)
  9258. {
  9259. AddStartupSequence(L"J");
  9260. }
  9261. TForm::Dispatch(Message);
  9262. break;
  9263. default:
  9264. TForm::Dispatch(Message);
  9265. break;
  9266. }
  9267. }
  9268. //---------------------------------------------------------------------------
  9269. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9270. {
  9271. // noop
  9272. }
  9273. //---------------------------------------------------------------------------
  9274. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  9275. {
  9276. TForm::Dispatch(&Message);
  9277. FSessionColors->Clear();
  9278. AddFixedSessionImages();
  9279. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9280. UpdateImages();
  9281. }
  9282. //---------------------------------------------------------------------------
  9283. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9284. {
  9285. TForm::Dispatch(&Message);
  9286. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9287. UpdatePixelsPerInchMainWindowCounter();
  9288. }
  9289. //---------------------------------------------------------------------------
  9290. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9291. {
  9292. AppLog(L"Main window WM_CLOSE");
  9293. // Cannot close window while we are busy.
  9294. // We cannot test this in FormCloseQuery as that is called also from
  9295. // Close(), which is called by CloseApplicationAction. So we can be busy
  9296. // there already even, when it is legitimate to close the application.
  9297. // Possibly a better place to handle this would be WMSysCommand.
  9298. if (NonVisualDataModule->Busy)
  9299. {
  9300. Message.Result = 1;
  9301. }
  9302. else
  9303. {
  9304. TForm::Dispatch(&Message);
  9305. }
  9306. }
  9307. //---------------------------------------------------------------------------
  9308. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9309. {
  9310. if (!FShowingChanged)
  9311. {
  9312. AddStartupSequence(L"D");
  9313. FShowingChanged = true;
  9314. }
  9315. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9316. bool NoSession = (ManagedSession == NULL);
  9317. // This calls TCustomScpExplorerForm::DoShow
  9318. TForm::Dispatch(&Message);
  9319. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9320. if (Showing && !FStarted)
  9321. {
  9322. FStarted = true;
  9323. InterfaceStarted();
  9324. }
  9325. if (Showing && NoSession)
  9326. {
  9327. // When we are starting minimized (i.e. from an installer),
  9328. // postpone showing Login dialog until we get restored.
  9329. // Otherwise the Login dialog (and Authentication window) show restored
  9330. // over invisible (minimized) main window.
  9331. if (WindowState == wsMinimized)
  9332. {
  9333. FNeedSession = true;
  9334. }
  9335. else
  9336. {
  9337. // This happens before application ever goes idle, so the toolbars would
  9338. // stay enabled (initial state) until the Login dialog is dismissed.
  9339. UpdateActions();
  9340. NonVisualDataModule->StartBusy();
  9341. try
  9342. {
  9343. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9344. // otherwise the dialog does not receive focus.
  9345. // With Commander interface the ProcessMessages is called already
  9346. // by TDriveView, but with Explorer interface, we need to call it explicily
  9347. Application->ProcessMessages();
  9348. // do not reload sessions, they have been loaded just now (optimization)
  9349. NeedSession(true);
  9350. }
  9351. __finally
  9352. {
  9353. NonVisualDataModule->EndBusy();
  9354. }
  9355. }
  9356. }
  9357. }
  9358. //---------------------------------------------------------------------------
  9359. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9360. {
  9361. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9362. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9363. }
  9364. //---------------------------------------------------------------------------
  9365. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9366. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9367. int & MaxHeight)
  9368. {
  9369. // workaround for bug in TWinControl.CalcConstraints
  9370. // Check for empty rect (restore from iconic state) is done there only after
  9371. // call to AdjustClientRect, which enlarges the rect (for forms).
  9372. TRect R = GetClientRect();
  9373. // when restoring from iconic state, place no restrictions
  9374. if (IsRectEmpty(R))
  9375. {
  9376. MinWidth = 0;
  9377. MinHeight = 0;
  9378. MaxWidth = 32000;
  9379. MaxHeight = 32000;
  9380. }
  9381. }
  9382. //---------------------------------------------------------------------------
  9383. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9384. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9385. {
  9386. // terminal can be already closed (e.g. dropped connection)
  9387. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9388. {
  9389. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9390. try
  9391. {
  9392. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9393. }
  9394. catch(...)
  9395. {
  9396. if (!Terminal->Active)
  9397. {
  9398. Close = true;
  9399. }
  9400. throw;
  9401. }
  9402. }
  9403. }
  9404. //---------------------------------------------------------------------------
  9405. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9406. {
  9407. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9408. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9409. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9410. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9411. {
  9412. OnGetSpaceAvailable = GetSpaceAvailable;
  9413. }
  9414. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9415. OnGetSpaceAvailable);
  9416. }
  9417. //---------------------------------------------------------------------------
  9418. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9419. {
  9420. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9421. Terminal->FillSessionDataForCode(Data.get());
  9422. return Data.release();
  9423. }
  9424. //---------------------------------------------------------------------------
  9425. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9426. {
  9427. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9428. DoGenerateUrlDialog(Data.get(), Paths);
  9429. }
  9430. //---------------------------------------------------------------------------
  9431. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9432. {
  9433. GenerateUrl(NULL);
  9434. }
  9435. //---------------------------------------------------------------------------
  9436. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9437. {
  9438. std::unique_ptr<TStrings> Paths(new TStringList());
  9439. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9440. GenerateUrl(Paths.get());
  9441. }
  9442. //---------------------------------------------------------------------------
  9443. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9444. {
  9445. FSessionColor = value;
  9446. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9447. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9448. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9449. DebugAssert(ColorItem != NULL);
  9450. ColorItem->Color = C;
  9451. NonVisualDataModule->ColorMenuItem->Color = C;
  9452. UpdateControls();
  9453. }
  9454. //---------------------------------------------------------------------------
  9455. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9456. {
  9457. if (value != FSessionColor)
  9458. {
  9459. UpdateSessionColor(value);
  9460. // Is null when called from LastTerminalClosed
  9461. if (Terminal != NULL)
  9462. {
  9463. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9464. }
  9465. }
  9466. }
  9467. //---------------------------------------------------------------------------
  9468. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9469. {
  9470. bool Result = FNoteTimer->Enabled;
  9471. if (Result)
  9472. {
  9473. // cannot cancel note too early
  9474. bool NotEarly =
  9475. (Now() - FNoteShown >
  9476. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9477. if (Force || NotEarly)
  9478. {
  9479. FNoteTimer->Enabled = false;
  9480. FNote = L"";
  9481. SAFE_DESTROY(FNoteData);
  9482. FOnNoteClick = NULL;
  9483. FNoteHints = FNotes->Text;
  9484. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9485. UpdateStatusBar();
  9486. }
  9487. }
  9488. return Result;
  9489. }
  9490. //---------------------------------------------------------------------------
  9491. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9492. {
  9493. DebugAssert(FNoteTimer->Enabled);
  9494. CancelNote(true);
  9495. }
  9496. //---------------------------------------------------------------------------
  9497. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9498. {
  9499. FNoteHints = FNotes->Text.TrimRight();
  9500. }
  9501. //---------------------------------------------------------------------------
  9502. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9503. {
  9504. int P = Note.Pos(L"\n");
  9505. if (P > 0)
  9506. {
  9507. Note.SetLength(P - 1);
  9508. }
  9509. FNotes->Add(FORMAT(L"[%s] %s",
  9510. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9511. while (FNotes->Count > 10)
  9512. {
  9513. FNotes->Delete(0);
  9514. }
  9515. if (UpdateNow)
  9516. {
  9517. UpdateNoteHints();
  9518. UpdateStatusBar();
  9519. }
  9520. }
  9521. //---------------------------------------------------------------------------
  9522. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  9523. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9524. {
  9525. int P = Note.Pos(L"\n");
  9526. if (P > 0)
  9527. {
  9528. Note.SetLength(P - 1);
  9529. }
  9530. UpdateNoteHints();
  9531. FNote = Note;
  9532. SAFE_DESTROY(FNoteData);
  9533. FNoteData = NoteData;
  9534. FOnNoteClick = OnNoteClick;
  9535. AddNote(Note, false);
  9536. UpdateStatusBar();
  9537. FNoteShown = Now();
  9538. FNoteTimer->Enabled = false;
  9539. if (Seconds == 0)
  9540. {
  9541. Seconds = WinConfiguration->NotificationsTimeout;
  9542. }
  9543. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9544. FNoteTimer->Enabled = true;
  9545. }
  9546. //---------------------------------------------------------------------------
  9547. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9548. {
  9549. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  9550. }
  9551. //---------------------------------------------------------------------------
  9552. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9553. {
  9554. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9555. {
  9556. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9557. }
  9558. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9559. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9560. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))),
  9561. 0, NULL, NULL);
  9562. }
  9563. //---------------------------------------------------------------------------
  9564. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9565. {
  9566. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9567. UnicodeString Note =
  9568. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9569. PostNote(Note, 0, NULL, NULL);
  9570. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9571. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9572. }
  9573. //---------------------------------------------------------------------------
  9574. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9575. {
  9576. WinConfiguration->FormatSizeBytes = Style;
  9577. }
  9578. //---------------------------------------------------------------------------
  9579. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9580. {
  9581. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9582. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9583. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9584. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  9585. }
  9586. //---------------------------------------------------------------------------
  9587. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9588. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9589. {
  9590. if (Panel->Index == 0)
  9591. {
  9592. if (FOnNoteClick != NULL)
  9593. {
  9594. // prevent the user data from being freed by possible call
  9595. // to CancelNote or PostNote during call to OnNoteClick
  9596. std::unique_ptr<TObject> NoteData(FNoteData);
  9597. TNotifyEvent OnNoteClick = FOnNoteClick;
  9598. FNoteData = NULL;
  9599. // need to cancel the note as we are going to delete its user data
  9600. CancelNote(true);
  9601. OnNoteClick(NoteData.get());
  9602. }
  9603. }
  9604. if (HasActiveTerminal() &&
  9605. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9606. {
  9607. FileSystemInfo();
  9608. }
  9609. }
  9610. //---------------------------------------------------------------------------
  9611. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9612. {
  9613. // workaround:
  9614. // 1) for unknown reason, disabling window, while minimized,
  9615. // prevents it from restoring, even if it was enabled again meanwhile
  9616. // 2) when disabling the main window, while another has focus
  9617. // minimize is no longer possible
  9618. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9619. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9620. // Shouldn't we use IsApplicationMinimized() here?
  9621. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9622. {
  9623. Enabled = false;
  9624. }
  9625. FLockLevel++;
  9626. }
  9627. //---------------------------------------------------------------------------
  9628. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9629. {
  9630. DebugAssert(FLockLevel > 0);
  9631. FLockLevel--;
  9632. if (FLockLevel == 0)
  9633. {
  9634. DebugAssert(FLockSuspendLevel == 0);
  9635. Enabled = true;
  9636. // VCL_COPY (TCustomForm.SetWindowFocus)
  9637. if (Active && (ActiveControl != NULL))
  9638. {
  9639. ::SetFocus(ActiveControl->Handle);
  9640. if (GetFocus() == ActiveControl->Handle)
  9641. {
  9642. ActiveControl->Perform(CM_UIACTIVATE, 0, 0);
  9643. }
  9644. }
  9645. }
  9646. }
  9647. //---------------------------------------------------------------------------
  9648. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9649. {
  9650. // We need to make sure that window is enabled when the last modal window closes
  9651. // otherwise focus is not restored correctly.
  9652. // So we re-enable the window when modal window opens and
  9653. // disable it back after is closes
  9654. if (FLockLevel > 0)
  9655. {
  9656. // while we have nesting counter, we know that we never be called
  9657. // recursivelly as Application->OnModalBegin is called only
  9658. // for the top-level modal window
  9659. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9660. {
  9661. // won't be disabled when conditions in LockWindow() were not satisfied
  9662. FDisabledOnLockSuspend = !Enabled;
  9663. // When minimized to tray (or actually when set to SW_HIDE),
  9664. // setting Enabled makes the window focusable even when there's
  9665. // modal window over it
  9666. if (!FTrayIcon->Visible)
  9667. {
  9668. Enabled = true;
  9669. }
  9670. }
  9671. FLockSuspendLevel++;
  9672. }
  9673. }
  9674. //---------------------------------------------------------------------------
  9675. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9676. {
  9677. if (FLockSuspendLevel > 0)
  9678. {
  9679. DebugAssert(FLockLevel > 0);
  9680. FLockSuspendLevel--;
  9681. // see comment in SuspendWindowLock
  9682. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9683. {
  9684. // Note that window can be enabled here, when we were minized to tray when
  9685. // was SuspendWindowLock() called.
  9686. // We should possibly do the same check as in LockWindow(),
  9687. // if it is ever possible that the consitions change between
  9688. // SuspendWindowLock() and ResumeWindowLock()
  9689. Enabled = !FDisabledOnLockSuspend;
  9690. }
  9691. }
  9692. }
  9693. //---------------------------------------------------------------------------
  9694. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9695. {
  9696. TTBXComboBoxItem * RemotePathComboBox =
  9697. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9698. if (!TextOnly)
  9699. {
  9700. TStrings * Items = RemotePathComboBox->Strings;
  9701. Items->BeginUpdate();
  9702. try
  9703. {
  9704. Items->Clear();
  9705. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9706. {
  9707. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9708. while (!IsUnixRootPath(APath))
  9709. {
  9710. int P = APath.LastDelimiter(L'/');
  9711. DebugAssert(P >= 0);
  9712. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9713. APath.SetLength(P - 1);
  9714. }
  9715. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9716. }
  9717. }
  9718. __finally
  9719. {
  9720. Items->EndUpdate();
  9721. }
  9722. }
  9723. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9724. // Setting ItemIndex to -1 does not reset its text
  9725. if (RemotePathComboBox->Strings->Count == 0)
  9726. {
  9727. RemotePathComboBox->Text = L"";
  9728. }
  9729. }
  9730. //---------------------------------------------------------------------------
  9731. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9732. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9733. {
  9734. if (AIndex < 0)
  9735. {
  9736. AIndex = Sender->ItemIndex;
  9737. }
  9738. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9739. }
  9740. //---------------------------------------------------------------------------
  9741. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9742. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9743. int & ImageIndex)
  9744. {
  9745. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9746. }
  9747. //---------------------------------------------------------------------------
  9748. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9749. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9750. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9751. {
  9752. if (!IsLocalBrowserMode())
  9753. {
  9754. ARect.Left += (10 * AIndex);
  9755. }
  9756. }
  9757. //---------------------------------------------------------------------------
  9758. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9759. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9760. {
  9761. AWidth += (10 * AIndex);
  9762. }
  9763. //---------------------------------------------------------------------------
  9764. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9765. {
  9766. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9767. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9768. int Index = RemotePathComboBox->ItemIndex;
  9769. while (Index < RemotePathComboBox->Strings->Count - 1)
  9770. {
  9771. APath = UnixExtractFileDir(APath);
  9772. Index++;
  9773. }
  9774. // VanDyke style paths
  9775. if (APath.IsEmpty())
  9776. {
  9777. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9778. APath = ROOTDIRECTORY;
  9779. }
  9780. if (RemoteDirView->Path != APath)
  9781. {
  9782. RemoteDirView->Path = APath;
  9783. }
  9784. }
  9785. //---------------------------------------------------------------------------
  9786. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9787. {
  9788. DoRemotePathComboBoxItemClick(Sender);
  9789. }
  9790. //---------------------------------------------------------------------------
  9791. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9792. {
  9793. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9794. DebugUsedParam(Sender);
  9795. UpdateRemotePathComboBox(true);
  9796. }
  9797. //---------------------------------------------------------------------------
  9798. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9799. {
  9800. DoRemotePathComboBoxCancel(Sender);
  9801. }
  9802. //---------------------------------------------------------------------------
  9803. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9804. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9805. {
  9806. ResetIncrementalSearch();
  9807. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9808. DebugAssert(DirView != NULL);
  9809. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9810. {
  9811. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9812. // OnEditing is called also from TCustomListView::CanEdit
  9813. if (Edit != NULL)
  9814. {
  9815. EditSelectBaseName(Edit);
  9816. }
  9817. }
  9818. }
  9819. //---------------------------------------------------------------------------
  9820. //---------------------------------------------------------------------------
  9821. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9822. {
  9823. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9824. Result->AutoDetectDnD = false;
  9825. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9826. Result->RenderDataOn = rdoEnterAndDropSync;
  9827. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9828. return Result;
  9829. }
  9830. //---------------------------------------------------------------------------
  9831. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9832. {
  9833. if (IsWin10Build(19041))
  9834. {
  9835. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9836. BOOL DarkMode = FImmersiveDarkMode ? TRUE : FALSE;
  9837. const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
  9838. DwmSetWindowAttribute(Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, &DarkMode, sizeof(DarkMode));
  9839. }
  9840. }
  9841. //---------------------------------------------------------------------------
  9842. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9843. {
  9844. TForm::CreateWnd();
  9845. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9846. UpdateDarkMode();
  9847. if (FSessionsDragDropFilesEx == NULL)
  9848. {
  9849. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9850. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9851. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9852. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9853. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9854. }
  9855. if (FQueueDragDropFilesEx == NULL)
  9856. {
  9857. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9858. // No need to set OnDragOver as we do not have any restrictions
  9859. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9860. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9861. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9862. }
  9863. }
  9864. //---------------------------------------------------------------------------
  9865. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9866. {
  9867. TForm::DestroyWnd();
  9868. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9869. FQueueDragDropFilesEx->DragDropControl = NULL;
  9870. }
  9871. //---------------------------------------------------------------------------
  9872. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9873. {
  9874. SideEnter(FCurrentSide);
  9875. FEverShown = true;
  9876. }
  9877. //---------------------------------------------------------------------------
  9878. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9879. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9880. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9881. {
  9882. if (!NonVisualDataModule->Busy)
  9883. {
  9884. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9885. Configuration->Usage->Inc(L"FileFinds");
  9886. LockWindow(true);
  9887. NonVisualDataModule->StartBusy();
  9888. WinConfiguration->LockedInterface = true;
  9889. try
  9890. {
  9891. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9892. }
  9893. __finally
  9894. {
  9895. WinConfiguration->LockedInterface = false;
  9896. NonVisualDataModule->EndBusy();
  9897. UnlockWindow();
  9898. }
  9899. }
  9900. }
  9901. //---------------------------------------------------------------------------
  9902. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9903. {
  9904. if (!NonVisualDataModule->Busy)
  9905. {
  9906. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9907. SetFocus();
  9908. RemoteDirView->Path = UnixExtractFilePath(Path);
  9909. UnicodeString FileName = UnixExtractFileName(Path);
  9910. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9911. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9912. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  9913. if (Item == NULL)
  9914. {
  9915. ReloadDirectory(osRemote);
  9916. Item = RemoteDirView->FindFileItem(FileName);
  9917. }
  9918. if (Item != NULL)
  9919. {
  9920. RemoteDirView->ItemFocused = Item;
  9921. RemoteDirView->ItemFocused->MakeVisible(false);
  9922. RemoteDirView->SetFocus();
  9923. }
  9924. }
  9925. }
  9926. //---------------------------------------------------------------------------
  9927. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  9928. {
  9929. bool Result = !NonVisualDataModule->Busy;
  9930. if (Result)
  9931. {
  9932. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9933. }
  9934. return Result;
  9935. }
  9936. //---------------------------------------------------------------------------
  9937. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  9938. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9939. {
  9940. if (CanOperateOnFoundFiles(ATerminal))
  9941. {
  9942. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  9943. FOnFileOperationFinished = OnFileOperationFinished;
  9944. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  9945. }
  9946. }
  9947. //---------------------------------------------------------------------------
  9948. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  9949. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9950. {
  9951. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  9952. }
  9953. //---------------------------------------------------------------------------
  9954. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  9955. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9956. {
  9957. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  9958. }
  9959. //---------------------------------------------------------------------------
  9960. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  9961. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9962. {
  9963. if (CanOperateOnFoundFiles(ATerminal))
  9964. {
  9965. for (int Index = 0; Index < FileList->Count; Index++)
  9966. {
  9967. UnicodeString FileName = FileList->Strings[Index];
  9968. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  9969. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  9970. OnFileOperationFinished(osRemote, FileName, true);
  9971. }
  9972. }
  9973. }
  9974. //---------------------------------------------------------------------------
  9975. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  9976. {
  9977. FFileFindTerminal = Terminal;
  9978. ShowFileFindDialog(
  9979. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  9980. DoDownloadFoundFiles, DoEditFoundFiles);
  9981. }
  9982. //---------------------------------------------------------------------------
  9983. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  9984. {
  9985. FTaskbarList = TaskbarList;
  9986. }
  9987. //---------------------------------------------------------------------------
  9988. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  9989. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  9990. {
  9991. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9992. if (Index >= 0)
  9993. {
  9994. if (Button == mbLeft)
  9995. {
  9996. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  9997. // If switching tab (switching session) takes long enough for user
  9998. // to actually release the button, "mouse down" is still raised,
  9999. // but we do not get "mouse up" event, so dragging is not cancelled,
  10000. // prevent that by not beginning dragging in the first place.
  10001. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  10002. if (IsKeyPressed(Key))
  10003. {
  10004. // when user clicks the "+", we get mouse down only after the session
  10005. // is closed, when new session tab is already on X:Y, so dragging
  10006. // starts, prevent that
  10007. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  10008. {
  10009. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10010. if (Terminal != NULL)
  10011. {
  10012. SessionsPageControl->BeginDrag(false);
  10013. }
  10014. }
  10015. }
  10016. }
  10017. else if (Button == mbMiddle)
  10018. {
  10019. // ignore middle-click for "New session tab" and the last local-local tab
  10020. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10021. if ((Session != NULL) && CanCloseSession(Session))
  10022. {
  10023. CloseSessionTab(Index);
  10024. }
  10025. }
  10026. }
  10027. }
  10028. //---------------------------------------------------------------------------
  10029. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  10030. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  10031. {
  10032. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10033. // do not allow dropping on the "+" tab
  10034. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10035. if ((TargetTerminal != NULL) &&
  10036. (SessionsPageControl->ActivePage->PageIndex != Index))
  10037. {
  10038. Configuration->Usage->Inc(L"SessionTabMoves");
  10039. // this is almost redundant as we would recreate tabs in SessionListChanged,
  10040. // but we want to actually prevent that to avoid flicker
  10041. SessionsPageControl->ActivePage->PageIndex = Index;
  10042. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  10043. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  10044. }
  10045. }
  10046. //---------------------------------------------------------------------------
  10047. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  10048. TObject * Sender, TObject * Source, int X, int Y,
  10049. TDragState /*State*/, bool & Accept)
  10050. {
  10051. Accept = (Sender == Source);
  10052. if (Accept)
  10053. {
  10054. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10055. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10056. // do not allow dragging to the "+" tab
  10057. Accept = (Terminal != NULL);
  10058. }
  10059. }
  10060. //---------------------------------------------------------------------------
  10061. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  10062. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  10063. {
  10064. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10065. if (Index < 0)
  10066. {
  10067. Effect = DROPEFFECT_NONE;
  10068. }
  10069. else
  10070. {
  10071. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10072. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  10073. if (!IsActiveTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  10074. {
  10075. Effect = DROPEFFECT_NONE;
  10076. }
  10077. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  10078. {
  10079. Effect = DROPEFFECT_COPY;
  10080. }
  10081. }
  10082. }
  10083. //---------------------------------------------------------------------------
  10084. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  10085. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  10086. {
  10087. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10088. // do not allow dropping on local-local, disconnected and the "+" tab
  10089. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  10090. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10091. if (DebugAlwaysTrue(IsActiveTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  10092. {
  10093. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  10094. if (!IsFileControl(DropSourceControl, osRemote))
  10095. {
  10096. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  10097. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  10098. // Why don't we use Terminal->CurrentDirectory directly?
  10099. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10100. // do not force queue, drag drop
  10101. false, true);
  10102. }
  10103. }
  10104. }
  10105. //---------------------------------------------------------------------------
  10106. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10107. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10108. {
  10109. // Downloads are handled in RemoteFileControlDDEnd
  10110. if (!IsFileControl(DropSourceControl, osRemote))
  10111. {
  10112. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10113. Terminal->CurrentDirectory,
  10114. // force queue, drag drop
  10115. true, true);
  10116. }
  10117. }
  10118. //---------------------------------------------------------------------------
  10119. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10120. {
  10121. FShowing = false;
  10122. // Do not save empty workspace
  10123. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10124. {
  10125. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10126. UnicodeString Name = WorkspaceName();
  10127. DoSaveWorkspace(
  10128. Name, DataList.get(),
  10129. !Configuration->DisablePasswordStoring &&
  10130. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10131. WinConfiguration->LastStoredSession = Name;
  10132. }
  10133. AppLog(L"Closing main window");
  10134. }
  10135. //---------------------------------------------------------------------------
  10136. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10137. {
  10138. TManagedTerminal * ManagedTerminal =
  10139. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10140. if (ManagedTerminal != NULL)
  10141. {
  10142. ManagedTerminal->DirectoryLoaded = Now();
  10143. }
  10144. }
  10145. //---------------------------------------------------------------------------
  10146. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10147. TListItem * /*Item*/, bool /*Selected*/)
  10148. {
  10149. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10150. switch (DirView->LastSelectMethod)
  10151. {
  10152. case smKeyboard:
  10153. Configuration->Usage->Inc(L"KeyboardSelections");
  10154. break;
  10155. case smMouse:
  10156. Configuration->Usage->Inc(L"MouseSelections");
  10157. break;
  10158. }
  10159. }
  10160. //---------------------------------------------------------------------------
  10161. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10162. {
  10163. if (Color != 0)
  10164. {
  10165. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10166. }
  10167. else
  10168. {
  10169. return FSessionTabImageIndex;
  10170. }
  10171. }
  10172. //---------------------------------------------------------------------------
  10173. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10174. {
  10175. TPngImageCollectionItem * Item =
  10176. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10177. FSessionColors->AddPng(Item->PngImage);
  10178. return FSessionColors->Count - 1;
  10179. }
  10180. //---------------------------------------------------------------------------
  10181. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10182. {
  10183. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10184. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10185. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10186. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10187. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10188. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10189. }
  10190. //---------------------------------------------------------------------------
  10191. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10192. {
  10193. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10194. }
  10195. //---------------------------------------------------------------------------
  10196. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10197. {
  10198. switch (Side)
  10199. {
  10200. case osLocal:
  10201. return FNewLocalTabTabImageIndex;
  10202. case osRemote:
  10203. case osCurrent:
  10204. return FNewRemoteTabTabImageIndex;
  10205. default:
  10206. DebugFail();
  10207. return -1;
  10208. }
  10209. }
  10210. //---------------------------------------------------------------------------
  10211. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10212. {
  10213. for (int Index = 0; Index < Control->ControlCount; Index++)
  10214. {
  10215. TControl * AControl = Control->Controls[Index];
  10216. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10217. if (WinControl != NULL)
  10218. {
  10219. CollectItemsWithTextDisplayMode(WinControl);
  10220. }
  10221. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10222. if (Toolbar != NULL)
  10223. {
  10224. // we care for top-level items only
  10225. TTBCustomItem * Items = Toolbar->Items;
  10226. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10227. {
  10228. TTBCustomItem * Item = Items->Items[ItemIndex];
  10229. if (((Item->DisplayMode == nbdmImageAndText) ||
  10230. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10231. EligibleForImageDisplayMode(Item))
  10232. {
  10233. FItemsWithTextDisplayMode.insert(Item);
  10234. }
  10235. }
  10236. }
  10237. }
  10238. }
  10239. //---------------------------------------------------------------------------
  10240. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10241. {
  10242. return true;
  10243. }
  10244. //---------------------------------------------------------------------------
  10245. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10246. {
  10247. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10248. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10249. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10250. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10251. bool Result = true;
  10252. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10253. {
  10254. TTBCustomItem * Item = *i;
  10255. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10256. if (Label != NULL)
  10257. {
  10258. // optimization
  10259. if (Label->Visible == SelectiveToolbarText)
  10260. {
  10261. Result = false;
  10262. }
  10263. else
  10264. {
  10265. Label->Visible = SelectiveToolbarText;
  10266. }
  10267. }
  10268. else
  10269. {
  10270. // optimization
  10271. if (Item->DisplayMode == DisplayMode)
  10272. {
  10273. Result = false;
  10274. }
  10275. else
  10276. {
  10277. Item->DisplayMode = DisplayMode;
  10278. }
  10279. }
  10280. ++i;
  10281. }
  10282. UpdateNewTabTab();
  10283. return Result;
  10284. }
  10285. //---------------------------------------------------------------------------
  10286. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10287. {
  10288. DebugFail();
  10289. }
  10290. //---------------------------------------------------------------------------
  10291. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10292. {
  10293. // Among other, a lock level is non zero, while directory is being loaded,
  10294. // even when it happens as a result of dirview navigation,
  10295. // i.e. when TNonVisualDataModule is NOT FBusy.
  10296. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10297. // Among other this prevents a panel auto update to occur while
  10298. // directory is changing.
  10299. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10300. }
  10301. //---------------------------------------------------------------------------
  10302. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10303. {
  10304. // While the window is disabled, we still seem to process menu shortcuts at least,
  10305. // so stop it at least here.
  10306. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10307. bool Result;
  10308. if (Allowed == aaUpdate)
  10309. {
  10310. Result = true;
  10311. }
  10312. else
  10313. {
  10314. Result = !NonVisualDataModule->Busy;
  10315. if (Result && (Allowed == aaShortCut))
  10316. {
  10317. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10318. Action->Update();
  10319. Result = Action->Enabled;
  10320. }
  10321. }
  10322. return Result;
  10323. }
  10324. //---------------------------------------------------------------------------
  10325. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10326. {
  10327. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10328. }
  10329. //---------------------------------------------------------------------------
  10330. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10331. {
  10332. // This is somewhat redundant to LockWindow() call from
  10333. // TTerminalManager::TerminalReadDirectoryProgress.
  10334. // But disabling window is known not to block keyboard shorcuts
  10335. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10336. if (Busy > 0)
  10337. {
  10338. if (NonVisualDataModule->Busy)
  10339. {
  10340. State = false;
  10341. }
  10342. else
  10343. {
  10344. NonVisualDataModule->StartBusy();
  10345. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10346. LockWindow();
  10347. }
  10348. }
  10349. else if (Busy < 0)
  10350. {
  10351. UnlockWindow();
  10352. NonVisualDataModule->EndBusy();
  10353. }
  10354. else
  10355. {
  10356. State = NonVisualDataModule->Busy;
  10357. }
  10358. }
  10359. //---------------------------------------------------------------------------
  10360. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10361. {
  10362. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10363. if (Index >= 0)
  10364. {
  10365. TPopupMenu * PopupMenu = NULL;
  10366. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10367. if (Session != NULL)
  10368. {
  10369. SessionsPageControl->ActivePageIndex = Index;
  10370. if (DebugAlwaysTrue(SessionTabSwitched()))
  10371. {
  10372. // copied from TControl.WMContextMenu
  10373. SendCancelMode(SessionsPageControl);
  10374. // explicit popup instead of using PopupMenu property
  10375. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10376. // while connecting yet not-connected session and hence
  10377. // allowing an access to commands over not-completely connected session
  10378. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10379. }
  10380. }
  10381. else
  10382. {
  10383. if (SupportsLocalBrowser())
  10384. {
  10385. PopupMenu = NonVisualDataModule->NewTabPopup;
  10386. }
  10387. }
  10388. if (PopupMenu != NULL)
  10389. {
  10390. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10391. PopupMenu->PopupComponent = SessionsPageControl;
  10392. PopupMenu->Popup(Point.x, Point.y);
  10393. }
  10394. }
  10395. Handled = true;
  10396. }
  10397. //---------------------------------------------------------------------------
  10398. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10399. {
  10400. return HasActiveTerminal() && Terminal->IsCapable[fcChangePassword];
  10401. }
  10402. //---------------------------------------------------------------------------
  10403. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10404. {
  10405. Configuration->Usage->Inc(L"PasswordChanges");
  10406. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10407. ChangePasswordData->DisableAuthentationsExceptPassword();
  10408. ChangePasswordData->ChangePassword = true;
  10409. std::unique_ptr<TTerminal> ChangePasswordSession(
  10410. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10411. ChangePasswordSession->AutoReadDirectory = false;
  10412. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10413. {
  10414. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10415. }
  10416. else
  10417. {
  10418. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10419. }
  10420. }
  10421. //---------------------------------------------------------------------------
  10422. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10423. {
  10424. // No nice way to assert SSH2
  10425. return HasActiveTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10426. }
  10427. //---------------------------------------------------------------------------
  10428. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10429. {
  10430. TOperationVisualizer OperationVisualizer;
  10431. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10432. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10433. }
  10434. //---------------------------------------------------------------------------
  10435. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  10436. {
  10437. TForm::ChangeScale(M, D);
  10438. int APixelsPerInch = GetControlPixelsPerInch(this);
  10439. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  10440. try
  10441. {
  10442. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  10443. }
  10444. __finally
  10445. {
  10446. GUIConfiguration->ChangeResourceModule(ResourceModule);
  10447. }
  10448. }
  10449. //---------------------------------------------------------------------------
  10450. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10451. {
  10452. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10453. }
  10454. //---------------------------------------------------------------------
  10455. class TPublicControl : public TControl
  10456. {
  10457. friend class TCustomScpExplorerForm;
  10458. };
  10459. //---------------------------------------------------------------------------
  10460. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10461. {
  10462. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10463. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10464. }
  10465. //---------------------------------------------------------------------------
  10466. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10467. {
  10468. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10469. OpenBookmark(Side, Bookmark);
  10470. }
  10471. //---------------------------------------------------------------------------
  10472. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10473. {
  10474. DoBookmarkClick(osLocal, Sender);
  10475. }
  10476. //---------------------------------------------------------------------------
  10477. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10478. {
  10479. DoBookmarkClick(osRemote, Sender);
  10480. }
  10481. //---------------------------------------------------------------------------
  10482. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10483. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10484. {
  10485. if (BookmarkList != NULL)
  10486. {
  10487. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10488. if (IsLocalBrowserMode())
  10489. {
  10490. Side = osLocal;
  10491. }
  10492. if (!WinConfiguration->UseLocationProfiles)
  10493. {
  10494. std::unique_ptr<TStringList> Directories(new TStringList());
  10495. Directories->CaseSensitive = (Side == osRemote);
  10496. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10497. {
  10498. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10499. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10500. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10501. {
  10502. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10503. Item->Caption = EscapeHotkey(Directory);
  10504. Item->ShortCut = Bookmark->ShortCut;
  10505. Item->OnClick = OnBookmarkClick;
  10506. Item->Tag = reinterpret_cast<int>(Bookmark);
  10507. Directories->Add(Directory);
  10508. Menu->Add(Item.release());
  10509. }
  10510. }
  10511. }
  10512. else
  10513. {
  10514. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10515. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10516. {
  10517. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10518. if (!Bookmark->Node.IsEmpty())
  10519. {
  10520. Folders->Add(Bookmark->Node);
  10521. }
  10522. }
  10523. for (int Index = 0; Index < Folders->Count; Index++)
  10524. {
  10525. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10526. Item->Caption = Folders->Strings[Index];
  10527. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10528. Folders->Objects[Index] = Item.get();
  10529. Menu->Add(Item.release());
  10530. }
  10531. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10532. {
  10533. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10534. TTBCustomItem * Parent;
  10535. if (!Bookmark->Node.IsEmpty())
  10536. {
  10537. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10538. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10539. }
  10540. else
  10541. {
  10542. Parent = Menu;
  10543. }
  10544. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10545. Item->Caption = Bookmark->Name;
  10546. Item->ShortCut = Bookmark->ShortCut;
  10547. Item->OnClick = OnBookmarkClick;
  10548. Item->Tag = reinterpret_cast<int>(Bookmark);
  10549. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10550. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10551. {
  10552. // No hint for location profiles that are actually mere "bookmarks"
  10553. }
  10554. else
  10555. {
  10556. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10557. UnicodeString LongHint;
  10558. if (!Bookmark->Local.IsEmpty())
  10559. {
  10560. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10561. }
  10562. if (!Bookmark->Remote.IsEmpty())
  10563. {
  10564. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10565. }
  10566. AddToList(Hint, LongHint, L"|");
  10567. Item->Hint = Hint;
  10568. }
  10569. Parent->Add(Item.release());
  10570. }
  10571. }
  10572. AddMenuSeparator(Menu);
  10573. }
  10574. }
  10575. //---------------------------------------------------------------------------
  10576. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10577. {
  10578. Menu->Clear();
  10579. std::unique_ptr<TTBCustomItem> Item;
  10580. Item.reset(new TTBXItem(Owner));
  10581. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10582. Item->Options = Item->Options << tboDefault;
  10583. Menu->Add(Item.release());
  10584. AddMenuSeparator(Menu);
  10585. if (Terminal != NULL)
  10586. {
  10587. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10588. }
  10589. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10590. Item.reset(new TTBXItem(Owner));
  10591. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10592. Menu->Add(Item.release());
  10593. }
  10594. //---------------------------------------------------------------------------
  10595. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10596. {
  10597. bool Result = true;
  10598. bool Remote = !IsSideLocalBrowser(Side);
  10599. try
  10600. {
  10601. UnicodeString APath = Path;
  10602. if (Remote)
  10603. {
  10604. Terminal->ExceptionOnFail = true;
  10605. }
  10606. else
  10607. {
  10608. APath = ExpandEnvironmentVariables(Path);
  10609. }
  10610. try
  10611. {
  10612. DirView(Side)->Path = APath;
  10613. }
  10614. __finally
  10615. {
  10616. if (Remote)
  10617. {
  10618. Terminal->ExceptionOnFail = false;
  10619. }
  10620. }
  10621. }
  10622. catch (Exception & E)
  10623. {
  10624. if (!Remote || Terminal->Active)
  10625. {
  10626. ShowExtendedExceptionEx(Terminal, &E);
  10627. Result = false;
  10628. }
  10629. else
  10630. {
  10631. throw;
  10632. }
  10633. }
  10634. return Result;
  10635. }
  10636. //---------------------------------------------------------------------------
  10637. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10638. {
  10639. // Make sure there some feedback even when loading tiny local folders
  10640. TInstantOperationVisualizer Visualizer;
  10641. DirView(Side)->ReloadDirectory();
  10642. }
  10643. //---------------------------------------------------------------------------
  10644. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10645. {
  10646. if (Index == SessionsPageControl->TabIndex)
  10647. {
  10648. CloseTab();
  10649. }
  10650. else
  10651. {
  10652. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10653. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10654. TTerminalManager * Manager = TTerminalManager::Instance();
  10655. if (!Terminal->Active)
  10656. {
  10657. Manager->FreeTerminal(Terminal);
  10658. }
  10659. else
  10660. {
  10661. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10662. if (CanCloseQueue(Queue))
  10663. {
  10664. Manager->FreeTerminal(Terminal);
  10665. }
  10666. }
  10667. }
  10668. }
  10669. //---------------------------------------------------------------------------
  10670. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10671. {
  10672. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10673. if (Session == NULL)
  10674. {
  10675. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10676. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10677. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10678. //P = SessionsPageControl->ClientToScreen(P);
  10679. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10680. }
  10681. else
  10682. {
  10683. CloseSessionTab(Index);
  10684. }
  10685. }
  10686. //---------------------------------------------------------------------------
  10687. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10688. {
  10689. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10690. {
  10691. TInstantOperationVisualizer Visualizer;
  10692. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10693. // before we create a new data object
  10694. ClipboardClear();
  10695. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10696. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10697. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10698. // Intermediate variable to WORKAROUND a crash in compiler
  10699. TObjectList * ClipboardFakeMonitors =
  10700. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10701. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10702. if (FClipboardDragDropFilesEx.get() == NULL)
  10703. {
  10704. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10705. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10706. }
  10707. FClipboardDragDropFilesEx->FileList->Clear();
  10708. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10709. FClipboardDragDropFilesEx->CopyToClipboard();
  10710. FClipboardTerminal = Terminal;
  10711. // Need full paths, as cwd can be different once files are pasted
  10712. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10713. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10714. {
  10715. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10716. }
  10717. AppLogFmt(L"Created fake clipboard directory \"%s\" and started drive monitors", (FClipboardFakeDirectory));
  10718. }
  10719. }
  10720. //---------------------------------------------------------------------------
  10721. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10722. {
  10723. if (OpenClipboard(0))
  10724. {
  10725. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10726. CloseClipboard();
  10727. }
  10728. }
  10729. //---------------------------------------------------------------------------
  10730. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10731. {
  10732. return !FClipboardFakeDirectory.IsEmpty();
  10733. }
  10734. //---------------------------------------------------------------------------
  10735. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10736. {
  10737. bool Deleted = RemoveDir(ApiPath(FClipboardFakeDirectory));
  10738. AppLogFmt(L"Clearing clipboard, deleted clipboard temporary folder \"%s\" - %d", (FClipboardFakeDirectory, int(Deleted)));
  10739. FClipboardFakeDirectory = UnicodeString();
  10740. FClipboardTerminal = NULL;
  10741. if (FDownloadingFromClipboard)
  10742. {
  10743. // We are called by the monitor, so attempt to release it would deadlock
  10744. FClipboardFakeMonitorsPendingReset = true;
  10745. }
  10746. else
  10747. {
  10748. FClipboardFakeMonitors.reset(NULL);
  10749. }
  10750. }
  10751. //---------------------------------------------------------------------------
  10752. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10753. {
  10754. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10755. {
  10756. ClipboardStop();
  10757. }
  10758. }
  10759. //---------------------------------------------------------------------------
  10760. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10761. {
  10762. TTerminalManager * Manager = TTerminalManager::Instance();
  10763. Manager->ActiveSession = FClipboardTerminal;
  10764. TTransferOperationParam Params;
  10765. Params.TargetDirectory = TargetDirectory;
  10766. Params.DragDrop = DragDrop;
  10767. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10768. }
  10769. //---------------------------------------------------------------------------
  10770. void TCustomScpExplorerForm::PasteFiles()
  10771. {
  10772. // Guard against possible race conditions
  10773. if (!FClipboardPasteTarget.IsEmpty())
  10774. {
  10775. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10776. UnicodeString Target = FClipboardPasteTarget;
  10777. FClipboardPasteTarget = EmptyStr;
  10778. // Can fail as it can be e.g. locked by AV, so we retry that later
  10779. bool Removed = RemoveDir(ApiPath(Target));
  10780. AppLogFmt(L"First attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10781. try
  10782. {
  10783. if (NonVisualDataModule->Busy)
  10784. {
  10785. AppLog(L"Is busy, cannot paste");
  10786. }
  10787. else
  10788. {
  10789. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10790. FClipboardFakeMonitorsPendingReset = false;
  10791. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10792. TAutoFlag Flag(FDownloadingFromClipboard);
  10793. AppLog(L"Downloading to paste target...");
  10794. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10795. AppLog(L"Downloaded to paste target...");
  10796. }
  10797. }
  10798. __finally
  10799. {
  10800. if (!Removed)
  10801. {
  10802. Removed = RemoveDir(ApiPath(Target));
  10803. AppLogFmt(L"Second attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10804. }
  10805. }
  10806. }
  10807. }
  10808. //---------------------------------------------------------------------------
  10809. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10810. {
  10811. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10812. // (as it pumps a Windows message queue while being shutted down)
  10813. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10814. // Is can happen that creation of our temporary directory is detected (even though we are creating it before starting the monitors).
  10815. // It tent do happen with later copy-pastes, probably because everything is cached already and monitors start quickly.
  10816. !IsPathToSameFile(FClipboardFakeDirectory, FileName) &&
  10817. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10818. {
  10819. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10820. FClipboardPasteTarget = FileName;
  10821. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10822. // Postponing removing (or actually whole pasting operation) seems to help.
  10823. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10824. }
  10825. }
  10826. //---------------------------------------------------------------------------
  10827. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10828. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10829. {
  10830. TFileMasks::TParams MaskParams;
  10831. MaskParams.Size = Size;
  10832. MaskParams.Modification = Modification;
  10833. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10834. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10835. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10836. if (!Local && Directory)
  10837. {
  10838. FileName = UnixExcludeTrailingBackslash(FileName);
  10839. }
  10840. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10841. {
  10842. bool ImplicitMatch;
  10843. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10844. !ImplicitMatch)
  10845. {
  10846. Color = Iter->Color;
  10847. break;
  10848. }
  10849. }
  10850. }
  10851. //---------------------------------------------------------------------------
  10852. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10853. {
  10854. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10855. if (!DirView->IsEditing())
  10856. {
  10857. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10858. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10859. // while searching
  10860. if (Key == VK_BACK)
  10861. {
  10862. if (!FIncrementalSearch.IsEmpty())
  10863. {
  10864. if (FIncrementalSearch.Length() == 1)
  10865. {
  10866. ResetIncrementalSearch();
  10867. }
  10868. else
  10869. {
  10870. UnicodeString NewText = FIncrementalSearch.SubString(1, FIncrementalSearch.Length() - 1);
  10871. IncrementalSearch(NewText, false, false);
  10872. }
  10873. Key = 0;
  10874. }
  10875. }
  10876. }
  10877. }
  10878. //---------------------------------------------------------------------------
  10879. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10880. {
  10881. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10882. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10883. {
  10884. // Filter control sequences.
  10885. // When not searching yet, prefer use of the space for toggling file selection
  10886. // (so we cannot incrementally search for a string starting with a space).
  10887. if ((Key > VK_SPACE) ||
  10888. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && !FIncrementalSearch.IsEmpty()))
  10889. {
  10890. IncrementalSearch(FIncrementalSearch + Key, false, false);
  10891. Key = 0;
  10892. }
  10893. }
  10894. }
  10895. //---------------------------------------------------------------------------
  10896. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10897. {
  10898. if (!FIncrementalSearch.IsEmpty())
  10899. {
  10900. FIncrementalSearch = L"";
  10901. DirView(osCurrent)->UpdateStatusBar();
  10902. }
  10903. }
  10904. //---------------------------------------------------------------------------
  10905. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10906. {
  10907. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  10908. if (Item == NULL)
  10909. {
  10910. MessageBeep(MB_ICONHAND);
  10911. }
  10912. else
  10913. {
  10914. TCustomDirView * ADirView = DirView(osCurrent);
  10915. {
  10916. TAutoNestingCounter Guard(FIncrementalSearching);
  10917. ADirView->FocusItem(Item);
  10918. if (ADirView->NortonLike == nlOff)
  10919. {
  10920. if ((ADirView->Selected != Item) ||
  10921. (ADirView->SelCount > 1))
  10922. {
  10923. ADirView->ClearSelection();
  10924. ADirView->Selected = Item;
  10925. }
  10926. }
  10927. }
  10928. FIncrementalSearch = Text;
  10929. Item->MakeVisible(false);
  10930. TListItem * NextItem = SearchFile(Text, true, Reverse);
  10931. FIncrementalSearchHaveNext = (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->ViewStyle == vsReport) ? ADirView->ColProperties->Count : 1;
  10986. int Index = 0;
  10987. while ((Index < ColCount) && !Matches)
  10988. {
  10989. bool Visible = (ADirView->ViewStyle == vsReport) ? 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 (!FIncrementalSearch.IsEmpty())
  11021. {
  11022. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  11023. bool Reverse = Shift.Contains(ssShift);
  11024. IncrementalSearch(FIncrementalSearch, true, Reverse);
  11025. Message.Result = 1;
  11026. return;
  11027. }
  11028. }
  11029. else if (Message.CharCode == VK_ESCAPE)
  11030. {
  11031. if (!FIncrementalSearch.IsEmpty())
  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);
  11332. FCalculateSizeOperation = &CalculateSizeOperation;
  11333. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11334. FOnFileOperationFinished = DirectorySizeCalculated;
  11335. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation);
  11336. FPrimaryOperation = foCalculateSize;
  11337. TCalculatedSizes CalculatedSizes;
  11338. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11339. if (LocalSide)
  11340. {
  11341. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  11342. FProgressSide = Side;
  11343. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11344. }
  11345. else
  11346. {
  11347. TCalculateSizeParams Params;
  11348. Params.Stats = &CalculateSizeOperation.Stats;
  11349. Params.UseCache = true;
  11350. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11351. }
  11352. }
  11353. //---------------------------------------------------------------------------
  11354. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(TOperationSide Side, const UnicodeString & FileName, bool Success)
  11355. {
  11356. DebugAlwaysTrue(FCalculateSizeOperation != NULL);
  11357. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11358. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11359. // optimization
  11360. bool GotExpectedItem =
  11361. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11362. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11363. int Index = -1;
  11364. if (DebugAlwaysTrue(GotExpectedItem))
  11365. {
  11366. Index = FCalculateSizeOperation->Index;
  11367. FCalculateSizeOperation->Index++;
  11368. }
  11369. else
  11370. {
  11371. TListItemsVector::iterator I =
  11372. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11373. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11374. {
  11375. Index = I - FCalculateSizeOperation->ListItems.begin();
  11376. }
  11377. }
  11378. if (DebugAlwaysTrue(Index >= 0) && Success)
  11379. {
  11380. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11381. ADirView->SetItemCalculatedSize(Item, Size);
  11382. }
  11383. }
  11384. //---------------------------------------------------------------------------
  11385. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11386. {
  11387. Accept = false;
  11388. }
  11389. //---------------------------------------------------------------------------
  11390. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11391. {
  11392. // Send Ctrl+Gray+ to the list view
  11393. TKeyboardState KeyState;
  11394. GetKeyboardState(KeyState);
  11395. TKeyboardState NewKeyState;
  11396. memset(NewKeyState, 0, sizeof(NewKeyState));
  11397. NewKeyState[VK_CONTROL] = 0x81;
  11398. SetKeyboardState(NewKeyState);
  11399. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11400. SetKeyboardState(KeyState);
  11401. }
  11402. //---------------------------------------------------------------------------
  11403. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11404. {
  11405. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11406. }
  11407. //---------------------------------------------------------------------------
  11408. void * TCustomScpExplorerForm::SaveFocus()
  11409. {
  11410. return NULL;
  11411. }
  11412. //---------------------------------------------------------------------------
  11413. void TCustomScpExplorerForm::RestoreFocus(void * Focus)
  11414. {
  11415. DebugUsedParam(Focus);
  11416. DebugAssert(Focus == NULL);
  11417. }