Login.cpp 108 KB

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