Login.cpp 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397
  1. //---------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <StrUtils.hpp>
  5. #include <CoreMain.h>
  6. #include <Common.h>
  7. #include <PuttyTools.h>
  8. #include <TextsWin.h>
  9. #include <TextsCore.h>
  10. #include <HelpWin.h>
  11. #include <VCLCommon.h>
  12. #include <limits>
  13. #include "WinInterface.h"
  14. #include "Login.h"
  15. #include "GUITools.h"
  16. #include "Tools.h"
  17. #include "Setup.h"
  18. #include "WinConfiguration.h"
  19. #include "ProgParams.h"
  20. #include "WinApi.h"
  21. #include "S3FileSystem.h"
  22. //---------------------------------------------------------------------
  23. #pragma link "ComboEdit"
  24. #pragma link "PasswordEdit"
  25. #pragma link "UpDownEdit"
  26. #pragma resource "*.dfm"
  27. //---------------------------------------------------------------------------
  28. const int SiteImageIndex = 1;
  29. const int OpenedFolderImageIndex = 2;
  30. const int ClosedFolderImageIndex = 3;
  31. const int WorkspaceImageIndex = 4;
  32. const int NewSiteImageIndex = 6;
  33. const int SiteColorMaskImageIndex = 8;
  34. //---------------------------------------------------------------------------
  35. const int LoginImageIndex = 0;
  36. const int OpenWorkspaceImageIndex = 5;
  37. const int OpenFolderImageIndex = 6;
  38. //---------------------------------------------------------------------------
  39. bool __fastcall DoLoginDialog(TList * DataList, TForm * LinkedForm)
  40. {
  41. DebugAssert(DataList != NULL);
  42. TLoginDialog * LoginDialog = SafeFormCreate<TLoginDialog>();
  43. bool Result;
  44. try
  45. {
  46. LoginDialog->Init(LinkedForm);
  47. Result = LoginDialog->Execute(DataList);
  48. }
  49. __finally
  50. {
  51. delete LoginDialog;
  52. }
  53. return Result;
  54. }
  55. //---------------------------------------------------------------------
  56. static const TFSProtocol FSOrder[] = { fsSFTPonly, fsSCPonly, fsFTP, fsWebDAV, fsS3 };
  57. //---------------------------------------------------------------------
  58. __fastcall TLoginDialog::TLoginDialog(TComponent* AOwner)
  59. : TForm(AOwner)
  60. {
  61. FNewSiteData = new TSessionData(L"");
  62. FInitialized = false;
  63. FHintNode = NULL;
  64. FScrollOnDragOver = new TTreeViewScrollOnDragOver(SessionTree, true);
  65. FDataList = NULL;
  66. FUpdatePortWithProtocol = true;
  67. FIncrementalSearching = 0;
  68. FEditing = false;
  69. FRenaming = false;
  70. FNewSiteKeepName = false;
  71. FForceNewSite = false;
  72. FLoading = false;
  73. FSortEnablePending = false;
  74. FSiteSearch = isName;
  75. FLinkedForm = NULL;
  76. FRestoring = false;
  77. FPrevPos = TPoint(std::numeric_limits<LONG>::min(), std::numeric_limits<LONG>::min());
  78. FWasEverS3 = false;
  79. // we need to make sure that window procedure is set asap
  80. // (so that CM_SHOWINGCHANGED handling is applied)
  81. UseSystemSettingsPre(this);
  82. FFixedSessionImages = SessionImageList->Count;
  83. DebugAssert(SiteColorMaskImageIndex == FFixedSessionImages - 1);
  84. FBasicGroupBaseHeight = BasicGroup->Height - BasicSshPanel->Height - BasicFtpPanel->Height - BasicS3Panel->Height;
  85. FNoteGroupOffset = NoteGroup->Top - (BasicGroup->Top + BasicGroup->Height);
  86. FUserNameLabel = UserNameLabel->Caption;
  87. FPasswordLabel = PasswordLabel->Caption;
  88. FSiteButtonsPadding = SitesPanel->ClientHeight - ToolsMenuButton->Top - ToolsMenuButton->Height;
  89. AutoSizeCheckBox(ShowAgainCheck);
  90. }
  91. //---------------------------------------------------------------------
  92. __fastcall TLoginDialog::~TLoginDialog()
  93. {
  94. delete FScrollOnDragOver;
  95. delete FNewSiteData;
  96. InvalidateSessionData();
  97. }
  98. //---------------------------------------------------------------------
  99. void __fastcall TLoginDialog::InvalidateSessionData()
  100. {
  101. delete FSessionData;
  102. FSessionData = NULL;
  103. }
  104. //---------------------------------------------------------------------
  105. void __fastcall TLoginDialog::Init(TForm * LinkedForm)
  106. {
  107. FLinkedForm = LinkedForm;
  108. LoadSessions();
  109. UnicodeString Dummy;
  110. RunPageantAction->Visible = FindTool(PageantTool, Dummy);
  111. RunPuttygenAction->Visible = FindTool(PuttygenTool, Dummy);
  112. UpdateControls();
  113. }
  114. //---------------------------------------------------------------------
  115. void __fastcall TLoginDialog::InitControls()
  116. {
  117. if (SessionTree->WindowProc != SessionTreeProc)
  118. {
  119. FOldSessionTreeProc = SessionTree->WindowProc;
  120. SessionTree->WindowProc = SessionTreeProc;
  121. }
  122. int FtpsNoneIndex = FtpsToIndex(ftpsNone);
  123. int FtpsImplicitIndex = FtpsToIndex(ftpsImplicit);
  124. // Items item setter is implemented as deleting and re-adding the item. If we do it for the last item
  125. // (explicit for FTP, implicit for WebDAV/S3), the ItemIndex is effectively reset to -1.
  126. // This happens when TLS is set in the default session settings.
  127. // Also as TransferProtocolComboChange is not triggered it results in currupted state in respect to protocol/tls to port number sync.
  128. int Index = FtpsCombo->ItemIndex;
  129. FtpsCombo->Items->Strings[FtpsImplicitIndex] = LoadStr(FTPS_IMPLICIT);
  130. FtpsCombo->Items->Strings[FtpsToIndex(ftpsExplicitTls)] = LoadStr(FTPS_EXPLICIT);
  131. FtpsCombo->ItemIndex = Index;
  132. Index = WebDavsCombo->ItemIndex;
  133. WebDavsCombo->Items->Strings[FtpsNoneIndex] = FtpsCombo->Items->Strings[FtpsNoneIndex];
  134. WebDavsCombo->Items->Strings[FtpsImplicitIndex] = FtpsCombo->Items->Strings[FtpsImplicitIndex];
  135. WebDavsCombo->ItemIndex = Index;
  136. BasicSshPanel->Top = BasicFtpPanel->Top;
  137. BasicS3Panel->Top = BasicFtpPanel->Top;
  138. SitesIncrementalSearchLabel->AutoSize = false;
  139. SitesIncrementalSearchLabel->Left = SessionTree->Left;
  140. SitesIncrementalSearchLabel->Width = SessionTree->Width;
  141. SitesIncrementalSearchLabel->Top = SessionTree->BoundsRect.Bottom - SitesIncrementalSearchLabel->Height;
  142. SitesIncrementalSearchLabel->Visible = false;
  143. ReadOnlyControl(TransferProtocolView);
  144. ReadOnlyControl(EncryptionView);
  145. ReadOnlyControl(NoteMemo);
  146. MenuButton(ToolsMenuButton);
  147. MenuButton(ManageButton);
  148. FixButtonImage(LoginButton);
  149. SelectScaledImageList(SessionImageList);
  150. SelectScaledImageList(ActionImageList);
  151. GenerateImages();
  152. if (SessionTree->Items->Count > 0)
  153. {
  154. SetNewSiteNodeLabel();
  155. }
  156. }
  157. //---------------------------------------------------------------------
  158. void TLoginDialog::UpdateLoginButton()
  159. {
  160. TAction * Action = DebugNotNull(dynamic_cast<TAction *>(LoginButton->Action));
  161. int ImageIndex = Action->ImageIndex;
  162. if (FButtonImagesMap.find(ImageIndex) == FButtonImagesMap.end())
  163. {
  164. int LoginIndex = AddLoginButtonImage(ImageIndex, true);
  165. FButtonImagesMap.insert(std::make_pair(ImageIndex, LoginIndex));
  166. AddLoginButtonImage(ImageIndex, false);
  167. }
  168. LoginButton->ImageIndex = FButtonImagesMap[ImageIndex];
  169. LoginButton->DisabledImageIndex = FButtonImagesMap[ImageIndex] + 1;
  170. CenterButtonImage(LoginButton);
  171. }
  172. //---------------------------------------------------------------------
  173. void __fastcall TLoginDialog::GenerateImages()
  174. {
  175. // Generate button images.
  176. // The button does not support alpha channel,
  177. // so we have to copy the PNG's to BMP's and use plain transparent color
  178. FButtonImageList.reset(new TImageList(this));
  179. FButtonImageList->SetSize(ActionImageList->Width, ActionImageList->Height);
  180. LoginButton->Images = FButtonImageList.get();
  181. FButtonImagesMap.clear();
  182. UpdateLoginButton();
  183. SessionImageList->BeginUpdate();
  184. try
  185. {
  186. while (SessionImageList->Count > FFixedSessionImages)
  187. {
  188. SessionImageList->Delete(SessionImageList->Count - 1);
  189. }
  190. RegenerateSessionColorsImageList(SessionImageList, SiteColorMaskImageIndex);
  191. }
  192. __finally
  193. {
  194. SessionImageList->EndUpdate();
  195. }
  196. }
  197. //---------------------------------------------------------------------
  198. void TLoginDialog::FloodFill(TBitmap * Bitmap, int X, int Y)
  199. {
  200. // A background is white, but there's also white used on the image itself.
  201. // So we first replace the background white with a unique color,
  202. // setting it as a transparent later.
  203. // This is obviously a hack specific to this particular image.
  204. // 16x16 version does not have any background
  205. if (Bitmap->Canvas->Pixels[X][Y] == clWhite)
  206. {
  207. Bitmap->Canvas->FloodFill(X, Y, clWhite, fsSurface);
  208. }
  209. }
  210. //---------------------------------------------------------------------
  211. int TLoginDialog::AddLoginButtonImage(int Index, bool Enabled)
  212. {
  213. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  214. Bitmap->SetSize(ActionImageList->Width, ActionImageList->Height);
  215. ActionImageList->Draw(Bitmap->Canvas, 0, 0, Index, Enabled);
  216. const TColor TransparentColor = clFuchsia;
  217. Bitmap->Canvas->Brush->Color = TransparentColor;
  218. FloodFill(Bitmap.get(), 0, 0);
  219. FloodFill(Bitmap.get(), Bitmap->Width - 1, Bitmap->Height - 1);
  220. FloodFill(Bitmap.get(), Bitmap->Width - 1, 0);
  221. return FButtonImageList->AddMasked(Bitmap.get(), TransparentColor);
  222. }
  223. //---------------------------------------------------------------------
  224. void __fastcall TLoginDialog::Init()
  225. {
  226. FInitialized = true;
  227. UseSystemSettingsPost(this);
  228. Caption = FormatFormCaption(this, Caption);
  229. InitControls();
  230. ReadOnlyControl(ContentsNameEdit);
  231. ReadOnlyControl(ContentsMemo);
  232. if (DebugAlwaysFalse(SessionTree->Items->Count == 0) ||
  233. ((SessionTree->Items->Count == 1) &&
  234. DebugAlwaysTrue(IsNewSiteNode(SessionTree->Items->GetFirstNode()))) ||
  235. FForceNewSite)
  236. {
  237. ActiveControl = HostNameEdit;
  238. }
  239. else
  240. {
  241. ActiveControl = SessionTree;
  242. }
  243. UpdateControls();
  244. }
  245. //---------------------------------------------------------------------
  246. TTreeNode * __fastcall TLoginDialog::AddSessionPath(UnicodeString Path,
  247. bool CanCreate, bool IsWorkspace)
  248. {
  249. TTreeNode * Parent = NULL;
  250. while (!Path.IsEmpty())
  251. {
  252. UnicodeString Folder = CutToChar(Path, L'/', false);
  253. TTreeNode * Node =
  254. ((Parent == NULL) ? SessionTree->Items->GetFirstNode() : Parent->getFirstChild());
  255. // note that we allow folder with the same name as existing session
  256. // on the same level (see also SessionTreeEdited)
  257. while ((Node != NULL) && (IsSessionNode(Node) || !AnsiSameText(Node->Text, Folder)))
  258. {
  259. Node = Node->getNextSibling();
  260. }
  261. if (Node == NULL)
  262. {
  263. if (!CanCreate)
  264. {
  265. return NULL;
  266. }
  267. else
  268. {
  269. TTreeNode * AParent = Parent;
  270. Parent = SessionTree->Items->AddChild(Parent, Folder);
  271. // once workspace, forever workspace
  272. if (!IsWorkspaceNode(Parent))
  273. {
  274. if (IsWorkspace)
  275. {
  276. SetNodeImage(Parent, WorkspaceImageIndex);
  277. }
  278. else
  279. {
  280. UpdateFolderNode(Parent);
  281. }
  282. }
  283. // optimization
  284. if (!FLoading)
  285. {
  286. // folders seem not to be sorted automatically (not having set the data property)
  287. if (AParent == NULL)
  288. {
  289. SessionTree->Items->AlphaSort();
  290. }
  291. else
  292. {
  293. AParent->AlphaSort();
  294. }
  295. }
  296. }
  297. }
  298. else
  299. {
  300. Parent = Node;
  301. }
  302. }
  303. return Parent;
  304. }
  305. //---------------------------------------------------------------------
  306. bool __fastcall TLoginDialog::IsFolderNode(TTreeNode * Node)
  307. {
  308. return (Node != NULL) && (Node->Data == NULL) && (Node->ImageIndex != WorkspaceImageIndex);
  309. }
  310. //---------------------------------------------------------------------
  311. bool __fastcall TLoginDialog::IsWorkspaceNode(TTreeNode * Node)
  312. {
  313. return (Node != NULL) && (Node->Data == NULL) && (Node->ImageIndex == WorkspaceImageIndex);
  314. }
  315. //---------------------------------------------------------------------
  316. bool __fastcall TLoginDialog::IsFolderOrWorkspaceNode(TTreeNode * Node)
  317. {
  318. return (Node != NULL) && (Node->Data == NULL);
  319. }
  320. //---------------------------------------------------------------------
  321. bool __fastcall TLoginDialog::IsSiteNode(TTreeNode * Node)
  322. {
  323. return (Node != NULL) && (Node->Data != NULL) && (Node->Data != FNewSiteData);
  324. }
  325. //---------------------------------------------------------------------
  326. bool __fastcall TLoginDialog::IsNewSiteNode(TTreeNode * Node)
  327. {
  328. return (Node != NULL) && (Node->Data != NULL) && (Node->Data == FNewSiteData);
  329. }
  330. //---------------------------------------------------------------------
  331. bool __fastcall TLoginDialog::IsSessionNode(TTreeNode * Node)
  332. {
  333. return (Node != NULL) && (Node->Data != NULL);
  334. }
  335. //---------------------------------------------------------------------
  336. TSessionData * __fastcall TLoginDialog::GetNodeSession(TTreeNode * Node)
  337. {
  338. return DebugNotNull(static_cast<TSessionData *>(Node->Data));
  339. }
  340. //---------------------------------------------------------------------
  341. TTreeNode * __fastcall TLoginDialog::AddSession(TSessionData * Data)
  342. {
  343. TTreeNode * Parent = AddSessionPath(UnixExtractFilePath(Data->Name), true, Data->IsWorkspace);
  344. TTreeNode * Node = SessionTree->Items->AddChild(Parent, UnixExtractFileName(Data->Name));
  345. Node->Data = Data;
  346. UpdateNodeImage(Node);
  347. return Node;
  348. }
  349. //---------------------------------------------------------------------------
  350. void __fastcall TLoginDialog::UpdateNodeImage(TTreeNode * Node)
  351. {
  352. SetNodeImage(Node, GetSessionImageIndex(GetNodeSession(Node)));
  353. }
  354. //---------------------------------------------------------------------
  355. int __fastcall TLoginDialog::GetSessionImageIndex(TSessionData * Data)
  356. {
  357. int Result;
  358. if (Data->Color != 0)
  359. {
  360. Result = GetSessionColorImage(SessionTree->Images, static_cast<TColor>(Data->Color), SiteColorMaskImageIndex);
  361. }
  362. else
  363. {
  364. Result = SiteImageIndex;
  365. }
  366. return Result;
  367. }
  368. //---------------------------------------------------------------------
  369. void __fastcall TLoginDialog::SetNodeImage(TTreeNode * Node, int ImageIndex)
  370. {
  371. Node->ImageIndex = ImageIndex;
  372. Node->SelectedIndex = ImageIndex;
  373. }
  374. //---------------------------------------------------------------------
  375. void __fastcall TLoginDialog::DestroySession(TSessionData * Data)
  376. {
  377. StoredSessions->Remove(Data);
  378. }
  379. //---------------------------------------------------------------------
  380. TTreeNode * __fastcall TLoginDialog::GetNewSiteNode()
  381. {
  382. TTreeNode * Result = SessionTree->Items->GetFirstNode();
  383. DebugAssert(IsNewSiteNode(Result));
  384. return Result;
  385. }
  386. //---------------------------------------------------------------------
  387. void __fastcall TLoginDialog::SetNewSiteNodeLabel()
  388. {
  389. GetNewSiteNode()->Text = LoadStr(LOGIN_NEW_SITE_NODE);
  390. }
  391. //---------------------------------------------------------------------
  392. void __fastcall TLoginDialog::LoadSessions()
  393. {
  394. {
  395. // Otherwise, once the selected node is deleted, another node is selected and we get failure
  396. // while trying to access its data somewhere in LoadContents
  397. TAutoFlag LoadingFlag(FLoading);
  398. SessionTree->Items->BeginUpdate();
  399. SessionTree->Images->BeginUpdate();
  400. try
  401. {
  402. // optimization
  403. SessionTree->SortType = Comctrls::stNone;
  404. SessionTree->Items->Clear();
  405. TTreeNode * Node = SessionTree->Items->AddChild(NULL, L"");
  406. Node->Data = FNewSiteData;
  407. SetNewSiteNodeLabel();
  408. SetNodeImage(Node, NewSiteImageIndex);
  409. DebugAssert(StoredSessions != NULL);
  410. for (int Index = 0; Index < StoredSessions->Count; Index++)
  411. {
  412. AddSession(StoredSessions->Sessions[Index]);
  413. }
  414. }
  415. __finally
  416. {
  417. // Restore sorting. Moreover, folders would not be sorted automatically even when
  418. // SortType is set (not having set the data property), so we would have to
  419. // call AlphaSort here explicitly
  420. SessionTree->SortType = Comctrls::stBoth;
  421. SessionTree->Images->EndUpdate();
  422. SessionTree->Items->EndUpdate();
  423. }
  424. }
  425. SessionTree->Selected = SessionTree->Items->GetFirstNode();
  426. UpdateControls();
  427. }
  428. //---------------------------------------------------------------------------
  429. void __fastcall TLoginDialog::UpdateFolderNode(TTreeNode * Node)
  430. {
  431. DebugAssert((Node->ImageIndex == 0) ||
  432. (Node->ImageIndex == OpenedFolderImageIndex) || (Node->ImageIndex == ClosedFolderImageIndex));
  433. SetNodeImage(Node, (Node->Expanded ? OpenedFolderImageIndex : ClosedFolderImageIndex));
  434. }
  435. //---------------------------------------------------------------------------
  436. void __fastcall TLoginDialog::NewSite()
  437. {
  438. TTreeNode * NewSiteNode = GetNewSiteNode();
  439. if (DebugAlwaysTrue(IsNewSiteNode(NewSiteNode)))
  440. {
  441. SessionTree->Selected = NewSiteNode;
  442. }
  443. LoadContents();
  444. }
  445. //---------------------------------------------------------------------------
  446. void __fastcall TLoginDialog::ResetNewSiteData()
  447. {
  448. if (DebugAlwaysTrue(StoredSessions != NULL))
  449. {
  450. FNewSiteData->CopyData(StoredSessions->DefaultSettings);
  451. }
  452. }
  453. //---------------------------------------------------------------------------
  454. void __fastcall TLoginDialog::Default()
  455. {
  456. ResetNewSiteData();
  457. NewSite();
  458. }
  459. //---------------------------------------------------------------------
  460. void __fastcall TLoginDialog::LoadContents()
  461. {
  462. bool UseContentsPanel;
  463. TTreeNode * Node = SessionTree->Selected;
  464. if (IsSessionNode(Node))
  465. {
  466. LoadSession(SelectedSession);
  467. UseContentsPanel = false;
  468. }
  469. else if (DebugAlwaysTrue(IsFolderOrWorkspaceNode(Node)))
  470. {
  471. UnicodeString NodePath = SessionNodePath(Node);
  472. ContentsNameEdit->Text = NodePath;
  473. UnicodeString CommonRoot = IsFolderNode(Node) ? UnixIncludeTrailingBackslash(NodePath) : UnicodeString();
  474. ContentsMemo->Lines->Text =
  475. GetFolderOrWorkspaceContents(Node, L"", CommonRoot);
  476. UseContentsPanel = true;
  477. if (IsFolderNode(Node))
  478. {
  479. ContentsGroupBox->Caption = LoadStr(LOGIN_SITE_FOLDER_CAPTION);
  480. }
  481. else if (DebugAlwaysTrue(IsWorkspaceNode(Node)))
  482. {
  483. ContentsGroupBox->Caption = LoadStr(LOGIN_WORKSPACE_CAPTION);
  484. }
  485. }
  486. SitePanel->Visible = !UseContentsPanel;
  487. ContentsPanel->Visible = UseContentsPanel;
  488. }
  489. //---------------------------------------------------------------------
  490. void __fastcall TLoginDialog::LoadSession(TSessionData * SessionData)
  491. {
  492. WinConfiguration->BeginMasterPasswordSession();
  493. try
  494. {
  495. PortNumberEdit->AsInteger = SessionData->PortNumber;
  496. int FtpsIndex = FtpsToIndex(SessionData->Ftps);
  497. FtpsCombo->ItemIndex = FtpsIndex;
  498. WebDavsCombo->ItemIndex = FtpsIndex;
  499. EncryptionView->Text =
  500. DebugAlwaysTrue(FtpsCombo->ItemIndex >= WebDavsCombo->ItemIndex) ? FtpsCombo->Text : WebDavsCombo->Text;
  501. bool AllowScpFallback;
  502. TransferProtocolCombo->ItemIndex = FSProtocolToIndex(SessionData->FSProtocol, AllowScpFallback);
  503. TransferProtocolView->Text = TransferProtocolCombo->Text;
  504. // Only after loading TransferProtocolCombo, so that we do not overwrite it with S3 defaults in TransferProtocolComboChange
  505. HostNameEdit->Text = SessionData->HostName;
  506. UserNameEdit->Text = SessionData->UserName;
  507. bool Editable = IsEditable();
  508. if (Editable)
  509. {
  510. PasswordEdit->Text = NormalizeString(SessionData->Password);
  511. }
  512. else
  513. {
  514. PasswordEdit->Text =
  515. SessionData->HasPassword() ?
  516. UnicodeString::StringOfChar(L'?', 16) : UnicodeString();
  517. }
  518. S3CredentialsEnvCheck3->Checked = SessionData->S3CredentialsEnv;
  519. S3ProfileCombo->Text = DefaultStr(SessionData->S3Profile, GetS3GeneralName());
  520. UpdateS3Credentials();
  521. NoteGroup->Visible = !Trim(SessionData->Note).IsEmpty();
  522. NoteMemo->Lines->Text = SessionData->Note;
  523. // just in case TransferProtocolComboChange is not triggered
  524. FDefaultPort = DefaultPort();
  525. FUpdatePortWithProtocol = true;
  526. if (SessionData != FSessionData)
  527. {
  528. // advanced
  529. InvalidateSessionData();
  530. // clone advanced settings only when really needed,
  531. // see also note in SessionAdvancedActionExecute
  532. if (Editable)
  533. {
  534. FSessionData = new TSessionData(L"");
  535. FSessionData->Assign(SessionData);
  536. }
  537. }
  538. else
  539. {
  540. // we should get here only when called from SessionAdvancedActionExecute
  541. DebugAssert(Editable);
  542. }
  543. }
  544. __finally
  545. {
  546. WinConfiguration->EndMasterPasswordSession();
  547. }
  548. UpdateControls();
  549. }
  550. //---------------------------------------------------------------------
  551. void __fastcall TLoginDialog::SaveSession(TSessionData * SessionData)
  552. {
  553. // advanced
  554. if (DebugAlwaysTrue(FSessionData != NULL))
  555. {
  556. SessionData->Assign(FSessionData);
  557. }
  558. SessionData->FSProtocol =
  559. // requiring SCP fallback distinction
  560. GetFSProtocol(true);
  561. if (SessionData->FSProtocol == fsS3)
  562. {
  563. SessionData->S3CredentialsEnv = S3CredentialsEnvCheck3->Checked;
  564. SessionData->S3Profile = GetS3Profile();
  565. }
  566. if (SessionData->HasAutoCredentials())
  567. {
  568. SessionData->UserName = UnicodeString();
  569. SessionData->Password = UnicodeString();
  570. SessionData->S3SessionToken = UnicodeString();
  571. }
  572. else
  573. {
  574. SessionData->UserName = UserNameEdit->Text.Trim();
  575. SessionData->Password = PasswordEdit->Text;
  576. }
  577. SessionData->PortNumber = PortNumberEdit->AsInteger;
  578. // Must be set after UserName, because HostName may be in format user@host,
  579. // Though now we parse the hostname right on this dialog (see HostNameEditExit), this is unlikely to ever be triggered.
  580. SessionData->HostName = HostNameEdit->Text.Trim();
  581. SessionData->Ftps = GetFtps();
  582. TSessionData * EditingSessionData = GetEditingSessionData();
  583. SessionData->Name =
  584. (EditingSessionData != NULL) ? EditingSessionData->Name :
  585. (FNewSiteKeepName ? SessionData->Name : SessionData->DefaultSessionName);
  586. }
  587. //---------------------------------------------------------------------
  588. bool __fastcall TLoginDialog::IsEditable()
  589. {
  590. return IsNewSiteNode(SessionTree->Selected) || FEditing;
  591. }
  592. //---------------------------------------------------------------------
  593. UnicodeString TLoginDialog::GetS3GeneralName()
  594. {
  595. return LoadStr(LOGIN_S3_GENERAL_CREDENTIALS);
  596. }
  597. //---------------------------------------------------------------------
  598. UnicodeString TLoginDialog::GetS3Profile()
  599. {
  600. UnicodeString Result;
  601. if (S3ProfileCombo->Text != GetS3GeneralName())
  602. {
  603. Result = S3ProfileCombo->Text;
  604. }
  605. return Result;
  606. }
  607. //---------------------------------------------------------------------
  608. void TLoginDialog::LoadS3Profiles()
  609. {
  610. std::unique_ptr<TStringList> Items(new TStringList());
  611. std::unique_ptr<TStrings> Profiles(GetS3Profiles());
  612. Items->AddStrings(Profiles.get());
  613. Items->Sort();
  614. Items->Insert(0, GetS3GeneralName());
  615. S3ProfileCombo->Items = Items.get();
  616. }
  617. //---------------------------------------------------------------------
  618. void __fastcall TLoginDialog::UpdateControls()
  619. {
  620. if (Visible && FInitialized)
  621. {
  622. bool Editable = IsEditable();
  623. TFSProtocol FSProtocol = GetFSProtocol(false);
  624. bool SshProtocol = IsSshProtocol(FSProtocol);
  625. bool FtpProtocol = (FSProtocol == fsFTP);
  626. bool WebDavProtocol = (FSProtocol == fsWebDAV);
  627. bool S3Protocol = (FSProtocol == fsS3);
  628. if (S3Protocol)
  629. {
  630. FWasEverS3 = true;
  631. }
  632. // session
  633. FtpsCombo->Visible = Editable && FtpProtocol;
  634. FtpsLabel->Visible = FtpProtocol;
  635. WebDavsCombo->Visible = Editable && (WebDavProtocol || S3Protocol);
  636. WebDavsLabel->Visible = WebDavProtocol || S3Protocol;
  637. EncryptionView->Visible = !Editable && (FtpProtocol || WebDavProtocol || S3Protocol);
  638. BasicSshPanel->Visible = SshProtocol;
  639. BasicFtpPanel->Visible = FtpProtocol && Editable;
  640. BasicS3Panel->Visible = S3Protocol && Editable;
  641. if (BasicS3Panel->Visible && (S3ProfileCombo->Items->Count == 0))
  642. {
  643. LoadS3Profiles();
  644. }
  645. // we do not support more than one at the same time
  646. DebugAssert((int(BasicSshPanel->Visible) + int(BasicFtpPanel->Visible) + int(BasicS3Panel->Visible)) <= 1);
  647. BasicGroup->Height =
  648. FBasicGroupBaseHeight +
  649. (BasicSshPanel->Visible ? BasicSshPanel->Height : 0) +
  650. (BasicFtpPanel->Visible ? BasicFtpPanel->Height : 0) +
  651. (BasicS3Panel->Visible ? BasicS3Panel->Height : 0);
  652. int NoteGroupTop = (BasicGroup->Top + BasicGroup->Height) + FNoteGroupOffset;
  653. NoteGroup->SetBounds(
  654. NoteGroup->Left, (BasicGroup->Top + BasicGroup->Height) + FNoteGroupOffset,
  655. NoteGroup->Width, NoteGroup->Top + NoteGroup->Height - NoteGroupTop);
  656. AnonymousLoginCheck->Checked =
  657. SameText(UserNameEdit->Text, AnonymousUserName) &&
  658. SameText(PasswordEdit->Text, AnonymousPassword);
  659. TransferProtocolCombo->Visible = Editable;
  660. TransferProtocolView->Visible = !TransferProtocolCombo->Visible;
  661. ReadOnlyControl(HostNameEdit, !Editable);
  662. ReadOnlyControl(PortNumberEdit, !Editable);
  663. PortNumberEdit->ButtonsVisible = Editable;
  664. // FSessionData may be NULL temporary even when Editable while switching nodes
  665. bool S3CredentialsEnv = S3Protocol && S3CredentialsEnvCheck3->Checked;
  666. bool NoAuth =
  667. Editable && (FSessionData != NULL) &&
  668. ((SshProtocol && FSessionData->SshNoUserAuth) ||
  669. S3CredentialsEnv);
  670. ReadOnlyAndEnabledControl(UserNameEdit, !Editable, !NoAuth);
  671. EnableControl(UserNameLabel, UserNameEdit->Enabled);
  672. ReadOnlyAndEnabledControl(PasswordEdit, !Editable, !NoAuth);
  673. EnableControl(PasswordLabel, PasswordEdit->Enabled);
  674. UserNameLabel->Caption = S3Protocol ? LoadStr(S3_ACCESS_KEY_ID_PROMPT) : FUserNameLabel;
  675. PasswordLabel->Caption = S3Protocol ? LoadStr(S3_SECRET_ACCESS_KEY_PROMPT) : FPasswordLabel;
  676. EnableControl(S3ProfileCombo, S3CredentialsEnv);
  677. // sites
  678. if (SitesIncrementalSearchLabel->Visible != FIncrementalSearchState.Searching)
  679. {
  680. if (!FIncrementalSearchState.Searching)
  681. {
  682. SitesIncrementalSearchLabel->Visible = false;
  683. SessionTree->Height = SitesIncrementalSearchLabel->BoundsRect.Bottom - SessionTree->Top;
  684. }
  685. else
  686. {
  687. SitesIncrementalSearchLabel->Visible = true;
  688. SessionTree->Height = SitesIncrementalSearchLabel->BoundsRect.Top - SessionTree->Top;
  689. }
  690. }
  691. if (FIncrementalSearchState.Searching)
  692. {
  693. SitesIncrementalSearchLabel->Caption = FormatIncrementalSearchStatus(FIncrementalSearchState);
  694. }
  695. EnableControl(ManageButton, !FEditing);
  696. EnableControl(ToolsMenuButton, !FEditing);
  697. EnableControl(CloseButton, !FEditing);
  698. DefaultButton(LoginButton, !FEditing && !FRenaming && !IsCloneToNewSiteDefault());
  699. CloseButton->Cancel = !FEditing && !FRenaming;
  700. DefaultButton(SaveButton, FEditing);
  701. EditCancelButton->Cancel = FEditing;
  702. SiteClonetoNewSiteMenuItem->Default = IsCloneToNewSiteDefault();
  703. SiteLoginMenuItem->Default = LoginButton->Default;
  704. UpdateButtonVisibility(SaveButton);
  705. UpdateButtonVisibility(EditButton);
  706. UpdateButtonVisibility(EditCancelButton);
  707. SaveAsSessionMenuItem->Visible = FEditing;
  708. }
  709. }
  710. //---------------------------------------------------------------------------
  711. void __fastcall TLoginDialog::UpdateButtonVisibility(TButton * Button)
  712. {
  713. TAction * Action = DebugNotNull(dynamic_cast<TAction *>(Button->Action));
  714. // when all action targets are hidden, action does not get updated,
  715. // so we need to do it manually
  716. Action->Update();
  717. // button visibility cannot be bound to action visibility,
  718. // so we do not bother setting action visibility, instead we manually
  719. // bind visibility to enabled state
  720. Button->Visible = Action->Enabled;
  721. }
  722. //---------------------------------------------------------------------------
  723. void __fastcall TLoginDialog::DataChange(TObject * /*Sender*/)
  724. {
  725. UpdateControls();
  726. }
  727. //---------------------------------------------------------------------------
  728. void __fastcall TLoginDialog::FormShow(TObject * /*Sender*/)
  729. {
  730. // this is called twice on startup, first with ControlState = [csRecreating]
  731. // we should probably filter this out, it would avoid need for explicit
  732. // LoadContents call below
  733. bool NeedInitialize = !FInitialized;
  734. if (NeedInitialize)
  735. {
  736. Init();
  737. }
  738. // WORKAROUND for a bug in the VCL layout code for bottom aligned controls
  739. // This is probably no longer needed after ComponentsPanel was removed
  740. int Offset = (SitesPanel->ClientHeight - FSiteButtonsPadding - ToolsMenuButton->Height) - ToolsMenuButton->Top;
  741. ToolsMenuButton->Top = ToolsMenuButton->Top + Offset;
  742. ManageButton->Top = ManageButton->Top + Offset;
  743. SessionTree->Height = SessionTree->Height + Offset;
  744. // Bit of a hack: Assume an auto open, when we are linked to the main form
  745. ShowAgainPanel->Visible = (FLinkedForm != NULL);
  746. // among other this makes the expanded nodes look like expanded,
  747. // because the LoadState call in Execute would be too early,
  748. // and some stray call to collapsed event during showing process,
  749. // make the image be set to collapsed.
  750. // Also LoadState calls RestoreFormSize that has to be
  751. // called only after DoFormWindowProc(CM_SHOWINGCHANGED).
  752. // See also comment about MakeVisible in LoadState().
  753. LoadState();
  754. if (NeedInitialize)
  755. {
  756. // Need to load contents only after state (as that selects initial node).
  757. // Explicit call is needed, as we get here during csRecreating phase,
  758. // when SessionTreeChange is not triggered, see initial method comment
  759. LoadContents();
  760. }
  761. UpdateControls();
  762. }
  763. //---------------------------------------------------------------------------
  764. void __fastcall TLoginDialog::SessionTreeChange(TObject * /*Sender*/,
  765. TTreeNode * /*Node*/)
  766. {
  767. if (!FLoading)
  768. {
  769. if (FIncrementalSearching <= 0)
  770. {
  771. // Make sure UpdateControls is called here, no matter what,
  772. // now it is always called from ResetSitesIncrementalSearch.
  773. // For the "else" scenario, UpdateControls is called later from SitesIncrementalSearch.
  774. ResetSitesIncrementalSearch();
  775. }
  776. if (FInitialized)
  777. {
  778. LoadContents();
  779. }
  780. }
  781. }
  782. //---------------------------------------------------------------------------
  783. TSessionData * __fastcall TLoginDialog::GetSessionData()
  784. {
  785. if (SelectedSession == FNewSiteData)
  786. {
  787. SaveSession(FNewSiteData);
  788. }
  789. return SelectedSession;
  790. }
  791. //---------------------------------------------------------------------------
  792. void __fastcall TLoginDialog::SessionTreeDblClick(TObject * /*Sender*/)
  793. {
  794. TPoint P = SessionTree->ScreenToClient(Mouse->CursorPos);
  795. TTreeNode * Node = SessionTree->GetNodeAt(P.x, P.y);
  796. // This may be false, when collapsed folder was double-clicked,
  797. // it got expanded, view was shifted to accommodate folder contents,
  798. // so that cursor now points to a different node (site).
  799. // This has to be evaluated before EnsureNotEditing,
  800. // as that may pop-up modal box.
  801. if (Node == SessionTree->Selected)
  802. {
  803. // EnsureNotEditing must be before CanOpen, as CanOpen checks for FEditing
  804. if (EnsureNotEditing())
  805. {
  806. if (IsCloneToNewSiteDefault())
  807. {
  808. CloneToNewSite();
  809. }
  810. // this can hardly be false
  811. // (after editing and clone tests above)
  812. // (except for empty folders, but those do not pass a condition below)
  813. else if (CanOpen())
  814. {
  815. if (IsSessionNode(Node) || IsWorkspaceNode(Node))
  816. {
  817. Login();
  818. }
  819. }
  820. }
  821. }
  822. }
  823. //---------------------------------------------------------------------------
  824. TSessionData * __fastcall TLoginDialog::GetSelectedSession()
  825. {
  826. // Selected can be temporarily NULL, e.g. while deleting selected node
  827. TTreeNode * Node = SessionTree->Selected;
  828. if ((Node != NULL) &&
  829. (IsSiteNode(Node) || IsNewSiteNode(Node)))
  830. {
  831. return GetNodeSession(Node);
  832. }
  833. else
  834. {
  835. return NULL;
  836. }
  837. }
  838. //---------------------------------------------------------------------------
  839. void __fastcall TLoginDialog::SessionTreeKeyDown(TObject * /*Sender*/,
  840. WORD & Key, TShiftState /*Shift*/)
  841. {
  842. if (!SessionTree->IsEditing())
  843. {
  844. if (Key == VK_DELETE)
  845. {
  846. DeleteSessionAction->Execute();
  847. Key = 0;
  848. }
  849. else if (Key == VK_F2)
  850. {
  851. RenameSessionAction->Execute();
  852. Key = 0;
  853. }
  854. else if (Key == VK_BACK)
  855. {
  856. Key = 0;
  857. }
  858. }
  859. }
  860. //---------------------------------------------------------------------------
  861. void __fastcall TLoginDialog::SessionTreeKeyPress(TObject * /*Sender*/, System::WideChar & Key)
  862. {
  863. if (!SessionTree->IsEditing())
  864. {
  865. // filter control sequences
  866. if (Key >= VK_SPACE)
  867. {
  868. if (!FIncrementalSearchState.Searching)
  869. {
  870. Configuration->Usage->Inc(L"SiteIncrementalSearches");
  871. }
  872. if (!SitesIncrementalSearch(FIncrementalSearchState.Text + Key, false, false, false))
  873. {
  874. MessageBeep(MB_ICONHAND);
  875. }
  876. Key = 0;
  877. }
  878. else if (Key == VK_BACK)
  879. {
  880. if (FIncrementalSearchState.Searching)
  881. {
  882. if (FIncrementalSearchState.Text.Length() <= 1)
  883. {
  884. ResetSitesIncrementalSearch();
  885. }
  886. else
  887. {
  888. UnicodeString NewText = LeftStr(FIncrementalSearchState.Text, FIncrementalSearchState.Text.Length() - 1);
  889. SitesIncrementalSearch(NewText, false, false, false);
  890. }
  891. Key = 0;
  892. }
  893. }
  894. else if ((Key == VK_RETURN) && IsCloneToNewSiteDefault())
  895. {
  896. CloneToNewSite();
  897. Key = 0;
  898. }
  899. }
  900. }
  901. //---------------------------------------------------------------------------
  902. void __fastcall TLoginDialog::EditSession()
  903. {
  904. HostNameEdit->SetFocus();
  905. }
  906. //---------------------------------------------------------------------------
  907. void __fastcall TLoginDialog::EditSessionActionExecute(TObject * /*Sender*/)
  908. {
  909. if (DebugAlwaysTrue(SelectedSession != NULL))
  910. {
  911. FEditing = true;
  912. EditSession();
  913. // reload session, to make sure we load decrypted password
  914. LoadContents();
  915. UpdateControls();
  916. }
  917. }
  918. //---------------------------------------------------------------------------
  919. TTreeNode * __fastcall TLoginDialog::FindSessionNode(TSessionData * SessionData, bool ByName)
  920. {
  921. TTreeNode * Node = SessionTree->Items->GetFirstNode();
  922. while (
  923. (Node != NULL) &&
  924. ((!ByName && (Node->Data != SessionData)) ||
  925. (ByName && (!IsSiteNode(Node) || (GetNodeSession(Node)->Name != SessionData->Name)))))
  926. {
  927. Node = Node->GetNext();
  928. }
  929. return Node;
  930. }
  931. //---------------------------------------------------------------------------
  932. TSessionData * __fastcall TLoginDialog::GetEditingSessionData()
  933. {
  934. return FEditing ? DebugNotNull(SelectedSession) : NULL;
  935. }
  936. //---------------------------------------------------------------------------
  937. void __fastcall TLoginDialog::SaveAsSession(bool ForceDialog)
  938. {
  939. // Parse hostname before saving
  940. // (HostNameEditExit is not triggered when child dialog pops up when it is invoked by accelerator)
  941. // We should better handle this automaticaly when focus is moved to another dialog.
  942. ParseHostName();
  943. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  944. SaveSession(SessionData.get());
  945. TSessionData * EditingSessionData = GetEditingSessionData();
  946. // collect list of empty folders (these are not persistent and known to login dialog only)
  947. std::unique_ptr<TStrings> NewFolders(new TStringList());
  948. TTreeNode * Node = SessionTree->Items->GetFirstNode();
  949. while (Node != NULL)
  950. {
  951. if (IsFolderNode(Node) && !Node->HasChildren)
  952. {
  953. NewFolders->Add(SessionNodePath(Node));
  954. }
  955. Node = Node->GetNext();
  956. }
  957. TSessionData * NewSession =
  958. DoSaveSession(SessionData.get(), EditingSessionData, ForceDialog, NewFolders.get());
  959. if (NewSession != NULL)
  960. {
  961. TTreeNode * ParentNode = AddSessionPath(UnixExtractFilePath(NewSession->SessionName), false, false);
  962. CheckIsSessionFolder(ParentNode);
  963. TTreeNode * Node = FindSessionNode(NewSession, false);
  964. if (Node == NULL)
  965. {
  966. Node = AddSession(NewSession);
  967. }
  968. if ((SessionTree->Selected != Node) &&
  969. IsSiteNode(SessionTree->Selected))
  970. {
  971. CancelEditing();
  972. }
  973. else
  974. {
  975. FEditing = false;
  976. }
  977. SessionTree->Selected = Node;
  978. SessionTree->SetFocus();
  979. // this
  980. // - updates TransferProtocolView and EncryptionView
  981. // - clears the password box, if user has not opted to save password
  982. // - reloads fake password
  983. LoadContents();
  984. UpdateControls();
  985. ResetNewSiteData();
  986. }
  987. }
  988. //---------------------------------------------------------------------------
  989. void __fastcall TLoginDialog::SaveSessionActionExecute(TObject * /*Sender*/)
  990. {
  991. bool NewSiteSelected = IsNewSiteNode(SessionTree->Selected);
  992. // for new site, the "save" command is actually "save as"
  993. SaveAsSession(NewSiteSelected);
  994. }
  995. //---------------------------------------------------------------------------
  996. void __fastcall TLoginDialog::SaveAsSessionActionExecute(TObject * /*Sender*/)
  997. {
  998. SaveAsSession(true);
  999. }
  1000. //---------------------------------------------------------------------------
  1001. UnicodeString __fastcall TLoginDialog::SessionNodePath(TTreeNode * Node)
  1002. {
  1003. UnicodeString Path;
  1004. if ((Node != NULL) && !IsNewSiteNode(Node))
  1005. {
  1006. Path = Node->Text;
  1007. Node = Node->Parent;
  1008. while (Node != NULL)
  1009. {
  1010. Path.Insert(UnixIncludeTrailingBackslash(Node->Text), 1);
  1011. Node = Node->Parent;
  1012. }
  1013. }
  1014. return Path;
  1015. }
  1016. //---------------------------------------------------------------------------
  1017. void __fastcall TLoginDialog::DeleteSessionActionExecute(TObject * /*Sender*/)
  1018. {
  1019. DebugAssert(SessionTree->Selected != NULL);
  1020. TMessageParams Params;
  1021. Params.ImageName = L"Delete file";
  1022. TTreeNode * Node = SessionTree->Selected;
  1023. if (IsSiteNode(Node))
  1024. {
  1025. TSessionData * Session = SelectedSession;
  1026. UnicodeString Message = MainInstructions(FMTLOAD(CONFIRM_DELETE_SESSION, (Session->SessionName)));
  1027. if (MessageDialog(Message,
  1028. qtConfirmation, qaOK | qaCancel, HELP_DELETE_SESSION, &Params) == qaOK)
  1029. {
  1030. try
  1031. {
  1032. WinConfiguration->DeleteSessionFromJumpList(Session->SessionName);
  1033. }
  1034. catch (Exception & E)
  1035. {
  1036. ShowExtendedException(&E);
  1037. }
  1038. Session->Remove();
  1039. DestroySession(Session);
  1040. SessionTree->Selected->Delete();
  1041. }
  1042. }
  1043. else if (IsFolderNode(Node) || IsWorkspaceNode(Node))
  1044. {
  1045. int Sessions = 0;
  1046. TTreeNode * ANode = Node->GetNext();
  1047. while ((ANode != NULL) && ANode->HasAsParent(Node))
  1048. {
  1049. if (IsSessionNode(ANode))
  1050. {
  1051. TSessionData * Session = GetNodeSession(ANode);
  1052. if (Session->Special)
  1053. {
  1054. SessionTree->Selected = ANode;
  1055. ANode->MakeVisible();
  1056. throw Exception(FMTLOAD(LOGIN_DELETE_SPECIAL_SESSION, (Session->SessionName)));
  1057. }
  1058. Sessions++;
  1059. }
  1060. ANode = ANode->GetNext();
  1061. }
  1062. UnicodeString Path = SessionNodePath(Node);
  1063. int Prompt;
  1064. UnicodeString HelpKeyword;
  1065. if (IsFolderNode(Node))
  1066. {
  1067. Prompt = LOGIN_DELETE_SESSION_FOLDER;
  1068. HelpKeyword = HELP_DELETE_SESSION_FOLDER;
  1069. }
  1070. else
  1071. {
  1072. Prompt = LOGIN_DELETE_WORKSPACE;
  1073. HelpKeyword = HELP_DELETE_WORKSPACE;
  1074. }
  1075. if ((Sessions == 0) ||
  1076. (MessageDialog(MainInstructions(FMTLOAD(Prompt, (Path, Sessions))),
  1077. qtConfirmation, qaOK | qaCancel, HelpKeyword, &Params) == qaOK))
  1078. {
  1079. if (IsWorkspaceNode(Node))
  1080. {
  1081. try
  1082. {
  1083. WinConfiguration->DeleteWorkspaceFromJumpList(Path);
  1084. }
  1085. catch (Exception & E)
  1086. {
  1087. ShowExtendedException(&E);
  1088. }
  1089. }
  1090. Node = SessionTree->Selected;
  1091. TTreeNode * ANode = Node->GetNext();
  1092. while ((ANode != NULL) && ANode->HasAsParent(Node))
  1093. {
  1094. if (IsSessionNode(ANode))
  1095. {
  1096. TSessionData * Session = GetNodeSession(ANode);
  1097. Session->Remove();
  1098. DestroySession(Session);
  1099. }
  1100. ANode = ANode->GetNext();
  1101. }
  1102. SessionTree->Selected->Delete();
  1103. }
  1104. }
  1105. }
  1106. //---------------------------------------------------------------------------
  1107. void __fastcall TLoginDialog::ReloadSessions(const UnicodeString & SelectSite)
  1108. {
  1109. SaveState();
  1110. if (!SelectSite.IsEmpty())
  1111. {
  1112. WinConfiguration->LastStoredSession = SelectSite;
  1113. }
  1114. LoadSessions();
  1115. LoadState();
  1116. }
  1117. //---------------------------------------------------------------------------
  1118. void __fastcall TLoginDialog::ImportSessionsActionExecute(TObject * /*Sender*/)
  1119. {
  1120. std::unique_ptr<TList> Imported(new TList());
  1121. if (DoImportSessionsDialog(Imported.get()) &&
  1122. // Can be empty when imported known_hosts
  1123. (Imported->Count > 0))
  1124. {
  1125. // Focus the first imported session.
  1126. // We should also consider expanding all newly created folders
  1127. UnicodeString SelectSite = static_cast<TSessionData *>(Imported->Items[0])->Name;
  1128. ReloadSessions(SelectSite);
  1129. // Focus the tree with focused imported session(s).
  1130. SessionTree->SetFocus();
  1131. }
  1132. }
  1133. //---------------------------------------------------------------------------
  1134. void __fastcall TLoginDialog::CleanUpActionExecute(TObject * /*Sender*/)
  1135. {
  1136. if (DoCleanupDialog())
  1137. {
  1138. SaveState();
  1139. LoadSessions();
  1140. LoadState();
  1141. }
  1142. }
  1143. //---------------------------------------------------------------------------
  1144. void __fastcall TLoginDialog::AboutActionExecute(TObject * /*Sender*/)
  1145. {
  1146. DoAboutDialog(Configuration);
  1147. }
  1148. //---------------------------------------------------------------------------
  1149. void __fastcall TLoginDialog::ActionListUpdate(TBasicAction * BasicAction,
  1150. bool &Handled)
  1151. {
  1152. bool SiteSelected = IsSiteNode(SessionTree->Selected);
  1153. bool FolderOrWorkspaceSelected = IsFolderOrWorkspaceNode(SessionTree->Selected);
  1154. bool WorkspaceSelected = IsWorkspaceNode(SessionTree->Selected);
  1155. TAction * Action = DebugNotNull(dynamic_cast<TAction *>(BasicAction));
  1156. bool PrevEnabled = Action->Enabled;
  1157. bool Editable = IsEditable();
  1158. if ((Action == EditSessionAction) ||
  1159. (Action == CloneToNewSiteAction))
  1160. {
  1161. Action->Enabled = SiteSelected && !FEditing;
  1162. }
  1163. else if (Action == EditCancelAction)
  1164. {
  1165. EditCancelAction->Enabled = FEditing;
  1166. }
  1167. else if (Action == DeleteSessionAction)
  1168. {
  1169. DeleteSessionAction->Enabled =
  1170. ((SiteSelected && !SelectedSession->Special && !FEditing) ||
  1171. FolderOrWorkspaceSelected);
  1172. }
  1173. else if (Action == RenameSessionAction)
  1174. {
  1175. RenameSessionAction->Enabled =
  1176. ((SiteSelected && !SelectedSession->Special && !FEditing) ||
  1177. FolderOrWorkspaceSelected);
  1178. }
  1179. else if (Action == DesktopIconAction)
  1180. {
  1181. DesktopIconAction->Enabled =
  1182. (SiteSelected && !FEditing) ||
  1183. (FolderOrWorkspaceSelected && HasNodeAnySession(SessionTree->Selected));
  1184. }
  1185. else if (Action == SendToHookAction)
  1186. {
  1187. SendToHookAction->Enabled = SiteSelected && !FEditing;
  1188. }
  1189. else if (Action == LoginAction)
  1190. {
  1191. LoginAction->Enabled = CanOpen();
  1192. LoginAction->Caption = FolderOrWorkspaceSelected ? LoadStr(LOGIN_OPEN) : LoadStr(LOGIN_LOGIN);
  1193. LoginAction->ImageIndex = FolderOrWorkspaceSelected ? (WorkspaceSelected ? OpenWorkspaceImageIndex : OpenFolderImageIndex) : LoginImageIndex;
  1194. UpdateLoginButton();
  1195. }
  1196. else if (Action == PuttyAction)
  1197. {
  1198. TSessionData * Data = GetSessionData();
  1199. Action->Enabled =
  1200. (IsSiteAndCanOpen() && !Data->IsLocalBrowser && !Data->Tunnel) ||
  1201. (IsFolderOrWorkspaceAndCanOpen() && IsFolderNode(SessionTree->Selected));
  1202. }
  1203. else if (Action == SaveSessionAction)
  1204. {
  1205. SaveSessionAction->Enabled = Editable;
  1206. }
  1207. else if (Action == SessionAdvancedAction)
  1208. {
  1209. SessionAdvancedAction->Enabled = Editable;
  1210. }
  1211. else if (Action == SessionRawAction)
  1212. {
  1213. SessionRawAction->Enabled = Editable;
  1214. }
  1215. else if (Action == SaveAsSessionAction)
  1216. {
  1217. // Save as is needed for new site only when !SupportsSplitButton()
  1218. SaveAsSessionAction->Enabled = Editable;
  1219. }
  1220. else if (Action == NewSessionFolderAction)
  1221. {
  1222. NewSessionFolderAction->Enabled = !FEditing;
  1223. }
  1224. else if (Action == PasteUrlAction)
  1225. {
  1226. UnicodeString ClipboardUrl;
  1227. Action->Enabled =
  1228. NonEmptyTextFromClipboard(ClipboardUrl) &&
  1229. StoredSessions->IsUrl(ClipboardUrl);
  1230. }
  1231. else if (Action == GenerateUrlAction2)
  1232. {
  1233. TSessionData * Data = GetSessionData();
  1234. // URL without hostname is pointless
  1235. Action->Enabled = (Data != NULL) && !Data->HostNameExpanded.IsEmpty() && !FEditing;
  1236. }
  1237. else if (Action == CopyParamRuleAction)
  1238. {
  1239. TSessionData * Data = GetSessionData();
  1240. // without hostname it's pointless
  1241. Action->Enabled = (Data != NULL) && !Data->HostNameExpanded.IsEmpty();
  1242. }
  1243. else if (Action == SearchSiteStartAction)
  1244. {
  1245. Action->Enabled = !SessionTree->IsEditing() && !FEditing;
  1246. }
  1247. else if (Action == SearchSiteNameStartOnlyAction)
  1248. {
  1249. Action->Checked = (FSiteSearch == isNameStartOnly);
  1250. }
  1251. else if (Action == SearchSiteNameAction)
  1252. {
  1253. Action->Checked = (FSiteSearch == isName);
  1254. }
  1255. else if (Action == SearchSiteAction)
  1256. {
  1257. Action->Checked = (FSiteSearch == isAll);
  1258. }
  1259. else if (Action == CheckForUpdatesAction)
  1260. {
  1261. Action->Visible = !IsUWP();
  1262. }
  1263. Handled = true;
  1264. // to update buttons visibility
  1265. if (PrevEnabled != Action->Enabled)
  1266. {
  1267. UpdateControls();
  1268. }
  1269. Idle();
  1270. }
  1271. //---------------------------------------------------------------------------
  1272. bool __fastcall TLoginDialog::IsCloneToNewSiteDefault()
  1273. {
  1274. return !FEditing && !FRenaming && IsSiteNode(SessionTree->Selected) && !StoredSessions->CanOpen(GetSessionData());
  1275. }
  1276. //---------------------------------------------------------------------------
  1277. bool TLoginDialog::IsSiteAndCanOpen()
  1278. {
  1279. TSessionData * Data = GetSessionData();
  1280. return
  1281. ((Data != NULL) && StoredSessions->CanOpen(Data) && !FEditing);
  1282. }
  1283. //---------------------------------------------------------------------------
  1284. bool TLoginDialog::IsFolderOrWorkspaceAndCanOpen()
  1285. {
  1286. return IsFolderOrWorkspaceNode(SessionTree->Selected) && HasNodeAnySession(SessionTree->Selected, true);
  1287. }
  1288. //---------------------------------------------------------------------------
  1289. bool __fastcall TLoginDialog::CanOpen()
  1290. {
  1291. return
  1292. IsSiteAndCanOpen() ||
  1293. IsFolderOrWorkspaceAndCanOpen();
  1294. }
  1295. //---------------------------------------------------------------------------
  1296. void __fastcall TLoginDialog::Idle()
  1297. {
  1298. if (SessionTree->IsEditing() != FRenaming)
  1299. {
  1300. FRenaming = SessionTree->IsEditing();
  1301. UpdateControls();
  1302. }
  1303. }
  1304. //---------------------------------------------------------------------------
  1305. bool __fastcall TLoginDialog::Execute(TList * DataList)
  1306. {
  1307. FDataList = DataList;
  1308. if (DataList->Count > 0)
  1309. {
  1310. TSessionData * SessionData = reinterpret_cast<TSessionData * >(DataList->Items[0]);
  1311. TTreeNode * Node = FindSessionNode(SessionData, true);
  1312. if (Node != NULL)
  1313. {
  1314. SessionTree->Selected = Node;
  1315. ActiveControl = SessionTree;
  1316. }
  1317. else
  1318. {
  1319. FNewSiteData->CopyData(SessionData);
  1320. FNewSiteData->Special = false;
  1321. if (!FNewSiteData->IsSameDecrypted(StoredSessions->DefaultSettings))
  1322. {
  1323. // we want to start with new site page
  1324. FForceNewSite = true;
  1325. }
  1326. LoadContents();
  1327. }
  1328. }
  1329. else
  1330. {
  1331. Default();
  1332. }
  1333. // Optimization. List view is recreated while showing the form,
  1334. // causing nodes repopulation and in a consequence a huge number of
  1335. // nodes comparison
  1336. SessionTree->SortType = Comctrls::stNone;
  1337. FSortEnablePending = true;
  1338. // Not calling LoadState here.
  1339. // It's redundant and does not work anyway, see comment in the method.
  1340. int AResult = ShowModal();
  1341. // When CanOpen is false, the DefaultResult() will fail finding a default button.
  1342. bool Result = CanOpen() && (AResult == DefaultResult());
  1343. SaveState();
  1344. if (Result)
  1345. {
  1346. SaveConfiguration();
  1347. // DataList saved already from FormCloseQuery
  1348. }
  1349. if (!ShowAgainCheck->Checked)
  1350. {
  1351. WinConfiguration->ShowLoginWhenNoSession = false;
  1352. }
  1353. return Result;
  1354. }
  1355. //---------------------------------------------------------------------------
  1356. void __fastcall TLoginDialog::SaveDataList(TList * DataList)
  1357. {
  1358. // Normally we would call this from Execute,
  1359. // but at that point the windows is already hidden.
  1360. // Cloning session data may pop up master password dialog:
  1361. // - if it happens between closing and destroying login dialog
  1362. // the next window will appear in background for some reason
  1363. // - and its actually even nicer when master password dialog pops up over
  1364. // the login dialog
  1365. DataList->Clear();
  1366. TTreeNode * Node = SessionTree->Selected;
  1367. if (IsFolderOrWorkspaceNode(Node))
  1368. {
  1369. UnicodeString Name = SessionNodePath(Node);
  1370. if (IsWorkspaceNode(Node))
  1371. {
  1372. try
  1373. {
  1374. WinConfiguration->AddWorkspaceToJumpList(Name);
  1375. }
  1376. catch (Exception & E)
  1377. {
  1378. ShowExtendedException(&E);
  1379. }
  1380. }
  1381. StoredSessions->GetFolderOrWorkspace(Name, DataList);
  1382. }
  1383. else
  1384. {
  1385. ParseHostName();
  1386. DataList->Add(CloneSelectedSession());
  1387. }
  1388. }
  1389. //---------------------------------------------------------------------------
  1390. TSessionData * __fastcall TLoginDialog::CloneSelectedSession()
  1391. {
  1392. TTreeNode * Node = SessionTree->Selected;
  1393. std::unique_ptr<TSessionData> Data2(new TSessionData(L""));
  1394. if (IsSiteNode(Node))
  1395. {
  1396. Data2->Assign(GetNodeSession(Node));
  1397. }
  1398. else if (DebugAlwaysTrue(IsNewSiteNode(Node)))
  1399. {
  1400. TSessionData * Data = GetSessionData();
  1401. Data2->Assign(Data);
  1402. // we carry the name of the edited stored session around while on the dialog,
  1403. // but we do not want it to leave the dialog, so that we can distinguish
  1404. // stored and ad-hoc sessions
  1405. Data2->Name = L"";
  1406. }
  1407. return Data2.release();
  1408. }
  1409. //---------------------------------------------------------------------------
  1410. void __fastcall TLoginDialog::SaveState()
  1411. {
  1412. DebugAssert(WinConfiguration != NULL);
  1413. WinConfiguration->BeginUpdate();
  1414. try
  1415. {
  1416. std::unique_ptr<TStringList> OpenedStoredSessionFolders(CreateSortedStringList());
  1417. for (int Index = 0; Index < SessionTree->Items->Count; Index++)
  1418. {
  1419. TTreeNode * Node = SessionTree->Items->Item[Index];
  1420. if (IsFolderNode(Node))
  1421. {
  1422. if (Node->Expanded)
  1423. {
  1424. OpenedStoredSessionFolders->Add(SessionNodePath(Node));
  1425. }
  1426. }
  1427. }
  1428. WinConfiguration->OpenedStoredSessionFolders = OpenedStoredSessionFolders->CommaText;
  1429. UnicodeString LastStoredSession = SessionNodePath(SessionTree->Selected);
  1430. if (IsFolderNode(SessionTree->Selected))
  1431. {
  1432. LastStoredSession = UnixIncludeTrailingBackslash(LastStoredSession);
  1433. }
  1434. WinConfiguration->LastStoredSession = LastStoredSession;
  1435. TLoginDialogConfiguration DialogConfiguration = CustomWinConfiguration->LoginDialog;
  1436. DialogConfiguration.WindowSize = StoreFormSize(this);
  1437. DialogConfiguration.SiteSearch = FSiteSearch;
  1438. CustomWinConfiguration->LoginDialog = DialogConfiguration;
  1439. }
  1440. __finally
  1441. {
  1442. WinConfiguration->EndUpdate();
  1443. }
  1444. }
  1445. //---------------------------------------------------------------------------
  1446. void __fastcall TLoginDialog::LoadOpenedStoredSessionFolders(
  1447. TTreeNode * Node, TStrings * OpenedStoredSessionFolders)
  1448. {
  1449. if (IsFolderNode(Node))
  1450. {
  1451. UnicodeString Path = SessionNodePath(Node);
  1452. if (OpenedStoredSessionFolders->IndexOf(Path) >= 0)
  1453. {
  1454. Node->Expand(false);
  1455. UpdateFolderNode(Node);
  1456. }
  1457. }
  1458. }
  1459. //---------------------------------------------------------------------------
  1460. void __fastcall TLoginDialog::LoadState()
  1461. {
  1462. // it does not make any sense to call this before
  1463. // DoFormWindowProc(CM_SHOWINGCHANGED), we would end up on wrong monitor
  1464. if (DebugAlwaysTrue(Visible))
  1465. {
  1466. RestoreFormSize(CustomWinConfiguration->LoginDialog.WindowSize, this);
  1467. }
  1468. FSiteSearch = CustomWinConfiguration->LoginDialog.SiteSearch;
  1469. TStringList * OpenedStoredSessionFolders = CreateSortedStringList();
  1470. try
  1471. {
  1472. OpenedStoredSessionFolders->CommaText = WinConfiguration->OpenedStoredSessionFolders;
  1473. for (int Index = 0; Index < SessionTree->Items->Count; Index++)
  1474. {
  1475. LoadOpenedStoredSessionFolders(
  1476. SessionTree->Items->Item[Index], OpenedStoredSessionFolders);
  1477. }
  1478. // tree view tries to make expanded node children all visible, what
  1479. // may scroll the selected node (what should be the first one here),
  1480. // out of the view
  1481. if (SessionTree->Selected != NULL)
  1482. {
  1483. // see comment for LastStoredSession branch below
  1484. DebugAssert(Visible);
  1485. SessionTree->Selected->MakeVisible();
  1486. }
  1487. }
  1488. __finally
  1489. {
  1490. delete OpenedStoredSessionFolders;
  1491. }
  1492. // calling TTreeNode::MakeVisible() when tree view is not visible yet,
  1493. // sometimes scrolls view horizontally when not needed
  1494. // (seems like it happens for sites that are at the same level
  1495. // as site folders, e.g. for the very last root-level site, as long as
  1496. // there are any folders)
  1497. if (!FForceNewSite &&
  1498. !WinConfiguration->LastStoredSession.IsEmpty() && DebugAlwaysTrue(Visible))
  1499. {
  1500. UnicodeString Path = UnixExcludeTrailingBackslash(WinConfiguration->LastStoredSession);
  1501. bool Folder = (Path != WinConfiguration->LastStoredSession);
  1502. UnicodeString ParentPath = UnixExtractFilePath(Path);
  1503. TTreeNode * Node;
  1504. if (ParentPath.IsEmpty())
  1505. {
  1506. Node = SessionTree->Items->GetFirstNode();
  1507. }
  1508. else
  1509. {
  1510. TTreeNode * Parent = AddSessionPath(ParentPath, false, false);
  1511. Node = (Parent != NULL) ? Parent->getFirstChild() : NULL;
  1512. }
  1513. if (Node != NULL)
  1514. {
  1515. UnicodeString Name = UnixExtractFileName(Path);
  1516. while ((Node != NULL) && (!SameText(Node->Text, Name) || (IsFolderNode(Node) != Folder)))
  1517. {
  1518. Node = Node->getNextSibling();
  1519. }
  1520. if (Node != NULL)
  1521. {
  1522. SessionTree->Selected = Node;
  1523. SessionTree->Selected->MakeVisible();
  1524. }
  1525. }
  1526. }
  1527. }
  1528. //---------------------------------------------------------------------------
  1529. void __fastcall TLoginDialog::SaveConfiguration()
  1530. {
  1531. DebugAssert(CustomWinConfiguration);
  1532. TTreeNode * Node = SessionTree->Selected;
  1533. if (IsWorkspaceNode(Node))
  1534. {
  1535. WinConfiguration->LastWorkspace = SessionNodePath(Node);
  1536. }
  1537. }
  1538. //---------------------------------------------------------------------------
  1539. void __fastcall TLoginDialog::PreferencesActionExecute(TObject * /*Sender*/)
  1540. {
  1541. ShowPreferencesDialog(::pmDefault);
  1542. }
  1543. //---------------------------------------------------------------------------
  1544. void __fastcall TLoginDialog::PreferencesLoggingActionExecute(TObject * /*Sender*/)
  1545. {
  1546. ShowPreferencesDialog(pmLogging);
  1547. }
  1548. //---------------------------------------------------------------------------
  1549. void __fastcall TLoginDialog::MasterPasswordRecrypt(TObject * /*Sender*/)
  1550. {
  1551. FNewSiteData->RecryptPasswords();
  1552. }
  1553. //---------------------------------------------------------------------------
  1554. void __fastcall TLoginDialog::ShowPreferencesDialog(TPreferencesMode PreferencesMode)
  1555. {
  1556. DebugAssert(CustomWinConfiguration->OnMasterPasswordRecrypt == NULL);
  1557. CustomWinConfiguration->OnMasterPasswordRecrypt = MasterPasswordRecrypt;
  1558. try
  1559. {
  1560. DoPreferencesDialog(PreferencesMode);
  1561. }
  1562. __finally
  1563. {
  1564. DebugAssert(CustomWinConfiguration->OnMasterPasswordRecrypt == MasterPasswordRecrypt);
  1565. CustomWinConfiguration->OnMasterPasswordRecrypt = NULL;
  1566. }
  1567. UpdateControls();
  1568. }
  1569. //---------------------------------------------------------------------------
  1570. void __fastcall TLoginDialog::ResetNewSessionActionExecute(TObject * /*Sender*/)
  1571. {
  1572. Default();
  1573. EditSession();
  1574. FNewSiteKeepName = false;
  1575. }
  1576. //---------------------------------------------------------------------------
  1577. void __fastcall TLoginDialog::CMDialogKey(TWMKeyDown & Message)
  1578. {
  1579. if (Message.CharCode == VK_TAB)
  1580. {
  1581. if (!FIncrementalSearchState.Text.IsEmpty())
  1582. {
  1583. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  1584. bool Reverse = Shift.Contains(ssShift);
  1585. if (!SitesIncrementalSearch(FIncrementalSearchState.Text, true, Reverse, true))
  1586. {
  1587. MessageBeep(MB_ICONHAND);
  1588. }
  1589. Message.Result = 1;
  1590. return;
  1591. }
  1592. }
  1593. else if (Message.CharCode == VK_ESCAPE)
  1594. {
  1595. if (FIncrementalSearchState.Searching)
  1596. {
  1597. ResetSitesIncrementalSearch();
  1598. Message.Result = 1;
  1599. return;
  1600. }
  1601. }
  1602. TForm::Dispatch(&Message);
  1603. }
  1604. //---------------------------------------------------------------------------
  1605. void __fastcall TLoginDialog::WMWindowPosChanged(TWMWindowPosChanged & Message)
  1606. {
  1607. TForm::Dispatch(&Message);
  1608. if (FLAGCLEAR(Message.WindowPos->flags, SWP_NOMOVE) && (FLinkedForm != NULL))
  1609. {
  1610. if (FPrevPos.X == std::numeric_limits<LONG>::min())
  1611. {
  1612. FPrevPos = BoundsRect.TopLeft();
  1613. }
  1614. TPoint P = TPoint(Message.WindowPos->x, Message.WindowPos->y);
  1615. if (FPrevPos != P)
  1616. {
  1617. if (!FRestoring)
  1618. {
  1619. FLinkedForm->SetBounds(
  1620. FLinkedForm->Left + (P.X - FPrevPos.X),
  1621. FLinkedForm->Top + (P.Y - FPrevPos.Y),
  1622. FLinkedForm->Width, FLinkedForm->Height);
  1623. }
  1624. FPrevPos = P;
  1625. }
  1626. }
  1627. }
  1628. //---------------------------------------------------------------------------
  1629. void __fastcall TLoginDialog::CMVisibleChanged(TMessage & Message)
  1630. {
  1631. TAutoFlag RestoringSwitch(FRestoring);
  1632. TForm::Dispatch(&Message);
  1633. }
  1634. //---------------------------------------------------------------------------
  1635. void __fastcall TLoginDialog::CMDpiChanged(TMessage & Message)
  1636. {
  1637. TForm::Dispatch(&Message);
  1638. GenerateImages();
  1639. CenterButtonImage(LoginButton);
  1640. AutoSizeCheckBox(ShowAgainCheck);
  1641. }
  1642. //---------------------------------------------------------------------------
  1643. void __fastcall TLoginDialog::Dispatch(void * Message)
  1644. {
  1645. TMessage * M = reinterpret_cast<TMessage*>(Message);
  1646. DebugAssert(M);
  1647. if (M->Msg == CM_DIALOGKEY)
  1648. {
  1649. CMDialogKey(*((TWMKeyDown *)Message));
  1650. }
  1651. else if (M->Msg == WM_MANAGES_CAPTION)
  1652. {
  1653. // caption managed in TLoginDialog::Init()
  1654. M->Result = 1;
  1655. }
  1656. else if (M->Msg == WM_WANTS_MOUSEWHEEL)
  1657. {
  1658. M->Result = 1;
  1659. }
  1660. else if (M->Msg == WM_CAN_DISPLAY_UPDATES)
  1661. {
  1662. M->Result = 1;
  1663. }
  1664. else if (M->Msg == CM_ACTIVATE)
  1665. {
  1666. // Called from TCustomForm.ShowModal
  1667. if (FSortEnablePending)
  1668. {
  1669. FSortEnablePending = false;
  1670. SessionTree->SortType = Comctrls::stBoth;
  1671. }
  1672. TForm::Dispatch(Message);
  1673. }
  1674. else if (M->Msg == WM_SYSCOMMAND)
  1675. {
  1676. if (!HandleMinimizeSysCommand(*M))
  1677. {
  1678. TForm::Dispatch(Message);
  1679. }
  1680. }
  1681. else if (M->Msg == WM_WINDOWPOSCHANGED)
  1682. {
  1683. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosChanged *>(M));
  1684. }
  1685. else if (M->Msg == CM_VISIBLECHANGED)
  1686. {
  1687. CMVisibleChanged(*M);
  1688. }
  1689. else if (M->Msg == CM_DPICHANGED)
  1690. {
  1691. CMDpiChanged(*M);
  1692. }
  1693. else
  1694. {
  1695. TForm::Dispatch(Message);
  1696. }
  1697. }
  1698. //---------------------------------------------------------------------------
  1699. void __fastcall TLoginDialog::SetDefaultSessionActionExecute(
  1700. TObject * /*Sender*/)
  1701. {
  1702. UnicodeString Message = MainInstructions(LoadStr(SET_DEFAULT_SESSION_SETTINGS));
  1703. if (MessageDialog(Message, qtConfirmation,
  1704. qaOK | qaCancel, HELP_SESSION_SAVE_DEFAULT) == qaOK)
  1705. {
  1706. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  1707. SaveSession(SessionData.get());
  1708. // See the comment to the other use of the method in DoSaveSession.
  1709. CustomWinConfiguration->AskForMasterPasswordIfNotSetAndNeededToPersistSessionData(SessionData.get());
  1710. StoredSessions->DefaultSettings = SessionData.get();
  1711. Default();
  1712. }
  1713. }
  1714. //---------------------------------------------------------------------------
  1715. void __fastcall TLoginDialog::ToolsMenuButtonClick(TObject * /*Sender*/)
  1716. {
  1717. MenuPopup(ToolsPopupMenu, ToolsMenuButton);
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. void __fastcall TLoginDialog::DesktopIconActionExecute(TObject * /*Sender*/)
  1721. {
  1722. TTreeNode * Node = SessionTree->Selected;
  1723. UnicodeString Message;
  1724. UnicodeString Name;
  1725. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  1726. int IconIndex = 0;
  1727. if (IsSiteNode(Node))
  1728. {
  1729. Name = GetNodeSession(Node)->Name;
  1730. Message = FMTLOAD(CONFIRM_CREATE_SHORTCUT, (Name));
  1731. AddToList(AdditionalParams, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), L" ");
  1732. IconIndex = SITE_ICON;
  1733. }
  1734. else if (IsFolderNode(Node))
  1735. {
  1736. Name = SessionNodePath(SessionTree->Selected);
  1737. Message = FMTLOAD(CONFIRM_CREATE_SHORTCUT_FOLDER, (Name));
  1738. IconIndex = SITE_FOLDER_ICON;
  1739. }
  1740. else if (IsWorkspaceNode(Node))
  1741. {
  1742. Name = SessionNodePath(SessionTree->Selected);
  1743. Message = FMTLOAD(CONFIRM_CREATE_SHORTCUT_WORKSPACE, (Name));
  1744. IconIndex = WORKSPACE_ICON;
  1745. }
  1746. else
  1747. {
  1748. DebugFail();
  1749. }
  1750. Message = MainInstructions(Message);
  1751. if (MessageDialog(Message, qtConfirmation, qaYes | qaNo, HELP_CREATE_SHORTCUT) == qaYes)
  1752. {
  1753. TInstantOperationVisualizer Visualizer;
  1754. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, IconIndex);
  1755. }
  1756. }
  1757. //---------------------------------------------------------------------------
  1758. void __fastcall TLoginDialog::SendToHookActionExecute(TObject * /*Sender*/)
  1759. {
  1760. DebugAssert(IsSiteNode(SessionTree->Selected));
  1761. DebugAssert(SelectedSession != NULL);
  1762. UnicodeString Message = MainInstructions(FMTLOAD(CONFIRM_CREATE_SENDTO, (SelectedSession->Name)));
  1763. if (MessageDialog(Message,
  1764. qtConfirmation, qaYes | qaNo, HELP_CREATE_SENDTO) == qaYes)
  1765. {
  1766. TInstantOperationVisualizer Visualizer;
  1767. UnicodeString AdditionalParams =
  1768. TProgramParams::FormatSwitch(SEND_TO_HOOK_SWITCH) + L" " +
  1769. TProgramParams::FormatSwitch(UPLOAD_SWITCH);
  1770. CreateDesktopSessionShortCut(SelectedSession->Name,
  1771. FMTLOAD(SESSION_SENDTO_HOOK_NAME2, (SelectedSession->LocalName, AppName)),
  1772. AdditionalParams,
  1773. CSIDL_SENDTO, SITE_ICON);
  1774. }
  1775. }
  1776. //---------------------------------------------------------------------------
  1777. bool __fastcall TLoginDialog::HasNodeAnySession(TTreeNode * Node, bool NeedCanOpen)
  1778. {
  1779. bool Result = false;
  1780. TTreeNode * ANode = Node->GetNext();
  1781. while (!Result && (ANode != NULL) && ANode->HasAsParent(Node))
  1782. {
  1783. Result =
  1784. IsSessionNode(ANode) &&
  1785. (!NeedCanOpen || StoredSessions->CanOpen(GetNodeSession(ANode)));
  1786. ANode = ANode->GetNext();
  1787. }
  1788. return Result;
  1789. }
  1790. //---------------------------------------------------------------------------
  1791. void __fastcall TLoginDialog::SessionTreeCustomDrawItem(
  1792. TCustomTreeView * Sender, TTreeNode * Node, TCustomDrawState State,
  1793. bool & DefaultDraw)
  1794. {
  1795. TFontStyles Styles = Sender->Canvas->Font->Style;
  1796. if (IsSessionNode(Node) && GetNodeSession(Node)->Special)
  1797. {
  1798. Styles = Styles << fsBold << fsUnderline;
  1799. }
  1800. else
  1801. {
  1802. Styles = Styles >> fsBold >> fsUnderline;
  1803. }
  1804. if (State.Empty() && !Node->DropTarget)
  1805. {
  1806. if (IsFolderOrWorkspaceNode(Node))
  1807. {
  1808. if (!HasNodeAnySession(Node))
  1809. {
  1810. Sender->Canvas->Font->Color = clGrayText;
  1811. }
  1812. }
  1813. }
  1814. Sender->Canvas->Font->Style = Styles;
  1815. DefaultDraw = true;
  1816. }
  1817. //---------------------------------------------------------------------------
  1818. void __fastcall TLoginDialog::CheckForUpdatesActionExecute(TObject * /*Sender*/)
  1819. {
  1820. CheckForUpdates(false);
  1821. }
  1822. //---------------------------------------------------------------------------
  1823. void __fastcall TLoginDialog::HelpButtonClick(TObject * /*Sender*/)
  1824. {
  1825. FormHelp(this);
  1826. }
  1827. //---------------------------------------------------------------------------
  1828. TModalResult __fastcall TLoginDialog::DefaultResult()
  1829. {
  1830. return ::DefaultResult(this, LoginButton);
  1831. }
  1832. //---------------------------------------------------------------------------
  1833. void __fastcall TLoginDialog::FormCloseQuery(TObject * /*Sender*/,
  1834. bool & CanClose)
  1835. {
  1836. // CanClose test is now probably redundant,
  1837. // once we have a fallback to LoginButton in DefaultResult
  1838. CanClose = EnsureNotEditing();
  1839. // When CanOpen is false, the DefaultResult() will fail finding a default button
  1840. if (CanClose && CanOpen() && (ModalResult == DefaultResult()))
  1841. {
  1842. SaveDataList(FDataList);
  1843. }
  1844. }
  1845. //---------------------------------------------------------------------------
  1846. void __fastcall TLoginDialog::SessionTreeEditing(TObject * /*Sender*/,
  1847. TTreeNode * Node, bool & AllowEdit)
  1848. {
  1849. DebugAssert(!FRenaming);
  1850. AllowEdit =
  1851. !FEditing &&
  1852. (IsFolderOrWorkspaceNode(Node) ||
  1853. (DebugAlwaysTrue(IsSiteNode(Node)) && !GetNodeSession(Node)->Special));
  1854. FRenaming = AllowEdit;
  1855. UpdateControls();
  1856. }
  1857. //---------------------------------------------------------------------------
  1858. void __fastcall TLoginDialog::RenameSessionActionExecute(TObject * /*Sender*/)
  1859. {
  1860. if (SessionTree->Selected != NULL)
  1861. {
  1862. // would be more appropriate in SessionTreeEditing, but it does not work there
  1863. ResetSitesIncrementalSearch();
  1864. SessionTree->SetFocus();
  1865. SessionTree->Selected->EditText();
  1866. }
  1867. }
  1868. //---------------------------------------------------------------------------
  1869. void __fastcall TLoginDialog::CheckDuplicateFolder(TTreeNode * Parent,
  1870. UnicodeString Text, TTreeNode * Node)
  1871. {
  1872. TTreeNode * ANode =
  1873. ((Parent == NULL) ? SessionTree->Items->GetFirstNode() :
  1874. Parent->getFirstChild());
  1875. // note that we allow folder with the same name as existing session
  1876. // on the same level (see also AddSession)
  1877. while ((ANode != NULL) &&
  1878. ((ANode == Node) || IsSessionNode(ANode) || !AnsiSameText(ANode->Text, Text)))
  1879. {
  1880. ANode = ANode->getNextSibling();
  1881. }
  1882. if (ANode != NULL)
  1883. {
  1884. throw Exception(MainInstructions(FMTLOAD(LOGIN_DUPLICATE_SESSION_FOLDER_WORKSPACE, (Text))));
  1885. }
  1886. }
  1887. //---------------------------------------------------------------------------
  1888. void __fastcall TLoginDialog::CheckIsSessionFolder(TTreeNode * Node)
  1889. {
  1890. if ((Node != NULL) && (Node->Parent != NULL))
  1891. {
  1892. CheckIsSessionFolder(Node->Parent);
  1893. }
  1894. if (IsWorkspaceNode(Node))
  1895. {
  1896. throw Exception(FMTLOAD(WORKSPACE_NOT_FOLDER, (SessionNodePath(Node))));
  1897. }
  1898. }
  1899. //---------------------------------------------------------------------------
  1900. void __fastcall TLoginDialog::SessionTreeEdited(TObject * /*Sender*/,
  1901. TTreeNode * Node, UnicodeString & S)
  1902. {
  1903. if ((Node->Text != S) && !S.IsEmpty())
  1904. {
  1905. TSessionData * Session = SelectedSession;
  1906. TSessionData::ValidateName(S);
  1907. if (Session != NULL)
  1908. {
  1909. UnicodeString Path = UnixExtractFilePath(Session->Name) + S;
  1910. SessionNameValidate(Path, Session->Name);
  1911. // remove from storage
  1912. Session->Remove();
  1913. TSessionData * NewSession = StoredSessions->NewSession(Path, Session);
  1914. // modified only, explicit
  1915. StoredSessions->Save(false, true);
  1916. // the session may be the same, if only letter case has changed
  1917. if (Session != NewSession)
  1918. {
  1919. // if we overwrite existing session, remove the original item
  1920. // (we must not delete the node we are editing)
  1921. TTreeNode * ANode =
  1922. ((Node->Parent == NULL) ? SessionTree->Items->GetFirstNode() :
  1923. Node->Parent->getFirstChild());
  1924. while ((ANode != NULL) && (ANode->Data != NewSession))
  1925. {
  1926. ANode = ANode->getNextSibling();
  1927. }
  1928. if (ANode != NULL)
  1929. {
  1930. ANode->Delete();
  1931. }
  1932. Node->Data = NewSession;
  1933. DestroySession(Session);
  1934. }
  1935. }
  1936. else
  1937. {
  1938. CheckDuplicateFolder(Node->Parent, S, Node);
  1939. UnicodeString ParentPath = UnixIncludeTrailingBackslash(SessionNodePath(Node->Parent));
  1940. UnicodeString OldRoot = ParentPath + Node->Text;
  1941. UnicodeString NewRoot = ParentPath + S;
  1942. bool AnySession = false;
  1943. TSortType PrevSortType = SessionTree->SortType;
  1944. // temporarily disable automatic sorting, so that nodes are kept in order
  1945. // while we traverse them. otherwise it may happen that we omit some.
  1946. SessionTree->SortType = Comctrls::stNone;
  1947. try
  1948. {
  1949. TTreeNode * ANode = Node->GetNext();
  1950. while ((ANode != NULL) && ANode->HasAsParent(Node))
  1951. {
  1952. if (IsSessionNode(ANode))
  1953. {
  1954. AnySession = true;
  1955. TSessionData * Session = GetNodeSession(ANode);
  1956. // remove from storage
  1957. Session->Remove();
  1958. UnicodeString Path = Session->Name;
  1959. DebugAssert(Path.SubString(1, OldRoot.Length()) == OldRoot);
  1960. Path.Delete(1, OldRoot.Length());
  1961. Path.Insert(NewRoot, 1);
  1962. TSessionData * NewSession = StoredSessions->NewSession(Path, Session);
  1963. // the session may be the same, if only letter case has changed
  1964. if (NewSession != Session)
  1965. {
  1966. ANode->Data = NewSession;
  1967. DestroySession(Session);
  1968. }
  1969. }
  1970. ANode = ANode->GetNext();
  1971. }
  1972. }
  1973. __finally
  1974. {
  1975. SessionTree->SortType = PrevSortType;
  1976. }
  1977. if (AnySession)
  1978. {
  1979. // modified only, explicit
  1980. StoredSessions->Save(false, true);
  1981. }
  1982. }
  1983. }
  1984. }
  1985. //---------------------------------------------------------------------------
  1986. int __fastcall TLoginDialog::FSProtocolToIndex(TFSProtocol FSProtocol,
  1987. bool & AllowScpFallback)
  1988. {
  1989. if (FSProtocol == fsSFTP)
  1990. {
  1991. AllowScpFallback = true;
  1992. bool Dummy;
  1993. return FSProtocolToIndex(fsSFTPonly, Dummy);
  1994. }
  1995. else
  1996. {
  1997. AllowScpFallback = false;
  1998. for (int Index = 0; Index < TransferProtocolCombo->Items->Count; Index++)
  1999. {
  2000. if (FSOrder[Index] == FSProtocol)
  2001. {
  2002. return Index;
  2003. }
  2004. }
  2005. // SFTP is always present
  2006. return FSProtocolToIndex(fsSFTP, AllowScpFallback);
  2007. }
  2008. }
  2009. //---------------------------------------------------------------------------
  2010. TFSProtocol __fastcall TLoginDialog::IndexToFSProtocol(int Index, bool AllowScpFallback)
  2011. {
  2012. bool InBounds = (Index >= 0) && (Index < static_cast<int>(LENOF(FSOrder)));
  2013. // can be temporary "unselected" while new language is being loaded
  2014. DebugAssert(InBounds || (Index == -1));
  2015. TFSProtocol Result = fsSFTP;
  2016. if (InBounds)
  2017. {
  2018. Result = FSOrder[Index];
  2019. if ((Result == fsSFTPonly) && AllowScpFallback)
  2020. {
  2021. Result = fsSFTP;
  2022. }
  2023. }
  2024. return Result;
  2025. }
  2026. //---------------------------------------------------------------------------
  2027. int __fastcall TLoginDialog::FtpsToIndex(TFtps Ftps)
  2028. {
  2029. switch (Ftps)
  2030. {
  2031. default:
  2032. DebugFail();
  2033. case ftpsNone:
  2034. return 0;
  2035. case ftpsImplicit:
  2036. return 1;
  2037. case ftpsExplicitTls:
  2038. case ftpsExplicitSsl:
  2039. return 2;
  2040. }
  2041. }
  2042. //---------------------------------------------------------------------------
  2043. TFtps __fastcall TLoginDialog::GetFtps()
  2044. {
  2045. TFSProtocol FSProtocol = GetFSProtocol(false);
  2046. int Index = (((FSProtocol == fsWebDAV) || (FSProtocol == fsS3)) ? WebDavsCombo->ItemIndex : FtpsCombo->ItemIndex);
  2047. TFtps Ftps;
  2048. switch (Index)
  2049. {
  2050. default:
  2051. DebugFail();
  2052. case 0:
  2053. Ftps = ftpsNone;
  2054. break;
  2055. case 1:
  2056. Ftps = ftpsImplicit;
  2057. break;
  2058. case 2:
  2059. Ftps = ftpsExplicitTls;
  2060. break;
  2061. }
  2062. return Ftps;
  2063. }
  2064. //---------------------------------------------------------------------------
  2065. TFSProtocol __fastcall TLoginDialog::GetFSProtocol(bool RequireScpFallbackDistinction)
  2066. {
  2067. bool AllowScpFallback = false;
  2068. if (RequireScpFallbackDistinction && DebugAlwaysTrue(FSessionData != NULL))
  2069. {
  2070. FSProtocolToIndex(FSessionData->FSProtocol, AllowScpFallback);
  2071. }
  2072. return IndexToFSProtocol(TransferProtocolCombo->ItemIndex, AllowScpFallback);
  2073. }
  2074. //---------------------------------------------------------------------------
  2075. int __fastcall TLoginDialog::DefaultPort()
  2076. {
  2077. return ::DefaultPort(GetFSProtocol(false), GetFtps());
  2078. }
  2079. //---------------------------------------------------------------------------
  2080. void TLoginDialog::UpdateS3Credentials()
  2081. {
  2082. if (S3CredentialsEnvCheck3->Checked)
  2083. {
  2084. UnicodeString S3Profile = GetS3Profile();
  2085. UserNameEdit->Text = S3EnvUserName(S3Profile);
  2086. PasswordEdit->Text = S3EnvPassword(S3Profile);
  2087. // Is not set when viewing stored session.
  2088. // We do this, so that when the checkbox is checked and unchecked, the token is preserved, the way username and password are.
  2089. if (FSessionData != NULL)
  2090. {
  2091. FSessionData->S3SessionToken = S3EnvSessionToken(S3Profile);
  2092. FSessionData->S3RoleArn = S3EnvRoleArn(S3Profile);
  2093. }
  2094. }
  2095. }
  2096. //---------------------------------------------------------------------------
  2097. void __fastcall TLoginDialog::TransferProtocolComboChange(TObject * Sender)
  2098. {
  2099. if (!NoUpdate)
  2100. {
  2101. if (GetFSProtocol(false) == fsS3)
  2102. {
  2103. // Note that this happens even when loading the session
  2104. // But the values will get overwritten.
  2105. WebDavsCombo->ItemIndex = FtpsToIndex(ftpsImplicit);
  2106. HostNameEdit->Text = S3HostName;
  2107. }
  2108. else
  2109. {
  2110. try
  2111. {
  2112. UnicodeString S3Profile = GetS3Profile();
  2113. if (HostNameEdit->Text == S3HostName)
  2114. {
  2115. HostNameEdit->Clear();
  2116. }
  2117. // Optimization to avoid querying AWS metadata service.
  2118. // Smarter would be to tell S3EnvXXX functions not to do expensive queries.
  2119. if (FWasEverS3)
  2120. {
  2121. if (UserNameEdit->Text == S3EnvUserName(S3Profile))
  2122. {
  2123. UserNameEdit->Clear();
  2124. }
  2125. if (PasswordEdit->Text == S3EnvPassword(S3Profile))
  2126. {
  2127. PasswordEdit->Clear();
  2128. }
  2129. if (FSessionData != NULL)
  2130. {
  2131. if (FSessionData->S3SessionToken == S3EnvSessionToken(S3Profile))
  2132. {
  2133. FSessionData->S3SessionToken = EmptyStr;
  2134. }
  2135. if (FSessionData->S3RoleArn == S3EnvRoleArn(S3Profile))
  2136. {
  2137. FSessionData->S3RoleArn = EmptyStr;
  2138. }
  2139. }
  2140. }
  2141. }
  2142. catch (...)
  2143. {
  2144. // noop
  2145. }
  2146. }
  2147. S3CredentialsEnvCheck3->Checked = false;
  2148. }
  2149. UpdatePortWithProtocol();
  2150. DataChange(Sender);
  2151. }
  2152. //---------------------------------------------------------------------------
  2153. void TLoginDialog::UpdatePortWithProtocol()
  2154. {
  2155. int ADefaultPort = DefaultPort();
  2156. if (!NoUpdate && FUpdatePortWithProtocol)
  2157. {
  2158. NoUpdate++;
  2159. try
  2160. {
  2161. if (PortNumberEdit->AsInteger == FDefaultPort)
  2162. {
  2163. PortNumberEdit->AsInteger = ADefaultPort;
  2164. }
  2165. }
  2166. __finally
  2167. {
  2168. NoUpdate--;
  2169. }
  2170. }
  2171. FDefaultPort = ADefaultPort;
  2172. }
  2173. //---------------------------------------------------------------------------
  2174. void __fastcall TLoginDialog::EncryptionComboChange(TObject * Sender)
  2175. {
  2176. UpdatePortWithProtocol();
  2177. DataChange(Sender);
  2178. }
  2179. //---------------------------------------------------------------------------
  2180. void __fastcall TLoginDialog::NavigationTreeCollapsing(
  2181. TObject * /*Sender*/, TTreeNode * /*Node*/, bool & AllowCollapse)
  2182. {
  2183. AllowCollapse = false;
  2184. }
  2185. //---------------------------------------------------------------------------
  2186. void __fastcall TLoginDialog::SessionTreeExpandedCollapsed(TObject * /*Sender*/,
  2187. TTreeNode * Node)
  2188. {
  2189. UpdateFolderNode(Node);
  2190. }
  2191. //---------------------------------------------------------------------------
  2192. void __fastcall TLoginDialog::SessionTreeCompare(TObject * /*Sender*/,
  2193. TTreeNode * Node1, TTreeNode * Node2, int /*Data*/, int & Compare)
  2194. {
  2195. bool Node1IsNewSite = IsNewSiteNode(Node1);
  2196. bool Node2IsNewSite = IsNewSiteNode(Node2);
  2197. bool Node1IsWorkspace = IsWorkspaceNode(Node1);
  2198. bool Node2IsWorkspace = IsWorkspaceNode(Node2);
  2199. bool Node1IsFolder = IsFolderNode(Node1);
  2200. bool Node2IsFolder = IsFolderNode(Node2);
  2201. if (Node1IsNewSite && !Node2IsNewSite)
  2202. {
  2203. Compare = -1;
  2204. }
  2205. else if (!Node1IsNewSite && Node2IsNewSite)
  2206. {
  2207. Compare = 1;
  2208. }
  2209. else if (Node1IsWorkspace && !Node2IsWorkspace)
  2210. {
  2211. Compare = -1;
  2212. }
  2213. else if (!Node1IsWorkspace && Node2IsWorkspace)
  2214. {
  2215. Compare = 1;
  2216. }
  2217. else if (Node1IsFolder && !Node2IsFolder)
  2218. {
  2219. Compare = -1;
  2220. }
  2221. else if (!Node1IsFolder && Node2IsFolder)
  2222. {
  2223. Compare = 1;
  2224. }
  2225. else if (Node1IsWorkspace || Node1IsFolder)
  2226. {
  2227. Compare = CompareLogicalText(Node1->Text, Node2->Text, true);
  2228. }
  2229. else
  2230. {
  2231. Compare = NamedObjectSortProc(Node1->Data, Node2->Data);
  2232. }
  2233. }
  2234. //---------------------------------------------------------------------------
  2235. void __fastcall TLoginDialog::NewSessionFolderInputDialogInitialize(
  2236. TObject * /*Sender*/, TInputDialogData * Data)
  2237. {
  2238. TCustomEdit * Edit = Data->Edit;
  2239. int P = Edit->Text.LastDelimiter(L"/");
  2240. if (P > 0)
  2241. {
  2242. Edit->SetFocus();
  2243. Edit->SelStart = P;
  2244. Edit->SelLength = Edit->Text.Length() - P;
  2245. }
  2246. }
  2247. //---------------------------------------------------------------------------
  2248. TTreeNode * __fastcall TLoginDialog::SessionFolderNode(TTreeNode * Node)
  2249. {
  2250. TTreeNode * Parent;
  2251. if (IsSessionNode(Node))
  2252. {
  2253. Parent = Node->Parent;
  2254. }
  2255. else if (IsFolderNode(Node))
  2256. {
  2257. Parent = Node;
  2258. }
  2259. else if (IsWorkspaceNode(Node))
  2260. {
  2261. Parent = NULL;
  2262. }
  2263. else
  2264. {
  2265. DebugAssert(Node == NULL);
  2266. Parent = NULL;
  2267. }
  2268. return Parent;
  2269. }
  2270. //---------------------------------------------------------------------------
  2271. TTreeNode * __fastcall TLoginDialog::CurrentSessionFolderNode()
  2272. {
  2273. return SessionFolderNode(SessionTree->Selected);
  2274. }
  2275. //---------------------------------------------------------------------------
  2276. void __fastcall TLoginDialog::NewSessionFolderActionExecute(
  2277. TObject * /*Sender*/)
  2278. {
  2279. UnicodeString Name =
  2280. UnixIncludeTrailingBackslash(SessionNodePath(CurrentSessionFolderNode())) +
  2281. LoadStr(NEW_FOLDER);
  2282. if (InputDialog(LoadStr(LOGIN_NEW_SESSION_FOLDER_CAPTION),
  2283. LoadStr(LOGIN_NEW_SESSION_FOLDER_PROMPT), Name, HELP_NEW_SESSION_FOLDER,
  2284. NULL, true, NewSessionFolderInputDialogInitialize))
  2285. {
  2286. Name = UnixExcludeTrailingBackslash(Name);
  2287. if (!Name.IsEmpty())
  2288. {
  2289. TTreeNode * Parent = AddSessionPath(UnixExtractFilePath(Name), true, false);
  2290. // this does not prevent creation of subfolder under workspace,
  2291. // if user creates more levels at once (but it does not show up anyway)
  2292. CheckIsSessionFolder(Parent);
  2293. CheckDuplicateFolder(Parent, UnixExtractFileName(Name), NULL);
  2294. TTreeNode * Node = AddSessionPath(Name, true, false);
  2295. SessionTree->Selected = Node;
  2296. Node->MakeVisible();
  2297. }
  2298. }
  2299. }
  2300. //---------------------------------------------------------------------------
  2301. TTreeNode * __fastcall TLoginDialog::NormalizeDropTarget(TTreeNode * DropTarget)
  2302. {
  2303. return IsWorkspaceNode(DropTarget) ? DropTarget : SessionFolderNode(DropTarget);
  2304. }
  2305. //---------------------------------------------------------------------------
  2306. bool __fastcall TLoginDialog::SessionAllowDrop(TTreeNode * DropTarget)
  2307. {
  2308. DropTarget = NormalizeDropTarget(DropTarget);
  2309. return
  2310. (SessionTree->Selected != NULL) &&
  2311. (SessionTree->Selected->Parent != DropTarget) &&
  2312. ((DropTarget == NULL) || IsFolderNode(DropTarget));
  2313. }
  2314. //---------------------------------------------------------------------------
  2315. void __fastcall TLoginDialog::SessionTreeProc(TMessage & AMessage)
  2316. {
  2317. if (AMessage.Msg == CM_DRAG)
  2318. {
  2319. TCMDrag & Message = reinterpret_cast<TCMDrag &>(AMessage);
  2320. // reimplement dmDragMove to avoid TCustomTreeView.DoDragOver,
  2321. // which resets DropTarget to pointed-to node
  2322. // (note that this disables OnDragOver event handler)
  2323. if ((Message.DragMessage == dmDragMove) ||
  2324. (Message.DragMessage == dmDragEnter) ||
  2325. (Message.DragMessage == dmDragLeave))
  2326. {
  2327. if (Message.DragMessage != dmDragMove)
  2328. {
  2329. // must call it at least for dmDragLeave, because it does some cleanup,
  2330. // but we need to override result below, as it defaults to "not accepted"
  2331. FOldSessionTreeProc(AMessage);
  2332. }
  2333. TDragControlObject * DragObject = dynamic_cast<TDragControlObject *>(Message.DragRec->Source);
  2334. if ((DragObject != NULL) && (DragObject->Control == SessionTree))
  2335. {
  2336. TPoint P = SessionTree->ScreenToClient(Message.DragRec->Pos);
  2337. TTreeNode * Node = SessionTree->GetNodeAt(P.x, P.y);
  2338. if (!SessionAllowDrop(Node))
  2339. {
  2340. DropTarget = NULL;
  2341. Message.Result = 0;
  2342. }
  2343. else
  2344. {
  2345. Message.Result = 1;
  2346. }
  2347. if (Message.DragMessage == dmDragMove)
  2348. {
  2349. SessionTree->DropTarget = NormalizeDropTarget(Node);
  2350. }
  2351. FScrollOnDragOver->DragOver(P);
  2352. }
  2353. else
  2354. {
  2355. Message.Result = 0;
  2356. }
  2357. }
  2358. else
  2359. {
  2360. FOldSessionTreeProc(AMessage);
  2361. }
  2362. }
  2363. else
  2364. {
  2365. FOldSessionTreeProc(AMessage);
  2366. }
  2367. }
  2368. //---------------------------------------------------------------------------
  2369. void __fastcall TLoginDialog::SessionTreeStartDrag(TObject * /*Sender*/,
  2370. TDragObject *& /*DragObject*/)
  2371. {
  2372. DebugAssert(SessionTree->Selected != NULL);
  2373. // neither session folders/workspaces, nor special sessions can be dragged
  2374. if ((SessionTree->Selected == NULL) ||
  2375. IsFolderOrWorkspaceNode(SessionTree->Selected) ||
  2376. IsNewSiteNode(SessionTree->Selected) ||
  2377. (IsSiteNode(SessionTree->Selected) && SelectedSession->Special))
  2378. {
  2379. Abort();
  2380. }
  2381. FScrollOnDragOver->StartDrag();
  2382. }
  2383. //---------------------------------------------------------------------------
  2384. void __fastcall TLoginDialog::SessionTreeDragDrop(TObject * Sender,
  2385. TObject * Source, int /*X*/, int /*Y*/)
  2386. {
  2387. TTreeNode * DropTarget = SessionTree->DropTarget;
  2388. if (DebugAlwaysTrue((Sender == Source) && SessionAllowDrop(DropTarget)) &&
  2389. // calling EnsureNotEditing only on drop, not on drag start,
  2390. // to avoid getting popup during unintended micro-dragging
  2391. EnsureNotEditing())
  2392. {
  2393. TSessionData * Session = SelectedSession;
  2394. UnicodeString Path =
  2395. UnixIncludeTrailingBackslash(SessionNodePath(DropTarget)) +
  2396. UnixExtractFileName(Session->SessionName);
  2397. SessionNameValidate(Path, Session->SessionName);
  2398. // remove from storage
  2399. Session->Remove();
  2400. TSessionData * NewSession = StoredSessions->NewSession(Path, Session);
  2401. // modified only, explicit
  2402. StoredSessions->Save(false, true);
  2403. // this should aways be the case
  2404. if (DebugAlwaysTrue(Session != NewSession))
  2405. {
  2406. TTreeNode * Node = SessionTree->Selected;
  2407. // look for overwritten node (if any)
  2408. TTreeNode * ANode = SessionTree->Items->GetFirstNode();
  2409. while (ANode != NULL)
  2410. {
  2411. if (ANode->Data == NewSession)
  2412. {
  2413. ANode->Delete();
  2414. break;
  2415. }
  2416. ANode = ANode->GetNext();
  2417. }
  2418. Node->MoveTo(DropTarget, naAddChild);
  2419. Node->Data = NewSession;
  2420. // try to make both visible
  2421. if (DropTarget != NULL)
  2422. {
  2423. DropTarget->MakeVisible();
  2424. }
  2425. Node->MakeVisible();
  2426. DestroySession(Session);
  2427. }
  2428. }
  2429. }
  2430. //---------------------------------------------------------------------------
  2431. UnicodeString __fastcall TLoginDialog::GetFolderOrWorkspaceContents(
  2432. TTreeNode * Node, const UnicodeString & Indent, const UnicodeString & CommonRoot)
  2433. {
  2434. UnicodeString Contents;
  2435. UnicodeString Path = SessionNodePath(Node);
  2436. std::unique_ptr<TStrings> Names(StoredSessions->GetFolderOrWorkspaceList(Path));
  2437. for (int Index = 0; Index < Names->Count; Index++)
  2438. {
  2439. UnicodeString Name = Names->Strings[Index];
  2440. if (StartsStr(CommonRoot, Name))
  2441. {
  2442. Name.Delete(1, CommonRoot.Length());
  2443. }
  2444. Contents += Indent + Name + L"\n";
  2445. }
  2446. return Contents;
  2447. }
  2448. //---------------------------------------------------------------------------
  2449. void __fastcall TLoginDialog::SessionTreeMouseMove(TObject * /*Sender*/,
  2450. TShiftState /*Shift*/, int X, int Y)
  2451. {
  2452. TTreeNode * Node = SessionTree->GetNodeAt(X, Y);
  2453. THitTests HitTest = SessionTree->GetHitTestInfoAt(X, Y);
  2454. if (Node != FHintNode)
  2455. {
  2456. Application->CancelHint();
  2457. UnicodeString Hint;
  2458. if (HitTest.Contains(htOnItem) || HitTest.Contains(htOnIcon) ||
  2459. HitTest.Contains(htOnLabel) || HitTest.Contains(htOnStateIcon))
  2460. {
  2461. FHintNode = Node;
  2462. if (IsSiteNode(Node))
  2463. {
  2464. Hint = GetNodeSession(Node)->InfoTip;
  2465. }
  2466. else if (IsWorkspaceNode(Node))
  2467. {
  2468. UnicodeString Path = SessionNodePath(Node);
  2469. Hint =
  2470. FMTLOAD(WORKSPACE_INFO_TIP, (Path)) + L"\n" +
  2471. // trim the trailing new line
  2472. TrimRight(GetFolderOrWorkspaceContents(Node, L" ", UnicodeString()));
  2473. }
  2474. else
  2475. {
  2476. Hint = L"";
  2477. }
  2478. }
  2479. else
  2480. {
  2481. FHintNode = NULL;
  2482. Hint = L"";
  2483. }
  2484. SessionTree->Hint = Hint;
  2485. }
  2486. }
  2487. //---------------------------------------------------------------------------
  2488. void __fastcall TLoginDialog::SessionTreeEndDrag(TObject * /*Sender*/,
  2489. TObject * /*Target*/, int /*X*/, int /*Y*/)
  2490. {
  2491. FScrollOnDragOver->EndDrag();
  2492. }
  2493. //---------------------------------------------------------------------------
  2494. void __fastcall TLoginDialog::AnonymousLoginCheckClick(TObject * /*Sender*/)
  2495. {
  2496. if (AnonymousLoginCheck->Checked)
  2497. {
  2498. UserNameEdit->Text = AnonymousUserName;
  2499. PasswordEdit->Text = AnonymousPassword;
  2500. }
  2501. UpdateControls();
  2502. }
  2503. //---------------------------------------------------------------------------
  2504. void __fastcall TLoginDialog::SaveButtonDropDownClick(TObject * /*Sender*/)
  2505. {
  2506. MenuPopup(SaveDropDownMenu, SaveButton);
  2507. }
  2508. //---------------------------------------------------------------------------
  2509. void __fastcall TLoginDialog::SessionTreeExpanding(TObject * /*Sender*/,
  2510. TTreeNode * Node, bool & AllowExpansion)
  2511. {
  2512. // to prevent workspace expansion
  2513. AllowExpansion = IsFolderNode(Node);
  2514. }
  2515. //---------------------------------------------------------------------------
  2516. void __fastcall TLoginDialog::RunPageantActionExecute(TObject * /*Sender*/)
  2517. {
  2518. ExecuteTool(PageantTool);
  2519. }
  2520. //---------------------------------------------------------------------------
  2521. void __fastcall TLoginDialog::RunPuttygenActionExecute(TObject * /*Sender*/)
  2522. {
  2523. ExecuteTool(PuttygenTool);
  2524. }
  2525. //---------------------------------------------------------------------------
  2526. void __fastcall TLoginDialog::PortNumberEditChange(TObject * Sender)
  2527. {
  2528. if (!NoUpdate)
  2529. {
  2530. bool WellKnownPort = false;
  2531. TFSProtocol FSProtocol;
  2532. TFtps Ftps = ftpsNone;
  2533. // For ambiguous port numbers, keep the current protocol, even if it is not the default protocol for the port
  2534. // (e.g. HTTPS vs S3 or FTP vs FTPES).
  2535. // So for example, when user selects FTPES and then types 2121 port, the protocol is not reset to FTP,
  2536. // once partial 21 is entered
  2537. TFSProtocol CurrentFSProtocol = GetFSProtocol(false);
  2538. int PortNumber = PortNumberEdit->AsInteger;
  2539. if (PortNumber == SshPortNumber)
  2540. {
  2541. FSProtocol = fsSFTP;
  2542. WellKnownPort = true;
  2543. }
  2544. else if (PortNumber == FtpPortNumber)
  2545. {
  2546. FSProtocol = fsFTP;
  2547. if ((CurrentFSProtocol == FSProtocol) && (GetFtps() == ftpsExplicitTls))
  2548. {
  2549. Ftps = ftpsExplicitTls;
  2550. }
  2551. WellKnownPort = true;
  2552. }
  2553. else if (PortNumber == FtpsImplicitPortNumber)
  2554. {
  2555. FSProtocol = fsFTP;
  2556. Ftps = ftpsImplicit;
  2557. WellKnownPort = true;
  2558. }
  2559. else if (PortNumber == HTTPPortNumber)
  2560. {
  2561. FSProtocol = (CurrentFSProtocol == fsS3) ? fsS3 : fsWebDAV;
  2562. WellKnownPort = true;
  2563. }
  2564. else if (PortNumber == HTTPSPortNumber)
  2565. {
  2566. FSProtocol = (CurrentFSProtocol == fsS3) ? fsS3 : fsWebDAV;
  2567. Ftps = ftpsImplicit;
  2568. WellKnownPort = true;
  2569. }
  2570. if (WellKnownPort)
  2571. {
  2572. bool AllowScpFallback;
  2573. int ProtocolIndex = FSProtocolToIndex(FSProtocol, AllowScpFallback);
  2574. if ((TransferProtocolCombo->ItemIndex == ProtocolIndex) &&
  2575. (GetFtps() == Ftps))
  2576. {
  2577. FUpdatePortWithProtocol = true;
  2578. }
  2579. else
  2580. {
  2581. FUpdatePortWithProtocol = false;
  2582. NoUpdate++;
  2583. try
  2584. {
  2585. TransferProtocolCombo->ItemIndex = ProtocolIndex;
  2586. int FtpsIndex = FtpsToIndex(Ftps);
  2587. FtpsCombo->ItemIndex = FtpsIndex;
  2588. WebDavsCombo->ItemIndex = FtpsIndex;
  2589. }
  2590. __finally
  2591. {
  2592. NoUpdate--;
  2593. }
  2594. }
  2595. }
  2596. }
  2597. DataChange(Sender);
  2598. }
  2599. //---------------------------------------------------------------------------
  2600. void __fastcall TLoginDialog::ExportActionExecute(TObject * /*Sender*/)
  2601. {
  2602. UnicodeString FileName = Configuration->GetDefaultIniFileExportPath();
  2603. if (SaveDialog(LoadStr(EXPORT_CONF_TITLE), LoadStr(EXPORT_CONF_FILTER), L"ini", FileName))
  2604. {
  2605. Configuration->Export(FileName);
  2606. }
  2607. }
  2608. //---------------------------------------------------------------------------
  2609. void __fastcall TLoginDialog::ImportActionExecute(TObject * /*Sender*/)
  2610. {
  2611. if (MessageDialog(LoadStr(IMPORT_CONFIGURATION2),
  2612. qtWarning, qaOK | qaCancel, HELP_IMPORT_CONFIGURATION) == qaOK)
  2613. {
  2614. std::unique_ptr<TOpenDialog> OpenDialog(new TOpenDialog(Application));
  2615. OpenDialog->Title = LoadStr(IMPORT_CONF_TITLE);
  2616. OpenDialog->Filter = LoadStr(EXPORT_CONF_FILTER);
  2617. OpenDialog->DefaultExt = L"ini";
  2618. OpenDialog->FileName = Configuration->GetDefaultIniFileExportPath();
  2619. if (OpenDialog->Execute())
  2620. {
  2621. // Before the session list gets destroyed
  2622. SessionTree->Items->Clear();
  2623. Configuration->Import(OpenDialog->FileName);
  2624. // Similar to TPreferencesDialog::CustomIniFileStorageChanged
  2625. ExecuteSelf(EmptyStr);
  2626. TerminateApplication();
  2627. }
  2628. }
  2629. }
  2630. //---------------------------------------------------------------------------
  2631. void __fastcall TLoginDialog::ResetSitesIncrementalSearch()
  2632. {
  2633. FIncrementalSearchState.Reset();
  2634. // this is to prevent active tree node being set back to Sites tab
  2635. // (from UpdateNavigationTree) when we are called from SessionTreeExit,
  2636. // while tab is changing
  2637. if (NoUpdate == 0)
  2638. {
  2639. UpdateControls();
  2640. }
  2641. }
  2642. //---------------------------------------------------------------------------
  2643. bool __fastcall TLoginDialog::SitesIncrementalSearch(
  2644. const UnicodeString & Text, bool SkipCurrent, bool Reverse, bool Expanding)
  2645. {
  2646. TTreeNode * Node = NULL;
  2647. if (!Expanding)
  2648. {
  2649. Node = SearchSite(Text, false, SkipCurrent, Reverse);
  2650. }
  2651. if (Node == NULL)
  2652. {
  2653. Node = SearchSite(Text, true, SkipCurrent, Reverse);
  2654. if (Node != NULL)
  2655. {
  2656. TTreeNode * Parent = Node->Parent;
  2657. while (Parent != NULL)
  2658. {
  2659. Parent->Expand(false);
  2660. Parent = Parent->Parent;
  2661. }
  2662. }
  2663. }
  2664. bool Result = (Node != NULL);
  2665. if (Result)
  2666. {
  2667. {
  2668. TAutoNestingCounter Guard(FIncrementalSearching);
  2669. SessionTree->Selected = Node;
  2670. }
  2671. FIncrementalSearchState.Searching = true;
  2672. FIncrementalSearchState.Text = Text;
  2673. // Tab always searches even in collapsed nodes
  2674. TTreeNode * NextNode = SearchSite(Text, true, true, Reverse);
  2675. FIncrementalSearchState.HaveNext =
  2676. (NextNode != NULL) && (NextNode != Node);
  2677. UpdateControls();
  2678. // make visible only after search panel is shown, what may obscure the node
  2679. Node->MakeVisible();
  2680. }
  2681. return Result;
  2682. }
  2683. //---------------------------------------------------------------------------
  2684. TTreeNode * __fastcall TLoginDialog::GetNextNode(TTreeNode * Node, bool Reverse)
  2685. {
  2686. if (Reverse)
  2687. {
  2688. Node = Node->GetPrev();
  2689. if (Node == NULL)
  2690. {
  2691. // GetLastNode
  2692. // https://stackoverflow.com/q/6257348/850848
  2693. Node = SessionTree->Items->GetFirstNode();
  2694. TTreeNode * Node2 = Node;
  2695. if (Node2 != NULL)
  2696. {
  2697. do
  2698. {
  2699. Node2 = Node;
  2700. if (Node != NULL)
  2701. {
  2702. Node = Node2->getNextSibling();
  2703. }
  2704. if (Node == NULL)
  2705. {
  2706. Node = Node2->getFirstChild();
  2707. }
  2708. }
  2709. while (Node != NULL);
  2710. }
  2711. Node = Node2;
  2712. }
  2713. }
  2714. else
  2715. {
  2716. Node = Node->GetNext();
  2717. if (Node == NULL)
  2718. {
  2719. Node = SessionTree->Items->GetFirstNode();
  2720. }
  2721. }
  2722. return Node;
  2723. }
  2724. //---------------------------------------------------------------------------
  2725. TTreeNode * __fastcall TLoginDialog::SearchSite(const UnicodeString & Text,
  2726. bool AllowExpanding, bool SkipCurrent, bool Reverse)
  2727. {
  2728. TTreeNode * CurrentNode =
  2729. (SessionTree->Selected != NULL) ? SessionTree->Selected : SessionTree->Items->GetFirstNode();
  2730. if (CurrentNode == NULL)
  2731. {
  2732. return NULL;
  2733. }
  2734. else
  2735. {
  2736. TTreeNode * Node = CurrentNode;
  2737. if (SkipCurrent)
  2738. {
  2739. Node = GetNextNode(Node, Reverse);
  2740. if (Node == NULL)
  2741. {
  2742. return NULL;
  2743. }
  2744. }
  2745. while (true)
  2746. {
  2747. bool Eligible = true;
  2748. TTreeNode * Parent = Node->Parent;
  2749. while (Eligible && (Parent != NULL))
  2750. {
  2751. Eligible =
  2752. IsFolderNode(Parent) &&
  2753. (Parent->Expanded || AllowExpanding);
  2754. Parent = Parent->Parent;
  2755. }
  2756. if (Eligible)
  2757. {
  2758. bool Matches = false;
  2759. switch (FSiteSearch)
  2760. {
  2761. case isNameStartOnly:
  2762. Matches = ContainsTextSemiCaseSensitive(Node->Text.SubString(1, Text.Length()), Text);
  2763. break;
  2764. case isName:
  2765. Matches = ContainsTextSemiCaseSensitive(Node->Text, Text);
  2766. break;
  2767. case isAll:
  2768. Matches = ContainsTextSemiCaseSensitive(Node->Text, Text);
  2769. if (!Matches && IsSiteNode(Node))
  2770. {
  2771. TSessionData * Data = GetNodeSession(Node);
  2772. Matches =
  2773. ContainsTextSemiCaseSensitive(Data->HostName, Text) ||
  2774. ContainsTextSemiCaseSensitive(Data->UserName, Text) ||
  2775. ContainsTextSemiCaseSensitive(Data->Note, Text);
  2776. }
  2777. break;
  2778. }
  2779. if (Matches)
  2780. {
  2781. return Node;
  2782. }
  2783. }
  2784. Node = GetNextNode(Node, Reverse);
  2785. if (Node == CurrentNode)
  2786. {
  2787. return NULL;
  2788. }
  2789. }
  2790. }
  2791. }
  2792. //---------------------------------------------------------------------------
  2793. void __fastcall TLoginDialog::SessionTreeExit(TObject * /*Sender*/)
  2794. {
  2795. ResetSitesIncrementalSearch();
  2796. }
  2797. //---------------------------------------------------------------------------
  2798. bool __fastcall TLoginDialog::EnsureNotEditing()
  2799. {
  2800. bool Result = !FEditing;
  2801. if (!Result)
  2802. {
  2803. UnicodeString Message = MainInstructions(LoadStr(LOGIN_SAVE_EDITING));
  2804. unsigned int Answer = MessageDialog(Message, qtConfirmation, qaYes |qaNo | qaCancel);
  2805. switch (Answer)
  2806. {
  2807. case qaYes:
  2808. SaveAsSession(false);
  2809. Result = true;
  2810. break;
  2811. case qaNo:
  2812. CancelEditing();
  2813. // Make sure OK button gets enabled
  2814. UpdateControls();
  2815. Result = true;
  2816. break;
  2817. default:
  2818. // noop;
  2819. break;
  2820. }
  2821. }
  2822. return Result;
  2823. }
  2824. //---------------------------------------------------------------------------
  2825. void __fastcall TLoginDialog::SessionTreeChanging(TObject * /*Sender*/,
  2826. TTreeNode * /*Node*/, bool & AllowChange)
  2827. {
  2828. if (!EnsureNotEditing())
  2829. {
  2830. AllowChange = false;
  2831. }
  2832. else
  2833. {
  2834. PersistNewSiteIfNeeded();
  2835. }
  2836. }
  2837. //---------------------------------------------------------------------------
  2838. void __fastcall TLoginDialog::PersistNewSiteIfNeeded()
  2839. {
  2840. // Visible: Never try to save data if we did not load any yet,
  2841. // otherwise we get "HostNameEdit" and such
  2842. if (Visible && IsNewSiteNode(SessionTree->Selected))
  2843. {
  2844. SaveSession(FNewSiteData);
  2845. }
  2846. }
  2847. //---------------------------------------------------------------------------
  2848. void __fastcall TLoginDialog::SessionAdvancedActionExecute(TObject * Sender)
  2849. {
  2850. // If we ever allow showing advanced settings, while read-only,
  2851. // we must make sure that FSessionData actually holds the advanced settings,
  2852. // what it currently does not, in order to avoid master password prompt,
  2853. // while cloning the session data in LoadSession.
  2854. // To implement this, we may delegate the cloning to TWinConfiguration and
  2855. // make use of FDontDecryptPasswords
  2856. if (DebugAlwaysTrue(FSessionData != NULL))
  2857. {
  2858. // parse hostname (it may change protocol particularly) before opening advanced settings
  2859. // (HostNameEditExit is not triggered when child dialog pops up when it is invoked by accelerator)
  2860. // We should better handle this automaticaly when focus is moved to another dialog.
  2861. ParseHostName();
  2862. SaveSession(FSessionData);
  2863. if (Sender == SessionAdvancedAction)
  2864. {
  2865. DoSiteAdvancedDialog(FSessionData);
  2866. }
  2867. else
  2868. {
  2869. DoSiteRawDialog(FSessionData);
  2870. }
  2871. // Needed only for Note.
  2872. // The only other property visible on Login dialog that Advanced site dialog
  2873. // can change is protocol (between fsSFTP and fsSFTPonly),
  2874. // difference of the two not being visible on Login dialog anyway.
  2875. LoadSession(FSessionData);
  2876. if (DebugAlwaysTrue(SessionTree->Selected != NULL) &&
  2877. IsSiteNode(SessionTree->Selected))
  2878. {
  2879. SetNodeImage(SessionTree->Selected, GetSessionImageIndex(FSessionData));
  2880. }
  2881. }
  2882. }
  2883. //---------------------------------------------------------------------------
  2884. TPopupMenu * __fastcall TLoginDialog::GetSelectedNodePopupMenu()
  2885. {
  2886. TPopupMenu * PopupMenu = NULL;
  2887. TTreeNode * Selected = SessionTree->Selected;
  2888. if (IsNewSiteNode(Selected))
  2889. {
  2890. PopupMenu = ManageNewSitePopupMenu;
  2891. }
  2892. else if (IsSiteNode(Selected))
  2893. {
  2894. PopupMenu = ManageSitePopupMenu;
  2895. }
  2896. else if (IsFolderNode(Selected))
  2897. {
  2898. PopupMenu = ManageFolderPopupMenu;
  2899. }
  2900. else if (IsWorkspaceNode(Selected))
  2901. {
  2902. PopupMenu = ManageWorkspacePopupMenu;
  2903. }
  2904. return DebugNotNull(PopupMenu);
  2905. }
  2906. //---------------------------------------------------------------------------
  2907. void __fastcall TLoginDialog::ManageButtonClick(TObject * /*Sender*/)
  2908. {
  2909. MenuPopup(GetSelectedNodePopupMenu(), ManageButton);
  2910. }
  2911. //---------------------------------------------------------------------------
  2912. void __fastcall TLoginDialog::SessionTreeMouseDown(TObject * /*Sender*/,
  2913. TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  2914. {
  2915. TTreeNode * Node = SessionTree->GetNodeAt(X, Y);
  2916. if ((Button == mbRight) && (Node != NULL))
  2917. {
  2918. SessionTree->Selected = Node;
  2919. }
  2920. }
  2921. //---------------------------------------------------------------------------
  2922. void __fastcall TLoginDialog::SessionTreeContextPopup(TObject * /*Sender*/,
  2923. TPoint & MousePos, bool & Handled)
  2924. {
  2925. ResetSitesIncrementalSearch();
  2926. TTreeNode * Node = SessionTree->GetNodeAt(MousePos.X, MousePos.Y);
  2927. // This is mostly to prevent context menu from poping up,
  2928. // while there is prompt to confirm cancelling session edit,
  2929. // when right mouse is clicked on non-selected node
  2930. if (Node != SessionTree->Selected)
  2931. {
  2932. Handled = true;
  2933. }
  2934. else
  2935. {
  2936. if (SessionTree->Selected != NULL)
  2937. {
  2938. SessionTree->PopupMenu = GetSelectedNodePopupMenu();
  2939. if (DebugNotNull(SessionTree->PopupMenu))
  2940. {
  2941. MenuPopup(SessionTree, MousePos, Handled);
  2942. }
  2943. }
  2944. }
  2945. }
  2946. //---------------------------------------------------------------------------
  2947. void __fastcall TLoginDialog::EditCancelActionExecute(TObject * /*Sender*/)
  2948. {
  2949. CancelEditing();
  2950. // reset back to saved settings
  2951. LoadContents();
  2952. UpdateControls();
  2953. // we do not want to see blinking cursor in read-only edit box
  2954. SessionTree->SetFocus();
  2955. }
  2956. //---------------------------------------------------------------------------
  2957. void __fastcall TLoginDialog::AdvancedButtonDropDownClick(TObject * /*Sender*/)
  2958. {
  2959. MenuPopup(SessionAdvancedPopupMenu, AdvancedButton);
  2960. }
  2961. //---------------------------------------------------------------------------
  2962. void __fastcall TLoginDialog::CancelEditing()
  2963. {
  2964. FEditing = false;
  2965. // reset back the color
  2966. UpdateNodeImage(SessionTree->Selected);
  2967. }
  2968. //---------------------------------------------------------------------------
  2969. void __fastcall TLoginDialog::CloneToNewSite()
  2970. {
  2971. FNewSiteData->CopyData(SelectedSession);
  2972. FNewSiteData->MakeUniqueIn(StoredSessions);
  2973. FNewSiteKeepName = true;
  2974. NewSite();
  2975. EditSession();
  2976. }
  2977. //---------------------------------------------------------------------------
  2978. void __fastcall TLoginDialog::CloneToNewSiteActionExecute(TObject * /*Sender*/)
  2979. {
  2980. CloneToNewSite();
  2981. }
  2982. //---------------------------------------------------------------------------
  2983. void __fastcall TLoginDialog::Login()
  2984. {
  2985. if (OpenInNewWindow() && !IsNewSiteNode(SessionTree->Selected))
  2986. {
  2987. UnicodeString Path = SessionNodePath(SessionTree->Selected);
  2988. ExecuteNewInstance(EncodeUrlString(Path));
  2989. // prevent closing the window, see below
  2990. ModalResult = mrNone;
  2991. }
  2992. else
  2993. {
  2994. // this is not needed when used from LoginButton,
  2995. // but is needed when used from popup menus
  2996. ModalResult = LoginButton->ModalResult;
  2997. }
  2998. }
  2999. //---------------------------------------------------------------------------
  3000. void __fastcall TLoginDialog::LoginActionExecute(TObject * /*Sender*/)
  3001. {
  3002. Login();
  3003. }
  3004. //---------------------------------------------------------------------------
  3005. void __fastcall TLoginDialog::PuttyActionExecute(TObject * /*Sender*/)
  3006. {
  3007. // following may take some time, so cache the shift key state,
  3008. // in case user manages to release it before following finishes
  3009. bool Close = !OpenInNewWindow();
  3010. std::unique_ptr<TList> DataList(new TList());
  3011. SaveDataList(DataList.get());
  3012. for (int Index = 0; Index < DataList->Count; Index++)
  3013. {
  3014. TSessionData * Data = reinterpret_cast<TSessionData *>(DataList->Items[Index]);
  3015. OpenSessionInPutty(Data);
  3016. }
  3017. if (Close)
  3018. {
  3019. ModalResult = CloseButton->ModalResult;
  3020. }
  3021. }
  3022. //---------------------------------------------------------------------------
  3023. void __fastcall TLoginDialog::LoginButtonDropDownClick(TObject * /*Sender*/)
  3024. {
  3025. MenuPopup(LoginDropDownMenu, LoginButton);
  3026. }
  3027. //---------------------------------------------------------------------------
  3028. void TLoginDialog::DoParseUrl(TSessionData * SessionData, const UnicodeString & Url)
  3029. {
  3030. // We do not want to pass in StoredSessions as we do not want the URL be
  3031. // parsed as pointing to a stored site.
  3032. bool DefaultsOnly; // unused
  3033. SessionData->ParseUrl(Url, NULL, NULL, DefaultsOnly, NULL, NULL, NULL, pufPreferProtocol);
  3034. SessionData->RequireDirectories = false;
  3035. }
  3036. //---------------------------------------------------------------------------
  3037. void __fastcall TLoginDialog::ParseUrl(const UnicodeString & Url)
  3038. {
  3039. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  3040. SaveSession(SessionData.get());
  3041. // Otherwise the colons would be misinterpreted as URL syntax
  3042. if (IsIPv6Literal(Url))
  3043. {
  3044. UnicodeString IPv6Literal = Url;
  3045. if (HasIP6LiteralBrackets(IPv6Literal))
  3046. {
  3047. IPv6Literal = StripIP6LiteralBrackets(IPv6Literal);
  3048. }
  3049. SessionData->HostName = IPv6Literal;
  3050. }
  3051. else
  3052. {
  3053. DoParseUrl(SessionData.get(), Url);
  3054. }
  3055. LoadSession(SessionData.get());
  3056. }
  3057. //---------------------------------------------------------------------------
  3058. void __fastcall TLoginDialog::PasteUrlActionExecute(TObject * /*Sender*/)
  3059. {
  3060. UnicodeString ClipboardUrl;
  3061. if (NonEmptyTextFromClipboard(ClipboardUrl))
  3062. {
  3063. if (!IsEditable())
  3064. {
  3065. // select new site node, when other node is selected and not in editing mode
  3066. SessionTree->Selected = GetNewSiteNode();
  3067. }
  3068. // sanity check
  3069. if (DebugAlwaysTrue(IsEditable()))
  3070. {
  3071. ParseUrl(ClipboardUrl);
  3072. }
  3073. // visualize the pasting
  3074. HostNameEdit->SetFocus();
  3075. HostNameEdit->SelectAll();
  3076. }
  3077. }
  3078. //---------------------------------------------------------------------------
  3079. void __fastcall TLoginDialog::ParseHostName()
  3080. {
  3081. UnicodeString HostName = HostNameEdit->Text.Trim();
  3082. if (!HostName.IsEmpty())
  3083. {
  3084. // All this check is probably unnecessary, keeping it just to be safe
  3085. std::unique_ptr<TSessionData> SessionData(new TSessionData(EmptyStr));
  3086. DoParseUrl(SessionData.get(), HostName);
  3087. std::unique_ptr<TSessionData> HostNameSessionData(new TSessionData(EmptyStr));
  3088. HostNameSessionData->HostName = HostName;
  3089. if ((HostNameSessionData->HostName != HostName) || // Has legacy HostName property parsing intervened?
  3090. (!SessionData->IsSameDecrypted(HostNameSessionData.get())))
  3091. {
  3092. ParseUrl(HostName);
  3093. }
  3094. }
  3095. }
  3096. //---------------------------------------------------------------------------
  3097. void __fastcall TLoginDialog::HostNameEditExit(TObject * /*Sender*/)
  3098. {
  3099. ParseHostName();
  3100. }
  3101. //---------------------------------------------------------------------------
  3102. void __fastcall TLoginDialog::GenerateUrlAction2Execute(TObject * /*Sender*/)
  3103. {
  3104. if (DebugAlwaysTrue(SelectedSession != NULL))
  3105. {
  3106. PersistNewSiteIfNeeded();
  3107. std::unique_ptr<TSessionData> Data(SelectedSession->Clone());
  3108. Data->LookupLastFingerprint();
  3109. DoGenerateUrlDialog(Data.get(), NULL);
  3110. }
  3111. }
  3112. //---------------------------------------------------------------------------
  3113. void __fastcall TLoginDialog::CopyParamRuleActionExecute(TObject * /*Sender*/)
  3114. {
  3115. TSessionData * Data = GetSessionData();
  3116. std::unique_ptr<TCopyParamList> CopyParamList(new TCopyParamList());
  3117. (*CopyParamList) = *GUIConfiguration->CopyParamList;
  3118. TCopyParamRuleData RuleData;
  3119. RuleData.HostName = Data->HostNameExpanded;
  3120. RuleData.UserName = Data->UserNameExpanded;
  3121. int CopyParamIndex = CopyParamList->Find(RuleData);
  3122. if (CopyParamIndex < 0)
  3123. {
  3124. TCopyParamRuleData RuleDataHostNameOnly;
  3125. RuleDataHostNameOnly.HostName = Data->HostNameExpanded;
  3126. CopyParamIndex = CopyParamList->Find(RuleDataHostNameOnly);
  3127. }
  3128. TCopyParamPresetMode Mode;
  3129. TCopyParamRuleData * CurrentRuleData = NULL;
  3130. if (CopyParamIndex < 0)
  3131. {
  3132. Mode = cpmAddCurrent;
  3133. CurrentRuleData = &RuleData;
  3134. }
  3135. else
  3136. {
  3137. Mode = cpmEdit;
  3138. }
  3139. TCopyParamType DefaultCopyParams;
  3140. if (DoCopyParamPresetDialog(
  3141. CopyParamList.get(), CopyParamIndex, Mode, CurrentRuleData, DefaultCopyParams))
  3142. {
  3143. GUIConfiguration->CopyParamList = CopyParamList.get();
  3144. }
  3145. }
  3146. //---------------------------------------------------------------------------
  3147. void __fastcall TLoginDialog::SearchSiteNameStartOnlyActionExecute(TObject * /*Sender*/)
  3148. {
  3149. FSiteSearch = isNameStartOnly;
  3150. }
  3151. //---------------------------------------------------------------------------
  3152. void __fastcall TLoginDialog::SearchSiteNameActionExecute(TObject * /*Sender*/)
  3153. {
  3154. FSiteSearch = isName;
  3155. }
  3156. //---------------------------------------------------------------------------
  3157. void __fastcall TLoginDialog::SearchSiteActionExecute(TObject * /*Sender*/)
  3158. {
  3159. FSiteSearch = isAll;
  3160. }
  3161. //---------------------------------------------------------------------------
  3162. void __fastcall TLoginDialog::ChangeScale(int M, int D)
  3163. {
  3164. TForm::ChangeScale(M, D);
  3165. FSiteButtonsPadding = MulDiv(FSiteButtonsPadding, M, D);
  3166. FBasicGroupBaseHeight = MulDiv(FBasicGroupBaseHeight, M, D);
  3167. FNoteGroupOffset = MulDiv(FNoteGroupOffset, M, D);
  3168. }
  3169. //---------------------------------------------------------------------------
  3170. void __fastcall TLoginDialog::PanelMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  3171. {
  3172. CountClicksForWindowPrint(this);
  3173. }
  3174. //---------------------------------------------------------------------------
  3175. void __fastcall TLoginDialog::S3CredentialsEnvCheck3Click(TObject *)
  3176. {
  3177. UpdateS3Credentials();
  3178. UpdateControls();
  3179. }
  3180. //---------------------------------------------------------------------------
  3181. void __fastcall TLoginDialog::S3ProfileComboChange(TObject *)
  3182. {
  3183. UpdateS3Credentials();
  3184. UpdateControls();
  3185. }
  3186. //---------------------------------------------------------------------------
  3187. void __fastcall TLoginDialog::ShowAgainCheckClick(TObject *)
  3188. {
  3189. if (!ShowAgainCheck->Checked)
  3190. {
  3191. if (MessageDialog(LoadStr(LOGIN_NOT_SHOWING_AGAIN), qtConfirmation, qaOK | qaCancel, HELP_SHOW_LOGIN) != qaOK)
  3192. {
  3193. ShowAgainCheck->Checked = true;
  3194. }
  3195. }
  3196. }
  3197. //---------------------------------------------------------------------------
  3198. void __fastcall TLoginDialog::SearchSiteStartActionExecute(TObject *)
  3199. {
  3200. SessionTree->SetFocus();
  3201. if (!FIncrementalSearchState.Searching)
  3202. {
  3203. FIncrementalSearchState.Searching = true;
  3204. FIncrementalSearchState.HaveNext = false;
  3205. DebugAssert(FIncrementalSearchState.Text.IsEmpty());
  3206. UpdateControls();
  3207. }
  3208. }
  3209. //---------------------------------------------------------------------------