Login.cpp 108 KB

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