1
0

Login.cpp 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322
  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. FSitesIncrementalSearchHaveNext = false;
  69. FEditing = false;
  70. FRenaming = false;
  71. FNewSiteKeepName = false;
  72. FForceNewSite = false;
  73. FLoading = false;
  74. FSortEnablePending = false;
  75. FSiteSearch = isName;
  76. FLinkedForm = NULL;
  77. FRestoring = false;
  78. FPrevPos = TPoint(std::numeric_limits<LONG>::min(), std::numeric_limits<LONG>::min());
  79. FWasEverS3 = false;
  80. // we need to make sure that window procedure is set asap
  81. // (so that CM_SHOWINGCHANGED handling is applied)
  82. UseSystemSettingsPre(this);
  83. FFixedSessionImages = SessionImageList->Count;
  84. DebugAssert(SiteColorMaskImageIndex == FFixedSessionImages - 1);
  85. FBasicGroupBaseHeight = BasicGroup->Height - BasicSshPanel->Height - BasicFtpPanel->Height - BasicS3Panel->Height;
  86. FNoteGroupOffset = NoteGroup->Top - (BasicGroup->Top + BasicGroup->Height);
  87. FUserNameLabel = UserNameLabel->Caption;
  88. FPasswordLabel = PasswordLabel->Caption;
  89. FSiteButtonsPadding = SitesPanel->ClientHeight - ToolsMenuButton->Top - ToolsMenuButton->Height;
  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 effectivelly 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. S3CredentialsEnvCheck2->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 = S3CredentialsEnvCheck2->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 HostNameEdit), 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 && S3CredentialsEnvCheck2->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 != !FSitesIncrementalSearch.IsEmpty())
  679. {
  680. if (FSitesIncrementalSearch.IsEmpty())
  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 (!FSitesIncrementalSearch.IsEmpty())
  692. {
  693. SitesIncrementalSearchLabel->Caption = FormatIncrementalSearchStatus(FSitesIncrementalSearch, FSitesIncrementalSearchHaveNext);
  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 (FSitesIncrementalSearch.IsEmpty())
  869. {
  870. Configuration->Usage->Inc(L"SiteIncrementalSearches");
  871. }
  872. if (!SitesIncrementalSearch(FSitesIncrementalSearch + Key, false, false, false))
  873. {
  874. MessageBeep(MB_ICONHAND);
  875. }
  876. Key = 0;
  877. }
  878. else if (Key == VK_BACK)
  879. {
  880. if (!FSitesIncrementalSearch.IsEmpty())
  881. {
  882. if (FSitesIncrementalSearch.Length() == 1)
  883. {
  884. ResetSitesIncrementalSearch();
  885. }
  886. else
  887. {
  888. UnicodeString NewText =
  889. FSitesIncrementalSearch.SubString(1, FSitesIncrementalSearch.Length() - 1);
  890. SitesIncrementalSearch(NewText, false, false, false);
  891. }
  892. Key = 0;
  893. }
  894. }
  895. else if ((Key == VK_RETURN) && IsCloneToNewSiteDefault())
  896. {
  897. CloneToNewSite();
  898. Key = 0;
  899. }
  900. }
  901. }
  902. //---------------------------------------------------------------------------
  903. void __fastcall TLoginDialog::EditSession()
  904. {
  905. HostNameEdit->SetFocus();
  906. }
  907. //---------------------------------------------------------------------------
  908. void __fastcall TLoginDialog::EditSessionActionExecute(TObject * /*Sender*/)
  909. {
  910. if (DebugAlwaysTrue(SelectedSession != NULL))
  911. {
  912. FEditing = true;
  913. EditSession();
  914. // reload session, to make sure we load decrypted password
  915. LoadContents();
  916. UpdateControls();
  917. }
  918. }
  919. //---------------------------------------------------------------------------
  920. TTreeNode * __fastcall TLoginDialog::FindSessionNode(TSessionData * SessionData, bool ByName)
  921. {
  922. TTreeNode * Node = SessionTree->Items->GetFirstNode();
  923. while (
  924. (Node != NULL) &&
  925. ((!ByName && (Node->Data != SessionData)) ||
  926. (ByName && (!IsSiteNode(Node) || (GetNodeSession(Node)->Name != SessionData->Name)))))
  927. {
  928. Node = Node->GetNext();
  929. }
  930. return Node;
  931. }
  932. //---------------------------------------------------------------------------
  933. TSessionData * __fastcall TLoginDialog::GetEditingSessionData()
  934. {
  935. return FEditing ? DebugNotNull(SelectedSession) : NULL;
  936. }
  937. //---------------------------------------------------------------------------
  938. void __fastcall TLoginDialog::SaveAsSession(bool ForceDialog)
  939. {
  940. // Parse hostname before saving
  941. // (HostNameEditExit is not triggered when child dialog pops up when it is invoked by accelerator)
  942. // We should better handle this automaticaly when focus is moved to another dialog.
  943. ParseHostName();
  944. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  945. SaveSession(SessionData.get());
  946. TSessionData * EditingSessionData = GetEditingSessionData();
  947. // collect list of empty folders (these are not persistent and known to login dialog only)
  948. std::unique_ptr<TStrings> NewFolders(new TStringList());
  949. TTreeNode * Node = SessionTree->Items->GetFirstNode();
  950. while (Node != NULL)
  951. {
  952. if (IsFolderNode(Node) && !Node->HasChildren)
  953. {
  954. NewFolders->Add(SessionNodePath(Node));
  955. }
  956. Node = Node->GetNext();
  957. }
  958. TSessionData * NewSession =
  959. DoSaveSession(SessionData.get(), EditingSessionData, ForceDialog, NewFolders.get());
  960. if (NewSession != NULL)
  961. {
  962. TTreeNode * ParentNode = AddSessionPath(UnixExtractFilePath(NewSession->SessionName), false, false);
  963. CheckIsSessionFolder(ParentNode);
  964. TTreeNode * Node = FindSessionNode(NewSession, false);
  965. if (Node == NULL)
  966. {
  967. Node = AddSession(NewSession);
  968. }
  969. if ((SessionTree->Selected != Node) &&
  970. IsSiteNode(SessionTree->Selected))
  971. {
  972. CancelEditing();
  973. }
  974. else
  975. {
  976. FEditing = false;
  977. }
  978. SessionTree->Selected = Node;
  979. SessionTree->SetFocus();
  980. // this
  981. // - updates TransferProtocolView and EncryptionView
  982. // - clears the password box, if user has not opted to save password
  983. // - reloads fake password
  984. LoadContents();
  985. UpdateControls();
  986. ResetNewSiteData();
  987. }
  988. }
  989. //---------------------------------------------------------------------------
  990. void __fastcall TLoginDialog::SaveSessionActionExecute(TObject * /*Sender*/)
  991. {
  992. bool NewSiteSelected = IsNewSiteNode(SessionTree->Selected);
  993. // for new site, the "save" command is actually "save as"
  994. SaveAsSession(NewSiteSelected);
  995. }
  996. //---------------------------------------------------------------------------
  997. void __fastcall TLoginDialog::SaveAsSessionActionExecute(TObject * /*Sender*/)
  998. {
  999. SaveAsSession(true);
  1000. }
  1001. //---------------------------------------------------------------------------
  1002. UnicodeString __fastcall TLoginDialog::SessionNodePath(TTreeNode * Node)
  1003. {
  1004. UnicodeString Path;
  1005. if ((Node != NULL) && !IsNewSiteNode(Node))
  1006. {
  1007. Path = Node->Text;
  1008. Node = Node->Parent;
  1009. while (Node != NULL)
  1010. {
  1011. Path.Insert(UnixIncludeTrailingBackslash(Node->Text), 1);
  1012. Node = Node->Parent;
  1013. }
  1014. }
  1015. return Path;
  1016. }
  1017. //---------------------------------------------------------------------------
  1018. void __fastcall TLoginDialog::DeleteSessionActionExecute(TObject * /*Sender*/)
  1019. {
  1020. DebugAssert(SessionTree->Selected != NULL);
  1021. TMessageParams Params;
  1022. Params.ImageName = L"Delete file";
  1023. TTreeNode * Node = SessionTree->Selected;
  1024. if (IsSiteNode(Node))
  1025. {
  1026. TSessionData * Session = SelectedSession;
  1027. UnicodeString Message = MainInstructions(FMTLOAD(CONFIRM_DELETE_SESSION, (Session->SessionName)));
  1028. if (MessageDialog(Message,
  1029. qtConfirmation, qaOK | qaCancel, HELP_DELETE_SESSION, &Params) == qaOK)
  1030. {
  1031. try
  1032. {
  1033. WinConfiguration->DeleteSessionFromJumpList(Session->SessionName);
  1034. }
  1035. catch (Exception & E)
  1036. {
  1037. ShowExtendedException(&E);
  1038. }
  1039. Session->Remove();
  1040. DestroySession(Session);
  1041. SessionTree->Selected->Delete();
  1042. }
  1043. }
  1044. else if (IsFolderNode(Node) || IsWorkspaceNode(Node))
  1045. {
  1046. int Sessions = 0;
  1047. TTreeNode * ANode = Node->GetNext();
  1048. while ((ANode != NULL) && ANode->HasAsParent(Node))
  1049. {
  1050. if (IsSessionNode(ANode))
  1051. {
  1052. TSessionData * Session = GetNodeSession(ANode);
  1053. if (Session->Special)
  1054. {
  1055. SessionTree->Selected = ANode;
  1056. ANode->MakeVisible();
  1057. throw Exception(FMTLOAD(LOGIN_DELETE_SPECIAL_SESSION, (Session->SessionName)));
  1058. }
  1059. Sessions++;
  1060. }
  1061. ANode = ANode->GetNext();
  1062. }
  1063. UnicodeString Path = SessionNodePath(Node);
  1064. int Prompt;
  1065. UnicodeString HelpKeyword;
  1066. if (IsFolderNode(Node))
  1067. {
  1068. Prompt = LOGIN_DELETE_SESSION_FOLDER;
  1069. HelpKeyword = HELP_DELETE_SESSION_FOLDER;
  1070. }
  1071. else
  1072. {
  1073. Prompt = LOGIN_DELETE_WORKSPACE;
  1074. HelpKeyword = HELP_DELETE_WORKSPACE;
  1075. }
  1076. if ((Sessions == 0) ||
  1077. (MessageDialog(MainInstructions(FMTLOAD(Prompt, (Path, Sessions))),
  1078. qtConfirmation, qaOK | qaCancel, HelpKeyword, &Params) == qaOK))
  1079. {
  1080. if (IsWorkspaceNode(Node))
  1081. {
  1082. try
  1083. {
  1084. WinConfiguration->DeleteWorkspaceFromJumpList(Path);
  1085. }
  1086. catch (Exception & E)
  1087. {
  1088. ShowExtendedException(&E);
  1089. }
  1090. }
  1091. Node = SessionTree->Selected;
  1092. TTreeNode * ANode = Node->GetNext();
  1093. while ((ANode != NULL) && ANode->HasAsParent(Node))
  1094. {
  1095. if (IsSessionNode(ANode))
  1096. {
  1097. TSessionData * Session = GetNodeSession(ANode);
  1098. Session->Remove();
  1099. DestroySession(Session);
  1100. }
  1101. ANode = ANode->GetNext();
  1102. }
  1103. SessionTree->Selected->Delete();
  1104. }
  1105. }
  1106. }
  1107. //---------------------------------------------------------------------------
  1108. void __fastcall TLoginDialog::ReloadSessions(const UnicodeString & SelectSite)
  1109. {
  1110. SaveState();
  1111. if (!SelectSite.IsEmpty())
  1112. {
  1113. WinConfiguration->LastStoredSession = SelectSite;
  1114. }
  1115. LoadSessions();
  1116. LoadState();
  1117. }
  1118. //---------------------------------------------------------------------------
  1119. void __fastcall TLoginDialog::ImportSessionsActionExecute(TObject * /*Sender*/)
  1120. {
  1121. std::unique_ptr<TList> Imported(new TList());
  1122. if (DoImportSessionsDialog(Imported.get()) &&
  1123. // Can be empty when imported known_hosts
  1124. (Imported->Count > 0))
  1125. {
  1126. // Focus the first imported session.
  1127. // We should also consider expanding all newly created folders
  1128. UnicodeString SelectSite = static_cast<TSessionData *>(Imported->Items[0])->Name;
  1129. ReloadSessions(SelectSite);
  1130. // Focus the tree with focused imported session(s).
  1131. SessionTree->SetFocus();
  1132. }
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. void __fastcall TLoginDialog::CleanUpActionExecute(TObject * /*Sender*/)
  1136. {
  1137. if (DoCleanupDialog())
  1138. {
  1139. SaveState();
  1140. LoadSessions();
  1141. LoadState();
  1142. }
  1143. }
  1144. //---------------------------------------------------------------------------
  1145. void __fastcall TLoginDialog::AboutActionExecute(TObject * /*Sender*/)
  1146. {
  1147. DoAboutDialog(Configuration);
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall TLoginDialog::ActionListUpdate(TBasicAction * BasicAction,
  1151. bool &Handled)
  1152. {
  1153. bool SiteSelected = IsSiteNode(SessionTree->Selected);
  1154. bool FolderOrWorkspaceSelected = IsFolderOrWorkspaceNode(SessionTree->Selected);
  1155. bool WorkspaceSelected = IsWorkspaceNode(SessionTree->Selected);
  1156. TAction * Action = DebugNotNull(dynamic_cast<TAction *>(BasicAction));
  1157. bool PrevEnabled = Action->Enabled;
  1158. bool Editable = IsEditable();
  1159. if ((Action == EditSessionAction) ||
  1160. (Action == CloneToNewSiteAction))
  1161. {
  1162. Action->Enabled = SiteSelected && !FEditing;
  1163. }
  1164. else if (Action == EditCancelAction)
  1165. {
  1166. EditCancelAction->Enabled = FEditing;
  1167. }
  1168. else if (Action == DeleteSessionAction)
  1169. {
  1170. DeleteSessionAction->Enabled =
  1171. ((SiteSelected && !SelectedSession->Special && !FEditing) ||
  1172. FolderOrWorkspaceSelected);
  1173. }
  1174. else if (Action == RenameSessionAction)
  1175. {
  1176. RenameSessionAction->Enabled =
  1177. ((SiteSelected && !SelectedSession->Special && !FEditing) ||
  1178. FolderOrWorkspaceSelected);
  1179. }
  1180. else if (Action == DesktopIconAction)
  1181. {
  1182. DesktopIconAction->Enabled =
  1183. (SiteSelected && !FEditing) ||
  1184. (FolderOrWorkspaceSelected && HasNodeAnySession(SessionTree->Selected));
  1185. }
  1186. else if (Action == SendToHookAction)
  1187. {
  1188. SendToHookAction->Enabled = SiteSelected && !FEditing;
  1189. }
  1190. else if (Action == LoginAction)
  1191. {
  1192. LoginAction->Enabled = CanOpen();
  1193. LoginAction->Caption = FolderOrWorkspaceSelected ? LoadStr(LOGIN_OPEN) : LoadStr(LOGIN_LOGIN);
  1194. LoginAction->ImageIndex = FolderOrWorkspaceSelected ? (WorkspaceSelected ? OpenWorkspaceImageIndex : OpenFolderImageIndex) : LoginImageIndex;
  1195. UpdateLoginButton();
  1196. }
  1197. else if (Action == PuttyAction)
  1198. {
  1199. TSessionData * Data = GetSessionData();
  1200. Action->Enabled =
  1201. (IsSiteAndCanOpen() && !Data->IsLocalBrowser && !Data->Tunnel) ||
  1202. (IsFolderOrWorkspaceAndCanOpen() && IsFolderNode(SessionTree->Selected));
  1203. }
  1204. else if (Action == SaveSessionAction)
  1205. {
  1206. SaveSessionAction->Enabled = Editable;
  1207. }
  1208. else if (Action == SessionAdvancedAction)
  1209. {
  1210. SessionAdvancedAction->Enabled = Editable;
  1211. }
  1212. else if (Action == SessionRawAction)
  1213. {
  1214. SessionRawAction->Enabled = Editable;
  1215. }
  1216. else if (Action == SaveAsSessionAction)
  1217. {
  1218. // Save as is needed for new site only when !SupportsSplitButton()
  1219. SaveAsSessionAction->Enabled = Editable;
  1220. }
  1221. else if (Action == NewSessionFolderAction)
  1222. {
  1223. NewSessionFolderAction->Enabled = !FEditing;
  1224. }
  1225. else if (Action == PasteUrlAction)
  1226. {
  1227. UnicodeString ClipboardUrl;
  1228. Action->Enabled =
  1229. NonEmptyTextFromClipboard(ClipboardUrl) &&
  1230. StoredSessions->IsUrl(ClipboardUrl);
  1231. }
  1232. else if (Action == GenerateUrlAction2)
  1233. {
  1234. TSessionData * Data = GetSessionData();
  1235. // URL without hostname is pointless
  1236. Action->Enabled = (Data != NULL) && !Data->HostNameExpanded.IsEmpty() && !FEditing;
  1237. }
  1238. else if (Action == CopyParamRuleAction)
  1239. {
  1240. TSessionData * Data = GetSessionData();
  1241. // without hostname it's pointless
  1242. Action->Enabled = (Data != NULL) && !Data->HostNameExpanded.IsEmpty();
  1243. }
  1244. else if (Action == SearchSiteNameStartOnlyAction)
  1245. {
  1246. Action->Checked = (FSiteSearch == isNameStartOnly);
  1247. }
  1248. else if (Action == SearchSiteNameAction)
  1249. {
  1250. Action->Checked = (FSiteSearch == isName);
  1251. }
  1252. else if (Action == SearchSiteAction)
  1253. {
  1254. Action->Checked = (FSiteSearch == isAll);
  1255. }
  1256. else if (Action == CheckForUpdatesAction)
  1257. {
  1258. Action->Visible = !IsUWP();
  1259. }
  1260. Handled = true;
  1261. // to update buttons visibility
  1262. if (PrevEnabled != Action->Enabled)
  1263. {
  1264. UpdateControls();
  1265. }
  1266. Idle();
  1267. }
  1268. //---------------------------------------------------------------------------
  1269. bool __fastcall TLoginDialog::IsCloneToNewSiteDefault()
  1270. {
  1271. return !FEditing && !FRenaming && IsSiteNode(SessionTree->Selected) && !StoredSessions->CanOpen(GetSessionData());
  1272. }
  1273. //---------------------------------------------------------------------------
  1274. bool TLoginDialog::IsSiteAndCanOpen()
  1275. {
  1276. TSessionData * Data = GetSessionData();
  1277. return
  1278. ((Data != NULL) && StoredSessions->CanOpen(Data) && !FEditing);
  1279. }
  1280. //---------------------------------------------------------------------------
  1281. bool TLoginDialog::IsFolderOrWorkspaceAndCanOpen()
  1282. {
  1283. return IsFolderOrWorkspaceNode(SessionTree->Selected) && HasNodeAnySession(SessionTree->Selected, true);
  1284. }
  1285. //---------------------------------------------------------------------------
  1286. bool __fastcall TLoginDialog::CanOpen()
  1287. {
  1288. return
  1289. IsSiteAndCanOpen() ||
  1290. IsFolderOrWorkspaceAndCanOpen();
  1291. }
  1292. //---------------------------------------------------------------------------
  1293. void __fastcall TLoginDialog::Idle()
  1294. {
  1295. if (SessionTree->IsEditing() != FRenaming)
  1296. {
  1297. FRenaming = SessionTree->IsEditing();
  1298. UpdateControls();
  1299. }
  1300. }
  1301. //---------------------------------------------------------------------------
  1302. bool __fastcall TLoginDialog::Execute(TList * DataList)
  1303. {
  1304. FDataList = DataList;
  1305. if (DataList->Count > 0)
  1306. {
  1307. TSessionData * SessionData = reinterpret_cast<TSessionData * >(DataList->Items[0]);
  1308. TTreeNode * Node = FindSessionNode(SessionData, true);
  1309. if (Node != NULL)
  1310. {
  1311. SessionTree->Selected = Node;
  1312. ActiveControl = SessionTree;
  1313. }
  1314. else
  1315. {
  1316. FNewSiteData->CopyData(SessionData);
  1317. FNewSiteData->Special = false;
  1318. if (!FNewSiteData->IsSameDecrypted(StoredSessions->DefaultSettings))
  1319. {
  1320. // we want to start with new site page
  1321. FForceNewSite = true;
  1322. }
  1323. LoadContents();
  1324. }
  1325. }
  1326. else
  1327. {
  1328. Default();
  1329. }
  1330. // Optimization. List view is recreated while showing the form,
  1331. // causing nodes repopulation and in a consequence a huge number of
  1332. // nodes comparison
  1333. SessionTree->SortType = Comctrls::stNone;
  1334. FSortEnablePending = true;
  1335. // Not calling LoadState here.
  1336. // It's redundant and does not work anyway, see comment in the method.
  1337. int AResult = ShowModal();
  1338. // When CanOpen is false, the DefaultResult() will fail finding a default button.
  1339. bool Result = CanOpen() && (AResult == DefaultResult());
  1340. SaveState();
  1341. if (Result)
  1342. {
  1343. SaveConfiguration();
  1344. // DataList saved already from FormCloseQuery
  1345. }
  1346. if (!ShowAgainCheck->Checked)
  1347. {
  1348. WinConfiguration->ShowLoginWhenNoSession = false;
  1349. }
  1350. return Result;
  1351. }
  1352. //---------------------------------------------------------------------------
  1353. void __fastcall TLoginDialog::SaveDataList(TList * DataList)
  1354. {
  1355. // Normally we would call this from Execute,
  1356. // but at that point the windows is already hidden.
  1357. // Cloning session data may pop up master password dialog:
  1358. // - if it happens between closing and destroyiong login dialog
  1359. // the next window will appear in background for some reason
  1360. // - and its actually even nicer when master password dialog pops up over
  1361. // the login dialog
  1362. DataList->Clear();
  1363. TTreeNode * Node = SessionTree->Selected;
  1364. if (IsFolderOrWorkspaceNode(Node))
  1365. {
  1366. UnicodeString Name = SessionNodePath(Node);
  1367. if (IsWorkspaceNode(Node))
  1368. {
  1369. try
  1370. {
  1371. WinConfiguration->AddWorkspaceToJumpList(Name);
  1372. }
  1373. catch (Exception & E)
  1374. {
  1375. ShowExtendedException(&E);
  1376. }
  1377. }
  1378. StoredSessions->GetFolderOrWorkspace(Name, DataList);
  1379. }
  1380. else
  1381. {
  1382. DataList->Add(CloneSelectedSession());
  1383. }
  1384. }
  1385. //---------------------------------------------------------------------------
  1386. TSessionData * __fastcall TLoginDialog::CloneSelectedSession()
  1387. {
  1388. TTreeNode * Node = SessionTree->Selected;
  1389. std::unique_ptr<TSessionData> Data2(new TSessionData(L""));
  1390. if (IsSiteNode(Node))
  1391. {
  1392. Data2->Assign(GetNodeSession(Node));
  1393. }
  1394. else if (DebugAlwaysTrue(IsNewSiteNode(Node)))
  1395. {
  1396. TSessionData * Data = GetSessionData();
  1397. Data2->Assign(Data);
  1398. // we carry the name of the edited stored session around while on the dialog,
  1399. // but we do not want it to leave the dialog, so that we can distinguish
  1400. // stored and ad-hoc sessions
  1401. Data2->Name = L"";
  1402. }
  1403. return Data2.release();
  1404. }
  1405. //---------------------------------------------------------------------------
  1406. void __fastcall TLoginDialog::SaveState()
  1407. {
  1408. DebugAssert(WinConfiguration != NULL);
  1409. WinConfiguration->BeginUpdate();
  1410. try
  1411. {
  1412. std::unique_ptr<TStringList> OpenedStoredSessionFolders(CreateSortedStringList());
  1413. for (int Index = 0; Index < SessionTree->Items->Count; Index++)
  1414. {
  1415. TTreeNode * Node = SessionTree->Items->Item[Index];
  1416. if (IsFolderNode(Node))
  1417. {
  1418. if (Node->Expanded)
  1419. {
  1420. OpenedStoredSessionFolders->Add(SessionNodePath(Node));
  1421. }
  1422. }
  1423. }
  1424. WinConfiguration->OpenedStoredSessionFolders = OpenedStoredSessionFolders->CommaText;
  1425. UnicodeString LastStoredSession = SessionNodePath(SessionTree->Selected);
  1426. if (IsFolderNode(SessionTree->Selected))
  1427. {
  1428. LastStoredSession = UnixIncludeTrailingBackslash(LastStoredSession);
  1429. }
  1430. WinConfiguration->LastStoredSession = LastStoredSession;
  1431. TLoginDialogConfiguration DialogConfiguration = CustomWinConfiguration->LoginDialog;
  1432. DialogConfiguration.WindowSize = StoreFormSize(this);
  1433. DialogConfiguration.SiteSearch = FSiteSearch;
  1434. CustomWinConfiguration->LoginDialog = DialogConfiguration;
  1435. }
  1436. __finally
  1437. {
  1438. WinConfiguration->EndUpdate();
  1439. }
  1440. }
  1441. //---------------------------------------------------------------------------
  1442. void __fastcall TLoginDialog::LoadOpenedStoredSessionFolders(
  1443. TTreeNode * Node, TStrings * OpenedStoredSessionFolders)
  1444. {
  1445. if (IsFolderNode(Node))
  1446. {
  1447. UnicodeString Path = SessionNodePath(Node);
  1448. if (OpenedStoredSessionFolders->IndexOf(Path) >= 0)
  1449. {
  1450. Node->Expand(false);
  1451. UpdateFolderNode(Node);
  1452. }
  1453. }
  1454. }
  1455. //---------------------------------------------------------------------------
  1456. void __fastcall TLoginDialog::LoadState()
  1457. {
  1458. // it does not make any sense to call this before
  1459. // DoFormWindowProc(CM_SHOWINGCHANGED), we would end up on wrong monitor
  1460. if (DebugAlwaysTrue(Visible))
  1461. {
  1462. RestoreFormSize(CustomWinConfiguration->LoginDialog.WindowSize, this);
  1463. }
  1464. FSiteSearch = CustomWinConfiguration->LoginDialog.SiteSearch;
  1465. TStringList * OpenedStoredSessionFolders = CreateSortedStringList();
  1466. try
  1467. {
  1468. OpenedStoredSessionFolders->CommaText = WinConfiguration->OpenedStoredSessionFolders;
  1469. for (int Index = 0; Index < SessionTree->Items->Count; Index++)
  1470. {
  1471. LoadOpenedStoredSessionFolders(
  1472. SessionTree->Items->Item[Index], OpenedStoredSessionFolders);
  1473. }
  1474. // tree view tries to make expanded node children all visible, what
  1475. // may scroll the selected node (what should be the first one here),
  1476. // out of the view
  1477. if (SessionTree->Selected != NULL)
  1478. {
  1479. // see comment for LastStoredSession branch below
  1480. DebugAssert(Visible);
  1481. SessionTree->Selected->MakeVisible();
  1482. }
  1483. }
  1484. __finally
  1485. {
  1486. delete OpenedStoredSessionFolders;
  1487. }
  1488. // calling TTreeNode::MakeVisible() when tree view is not visible yet,
  1489. // sometimes scrolls view horizontally when not needed
  1490. // (seems like it happens for sites that are at the same level
  1491. // as site folders, e.g. for the very last root-level site, as long as
  1492. // there are any folders)
  1493. if (!FForceNewSite &&
  1494. !WinConfiguration->LastStoredSession.IsEmpty() && DebugAlwaysTrue(Visible))
  1495. {
  1496. UnicodeString Path = UnixExcludeTrailingBackslash(WinConfiguration->LastStoredSession);
  1497. bool Folder = (Path != WinConfiguration->LastStoredSession);
  1498. UnicodeString ParentPath = UnixExtractFilePath(Path);
  1499. TTreeNode * Node;
  1500. if (ParentPath.IsEmpty())
  1501. {
  1502. Node = SessionTree->Items->GetFirstNode();
  1503. }
  1504. else
  1505. {
  1506. TTreeNode * Parent = AddSessionPath(ParentPath, false, false);
  1507. Node = (Parent != NULL) ? Parent->getFirstChild() : NULL;
  1508. }
  1509. if (Node != NULL)
  1510. {
  1511. UnicodeString Name = UnixExtractFileName(Path);
  1512. while ((Node != NULL) && (!SameText(Node->Text, Name) || (IsFolderNode(Node) != Folder)))
  1513. {
  1514. Node = Node->getNextSibling();
  1515. }
  1516. if (Node != NULL)
  1517. {
  1518. SessionTree->Selected = Node;
  1519. SessionTree->Selected->MakeVisible();
  1520. }
  1521. }
  1522. }
  1523. }
  1524. //---------------------------------------------------------------------------
  1525. void __fastcall TLoginDialog::SaveConfiguration()
  1526. {
  1527. DebugAssert(CustomWinConfiguration);
  1528. TTreeNode * Node = SessionTree->Selected;
  1529. if (IsWorkspaceNode(Node))
  1530. {
  1531. WinConfiguration->LastWorkspace = SessionNodePath(Node);
  1532. }
  1533. }
  1534. //---------------------------------------------------------------------------
  1535. void __fastcall TLoginDialog::PreferencesActionExecute(TObject * /*Sender*/)
  1536. {
  1537. ShowPreferencesDialog(::pmDefault);
  1538. }
  1539. //---------------------------------------------------------------------------
  1540. void __fastcall TLoginDialog::PreferencesLoggingActionExecute(TObject * /*Sender*/)
  1541. {
  1542. ShowPreferencesDialog(pmLogging);
  1543. }
  1544. //---------------------------------------------------------------------------
  1545. void __fastcall TLoginDialog::MasterPasswordRecrypt(TObject * /*Sender*/)
  1546. {
  1547. FNewSiteData->RecryptPasswords();
  1548. }
  1549. //---------------------------------------------------------------------------
  1550. void __fastcall TLoginDialog::ShowPreferencesDialog(TPreferencesMode PreferencesMode)
  1551. {
  1552. DebugAssert(CustomWinConfiguration->OnMasterPasswordRecrypt == NULL);
  1553. CustomWinConfiguration->OnMasterPasswordRecrypt = MasterPasswordRecrypt;
  1554. try
  1555. {
  1556. DoPreferencesDialog(PreferencesMode);
  1557. }
  1558. __finally
  1559. {
  1560. DebugAssert(CustomWinConfiguration->OnMasterPasswordRecrypt == MasterPasswordRecrypt);
  1561. CustomWinConfiguration->OnMasterPasswordRecrypt = NULL;
  1562. }
  1563. UpdateControls();
  1564. }
  1565. //---------------------------------------------------------------------------
  1566. void __fastcall TLoginDialog::ResetNewSessionActionExecute(TObject * /*Sender*/)
  1567. {
  1568. Default();
  1569. EditSession();
  1570. FNewSiteKeepName = false;
  1571. }
  1572. //---------------------------------------------------------------------------
  1573. void __fastcall TLoginDialog::CMDialogKey(TWMKeyDown & Message)
  1574. {
  1575. if (Message.CharCode == VK_TAB)
  1576. {
  1577. if (!FSitesIncrementalSearch.IsEmpty())
  1578. {
  1579. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  1580. bool Reverse = Shift.Contains(ssShift);
  1581. if (!SitesIncrementalSearch(FSitesIncrementalSearch, true, Reverse, true))
  1582. {
  1583. MessageBeep(MB_ICONHAND);
  1584. }
  1585. Message.Result = 1;
  1586. return;
  1587. }
  1588. }
  1589. else if (Message.CharCode == VK_ESCAPE)
  1590. {
  1591. if (!FSitesIncrementalSearch.IsEmpty())
  1592. {
  1593. ResetSitesIncrementalSearch();
  1594. Message.Result = 1;
  1595. return;
  1596. }
  1597. }
  1598. TForm::Dispatch(&Message);
  1599. }
  1600. //---------------------------------------------------------------------------
  1601. void __fastcall TLoginDialog::WMWindowPosChanged(TWMWindowPosChanged & Message)
  1602. {
  1603. TForm::Dispatch(&Message);
  1604. if (FLAGCLEAR(Message.WindowPos->flags, SWP_NOMOVE) && (FLinkedForm != NULL))
  1605. {
  1606. if (FPrevPos.X == std::numeric_limits<LONG>::min())
  1607. {
  1608. FPrevPos = BoundsRect.TopLeft();
  1609. }
  1610. TPoint P = TPoint(Message.WindowPos->x, Message.WindowPos->y);
  1611. if (FPrevPos != P)
  1612. {
  1613. if (!FRestoring)
  1614. {
  1615. FLinkedForm->SetBounds(
  1616. FLinkedForm->Left + (P.X - FPrevPos.X),
  1617. FLinkedForm->Top + (P.Y - FPrevPos.Y),
  1618. FLinkedForm->Width, FLinkedForm->Height);
  1619. }
  1620. FPrevPos = P;
  1621. }
  1622. }
  1623. }
  1624. //---------------------------------------------------------------------------
  1625. void __fastcall TLoginDialog::CMVisibleChanged(TMessage & Message)
  1626. {
  1627. TAutoFlag RestoringSwitch(FRestoring);
  1628. TForm::Dispatch(&Message);
  1629. }
  1630. //---------------------------------------------------------------------------
  1631. void __fastcall TLoginDialog::CMDpiChanged(TMessage & Message)
  1632. {
  1633. TForm::Dispatch(&Message);
  1634. GenerateImages();
  1635. CenterButtonImage(LoginButton);
  1636. }
  1637. //---------------------------------------------------------------------------
  1638. void __fastcall TLoginDialog::Dispatch(void * Message)
  1639. {
  1640. TMessage * M = reinterpret_cast<TMessage*>(Message);
  1641. DebugAssert(M);
  1642. if (M->Msg == CM_DIALOGKEY)
  1643. {
  1644. CMDialogKey(*((TWMKeyDown *)Message));
  1645. }
  1646. else if (M->Msg == WM_MANAGES_CAPTION)
  1647. {
  1648. // caption managed in TLoginDialog::Init()
  1649. M->Result = 1;
  1650. }
  1651. else if (M->Msg == WM_WANTS_MOUSEWHEEL)
  1652. {
  1653. M->Result = 1;
  1654. }
  1655. else if (M->Msg == WM_CAN_DISPLAY_UPDATES)
  1656. {
  1657. M->Result = 1;
  1658. }
  1659. else if (M->Msg == CM_ACTIVATE)
  1660. {
  1661. // Called from TCustomForm.ShowModal
  1662. if (FSortEnablePending)
  1663. {
  1664. FSortEnablePending = false;
  1665. SessionTree->SortType = Comctrls::stBoth;
  1666. }
  1667. TForm::Dispatch(Message);
  1668. }
  1669. else if (M->Msg == WM_SYSCOMMAND)
  1670. {
  1671. if (!HandleMinimizeSysCommand(*M))
  1672. {
  1673. TForm::Dispatch(Message);
  1674. }
  1675. }
  1676. else if (M->Msg == WM_WINDOWPOSCHANGED)
  1677. {
  1678. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosChanged *>(M));
  1679. }
  1680. else if (M->Msg == CM_VISIBLECHANGED)
  1681. {
  1682. CMVisibleChanged(*M);
  1683. }
  1684. else if (M->Msg == CM_DPICHANGED)
  1685. {
  1686. CMDpiChanged(*M);
  1687. }
  1688. else
  1689. {
  1690. TForm::Dispatch(Message);
  1691. }
  1692. }
  1693. //---------------------------------------------------------------------------
  1694. void __fastcall TLoginDialog::SetDefaultSessionActionExecute(
  1695. TObject * /*Sender*/)
  1696. {
  1697. UnicodeString Message = MainInstructions(LoadStr(SET_DEFAULT_SESSION_SETTINGS));
  1698. if (MessageDialog(Message, qtConfirmation,
  1699. qaOK | qaCancel, HELP_SESSION_SAVE_DEFAULT) == qaOK)
  1700. {
  1701. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  1702. SaveSession(SessionData.get());
  1703. // See the comment to the other use of the method in DoSaveSession.
  1704. CustomWinConfiguration->AskForMasterPasswordIfNotSetAndNeededToPersistSessionData(SessionData.get());
  1705. StoredSessions->DefaultSettings = SessionData.get();
  1706. Default();
  1707. }
  1708. }
  1709. //---------------------------------------------------------------------------
  1710. void __fastcall TLoginDialog::ToolsMenuButtonClick(TObject * /*Sender*/)
  1711. {
  1712. MenuPopup(ToolsPopupMenu, ToolsMenuButton);
  1713. }
  1714. //---------------------------------------------------------------------------
  1715. void __fastcall TLoginDialog::DesktopIconActionExecute(TObject * /*Sender*/)
  1716. {
  1717. TTreeNode * Node = SessionTree->Selected;
  1718. UnicodeString Message;
  1719. UnicodeString Name;
  1720. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  1721. int IconIndex = 0;
  1722. if (IsSiteNode(Node))
  1723. {
  1724. Name = GetNodeSession(Node)->Name;
  1725. Message = FMTLOAD(CONFIRM_CREATE_SHORTCUT, (Name));
  1726. AddToList(AdditionalParams, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), L" ");
  1727. IconIndex = SITE_ICON;
  1728. }
  1729. else if (IsFolderNode(Node))
  1730. {
  1731. Name = SessionNodePath(SessionTree->Selected);
  1732. Message = FMTLOAD(CONFIRM_CREATE_SHORTCUT_FOLDER, (Name));
  1733. IconIndex = SITE_FOLDER_ICON;
  1734. }
  1735. else if (IsWorkspaceNode(Node))
  1736. {
  1737. Name = SessionNodePath(SessionTree->Selected);
  1738. Message = FMTLOAD(CONFIRM_CREATE_SHORTCUT_WORKSPACE, (Name));
  1739. IconIndex = WORKSPACE_ICON;
  1740. }
  1741. else
  1742. {
  1743. DebugFail();
  1744. }
  1745. Message = MainInstructions(Message);
  1746. if (MessageDialog(Message, qtConfirmation, qaYes | qaNo, HELP_CREATE_SHORTCUT) == qaYes)
  1747. {
  1748. TInstantOperationVisualizer Visualizer;
  1749. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, IconIndex);
  1750. }
  1751. }
  1752. //---------------------------------------------------------------------------
  1753. void __fastcall TLoginDialog::SendToHookActionExecute(TObject * /*Sender*/)
  1754. {
  1755. DebugAssert(IsSiteNode(SessionTree->Selected));
  1756. DebugAssert(SelectedSession != NULL);
  1757. UnicodeString Message = MainInstructions(FMTLOAD(CONFIRM_CREATE_SENDTO, (SelectedSession->Name)));
  1758. if (MessageDialog(Message,
  1759. qtConfirmation, qaYes | qaNo, HELP_CREATE_SENDTO) == qaYes)
  1760. {
  1761. TInstantOperationVisualizer Visualizer;
  1762. UnicodeString AdditionalParams =
  1763. TProgramParams::FormatSwitch(SEND_TO_HOOK_SWITCH) + L" " +
  1764. TProgramParams::FormatSwitch(UPLOAD_SWITCH);
  1765. CreateDesktopSessionShortCut(SelectedSession->Name,
  1766. FMTLOAD(SESSION_SENDTO_HOOK_NAME2, (SelectedSession->LocalName, AppName)),
  1767. AdditionalParams,
  1768. CSIDL_SENDTO, SITE_ICON);
  1769. }
  1770. }
  1771. //---------------------------------------------------------------------------
  1772. bool __fastcall TLoginDialog::HasNodeAnySession(TTreeNode * Node, bool NeedCanOpen)
  1773. {
  1774. bool Result = false;
  1775. TTreeNode * ANode = Node->GetNext();
  1776. while (!Result && (ANode != NULL) && ANode->HasAsParent(Node))
  1777. {
  1778. Result =
  1779. IsSessionNode(ANode) &&
  1780. (!NeedCanOpen || StoredSessions->CanOpen(GetNodeSession(ANode)));
  1781. ANode = ANode->GetNext();
  1782. }
  1783. return Result;
  1784. }
  1785. //---------------------------------------------------------------------------
  1786. void __fastcall TLoginDialog::SessionTreeCustomDrawItem(
  1787. TCustomTreeView * Sender, TTreeNode * Node, TCustomDrawState State,
  1788. bool & DefaultDraw)
  1789. {
  1790. TFontStyles Styles = Sender->Canvas->Font->Style;
  1791. if (IsSessionNode(Node) && GetNodeSession(Node)->Special)
  1792. {
  1793. Styles = Styles << fsBold << fsUnderline;
  1794. }
  1795. else
  1796. {
  1797. Styles = Styles >> fsBold >> fsUnderline;
  1798. }
  1799. if (State.Empty() && !Node->DropTarget)
  1800. {
  1801. if (IsFolderOrWorkspaceNode(Node))
  1802. {
  1803. if (!HasNodeAnySession(Node))
  1804. {
  1805. Sender->Canvas->Font->Color = clGrayText;
  1806. }
  1807. }
  1808. }
  1809. Sender->Canvas->Font->Style = Styles;
  1810. DefaultDraw = true;
  1811. }
  1812. //---------------------------------------------------------------------------
  1813. void __fastcall TLoginDialog::CheckForUpdatesActionExecute(TObject * /*Sender*/)
  1814. {
  1815. CheckForUpdates(false);
  1816. }
  1817. //---------------------------------------------------------------------------
  1818. void __fastcall TLoginDialog::HelpButtonClick(TObject * /*Sender*/)
  1819. {
  1820. FormHelp(this);
  1821. }
  1822. //---------------------------------------------------------------------------
  1823. TModalResult __fastcall TLoginDialog::DefaultResult()
  1824. {
  1825. return ::DefaultResult(this, LoginButton);
  1826. }
  1827. //---------------------------------------------------------------------------
  1828. void __fastcall TLoginDialog::FormCloseQuery(TObject * /*Sender*/,
  1829. bool & CanClose)
  1830. {
  1831. // CanClose test is now probably redundant,
  1832. // once we have a fallback to LoginButton in DefaultResult
  1833. CanClose = EnsureNotEditing();
  1834. // When CanOpen is false, the DefaultResult() will fail finding a default button
  1835. if (CanClose && CanOpen() && (ModalResult == DefaultResult()))
  1836. {
  1837. SaveDataList(FDataList);
  1838. }
  1839. }
  1840. //---------------------------------------------------------------------------
  1841. void __fastcall TLoginDialog::SessionTreeEditing(TObject * /*Sender*/,
  1842. TTreeNode * Node, bool & AllowEdit)
  1843. {
  1844. DebugAssert(!FRenaming);
  1845. AllowEdit =
  1846. IsFolderOrWorkspaceNode(Node) ||
  1847. (DebugAlwaysTrue(IsSiteNode(Node)) && !GetNodeSession(Node)->Special);
  1848. FRenaming = AllowEdit;
  1849. UpdateControls();
  1850. }
  1851. //---------------------------------------------------------------------------
  1852. void __fastcall TLoginDialog::RenameSessionActionExecute(TObject * /*Sender*/)
  1853. {
  1854. if (SessionTree->Selected != NULL)
  1855. {
  1856. // would be more appropriate in SessionTreeEditing, but it does not work there
  1857. ResetSitesIncrementalSearch();
  1858. SessionTree->SetFocus();
  1859. SessionTree->Selected->EditText();
  1860. }
  1861. }
  1862. //---------------------------------------------------------------------------
  1863. void __fastcall TLoginDialog::CheckDuplicateFolder(TTreeNode * Parent,
  1864. UnicodeString Text, TTreeNode * Node)
  1865. {
  1866. TTreeNode * ANode =
  1867. ((Parent == NULL) ? SessionTree->Items->GetFirstNode() :
  1868. Parent->getFirstChild());
  1869. // note that we allow folder with the same name as existing session
  1870. // on the same level (see also AddSession)
  1871. while ((ANode != NULL) &&
  1872. ((ANode == Node) || IsSessionNode(ANode) || !AnsiSameText(ANode->Text, Text)))
  1873. {
  1874. ANode = ANode->getNextSibling();
  1875. }
  1876. if (ANode != NULL)
  1877. {
  1878. throw Exception(MainInstructions(FMTLOAD(LOGIN_DUPLICATE_SESSION_FOLDER_WORKSPACE, (Text))));
  1879. }
  1880. }
  1881. //---------------------------------------------------------------------------
  1882. void __fastcall TLoginDialog::CheckIsSessionFolder(TTreeNode * Node)
  1883. {
  1884. if ((Node != NULL) && (Node->Parent != NULL))
  1885. {
  1886. CheckIsSessionFolder(Node->Parent);
  1887. }
  1888. if (IsWorkspaceNode(Node))
  1889. {
  1890. throw Exception(FMTLOAD(WORKSPACE_NOT_FOLDER, (SessionNodePath(Node))));
  1891. }
  1892. }
  1893. //---------------------------------------------------------------------------
  1894. void __fastcall TLoginDialog::SessionTreeEdited(TObject * /*Sender*/,
  1895. TTreeNode * Node, UnicodeString & S)
  1896. {
  1897. if ((Node->Text != S) && !S.IsEmpty())
  1898. {
  1899. TSessionData * Session = SelectedSession;
  1900. TSessionData::ValidateName(S);
  1901. if (Session != NULL)
  1902. {
  1903. UnicodeString Path = UnixExtractFilePath(Session->Name) + S;
  1904. SessionNameValidate(Path, Session->Name);
  1905. // remove from storage
  1906. Session->Remove();
  1907. TSessionData * NewSession = StoredSessions->NewSession(Path, Session);
  1908. // modified only, explicit
  1909. StoredSessions->Save(false, true);
  1910. // the session may be the same, if only letter case has changed
  1911. if (Session != NewSession)
  1912. {
  1913. // if we overwrite existing session, remove the original item
  1914. // (we must not delete the node we are editing)
  1915. TTreeNode * ANode =
  1916. ((Node->Parent == NULL) ? SessionTree->Items->GetFirstNode() :
  1917. Node->Parent->getFirstChild());
  1918. while ((ANode != NULL) && (ANode->Data != NewSession))
  1919. {
  1920. ANode = ANode->getNextSibling();
  1921. }
  1922. if (ANode != NULL)
  1923. {
  1924. ANode->Delete();
  1925. }
  1926. Node->Data = NewSession;
  1927. DestroySession(Session);
  1928. }
  1929. }
  1930. else
  1931. {
  1932. CheckDuplicateFolder(Node->Parent, S, Node);
  1933. UnicodeString ParentPath = UnixIncludeTrailingBackslash(SessionNodePath(Node->Parent));
  1934. UnicodeString OldRoot = ParentPath + Node->Text;
  1935. UnicodeString NewRoot = ParentPath + S;
  1936. bool AnySession = false;
  1937. TSortType PrevSortType = SessionTree->SortType;
  1938. // temporarily disable automatic sorting, so that nodes are kept in order
  1939. // while we traverse them. otherwise it may happen that we omit some.
  1940. SessionTree->SortType = Comctrls::stNone;
  1941. try
  1942. {
  1943. TTreeNode * ANode = Node->GetNext();
  1944. while ((ANode != NULL) && ANode->HasAsParent(Node))
  1945. {
  1946. if (IsSessionNode(ANode))
  1947. {
  1948. AnySession = true;
  1949. TSessionData * Session = GetNodeSession(ANode);
  1950. // remove from storage
  1951. Session->Remove();
  1952. UnicodeString Path = Session->Name;
  1953. DebugAssert(Path.SubString(1, OldRoot.Length()) == OldRoot);
  1954. Path.Delete(1, OldRoot.Length());
  1955. Path.Insert(NewRoot, 1);
  1956. TSessionData * NewSession = StoredSessions->NewSession(Path, Session);
  1957. // the session may be the same, if only letter case has changed
  1958. if (NewSession != Session)
  1959. {
  1960. ANode->Data = NewSession;
  1961. DestroySession(Session);
  1962. }
  1963. }
  1964. ANode = ANode->GetNext();
  1965. }
  1966. }
  1967. __finally
  1968. {
  1969. SessionTree->SortType = PrevSortType;
  1970. }
  1971. if (AnySession)
  1972. {
  1973. // modified only, explicit
  1974. StoredSessions->Save(false, true);
  1975. }
  1976. }
  1977. }
  1978. }
  1979. //---------------------------------------------------------------------------
  1980. int __fastcall TLoginDialog::FSProtocolToIndex(TFSProtocol FSProtocol,
  1981. bool & AllowScpFallback)
  1982. {
  1983. if (FSProtocol == fsSFTP)
  1984. {
  1985. AllowScpFallback = true;
  1986. bool Dummy;
  1987. return FSProtocolToIndex(fsSFTPonly, Dummy);
  1988. }
  1989. else
  1990. {
  1991. AllowScpFallback = false;
  1992. for (int Index = 0; Index < TransferProtocolCombo->Items->Count; Index++)
  1993. {
  1994. if (FSOrder[Index] == FSProtocol)
  1995. {
  1996. return Index;
  1997. }
  1998. }
  1999. // SFTP is always present
  2000. return FSProtocolToIndex(fsSFTP, AllowScpFallback);
  2001. }
  2002. }
  2003. //---------------------------------------------------------------------------
  2004. TFSProtocol __fastcall TLoginDialog::IndexToFSProtocol(int Index, bool AllowScpFallback)
  2005. {
  2006. bool InBounds = (Index >= 0) && (Index < static_cast<int>(LENOF(FSOrder)));
  2007. // can be temporary "unselected" while new language is being loaded
  2008. DebugAssert(InBounds || (Index == -1));
  2009. TFSProtocol Result = fsSFTP;
  2010. if (InBounds)
  2011. {
  2012. Result = FSOrder[Index];
  2013. if ((Result == fsSFTPonly) && AllowScpFallback)
  2014. {
  2015. Result = fsSFTP;
  2016. }
  2017. }
  2018. return Result;
  2019. }
  2020. //---------------------------------------------------------------------------
  2021. int __fastcall TLoginDialog::FtpsToIndex(TFtps Ftps)
  2022. {
  2023. switch (Ftps)
  2024. {
  2025. default:
  2026. DebugFail();
  2027. case ftpsNone:
  2028. return 0;
  2029. case ftpsImplicit:
  2030. return 1;
  2031. case ftpsExplicitTls:
  2032. case ftpsExplicitSsl:
  2033. return 2;
  2034. }
  2035. }
  2036. //---------------------------------------------------------------------------
  2037. TFtps __fastcall TLoginDialog::GetFtps()
  2038. {
  2039. TFSProtocol FSProtocol = GetFSProtocol(false);
  2040. int Index = (((FSProtocol == fsWebDAV) || (FSProtocol == fsS3)) ? WebDavsCombo->ItemIndex : FtpsCombo->ItemIndex);
  2041. TFtps Ftps;
  2042. switch (Index)
  2043. {
  2044. default:
  2045. DebugFail();
  2046. case 0:
  2047. Ftps = ftpsNone;
  2048. break;
  2049. case 1:
  2050. Ftps = ftpsImplicit;
  2051. break;
  2052. case 2:
  2053. Ftps = ftpsExplicitTls;
  2054. break;
  2055. }
  2056. return Ftps;
  2057. }
  2058. //---------------------------------------------------------------------------
  2059. TFSProtocol __fastcall TLoginDialog::GetFSProtocol(bool RequireScpFallbackDistinction)
  2060. {
  2061. bool AllowScpFallback = false;
  2062. if (RequireScpFallbackDistinction && DebugAlwaysTrue(FSessionData != NULL))
  2063. {
  2064. FSProtocolToIndex(FSessionData->FSProtocol, AllowScpFallback);
  2065. }
  2066. return IndexToFSProtocol(TransferProtocolCombo->ItemIndex, AllowScpFallback);
  2067. }
  2068. //---------------------------------------------------------------------------
  2069. int __fastcall TLoginDialog::DefaultPort()
  2070. {
  2071. return ::DefaultPort(GetFSProtocol(false), GetFtps());
  2072. }
  2073. //---------------------------------------------------------------------------
  2074. void TLoginDialog::UpdateS3Credentials()
  2075. {
  2076. if (S3CredentialsEnvCheck2->Checked)
  2077. {
  2078. UnicodeString S3Profile = GetS3Profile();
  2079. UserNameEdit->Text = S3EnvUserName(S3Profile);
  2080. PasswordEdit->Text = S3EnvPassword(S3Profile);
  2081. // Is not set when viewing stored session.
  2082. // We do this, so that when the checkbox is checked and unchecked, the token is preserved, the way username and password are.
  2083. if (FSessionData != NULL)
  2084. {
  2085. FSessionData->S3SessionToken = S3EnvSessionToken(S3Profile);
  2086. }
  2087. }
  2088. }
  2089. //---------------------------------------------------------------------------
  2090. void __fastcall TLoginDialog::TransferProtocolComboChange(TObject * Sender)
  2091. {
  2092. if (!NoUpdate)
  2093. {
  2094. if (GetFSProtocol(false) == fsS3)
  2095. {
  2096. // Note that this happens even when loading the session
  2097. // But the values will get overwritten.
  2098. WebDavsCombo->ItemIndex = FtpsToIndex(ftpsImplicit);
  2099. HostNameEdit->Text = S3HostName;
  2100. }
  2101. else
  2102. {
  2103. try
  2104. {
  2105. UnicodeString S3Profile = GetS3Profile();
  2106. if (HostNameEdit->Text == S3HostName)
  2107. {
  2108. HostNameEdit->Clear();
  2109. }
  2110. // Optimization to avoid querying AWS metadata service.
  2111. // Smarter would be to tell S3EnvXXX functions not to do expensive queries.
  2112. if (FWasEverS3)
  2113. {
  2114. if (UserNameEdit->Text == S3EnvUserName(S3Profile))
  2115. {
  2116. UserNameEdit->Clear();
  2117. }
  2118. if (PasswordEdit->Text == S3EnvPassword(S3Profile))
  2119. {
  2120. PasswordEdit->Clear();
  2121. }
  2122. if ((FSessionData != NULL) && (FSessionData->S3SessionToken == S3EnvSessionToken(S3Profile)))
  2123. {
  2124. FSessionData->S3SessionToken = UnicodeString();
  2125. }
  2126. }
  2127. }
  2128. catch (...)
  2129. {
  2130. // noop
  2131. }
  2132. }
  2133. S3CredentialsEnvCheck2->Checked = false;
  2134. }
  2135. UpdatePortWithProtocol();
  2136. DataChange(Sender);
  2137. }
  2138. //---------------------------------------------------------------------------
  2139. void TLoginDialog::UpdatePortWithProtocol()
  2140. {
  2141. int ADefaultPort = DefaultPort();
  2142. if (!NoUpdate && FUpdatePortWithProtocol)
  2143. {
  2144. NoUpdate++;
  2145. try
  2146. {
  2147. if (PortNumberEdit->AsInteger == FDefaultPort)
  2148. {
  2149. PortNumberEdit->AsInteger = ADefaultPort;
  2150. }
  2151. }
  2152. __finally
  2153. {
  2154. NoUpdate--;
  2155. }
  2156. }
  2157. FDefaultPort = ADefaultPort;
  2158. }
  2159. //---------------------------------------------------------------------------
  2160. void __fastcall TLoginDialog::EncryptionComboChange(TObject * Sender)
  2161. {
  2162. UpdatePortWithProtocol();
  2163. DataChange(Sender);
  2164. }
  2165. //---------------------------------------------------------------------------
  2166. void __fastcall TLoginDialog::NavigationTreeCollapsing(
  2167. TObject * /*Sender*/, TTreeNode * /*Node*/, bool & AllowCollapse)
  2168. {
  2169. AllowCollapse = false;
  2170. }
  2171. //---------------------------------------------------------------------------
  2172. void __fastcall TLoginDialog::SessionTreeExpandedCollapsed(TObject * /*Sender*/,
  2173. TTreeNode * Node)
  2174. {
  2175. UpdateFolderNode(Node);
  2176. }
  2177. //---------------------------------------------------------------------------
  2178. void __fastcall TLoginDialog::SessionTreeCompare(TObject * /*Sender*/,
  2179. TTreeNode * Node1, TTreeNode * Node2, int /*Data*/, int & Compare)
  2180. {
  2181. bool Node1IsNewSite = IsNewSiteNode(Node1);
  2182. bool Node2IsNewSite = IsNewSiteNode(Node2);
  2183. bool Node1IsWorkspace = IsWorkspaceNode(Node1);
  2184. bool Node2IsWorkspace = IsWorkspaceNode(Node2);
  2185. bool Node1IsFolder = IsFolderNode(Node1);
  2186. bool Node2IsFolder = IsFolderNode(Node2);
  2187. if (Node1IsNewSite && !Node2IsNewSite)
  2188. {
  2189. Compare = -1;
  2190. }
  2191. else if (!Node1IsNewSite && Node2IsNewSite)
  2192. {
  2193. Compare = 1;
  2194. }
  2195. else if (Node1IsWorkspace && !Node2IsWorkspace)
  2196. {
  2197. Compare = -1;
  2198. }
  2199. else if (!Node1IsWorkspace && Node2IsWorkspace)
  2200. {
  2201. Compare = 1;
  2202. }
  2203. else if (Node1IsFolder && !Node2IsFolder)
  2204. {
  2205. Compare = -1;
  2206. }
  2207. else if (!Node1IsFolder && Node2IsFolder)
  2208. {
  2209. Compare = 1;
  2210. }
  2211. else if (Node1IsWorkspace || Node1IsFolder)
  2212. {
  2213. Compare = CompareLogicalText(Node1->Text, Node2->Text, true);
  2214. }
  2215. else
  2216. {
  2217. Compare = NamedObjectSortProc(Node1->Data, Node2->Data);
  2218. }
  2219. }
  2220. //---------------------------------------------------------------------------
  2221. void __fastcall TLoginDialog::NewSessionFolderInputDialogInitialize(
  2222. TObject * /*Sender*/, TInputDialogData * Data)
  2223. {
  2224. TCustomEdit * Edit = Data->Edit;
  2225. int P = Edit->Text.LastDelimiter(L"/");
  2226. if (P > 0)
  2227. {
  2228. Edit->SetFocus();
  2229. Edit->SelStart = P;
  2230. Edit->SelLength = Edit->Text.Length() - P;
  2231. }
  2232. }
  2233. //---------------------------------------------------------------------------
  2234. TTreeNode * __fastcall TLoginDialog::SessionFolderNode(TTreeNode * Node)
  2235. {
  2236. TTreeNode * Parent;
  2237. if (IsSessionNode(Node))
  2238. {
  2239. Parent = Node->Parent;
  2240. }
  2241. else if (IsFolderNode(Node))
  2242. {
  2243. Parent = Node;
  2244. }
  2245. else if (IsWorkspaceNode(Node))
  2246. {
  2247. Parent = NULL;
  2248. }
  2249. else
  2250. {
  2251. DebugAssert(Node == NULL);
  2252. Parent = NULL;
  2253. }
  2254. return Parent;
  2255. }
  2256. //---------------------------------------------------------------------------
  2257. TTreeNode * __fastcall TLoginDialog::CurrentSessionFolderNode()
  2258. {
  2259. return SessionFolderNode(SessionTree->Selected);
  2260. }
  2261. //---------------------------------------------------------------------------
  2262. void __fastcall TLoginDialog::NewSessionFolderActionExecute(
  2263. TObject * /*Sender*/)
  2264. {
  2265. UnicodeString Name =
  2266. UnixIncludeTrailingBackslash(SessionNodePath(CurrentSessionFolderNode())) +
  2267. LoadStr(NEW_FOLDER);
  2268. if (InputDialog(LoadStr(LOGIN_NEW_SESSION_FOLDER_CAPTION),
  2269. LoadStr(LOGIN_NEW_SESSION_FOLDER_PROMPT), Name, HELP_NEW_SESSION_FOLDER,
  2270. NULL, true, NewSessionFolderInputDialogInitialize))
  2271. {
  2272. Name = UnixExcludeTrailingBackslash(Name);
  2273. if (!Name.IsEmpty())
  2274. {
  2275. TTreeNode * Parent = AddSessionPath(UnixExtractFilePath(Name), true, false);
  2276. // this does not prevent creation of subfolder under workspace,
  2277. // if user creates more levels at once (but it does not show up anyway)
  2278. CheckIsSessionFolder(Parent);
  2279. CheckDuplicateFolder(Parent, UnixExtractFileName(Name), NULL);
  2280. TTreeNode * Node = AddSessionPath(Name, true, false);
  2281. SessionTree->Selected = Node;
  2282. Node->MakeVisible();
  2283. }
  2284. }
  2285. }
  2286. //---------------------------------------------------------------------------
  2287. TTreeNode * __fastcall TLoginDialog::NormalizeDropTarget(TTreeNode * DropTarget)
  2288. {
  2289. return IsWorkspaceNode(DropTarget) ? DropTarget : SessionFolderNode(DropTarget);
  2290. }
  2291. //---------------------------------------------------------------------------
  2292. bool __fastcall TLoginDialog::SessionAllowDrop(TTreeNode * DropTarget)
  2293. {
  2294. DropTarget = NormalizeDropTarget(DropTarget);
  2295. return
  2296. (SessionTree->Selected != NULL) &&
  2297. (SessionTree->Selected->Parent != DropTarget) &&
  2298. ((DropTarget == NULL) || IsFolderNode(DropTarget));
  2299. }
  2300. //---------------------------------------------------------------------------
  2301. void __fastcall TLoginDialog::SessionTreeProc(TMessage & AMessage)
  2302. {
  2303. if (AMessage.Msg == CM_DRAG)
  2304. {
  2305. TCMDrag & Message = reinterpret_cast<TCMDrag &>(AMessage);
  2306. // reimplement dmDragMove to avoid TCustomTreeView.DoDragOver,
  2307. // which resets DropTarget to pointed-to node
  2308. // (note that this disables OnDragOver event handler)
  2309. if ((Message.DragMessage == dmDragMove) ||
  2310. (Message.DragMessage == dmDragEnter) ||
  2311. (Message.DragMessage == dmDragLeave))
  2312. {
  2313. if (Message.DragMessage != dmDragMove)
  2314. {
  2315. // must call it at least for dmDragLeave, because it does some cleanup,
  2316. // but we need to override result below, as it defaults to "not accepted"
  2317. FOldSessionTreeProc(AMessage);
  2318. }
  2319. TDragControlObject * DragObject = dynamic_cast<TDragControlObject *>(Message.DragRec->Source);
  2320. if ((DragObject != NULL) && (DragObject->Control == SessionTree))
  2321. {
  2322. TPoint P = SessionTree->ScreenToClient(Message.DragRec->Pos);
  2323. TTreeNode * Node = SessionTree->GetNodeAt(P.x, P.y);
  2324. if (!SessionAllowDrop(Node))
  2325. {
  2326. DropTarget = NULL;
  2327. Message.Result = 0;
  2328. }
  2329. else
  2330. {
  2331. Message.Result = 1;
  2332. }
  2333. if (Message.DragMessage == dmDragMove)
  2334. {
  2335. SessionTree->DropTarget = NormalizeDropTarget(Node);
  2336. }
  2337. FScrollOnDragOver->DragOver(P);
  2338. }
  2339. else
  2340. {
  2341. Message.Result = 0;
  2342. }
  2343. }
  2344. else
  2345. {
  2346. FOldSessionTreeProc(AMessage);
  2347. }
  2348. }
  2349. else
  2350. {
  2351. FOldSessionTreeProc(AMessage);
  2352. }
  2353. }
  2354. //---------------------------------------------------------------------------
  2355. void __fastcall TLoginDialog::SessionTreeStartDrag(TObject * /*Sender*/,
  2356. TDragObject *& /*DragObject*/)
  2357. {
  2358. DebugAssert(SessionTree->Selected != NULL);
  2359. // neither session folders/workspaces, nor special sessions can be dragged
  2360. if ((SessionTree->Selected == NULL) ||
  2361. IsFolderOrWorkspaceNode(SessionTree->Selected) ||
  2362. IsNewSiteNode(SessionTree->Selected) ||
  2363. (IsSiteNode(SessionTree->Selected) && SelectedSession->Special))
  2364. {
  2365. Abort();
  2366. }
  2367. FScrollOnDragOver->StartDrag();
  2368. }
  2369. //---------------------------------------------------------------------------
  2370. void __fastcall TLoginDialog::SessionTreeDragDrop(TObject * Sender,
  2371. TObject * Source, int /*X*/, int /*Y*/)
  2372. {
  2373. TTreeNode * DropTarget = SessionTree->DropTarget;
  2374. if (DebugAlwaysTrue((Sender == Source) && SessionAllowDrop(DropTarget)) &&
  2375. // calling EnsureNotEditing only on drop, not on drag start,
  2376. // to avoid getting popup during unintended micro-dragging
  2377. EnsureNotEditing())
  2378. {
  2379. TSessionData * Session = SelectedSession;
  2380. UnicodeString Path =
  2381. UnixIncludeTrailingBackslash(SessionNodePath(DropTarget)) +
  2382. UnixExtractFileName(Session->SessionName);
  2383. SessionNameValidate(Path, Session->SessionName);
  2384. // remove from storage
  2385. Session->Remove();
  2386. TSessionData * NewSession = StoredSessions->NewSession(Path, Session);
  2387. // modified only, explicit
  2388. StoredSessions->Save(false, true);
  2389. // this should aways be the case
  2390. if (DebugAlwaysTrue(Session != NewSession))
  2391. {
  2392. TTreeNode * Node = SessionTree->Selected;
  2393. // look for overwritten node (if any)
  2394. TTreeNode * ANode = SessionTree->Items->GetFirstNode();
  2395. while (ANode != NULL)
  2396. {
  2397. if (ANode->Data == NewSession)
  2398. {
  2399. ANode->Delete();
  2400. break;
  2401. }
  2402. ANode = ANode->GetNext();
  2403. }
  2404. Node->MoveTo(DropTarget, naAddChild);
  2405. Node->Data = NewSession;
  2406. // try to make both visible
  2407. if (DropTarget != NULL)
  2408. {
  2409. DropTarget->MakeVisible();
  2410. }
  2411. Node->MakeVisible();
  2412. DestroySession(Session);
  2413. }
  2414. }
  2415. }
  2416. //---------------------------------------------------------------------------
  2417. UnicodeString __fastcall TLoginDialog::GetFolderOrWorkspaceContents(
  2418. TTreeNode * Node, const UnicodeString & Indent, const UnicodeString & CommonRoot)
  2419. {
  2420. UnicodeString Contents;
  2421. UnicodeString Path = SessionNodePath(Node);
  2422. std::unique_ptr<TStrings> Names(StoredSessions->GetFolderOrWorkspaceList(Path));
  2423. for (int Index = 0; Index < Names->Count; Index++)
  2424. {
  2425. UnicodeString Name = Names->Strings[Index];
  2426. if (StartsStr(CommonRoot, Name))
  2427. {
  2428. Name.Delete(1, CommonRoot.Length());
  2429. }
  2430. Contents += Indent + Name + L"\n";
  2431. }
  2432. return Contents;
  2433. }
  2434. //---------------------------------------------------------------------------
  2435. void __fastcall TLoginDialog::SessionTreeMouseMove(TObject * /*Sender*/,
  2436. TShiftState /*Shift*/, int X, int Y)
  2437. {
  2438. TTreeNode * Node = SessionTree->GetNodeAt(X, Y);
  2439. THitTests HitTest = SessionTree->GetHitTestInfoAt(X, Y);
  2440. if (Node != FHintNode)
  2441. {
  2442. Application->CancelHint();
  2443. UnicodeString Hint;
  2444. if (HitTest.Contains(htOnItem) || HitTest.Contains(htOnIcon) ||
  2445. HitTest.Contains(htOnLabel) || HitTest.Contains(htOnStateIcon))
  2446. {
  2447. FHintNode = Node;
  2448. if (IsSiteNode(Node))
  2449. {
  2450. Hint = GetNodeSession(Node)->InfoTip;
  2451. }
  2452. else if (IsWorkspaceNode(Node))
  2453. {
  2454. UnicodeString Path = SessionNodePath(Node);
  2455. Hint =
  2456. FMTLOAD(WORKSPACE_INFO_TIP, (Path)) + L"\n" +
  2457. // trim the trailing new line
  2458. TrimRight(GetFolderOrWorkspaceContents(Node, L" ", UnicodeString()));
  2459. }
  2460. else
  2461. {
  2462. Hint = L"";
  2463. }
  2464. }
  2465. else
  2466. {
  2467. FHintNode = NULL;
  2468. Hint = L"";
  2469. }
  2470. SessionTree->Hint = Hint;
  2471. }
  2472. }
  2473. //---------------------------------------------------------------------------
  2474. void __fastcall TLoginDialog::SessionTreeEndDrag(TObject * /*Sender*/,
  2475. TObject * /*Target*/, int /*X*/, int /*Y*/)
  2476. {
  2477. FScrollOnDragOver->EndDrag();
  2478. }
  2479. //---------------------------------------------------------------------------
  2480. void __fastcall TLoginDialog::AnonymousLoginCheckClick(TObject * /*Sender*/)
  2481. {
  2482. if (AnonymousLoginCheck->Checked)
  2483. {
  2484. UserNameEdit->Text = AnonymousUserName;
  2485. PasswordEdit->Text = AnonymousPassword;
  2486. }
  2487. UpdateControls();
  2488. }
  2489. //---------------------------------------------------------------------------
  2490. void __fastcall TLoginDialog::SaveButtonDropDownClick(TObject * /*Sender*/)
  2491. {
  2492. MenuPopup(SaveDropDownMenu, SaveButton);
  2493. }
  2494. //---------------------------------------------------------------------------
  2495. void __fastcall TLoginDialog::SessionTreeExpanding(TObject * /*Sender*/,
  2496. TTreeNode * Node, bool & AllowExpansion)
  2497. {
  2498. // to prevent workspace expansion
  2499. AllowExpansion = IsFolderNode(Node);
  2500. }
  2501. //---------------------------------------------------------------------------
  2502. void __fastcall TLoginDialog::RunPageantActionExecute(TObject * /*Sender*/)
  2503. {
  2504. ExecuteTool(PageantTool);
  2505. }
  2506. //---------------------------------------------------------------------------
  2507. void __fastcall TLoginDialog::RunPuttygenActionExecute(TObject * /*Sender*/)
  2508. {
  2509. ExecuteTool(PuttygenTool);
  2510. }
  2511. //---------------------------------------------------------------------------
  2512. void __fastcall TLoginDialog::PortNumberEditChange(TObject * Sender)
  2513. {
  2514. if (!NoUpdate)
  2515. {
  2516. bool WellKnownPort = false;
  2517. TFSProtocol FSProtocol;
  2518. TFtps Ftps = ftpsNone;
  2519. int PortNumber = PortNumberEdit->AsInteger;
  2520. if (PortNumber == SshPortNumber)
  2521. {
  2522. FSProtocol = fsSFTP;
  2523. WellKnownPort = true;
  2524. }
  2525. else if (PortNumber == FtpPortNumber)
  2526. {
  2527. FSProtocol = fsFTP;
  2528. WellKnownPort = true;
  2529. }
  2530. else if (PortNumber == FtpsImplicitPortNumber)
  2531. {
  2532. FSProtocol = fsFTP;
  2533. Ftps = ftpsImplicit;
  2534. WellKnownPort = true;
  2535. }
  2536. else if (PortNumber == HTTPPortNumber)
  2537. {
  2538. FSProtocol = fsWebDAV;
  2539. WellKnownPort = true;
  2540. }
  2541. else if (PortNumber == HTTPSPortNumber)
  2542. {
  2543. FSProtocol = fsWebDAV;
  2544. Ftps = ftpsImplicit;
  2545. WellKnownPort = true;
  2546. }
  2547. if (WellKnownPort)
  2548. {
  2549. bool AllowScpFallback;
  2550. int ProtocolIndex = FSProtocolToIndex(FSProtocol, AllowScpFallback);
  2551. if ((TransferProtocolCombo->ItemIndex == ProtocolIndex) &&
  2552. (GetFtps() == Ftps))
  2553. {
  2554. FUpdatePortWithProtocol = true;
  2555. }
  2556. else
  2557. {
  2558. FUpdatePortWithProtocol = false;
  2559. NoUpdate++;
  2560. try
  2561. {
  2562. TransferProtocolCombo->ItemIndex = ProtocolIndex;
  2563. int FtpsIndex = FtpsToIndex(Ftps);
  2564. FtpsCombo->ItemIndex = FtpsIndex;
  2565. WebDavsCombo->ItemIndex = FtpsIndex;
  2566. }
  2567. __finally
  2568. {
  2569. NoUpdate--;
  2570. }
  2571. }
  2572. }
  2573. }
  2574. DataChange(Sender);
  2575. }
  2576. //---------------------------------------------------------------------------
  2577. void __fastcall TLoginDialog::ExportActionExecute(TObject * /*Sender*/)
  2578. {
  2579. UnicodeString FileName = Configuration->GetDefaultIniFileExportPath();
  2580. if (SaveDialog(LoadStr(EXPORT_CONF_TITLE), LoadStr(EXPORT_CONF_FILTER), L"ini", FileName))
  2581. {
  2582. Configuration->Export(FileName);
  2583. }
  2584. }
  2585. //---------------------------------------------------------------------------
  2586. void __fastcall TLoginDialog::ImportActionExecute(TObject * /*Sender*/)
  2587. {
  2588. if (MessageDialog(LoadStr(IMPORT_CONFIGURATION2),
  2589. qtWarning, qaOK | qaCancel, HELP_IMPORT_CONFIGURATION) == qaOK)
  2590. {
  2591. std::unique_ptr<TOpenDialog> OpenDialog(new TOpenDialog(Application));
  2592. OpenDialog->Title = LoadStr(IMPORT_CONF_TITLE);
  2593. OpenDialog->Filter = LoadStr(EXPORT_CONF_FILTER);
  2594. OpenDialog->DefaultExt = L"ini";
  2595. OpenDialog->FileName = Configuration->GetDefaultIniFileExportPath();
  2596. if (OpenDialog->Execute())
  2597. {
  2598. // Before the session list gets destroyed
  2599. SessionTree->Items->Clear();
  2600. Configuration->Import(OpenDialog->FileName);
  2601. // Similar to TPreferencesDialog::CustomIniFileStorageChanged
  2602. ExecuteSelf(EmptyStr);
  2603. TerminateApplication();
  2604. }
  2605. }
  2606. }
  2607. //---------------------------------------------------------------------------
  2608. void __fastcall TLoginDialog::ResetSitesIncrementalSearch()
  2609. {
  2610. FSitesIncrementalSearch = L"";
  2611. // this is to prevent active tree node being set back to Sites tab
  2612. // (from UpdateNavigationTree) when we are called from SessionTreeExit,
  2613. // while tab is changing
  2614. if (NoUpdate == 0)
  2615. {
  2616. UpdateControls();
  2617. }
  2618. }
  2619. //---------------------------------------------------------------------------
  2620. bool __fastcall TLoginDialog::SitesIncrementalSearch(
  2621. const UnicodeString & Text, bool SkipCurrent, bool Reverse, bool Expanding)
  2622. {
  2623. TTreeNode * Node = NULL;
  2624. if (!Expanding)
  2625. {
  2626. Node = SearchSite(Text, false, SkipCurrent, Reverse);
  2627. }
  2628. if (Node == NULL)
  2629. {
  2630. Node = SearchSite(Text, true, SkipCurrent, Reverse);
  2631. if (Node != NULL)
  2632. {
  2633. TTreeNode * Parent = Node->Parent;
  2634. while (Parent != NULL)
  2635. {
  2636. Parent->Expand(false);
  2637. Parent = Parent->Parent;
  2638. }
  2639. }
  2640. }
  2641. bool Result = (Node != NULL);
  2642. if (Result)
  2643. {
  2644. {
  2645. TAutoNestingCounter Guard(FIncrementalSearching);
  2646. SessionTree->Selected = Node;
  2647. }
  2648. FSitesIncrementalSearch = Text;
  2649. // Tab always searches even in collapsed nodes
  2650. TTreeNode * NextNode = SearchSite(Text, true, true, Reverse);
  2651. FSitesIncrementalSearchHaveNext =
  2652. (NextNode != NULL) && (NextNode != Node);
  2653. UpdateControls();
  2654. // make visible only after search panel is shown, what may obscure the node
  2655. Node->MakeVisible();
  2656. }
  2657. return Result;
  2658. }
  2659. //---------------------------------------------------------------------------
  2660. TTreeNode * __fastcall TLoginDialog::GetNextNode(TTreeNode * Node, bool Reverse)
  2661. {
  2662. if (Reverse)
  2663. {
  2664. Node = Node->GetPrev();
  2665. if (Node == NULL)
  2666. {
  2667. // GetLastNode
  2668. // https://stackoverflow.com/q/6257348/850848
  2669. Node = SessionTree->Items->GetFirstNode();
  2670. TTreeNode * Node2 = Node;
  2671. if (Node2 != NULL)
  2672. {
  2673. do
  2674. {
  2675. Node2 = Node;
  2676. if (Node != NULL)
  2677. {
  2678. Node = Node2->getNextSibling();
  2679. }
  2680. if (Node == NULL)
  2681. {
  2682. Node = Node2->getFirstChild();
  2683. }
  2684. }
  2685. while (Node != NULL);
  2686. }
  2687. Node = Node2;
  2688. }
  2689. }
  2690. else
  2691. {
  2692. Node = Node->GetNext();
  2693. if (Node == NULL)
  2694. {
  2695. Node = SessionTree->Items->GetFirstNode();
  2696. }
  2697. }
  2698. return Node;
  2699. }
  2700. //---------------------------------------------------------------------------
  2701. TTreeNode * __fastcall TLoginDialog::SearchSite(const UnicodeString & Text,
  2702. bool AllowExpanding, bool SkipCurrent, bool Reverse)
  2703. {
  2704. TTreeNode * CurrentNode =
  2705. (SessionTree->Selected != NULL) ? SessionTree->Selected : SessionTree->Items->GetFirstNode();
  2706. if (CurrentNode == NULL)
  2707. {
  2708. return NULL;
  2709. }
  2710. else
  2711. {
  2712. TTreeNode * Node = CurrentNode;
  2713. if (SkipCurrent)
  2714. {
  2715. Node = GetNextNode(Node, Reverse);
  2716. if (Node == NULL)
  2717. {
  2718. return NULL;
  2719. }
  2720. }
  2721. while (true)
  2722. {
  2723. bool Eligible = true;
  2724. TTreeNode * Parent = Node->Parent;
  2725. while (Eligible && (Parent != NULL))
  2726. {
  2727. Eligible =
  2728. IsFolderNode(Parent) &&
  2729. (Parent->Expanded || AllowExpanding);
  2730. Parent = Parent->Parent;
  2731. }
  2732. if (Eligible)
  2733. {
  2734. bool Matches = false;
  2735. switch (FSiteSearch)
  2736. {
  2737. case isNameStartOnly:
  2738. Matches = ContainsTextSemiCaseSensitive(Node->Text.SubString(1, Text.Length()), Text);
  2739. break;
  2740. case isName:
  2741. Matches = ContainsTextSemiCaseSensitive(Node->Text, Text);
  2742. break;
  2743. case isAll:
  2744. Matches = ContainsTextSemiCaseSensitive(Node->Text, Text);
  2745. if (!Matches && IsSiteNode(Node))
  2746. {
  2747. TSessionData * Data = GetNodeSession(Node);
  2748. Matches =
  2749. ContainsTextSemiCaseSensitive(Data->HostName, Text) ||
  2750. ContainsTextSemiCaseSensitive(Data->UserName, Text) ||
  2751. ContainsTextSemiCaseSensitive(Data->Note, Text);
  2752. }
  2753. break;
  2754. }
  2755. if (Matches)
  2756. {
  2757. return Node;
  2758. }
  2759. }
  2760. Node = GetNextNode(Node, Reverse);
  2761. if (Node == CurrentNode)
  2762. {
  2763. return NULL;
  2764. }
  2765. }
  2766. }
  2767. }
  2768. //---------------------------------------------------------------------------
  2769. void __fastcall TLoginDialog::SessionTreeExit(TObject * /*Sender*/)
  2770. {
  2771. ResetSitesIncrementalSearch();
  2772. }
  2773. //---------------------------------------------------------------------------
  2774. bool __fastcall TLoginDialog::EnsureNotEditing()
  2775. {
  2776. bool Result = !FEditing;
  2777. if (!Result)
  2778. {
  2779. UnicodeString Message = MainInstructions(LoadStr(LOGIN_SAVE_EDITING));
  2780. unsigned int Answer = MessageDialog(Message, qtConfirmation, qaYes |qaNo | qaCancel);
  2781. switch (Answer)
  2782. {
  2783. case qaYes:
  2784. SaveAsSession(false);
  2785. Result = true;
  2786. break;
  2787. case qaNo:
  2788. CancelEditing();
  2789. // Make sure OK button gets enabled
  2790. UpdateControls();
  2791. Result = true;
  2792. break;
  2793. default:
  2794. // noop;
  2795. break;
  2796. }
  2797. }
  2798. return Result;
  2799. }
  2800. //---------------------------------------------------------------------------
  2801. void __fastcall TLoginDialog::SessionTreeChanging(TObject * /*Sender*/,
  2802. TTreeNode * /*Node*/, bool & AllowChange)
  2803. {
  2804. if (!EnsureNotEditing())
  2805. {
  2806. AllowChange = false;
  2807. }
  2808. else
  2809. {
  2810. PersistNewSiteIfNeeded();
  2811. }
  2812. }
  2813. //---------------------------------------------------------------------------
  2814. void __fastcall TLoginDialog::PersistNewSiteIfNeeded()
  2815. {
  2816. // Visible: Never try to save data if we did not load any yet,
  2817. // otherwise we get "HostNameEdit" and such
  2818. if (Visible && IsNewSiteNode(SessionTree->Selected))
  2819. {
  2820. SaveSession(FNewSiteData);
  2821. }
  2822. }
  2823. //---------------------------------------------------------------------------
  2824. void __fastcall TLoginDialog::SessionAdvancedActionExecute(TObject * Sender)
  2825. {
  2826. // If we ever allow showing advanced settings, while read-only,
  2827. // we must make sure that FSessionData actually holds the advanced settings,
  2828. // what it currently does not, in order to avoid master password prompt,
  2829. // while cloning the session data in LoadSession.
  2830. // To implement this, we may delegate the cloning to TWinConfiguration and
  2831. // make use of FDontDecryptPasswords
  2832. if (DebugAlwaysTrue(FSessionData != NULL))
  2833. {
  2834. // parse hostname (it may change protocol particularly) before opening advanced settings
  2835. // (HostNameEditExit is not triggered when child dialog pops up when it is invoked by accelerator)
  2836. // We should better handle this automaticaly when focus is moved to another dialog.
  2837. ParseHostName();
  2838. SaveSession(FSessionData);
  2839. if (Sender == SessionAdvancedAction)
  2840. {
  2841. DoSiteAdvancedDialog(FSessionData);
  2842. }
  2843. else
  2844. {
  2845. DoSiteRawDialog(FSessionData);
  2846. }
  2847. // Needed only for Note.
  2848. // The only other property visible on Login dialog that Advanced site dialog
  2849. // can change is protocol (between fsSFTP and fsSFTPonly),
  2850. // difference of the two not being visible on Login dialog anyway.
  2851. LoadSession(FSessionData);
  2852. if (DebugAlwaysTrue(SessionTree->Selected != NULL) &&
  2853. IsSiteNode(SessionTree->Selected))
  2854. {
  2855. SetNodeImage(SessionTree->Selected, GetSessionImageIndex(FSessionData));
  2856. }
  2857. }
  2858. }
  2859. //---------------------------------------------------------------------------
  2860. TPopupMenu * __fastcall TLoginDialog::GetSelectedNodePopupMenu()
  2861. {
  2862. TPopupMenu * PopupMenu = NULL;
  2863. TTreeNode * Selected = SessionTree->Selected;
  2864. if (IsNewSiteNode(Selected))
  2865. {
  2866. PopupMenu = ManageNewSitePopupMenu;
  2867. }
  2868. else if (IsSiteNode(Selected))
  2869. {
  2870. PopupMenu = ManageSitePopupMenu;
  2871. }
  2872. else if (IsFolderNode(Selected))
  2873. {
  2874. PopupMenu = ManageFolderPopupMenu;
  2875. }
  2876. else if (IsWorkspaceNode(Selected))
  2877. {
  2878. PopupMenu = ManageWorkspacePopupMenu;
  2879. }
  2880. return DebugNotNull(PopupMenu);
  2881. }
  2882. //---------------------------------------------------------------------------
  2883. void __fastcall TLoginDialog::ManageButtonClick(TObject * /*Sender*/)
  2884. {
  2885. MenuPopup(GetSelectedNodePopupMenu(), ManageButton);
  2886. }
  2887. //---------------------------------------------------------------------------
  2888. void __fastcall TLoginDialog::SessionTreeMouseDown(TObject * /*Sender*/,
  2889. TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  2890. {
  2891. TTreeNode * Node = SessionTree->GetNodeAt(X, Y);
  2892. if ((Button == mbRight) && (Node != NULL))
  2893. {
  2894. SessionTree->Selected = Node;
  2895. }
  2896. }
  2897. //---------------------------------------------------------------------------
  2898. void __fastcall TLoginDialog::SessionTreeContextPopup(TObject * /*Sender*/,
  2899. TPoint & MousePos, bool & Handled)
  2900. {
  2901. ResetSitesIncrementalSearch();
  2902. TTreeNode * Node = SessionTree->GetNodeAt(MousePos.X, MousePos.Y);
  2903. // This is mostly to prevent context menu from poping up,
  2904. // while there is prompt to confirm cancelling session edit,
  2905. // when right mouse is clicked on non-selected node
  2906. if (Node != SessionTree->Selected)
  2907. {
  2908. Handled = true;
  2909. }
  2910. else
  2911. {
  2912. if (SessionTree->Selected != NULL)
  2913. {
  2914. SessionTree->PopupMenu = GetSelectedNodePopupMenu();
  2915. if (DebugNotNull(SessionTree->PopupMenu))
  2916. {
  2917. MenuPopup(SessionTree, MousePos, Handled);
  2918. }
  2919. }
  2920. }
  2921. }
  2922. //---------------------------------------------------------------------------
  2923. void __fastcall TLoginDialog::EditCancelActionExecute(TObject * /*Sender*/)
  2924. {
  2925. CancelEditing();
  2926. // reset back to saved settings
  2927. LoadContents();
  2928. UpdateControls();
  2929. // we do not want to see blinking cursor in read-only edit box
  2930. SessionTree->SetFocus();
  2931. }
  2932. //---------------------------------------------------------------------------
  2933. void __fastcall TLoginDialog::AdvancedButtonDropDownClick(TObject * /*Sender*/)
  2934. {
  2935. MenuPopup(SessionAdvancedPopupMenu, AdvancedButton);
  2936. }
  2937. //---------------------------------------------------------------------------
  2938. void __fastcall TLoginDialog::CancelEditing()
  2939. {
  2940. FEditing = false;
  2941. // reset back the color
  2942. UpdateNodeImage(SessionTree->Selected);
  2943. }
  2944. //---------------------------------------------------------------------------
  2945. void __fastcall TLoginDialog::CloneToNewSite()
  2946. {
  2947. FNewSiteData->CopyData(SelectedSession);
  2948. FNewSiteData->MakeUniqueIn(StoredSessions);
  2949. FNewSiteKeepName = true;
  2950. NewSite();
  2951. EditSession();
  2952. }
  2953. //---------------------------------------------------------------------------
  2954. void __fastcall TLoginDialog::CloneToNewSiteActionExecute(TObject * /*Sender*/)
  2955. {
  2956. CloneToNewSite();
  2957. }
  2958. //---------------------------------------------------------------------------
  2959. void __fastcall TLoginDialog::Login()
  2960. {
  2961. if (OpenInNewWindow() && !IsNewSiteNode(SessionTree->Selected))
  2962. {
  2963. UnicodeString Path = SessionNodePath(SessionTree->Selected);
  2964. ExecuteNewInstance(EncodeUrlString(Path));
  2965. // prevent closing the window, see below
  2966. ModalResult = mrNone;
  2967. }
  2968. else
  2969. {
  2970. // this is not needed when used from LoginButton,
  2971. // but is needed when used from popup menus
  2972. ModalResult = LoginButton->ModalResult;
  2973. }
  2974. }
  2975. //---------------------------------------------------------------------------
  2976. void __fastcall TLoginDialog::LoginActionExecute(TObject * /*Sender*/)
  2977. {
  2978. Login();
  2979. }
  2980. //---------------------------------------------------------------------------
  2981. void __fastcall TLoginDialog::PuttyActionExecute(TObject * /*Sender*/)
  2982. {
  2983. // following may take some time, so cache the shift key state,
  2984. // in case user manages to release it before following finishes
  2985. bool Close = !OpenInNewWindow();
  2986. std::unique_ptr<TList> DataList(new TList());
  2987. SaveDataList(DataList.get());
  2988. for (int Index = 0; Index < DataList->Count; Index++)
  2989. {
  2990. TSessionData * Data = reinterpret_cast<TSessionData *>(DataList->Items[Index]);
  2991. OpenSessionInPutty(Data);
  2992. }
  2993. if (Close)
  2994. {
  2995. ModalResult = CloseButton->ModalResult;
  2996. }
  2997. }
  2998. //---------------------------------------------------------------------------
  2999. void __fastcall TLoginDialog::LoginButtonDropDownClick(TObject * /*Sender*/)
  3000. {
  3001. MenuPopup(LoginDropDownMenu, LoginButton);
  3002. }
  3003. //---------------------------------------------------------------------------
  3004. void __fastcall TLoginDialog::ParseUrl(const UnicodeString & Url)
  3005. {
  3006. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  3007. SaveSession(SessionData.get());
  3008. // We do not want to pass in StoredSessions as we do not want the URL be
  3009. // parsed as pointing to a stored site.
  3010. bool DefaultsOnly; // unused
  3011. SessionData->ParseUrl(Url, NULL, NULL, DefaultsOnly, NULL, NULL, NULL, pufPreferProtocol);
  3012. LoadSession(SessionData.get());
  3013. }
  3014. //---------------------------------------------------------------------------
  3015. void __fastcall TLoginDialog::PasteUrlActionExecute(TObject * /*Sender*/)
  3016. {
  3017. UnicodeString ClipboardUrl;
  3018. if (NonEmptyTextFromClipboard(ClipboardUrl))
  3019. {
  3020. if (!IsEditable())
  3021. {
  3022. // select new site node, when other node is selected and not in editing mode
  3023. SessionTree->Selected = GetNewSiteNode();
  3024. }
  3025. // sanity check
  3026. if (DebugAlwaysTrue(IsEditable()))
  3027. {
  3028. ParseUrl(ClipboardUrl);
  3029. }
  3030. // visualize the pasting
  3031. HostNameEdit->SetFocus();
  3032. HostNameEdit->SelectAll();
  3033. }
  3034. }
  3035. //---------------------------------------------------------------------------
  3036. void __fastcall TLoginDialog::ParseHostName()
  3037. {
  3038. UnicodeString HostName = HostNameEdit->Text;
  3039. if (!HostName.IsEmpty() &&
  3040. (StoredSessions->IsUrl(HostName) || (HostName.Pos(L"@") > 0)))
  3041. {
  3042. ParseUrl(HostName);
  3043. }
  3044. }
  3045. //---------------------------------------------------------------------------
  3046. void __fastcall TLoginDialog::HostNameEditExit(TObject * /*Sender*/)
  3047. {
  3048. ParseHostName();
  3049. }
  3050. //---------------------------------------------------------------------------
  3051. void __fastcall TLoginDialog::GenerateUrlAction2Execute(TObject * /*Sender*/)
  3052. {
  3053. if (DebugAlwaysTrue(SelectedSession != NULL))
  3054. {
  3055. PersistNewSiteIfNeeded();
  3056. std::unique_ptr<TSessionData> Data(SelectedSession->Clone());
  3057. Data->LookupLastFingerprint();
  3058. DoGenerateUrlDialog(Data.get(), NULL);
  3059. }
  3060. }
  3061. //---------------------------------------------------------------------------
  3062. void __fastcall TLoginDialog::CopyParamRuleActionExecute(TObject * /*Sender*/)
  3063. {
  3064. TSessionData * Data = GetSessionData();
  3065. std::unique_ptr<TCopyParamList> CopyParamList(new TCopyParamList());
  3066. (*CopyParamList) = *GUIConfiguration->CopyParamList;
  3067. TCopyParamRuleData RuleData;
  3068. RuleData.HostName = Data->HostNameExpanded;
  3069. RuleData.UserName = Data->UserNameExpanded;
  3070. int CopyParamIndex = CopyParamList->Find(RuleData);
  3071. if (CopyParamIndex < 0)
  3072. {
  3073. TCopyParamRuleData RuleDataHostNameOnly;
  3074. RuleDataHostNameOnly.HostName = Data->HostNameExpanded;
  3075. CopyParamIndex = CopyParamList->Find(RuleDataHostNameOnly);
  3076. }
  3077. TCopyParamPresetMode Mode;
  3078. TCopyParamRuleData * CurrentRuleData = NULL;
  3079. if (CopyParamIndex < 0)
  3080. {
  3081. Mode = cpmAddCurrent;
  3082. CurrentRuleData = &RuleData;
  3083. }
  3084. else
  3085. {
  3086. Mode = cpmEdit;
  3087. }
  3088. TCopyParamType DefaultCopyParams;
  3089. if (DoCopyParamPresetDialog(
  3090. CopyParamList.get(), CopyParamIndex, Mode, CurrentRuleData, DefaultCopyParams))
  3091. {
  3092. GUIConfiguration->CopyParamList = CopyParamList.get();
  3093. }
  3094. }
  3095. //---------------------------------------------------------------------------
  3096. void __fastcall TLoginDialog::SearchSiteNameStartOnlyActionExecute(TObject * /*Sender*/)
  3097. {
  3098. FSiteSearch = isNameStartOnly;
  3099. }
  3100. //---------------------------------------------------------------------------
  3101. void __fastcall TLoginDialog::SearchSiteNameActionExecute(TObject * /*Sender*/)
  3102. {
  3103. FSiteSearch = isName;
  3104. }
  3105. //---------------------------------------------------------------------------
  3106. void __fastcall TLoginDialog::SearchSiteActionExecute(TObject * /*Sender*/)
  3107. {
  3108. FSiteSearch = isAll;
  3109. }
  3110. //---------------------------------------------------------------------------
  3111. void __fastcall TLoginDialog::ChangeScale(int M, int D)
  3112. {
  3113. TForm::ChangeScale(M, D);
  3114. FSiteButtonsPadding = MulDiv(FSiteButtonsPadding, M, D);
  3115. FBasicGroupBaseHeight = MulDiv(FBasicGroupBaseHeight, M, D);
  3116. FNoteGroupOffset = MulDiv(FNoteGroupOffset, M, D);
  3117. }
  3118. //---------------------------------------------------------------------------
  3119. void __fastcall TLoginDialog::PanelMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  3120. {
  3121. CountClicksForWindowPrint(this);
  3122. }
  3123. //---------------------------------------------------------------------------
  3124. void __fastcall TLoginDialog::S3CredentialsEnvCheck2Click(TObject *)
  3125. {
  3126. UpdateS3Credentials();
  3127. UpdateControls();
  3128. }
  3129. //---------------------------------------------------------------------------
  3130. void __fastcall TLoginDialog::S3ProfileComboChange(TObject *)
  3131. {
  3132. UpdateS3Credentials();
  3133. UpdateControls();
  3134. }
  3135. //---------------------------------------------------------------------------