From 90ab0b6cf1f8e042c0d19121ca70aad1482d1e67 Mon Sep 17 00:00:00 2001 From: Ansgar Becker Date: Sun, 19 Aug 2012 10:55:08 +0000 Subject: [PATCH] Refactor logic for reading and writing application and session settings: * Introduce TAppSettings, created in dpr file * Implement read and write methods, and replace callers of GetRegValue and MainReg.WriteInt/... with these * Optimize read and write methods for avoiding redundant accesses to registry * Auto-remove stored default settings from registry to avoid registry spam * Replace synced MainForm.pref* variables with TAppSettings.Read* calls * Move SetLocales call to dpr file * Move MainForm.FDirname* variables to appropriate methods in helpers.pas * Implement TQueryHistory.Create(SessionPath), reading its items within constructor --- packages/delphiXE/heidisql.dpr | 10 +- source/bineditor.pas | 13 +- source/column_selection.pas | 2 +- source/connections.pas | 53 +- source/const.inc | 291 +-------- source/copytable.pas | 70 +- source/createdatabase.pas | 4 +- source/dbconnection.pas | 146 ++--- source/editvar.pas | 9 +- source/exportgrid.pas | 45 +- source/grideditlinks.pas | 13 +- source/helpers.pas | 1123 ++++++++++++++++++++++++-------- source/insertfiles.pas | 9 +- source/loaddata.pas | 57 +- source/main.pas | 824 ++++++++++------------- source/options.pas | 236 +++---- source/routine_editor.pas | 1 - source/searchreplace.pas | 9 +- source/selectdbobject.pas | 9 +- source/sqlhelp.pas | 25 +- source/syncdb.pas | 2 +- source/table_editor.pas | 5 +- source/tabletools.pas | 69 +- source/texteditor.pas | 13 +- source/updatecheck.pas | 3 +- source/usermanager.pas | 13 +- 26 files changed, 1593 insertions(+), 1461 deletions(-) diff --git a/packages/delphiXE/heidisql.dpr b/packages/delphiXE/heidisql.dpr index 9d6cd3ba..92165c37 100644 --- a/packages/delphiXE/heidisql.dpr +++ b/packages/delphiXE/heidisql.dpr @@ -46,15 +46,11 @@ uses {$R ..\..\res\manifest.RES} {$R ..\..\res\updater.RES} -var - DoStop, prefAllowMultipleInstances: Boolean; begin - prefAllowMultipleInstances := GetRegValue(REGNAME_MULTI_INSTANCES, DEFAULT_MULTI_INSTANCES); + SetLocales; + AppSettings := TAppSettings.Create; SecondInstMsgId := RegisterWindowMessage(APPNAME); - DoStop := False; - if not prefAllowMultipleInstances then - DoStop := CheckForSecondInstance; - if DoStop then + if (not AppSettings.ReadBool(asAllowMultipleInstances)) and CheckForSecondInstance then Application.Terminate else begin Application.Initialize; diff --git a/source/bineditor.pas b/source/bineditor.pas index 2409c224..ff8d9889 100644 --- a/source/bineditor.pas +++ b/source/bineditor.pas @@ -85,19 +85,18 @@ end; procedure TfrmBinEditor.FormDestroy(Sender: TObject); begin - OpenRegistry; - MainReg.WriteInteger( REGNAME_EDITOR_WIDTH, Width ); - MainReg.WriteInteger( REGNAME_EDITOR_HEIGHT, Height ); - MainReg.WriteBool(REGNAME_EDITOR_WORDWRAP, btnWrap.Down); + AppSettings.WriteInt(asMemoEditorWidth, Width); + AppSettings.WriteInt(asMemoEditorHeight, Height); + AppSettings.WriteBool(asMemoEditorWrap, btnWrap.Down); end; procedure TfrmBinEditor.FormShow(Sender: TObject); begin // Restore form dimensions - Width := GetRegValue(REGNAME_EDITOR_WIDTH, DEFAULT_EDITOR_WIDTH); - Height := GetRegValue(REGNAME_EDITOR_HEIGHT, DEFAULT_EDITOR_HEIGHT); - if GetRegValue(REGNAME_EDITOR_WORDWRAP, btnWrap.Down) then + Width := AppSettings.ReadInt(asMemoEditorWidth); + Height := AppSettings.ReadInt(asMemoEditorHeight); + if AppSettings.ReadBool(asMemoEditorWrap) then btnWrap.Click; // Fix label position: lblTextLength.Top := tlbStandard.Top + (tlbStandard.Height-lblTextLength.Height) div 2; diff --git a/source/column_selection.pas b/source/column_selection.pas index 2baf5fac..a1359d47 100644 --- a/source/column_selection.pas +++ b/source/column_selection.pas @@ -64,7 +64,7 @@ begin chklistColumnsClickCheck( Sender ); // Restore last used sorting state from registry - chkSort.Checked := GetRegValue(REGNAME_SORTDISPLAYEDCOLUMNS, chkSort.Checked); + chkSort.Checked := AppSettings.ReadBool(asDisplayedColumnsSorted); end; diff --git a/source/connections.pas b/source/connections.pas index 02120ecd..05844f75 100644 --- a/source/connections.pas +++ b/source/connections.pas @@ -176,9 +176,9 @@ begin // Fix GUI stuff InheritFont(Font); SetWindowSizeGrip(Handle, True); - Width := GetRegValue(REGNAME_SESSMNGR_WINWIDTH, Width); - Height := GetRegValue(REGNAME_SESSMNGR_WINHEIGHT, Height); - ListSessions.Width := GetRegValue(REGNAME_SESSMNGR_LISTWIDTH, ListSessions.Width); + Width := AppSettings.ReadInt(asSessionManagerWindowWidth); + Height := AppSettings.ReadInt(asSessionManagerWindowHeight); + ListSessions.Width := AppSettings.ReadInt(asSessionManagerListWidth); splitterMain.OnMoved(Sender); FixVT(ListSessions); MainForm.RestoreListSetup(ListSessions); @@ -199,8 +199,8 @@ begin // Focus last session SelectNode(ListSessions, nil); - LastSessions := Explode(DELIM, GetRegValue(REGNAME_LASTSESSIONS, '')); - LastActiveSession := GetRegValue(REGNAME_LASTACTIVESESSION, ''); + LastSessions := Explode(DELIM, AppSettings.ReadString(asLastSessions)); + LastActiveSession := AppSettings.ReadString(asLastActiveSession); if (LastActiveSession = '') and (LastSessions.Count > 0) then LastActiveSession := LastSessions[0]; Node := ListSessions.GetFirst; @@ -246,10 +246,9 @@ end; procedure Tconnform.FormDestroy(Sender: TObject); begin // Save GUI stuff - OpenRegistry; - MainReg.WriteInteger(REGNAME_SESSMNGR_LISTWIDTH, ListSessions.Width); - MainReg.WriteInteger(REGNAME_SESSMNGR_WINWIDTH, Width); - MainReg.WriteInteger(REGNAME_SESSMNGR_WINHEIGHT, Height); + AppSettings.WriteInt(asSessionManagerListWidth, ListSessions.Width); + AppSettings.WriteInt(asSessionManagerWindowWidth, Width); + AppSettings.WriteInt(asSessionManagerWindowHeight, Height); MainForm.SaveListSetup(ListSessions); end; @@ -437,10 +436,8 @@ begin Sess := ListSessions.GetNodeData(Node); if MessageDialog('Delete session "' + Sess.SessionName + '" ?', mtConfirmation, [mbYes, mbCancel]) = mrYes then begin - OpenRegistry; - MainReg.OpenKey(REGKEY_SESSIONS, False); - if MainReg.KeyExists(Sess.SessionPath) then - MainReg.DeleteKey(Sess.SessionPath); + AppSettings.SessionPath := Sess.SessionPath; + AppSettings.DeleteCurrentKey; if Assigned(Node.NextSibling) then FocusNode := Node.NextSibling else if Assigned(Node.PrevSibling) then @@ -586,9 +583,9 @@ begin RegKey := Sess.SessionPath + '\'; end; - // Fetch from registry using helpers:GetSessionNames() + // Fetch from registry Folders := TStringList.Create; - Result := GetSessionNames(RegKey, Folders); + Result := AppSettings.GetSessionNames(RegKey, Folders); Result.AddStrings(Folders); Folders.Free; end; @@ -643,11 +640,8 @@ begin ErrorDialog('Session "'+ParentKey+FocusedSess.SessionName+'" already exists!') else begin try - OpenRegistry; - MainReg.OpenKey(REGKEY_SESSIONS, False); - if not MainReg.KeyExists(FocusedSess.SessionPath) then - raise Exception.Create('Misconfigured session path: '+FocusedSess.SessionPath); - MainReg.MoveKey(FocusedSess.SessionPath, ParentKey+FocusedSess.SessionName, True); + AppSettings.SessionPath := FocusedSess.SessionPath; + AppSettings.MoveCurrentKey(REGKEY_SESSIONS+'\'+ParentKey+FocusedSess.SessionName); ListSessions.MoveTo(ListSessions.FocusedNode, TargetNode, AttachMode, False); FocusedSess.SessionPath := ParentKey+FocusedSess.SessionName; except @@ -762,25 +756,25 @@ begin lblCounterRight.Caption := 'not available'; lblCounterRight.Enabled := False; - if (not Assigned(ListSessions.FocusedNode)) - or (not MainReg.KeyExists(RegPath + REGKEY_SESSIONS + '\' + SelectedSessionPath)) then + if not Assigned(ListSessions.FocusedNode) then Exit; + AppSettings.SessionPath := SelectedSessionPath; DummyDate := StrToDateTime('2000-01-01'); - LastConnect := StrToDateTimeDef(GetRegValue(REGNAME_LASTCONNECT, '', SelectedSessionPath), DummyDate); + LastConnect := StrToDateTimeDef(AppSettings.ReadString(asLastConnect), DummyDate); if LastConnect <> DummyDate then begin lblLastConnectRight.Hint := DateTimeToStr(LastConnect); lblLastConnectRight.Caption := DateBackFriendlyCaption(LastConnect); lblLastConnectRight.Enabled := True; end; - Created := StrToDateTimeDef(GetRegValue(REGNAME_SESSIONCREATED, '', SelectedSessionPath), DummyDate); + Created := StrToDateTimeDef(AppSettings.ReadString(asSessionCreated), DummyDate); if Created <> DummyDate then begin lblCreatedRight.Hint := DateTimeToStr(Created); lblCreatedRight.Caption := DateBackFriendlyCaption(Created); lblCreatedRight.Enabled := True; end; - Connects := GetRegValue(REGNAME_CONNECTCOUNT, 0, SelectedSessionPath); - Refused := GetRegValue(REGNAME_REFUSEDCOUNT, 0, SelectedSessionPath); + Connects := AppSettings.ReadInt(asConnectCount); + Refused := AppSettings.ReadInt(asRefusedCount); lblCounterRight.Enabled := Connects + Refused > 0; if Connects > 0 then begin lblCounterRight.Caption := 'Successful connects: '+IntToStr(Connects); @@ -814,13 +808,12 @@ begin // Rename session Sess := Sender.GetNodeData(Node); SiblingSessions := NodeSessionNames(Node.Parent, ParentKey); - OpenRegistry; - MainReg.OpenKey(REGKEY_SESSIONS, False); if SiblingSessions.IndexOf(NewText) > -1 then begin ErrorDialog('Session "'+ParentKey+NewText+'" already exists!'); NewText := Sess.SessionName; end else begin - MainReg.MoveKey(Sess.SessionPath, ParentKey+NewText, true); + AppSettings.SessionPath := Sess.SessionPath; + AppSettings.MoveCurrentKey(REGKEY_SESSIONS+'\'+ParentKey+NewText); // Also fix internal session names in main form, which gets used to store e.g. "lastuseddb" later for Connection in MainForm.Connections do begin if Connection.Parameters.SessionPath = Sess.SessionPath then @@ -896,7 +889,7 @@ begin Params := CurrentParams; case Params.NetTypeGroup of ngMySQL: - updownPort.Position := DEFAULT_PORT; + updownPort.Position := MakeInt(AppSettings.GetDefaultString(asPort)); ngMSSQL: updownPort.Position := 1433; end; diff --git a/source/const.inc b/source/const.inc index 2aa45313..6000ddf5 100644 --- a/source/const.inc +++ b/source/const.inc @@ -8,13 +8,14 @@ const LB_WIDE = WideChar($2027); // Placeholder text for NULL values - TEXT_NULL = '(NULL)'; + TEXT_NULL = '(NULL)'; // General things - APPNAME = 'HeidiSQL'; - APPDOMAIN = 'http://www.heidisql.com/'; - REGKEY_SESSIONS = 'Servers'; + APPNAME = 'HeidiSQL'; + APPDOMAIN = 'http://www.heidisql.com/'; + REGKEY_SESSIONS = 'Servers'; REGKEY_QUERYHISTORY = 'QueryHistory'; + REGKEY_RECENTFILTERS = 'RecentFilters'; // Some unique char, used to separate e.g. selected columns in registry DELIM = '|'; CHR10REPLACEMENT = '<}}}>'; @@ -24,290 +25,9 @@ const // Used by maskSQL and fixSQL: SQL_VERSION_ANSI = -1; - // Various names of registry variables - // User-changable variables have a default value - // Note: Color values are in HEX format: $00BBGGRR - REGNAME_HIDDENCOLUMNS = 'HiddenColumns'; - REGNAME_FILTER = 'Filter'; - REGNAME_SORT = 'Sort'; - REGNAME_SORTDISPLAYEDCOLUMNS = 'DisplayedColumnsSorted'; - REGNAME_LASTSESSIONS = 'LastSessions'; - REGNAME_LASTACTIVESESSION = 'LastActiveSession'; - REGNAME_AUTORECONNECT = 'AutoReconnect'; - DEFAULT_AUTORECONNECT = False; - REGNAME_RESTORELASTUSEDDB = 'RestoreLastUsedDB'; - DEFAULT_RESTORELASTUSEDDB = True; - REGNAME_LASTUSEDDB = 'lastUsedDB'; - REGNAME_TREEBACKGROUND = 'TreeBackground'; - DEFAULT_TREEBACKGROUND = clNone; - REGNAME_FONTNAME = 'FontName'; - DEFAULT_FONTNAME = 'Courier New'; - REGNAME_FONTSIZE = 'FontSize'; - DEFAULT_FONTSIZE = 9; - REGNAME_TABWIDTH = 'TabWidth'; - DEFAULT_TABWIDTH = 3; - REGNAME_DATAFONTNAME = 'DataFontName'; - DEFAULT_DATAFONTNAME = 'Tahoma'; - REGNAME_DATAFONTSIZE = 'DataFontSize'; - DEFAULT_DATAFONTSIZE = 8; - // how much memory we're aiming to use for the - // data grid and it's automatic limit function - REGNAME_LOGSQLNUM = 'logsqlnum'; - DEFAULT_LOGSQLNUM = 300; - REGNAME_LOGSQLWIDTH = 'logsqlwidth'; - DEFAULT_LOGSQLWIDTH = 2000; - REGNAME_LOGDIR = 'SessionLogsDirectory'; - REGNAME_LOG_HORIZONTALSCROLLBAR = 'LogHorizontalScrollbar'; - REGPREFIX_SQLATTRI = 'SQL Attr '; - REGPOSTFIX_SQL_FG = ' Foreground'; - REGPOSTFIX_SQL_BG = ' Background'; - REGPOSTFIX_SQL_STYLE = ' Style'; - REGNAME_SQLCOLACTIVELINE = 'SQLColActiveLine'; - DEFAULT_SQLCOLACTIVELINE = $00FFFFFF; // clWhite - REGNAME_MAXCOLWIDTH = 'MaxColWidth'; - DEFAULT_MAXCOLWIDTH = 300; - REGNAME_MAXTOTALROWS = 'DatagridMaximumRows'; - DEFAULT_MAXTOTALROWS = 100000; - REGNAME_ROWSPERSTEP = 'DatagridRowsPerStep'; - DEFAULT_ROWSPERSTEP = 1000; - REGNAME_GRIDROWSLINECOUNT = 'GridRowLineCount'; - DEFAULT_GRIDROWSLINECOUNT = 1; - REGNAME_REMEMBERFILTERS = 'RememberFilters'; - DEFAULT_REMEMBERFILTERS = True; - REGNAME_LOGTOFILE = 'LogToFile'; - DEFAULT_LOGTOFILE = False; - REGNAME_WINMAXIMIZED = 'MainWinMaximized'; - REGNAME_WINLEFT = 'MainWinLeft'; - REGNAME_WINTOP = 'MainWinTop'; - REGNAME_WINWIDTH = 'MainWinWidth'; - REGNAME_WINHEIGHT = 'MainWinHeight'; - REGNAME_WINONMONITOR = 'MainWinOnMonitor'; - REGNAME_TOOLBAR2LEFT = 'ToolBar2Left'; - REGNAME_TOOLBAR2TOP = 'ToolBar2Top'; - REGNAME_TOOLBARDATALEFT = 'ToolBarDataLeft'; - REGNAME_TOOLBARDATATOP = 'ToolBarDataTop'; - REGNAME_TOOLBARQUERYLEFT = 'ToolBarQueryLeft'; - REGNAME_TOOLBARQUERYTOP = 'ToolBarQueryTop'; - REGNAME_QUERYMEMOHEIGHT = 'querymemoheight'; - REGNAME_DBTREEWIDTH = 'dbtreewidth'; - REGNAME_PREVIEW_HEIGHT = 'DataPreviewHeight'; - REGNAME_PREVIEW_ENABLED = 'DataPreviewEnabled'; - REGNAME_SQLOUTHEIGHT = 'sqloutheight'; - REGNAME_QUERYHELPERSWIDTH = 'queryhelperswidth'; - REGNAME_STOPONERRORSINBATCH = 'StopOnErrorsInBatchMode'; - DEFAULT_STOPONERRORSINBATCH = True; - REGNAME_WRAPLINES = 'WrapLongLines'; - REGNAME_BLOBASTEXT = 'DisplayBLOBsAsText'; - DEFAULT_BLOBASTEXT = False; - REGNAME_SINGLEQUERIES = 'SingleQueries'; - REGNAME_EDITOR_WIDTH = 'MemoEditorWidth'; - DEFAULT_EDITOR_WIDTH = 100; - REGNAME_EDITOR_HEIGHT = 'MemoEditorHeight'; - DEFAULT_EDITOR_HEIGHT = 100; - REGNAME_EDITOR_WORDWRAP = 'MemoEditorWrap'; - REGNAME_DELIMITER = 'Delimiter'; - DEFAULT_DELIMITER = ';'; - REGNAME_SQLHELPWINLEFT = 'SQLHelp_WindowLeft'; - REGNAME_SQLHELPWINTOP = 'SQLHelp_WindowTop'; - REGNAME_SQLHELPWINWIDTH = 'SQLHelp_WindowWidth'; - REGNAME_SQLHELPWINHEIGHT = 'SQLHelp_WindowHeight'; - REGNAME_SQLHELPPLWIDTH = 'SQLHelp_PnlLeftWidth'; - REGNAME_SQLHELPPRHEIGHT = 'SQLHelp_PnlRightTopHeight'; - REGNAME_TABLEEDITOR_TABSHEIGHT = 'TableEditorTabsHeight'; - DEFAULT_TABLEEDITOR_TABSHEIGHT = 150; - REGNAME_HOST = 'Host'; - DEFAULT_HOST = '127.0.0.1'; - REGNAME_USER = 'User'; - DEFAULT_USER = 'root'; - REGNAME_PASSWORD = 'Password'; - REGNAME_WINDOWSAUTH = 'WindowsAuth'; - REGNAME_LOGINPROMPT = 'LoginPrompt'; - REGNAME_PORT = 'Port'; - DEFAULT_PORT = 3306; - REGNAME_PLINKEXE = 'PlinkExecutable'; - REGNAME_SSHHOST = 'SSHtunnelHost'; - REGNAME_SSHPORT = 'SSHtunnelHostPort'; - DEFAULT_SSHPORT = 22; - REGNAME_SSHLOCALPORT = 'SSHtunnelPort'; - REGNAME_SSHUSER = 'SSHtunnelUser'; - REGNAME_SSHPASSWORD = 'SSHtunnelPassword'; - REGNAME_SSHTIMEOUT = 'SSHtunnelTimeout'; - DEFAULT_SSHTIMEOUT = 4; - REGNAME_SSHKEY = 'SSHtunnelPrivateKey'; - REGNAME_SSL_ACTIVE = 'SSL_Active'; - REGNAME_SSL_KEY = 'SSL_Key'; - REGNAME_SSL_CERT = 'SSL_Cert'; - REGNAME_SSL_CA = 'SSL_CA'; - REGNAME_NETTYPE = 'NetType'; - REGNAME_COMPRESSED = 'Compressed'; - DEFAULT_COMPRESSED = False; - REGNAME_LOCALTIMEZONE = 'LocalTimeZone'; - DEFAULT_LOCALTIMEZONE = False; - REGNAME_STARTUPSCRIPT = 'StartupScriptFilename'; - REGNAME_DATABASES = 'Databases'; - REGNAME_DATABASE_FILTER = 'DatabaseFilter'; - REGNAME_EXP_CREATEDB = 'ExportSQL_CreateDatabases'; - REGNAME_EXP_DROPDB = 'ExportSQL_DropDatabases'; - REGNAME_EXP_CREATETABLE = 'ExportSQL_CreateTables'; - REGNAME_EXP_DROPTABLE = 'ExportSQL_DropTables'; - REGNAME_EXP_DATAHOW = 'ExportSQL_DataHow'; - REGNAME_EXP_OUTFILES = 'ExportSQL_Filenames'; - REGNAME_EXP_OUTDIRS = 'ExportSQL_Directories'; - REGNAME_EXP_OUTDATABASE = 'ExportSQL_Database'; - REGNAME_EXP_OUTSERVERDB = 'ExportSQL_ServerDatabase'; - REGNAME_EXP_OUTPUT = 'ExportSQL_Output'; - REGNAME_GEXP_OUTPUTCOPY = 'GridExportOutputCopy'; - REGNAME_GEXP_OUTPUTFILE = 'GridExportOutputFile'; - REGNAME_GEXP_FILENAME = 'GridExportFilename'; - REGNAME_GEXP_RECENTFILES = 'GridExportRecentFiles'; - REGNAME_GEXP_ENCODING = 'GridExportEncoding'; - REGNAME_GEXP_FORMAT = 'GridExportFormat'; - REGNAME_GEXP_SELECTION = 'GridExportSelection'; - REGNAME_GEXP_COLUMNNAMES = 'GridExportColumnNames'; - REGNAME_GEXP_SEPARATOR = 'GridExportSeparator'; - REGNAME_GEXP_ENCLOSER = 'GridExportEncloser'; - REGNAME_GEXP_TERMINATOR = 'GridExportTerminator'; - REGNAME_CSV_SEPARATOR = 'CSVSeparatorV2'; - DEFAULT_CSV_SEPARATOR = ';'; - REGNAME_CSV_ENCLOSER = 'CSVEncloserV2'; - DEFAULT_CSV_ENCLOSER = '"'; - REGNAME_CSV_TERMINATOR = 'CSVTerminator'; - DEFAULT_CSV_TERMINATOR = '\r\n'; - REGNAME_CSV_ESCAPER = 'CSVImportFieldEscaperV2'; - REGNAME_CSV_WINDOWWIDTH = 'CSVImportWindowWidth'; - REGNAME_CSV_WINDOWHEIGHT = 'CSVImportWindowHeight'; - REGNAME_CSV_FILENAME = 'loadfilename'; - REGNAME_CSV_ENCLOPTION = 'CSVImportFieldsEnclosedOptionallyV2'; - REGNAME_CSV_IGNORELINES = 'CSVImportIgnoreLines'; - REGNAME_CSV_LOWPRIO = 'CSVImportLowPriority'; - REGNAME_CSV_LOCALNUMBERS = 'CSVImportLocalNumbers'; - REGNAME_CSV_TRUNCATETABLE = 'CSVImportTruncateTable'; - REGNAME_CSV_DUPLICATES = 'CSVImportDuplicateHandling'; - REGNAME_CSV_PARSEMETHOD = 'CSVImportParseMethod'; - REGNAME_DO_UPDATECHECK = 'Updatecheck'; - DEFAULT_DO_UPDATECHECK = False; - REGNAME_DO_UPDATECHECK_BUILDS = 'UpdatecheckBuilds'; - DEFAULT_DO_UPDATECHECK_BUILDS = False; - REGNAME_UPDATECHECK_INTERVAL = 'UpdatecheckInterval'; - DEFAULT_UPDATECHECK_INTERVAL = 3; - REGNAME_LAST_UPDATECHECK = 'UpdatecheckLastrun'; - REGNAME_TOOLSWINWIDTH = 'TableTools_WindowWidth'; - REGNAME_TOOLSWINHEIGHT = 'TableTools_WindowHeight'; - REGNAME_TOOLSTREEWIDTH = 'TableTools_TreeWidth'; - REGNAME_TOOLSFINDTEXT = 'TableTools_FindText'; - REGNAME_TOOLSDATATYPE = 'TableTools_Datatype'; - REGNAME_TOOLSCASESENSITIVE = 'TableTools_FindCaseSensitive'; - REGNAME_FILEIMPORTWINWIDTH = 'FileImport_WindowWidth'; - REGNAME_FILEIMPORTWINHEIGHT = 'FileImport_WindowHeight'; - REGNAME_EDITVARWINWIDTH = 'EditVar_WindowWidth'; - REGNAME_EDITVARWINHEIGHT = 'EditVar_WindowHeight'; - REGNAME_USERMNGR_WINWIDTH = 'Usermanager_WindowWidth'; - REGNAME_USERMNGR_WINHEIGHT = 'Usermanager_WindowHeight'; - REGNAME_USERMNGR_LISTWIDTH = 'Usermanager_ListWidth'; - REGNAME_SELECTDBO_WINWIDTH = 'SelectDBO_WindowWidth'; - REGNAME_SELECTDBO_WINHEIGHT = 'SelectDBO_WindowHeight'; - REGNAME_SESSMNGR_LISTWIDTH = 'SessionManager_ListWidth'; - REGNAME_SESSMNGR_WINWIDTH = 'SessionManager_WindowWidth'; - REGNAME_SESSMNGR_WINHEIGHT = 'SessionManager_WindowHeight'; - REGNAME_COPYTABLE_WINHEIGHT = 'CopyTable_WindowHeight'; - REGNAME_COPYTABLE_WINWIDTH = 'CopyTable_WindowWidth'; - REGNAME_COPYTABLE_COLUMNS = 'CopyTable_Columns'; - REGNAME_COPYTABLE_KEYS = 'CopyTable_Keys'; - REGNAME_COPYTABLE_FOREIGN = 'CopyTable_ForeignKeys'; - REGNAME_COPYTABLE_DATA = 'CopyTable_Data'; - REGNAME_FILTERS = 'RecentFilters'; - REGNAME_SERVERVERSION = 'ServerVersion'; - REGNAME_SERVERVERSION_FULL = 'ServerVersionFull'; - REGNAME_LASTCONNECT = 'LastConnect'; - REGNAME_CONNECTCOUNT = 'ConnectCount'; - REGNAME_REFUSEDCOUNT = 'RefusedCount'; - REGNAME_SESSIONCREATED = 'SessionCreated'; - REGNAME_SESSIONFOLDER = 'Folder'; - REGNAME_DO_STATISTICS = 'DoUsageStatistics'; - DEFAULT_DO_STATISTICS = False; - REGNAME_LAST_STATSCALL = 'LastUsageStatisticCall'; - REGNAME_DISPLAYBARS = 'DisplayBars'; - DEFAULT_DISPLAYBARS = true; - REGNAME_BARCOLOR = 'BarColor'; - DEFAULT_BARCOLOR = $00BBFFDD; - REGNAME_MYSQLBINARIES = 'MySQL_Binaries'; - DEFAULT_MYSQLBINARIES = ''; - REGNAME_PROMPTFILESAVE = 'PromptSaveFileOnTabClose'; - DEFAULT_PROMPTFILESAVE = True; - REGNAME_COMPLETIONPROPOSAL = 'CompletionProposal'; - DEFAULT_COMPLETIONPROPOSAL = True; - REGNAME_TABSTOSPACES = 'TabsToSpaces'; - DEFAULT_TABSTOSPACES = False; - REGNAME_FILTERACTIVE = 'FilterPanel'; - DEFAULT_FILTERACTIVE = False; - REGNAME_MULTI_INSTANCES = 'AllowMultipleInstances'; - DEFAULT_MULTI_INSTANCES = True; - REGNAME_SEARCHTEXT = 'FindDialogSearchHistory'; - REGNAME_REPLACETEXT = 'FindDialogReplaceHistory'; - REGNAME_MAXQUERYRESULTS = 'MaxQueryResults'; - DEFAULT_MAXQUERYRESULTS = 10; - REGNAME_SETEDITORWIDTH = 'SetEditorWidth'; - DEFAULT_SETEDITORWIDTH = 100; - REGNAME_SETEDITORHEIGHT = 'SetEditorHeight'; - DEFAULT_SETEDITORHEIGHT = 130; - - // Log events - REGNAME_LOG_ERRORS = 'LogErrors'; - DEFAULT_LOG_ERRORS = True; - REGNAME_LOG_USERSQL = 'LogUserSQL'; - DEFAULT_LOG_USERSQL = True; - REGNAME_LOG_SQL = 'LogSQL'; - DEFAULT_LOG_SQL = True; - REGNAME_LOG_INFOS = 'LogInfos'; - DEFAULT_LOG_INFOS = True; - REGNAME_LOG_DEBUG = 'LogDebug'; - DEFAULT_LOG_DEBUG = False; - - REGNAME_FIELDCOLOR_INTEGER = 'FieldColor_Numeric'; - REGNAME_FIELDCOLOR_REAL = 'FieldColor_Real'; - REGNAME_FIELDCOLOR_TEXT = 'FieldColor_Text'; - REGNAME_FIELDCOLOR_BINARY = 'FieldColor_Binary'; - REGNAME_FIELDCOLOR_DATETIME = 'FieldColor_Datetime'; - REGNAME_FIELDCOLOR_SPATIAL = 'FieldColor_Spatial'; - REGNAME_FIELDCOLOR_OTHER = 'FieldColor_Other'; - DEFAULT_FIELDCOLOR_INTEGER = $00FF0000; // clBlue - DEFAULT_FIELDCOLOR_REAL = $00FF0048; // violet - DEFAULT_FIELDCOLOR_TEXT = $00008000; // clGreen - DEFAULT_FIELDCOLOR_BINARY = $00800080; // clPurple - DEFAULT_FIELDCOLOR_DATETIME = $00000080; // clMaroon - DEFAULT_FIELDCOLOR_SPATIAL = $00808000; // clOlive - DEFAULT_FIELDCOLOR_OTHER = $00008080; // clTeal COLORSHIFT_NULLFIELDS = 70; // Brightness adjustment to add to normal field colors for NULL values COLORSHIFT_SORTCOLUMNS = 12; // Brightness adjustment to add to sorted column backgrounds - REGNAME_FIELDEDITOR_BINARY = 'FieldEditor_Binary'; - REGNAME_FIELDEDITOR_DATETIME = 'FieldEditor_Datetime'; - REGNAME_PREFILL_DATETIME = 'FieldEditor_Datetime_Prefill'; - REGNAME_FIELDEDITOR_ENUM = 'FieldEditor_Enum'; - REGNAME_FIELDEDITOR_SET = 'FieldEditor_Set'; - DEFAULT_FIELDEDITOR_BINARY = True; - DEFAULT_FIELDEDITOR_DATETIME = True; - DEFAULT_PREFILL_DATETIME = True; - DEFAULT_FIELDEDITOR_ENUM = True; - DEFAULT_FIELDEDITOR_SET = True; - - REGNAME_BG_NULL = 'Field_NullBackground'; - DEFAULT_BG_NULL = $00FF00FF; // clMagenta - - REGNAME_GROUPOBJECTS = 'GroupTreeObjects'; - DEFAULT_GROUPOBJECTS = False; - REGNAME_SIZECOL_TREE = 'DisplayObjectSizeColumn'; - DEFAULT_SIZECOL_TREE = True; - - REGPREFIX_COLWIDTHS = 'ColWidths_'; - REGPREFIX_COLSVISIBLE = 'ColsVisible_'; - REGPREFIX_COLPOS = 'ColPositions_'; - REGPREFIX_COLSORT = 'ColSort_'; - REGPREFIX_DATEEDITOR_CURSOR = 'DateTimeEditor_CursorPos_Type'; - REGPREFIX_SHORTCUT1 = 'Shortcut1_'; - REGPREFIX_SHORTCUT2 = 'Shortcut2_'; - REGPREFIX_COPYTABLE_FILTERS = 'CopyTable_RecentFilter_'; - // Various iconindexes ICONINDEX_PRIMARYKEY = 25; ICONINDEX_FIELD = 42; @@ -365,6 +85,7 @@ const MSG_NOGRIDEDITING = 'Selected columns don''t contain a sufficient set of key columns to allow editing. Please select primary or unique key columns, or just all columns.'; SIdle = 'Idle.'; SUnsupported = 'Not supported by this server'; + SUnsupportedSettingsDatatype = 'Unsupported datatype for setting "%s"'; MsgSQLError: String = 'SQL Error (%d): %s'; MsgUnhandledNetType: String = 'Unhandled connection type (%d)'; MsgDisconnect: String = 'Connection to %s closed at %s'; diff --git a/source/copytable.pas b/source/copytable.pas index 4cc83eaf..d98f83f5 100644 --- a/source/copytable.pas +++ b/source/copytable.pas @@ -66,8 +66,8 @@ const procedure TCopyTableForm.FormCreate(Sender: TObject); begin InheritFont(Font); - Width := GetRegValue(REGNAME_COPYTABLE_WINWIDTH, Width); - Height := GetRegValue(REGNAME_COPYTABLE_WINHEIGHT, Height); + Width := AppSettings.ReadInt(asCopyTableWindowWidth); + Height := AppSettings.ReadInt(asCopyTableWindowHeight); SetWindowSizeGrip(Handle, True); MainForm.SetupSynEditors; FixVT(TreeElements); @@ -80,8 +80,8 @@ end; procedure TCopyTableForm.FormDestroy(Sender: TObject); begin // Save GUI stuff - MainReg.WriteInteger(REGNAME_COPYTABLE_WINWIDTH, Width); - MainReg.WriteInteger(REGNAME_COPYTABLE_WINHEIGHT, Height); + AppSettings.WriteInt(asCopyTableWindowWidth, Width); + AppSettings.WriteInt(asCopyTableWindowHeight, Height); end; @@ -90,8 +90,7 @@ var Filter: String; Dummy: String; Obj: PDBObject; - Values: TStringList; - i, j: Integer; + i: Integer; Item: TMenuItem; Tree: TVirtualStringTree; begin @@ -129,17 +128,12 @@ begin // Load recent WHERE clauses from registry into dropdown menu popupRecentFilters.Items.Clear; - OpenRegistry; - Values := TStringList.Create; - MainReg.GetValueNames(Values); - j := 0; - for i:=0 to Values.Count-1 do begin - if Pos(REGPREFIX_COPYTABLE_FILTERS, Values[i]) <> 1 then - continue; - Inc(j); - Filter := MainReg.ReadString(Values[i]); + for i:=1 to 20 do begin + Filter := AppSettings.ReadString(asCopyTableRecentFilter, IntToStr(i)); + if IsEmpty(Filter) then + Continue; Item := TMenuItem.Create(popupRecentFilters); - Item.Caption := IntToStr(j) + ' ' + sstr(Filter, 100); + Item.Caption := IntToStr(i) + ' ' + sstr(Filter, 100); Item.Hint := Filter; Item.OnClick := RecentFilterClick; popupRecentFilters.Items.Add(Item); @@ -152,43 +146,39 @@ end; procedure TCopyTableForm.FormClose(Sender: TObject; var Action: TCloseAction); var Node: PVirtualNode; - Option, Filter: String; - Values, NewValues: TStringList; + Option: TAppSettingIndex; + Filter: String; + NewValues: TStringList; i: Integer; begin // Save first level node check options Node := TreeElements.GetFirst; while Assigned(Node) do begin case Node.Index of - nColumns: Option := REGNAME_COPYTABLE_COLUMNS; - nKeys: Option := REGNAME_COPYTABLE_KEYS; - nForeignKeys: Option := REGNAME_COPYTABLE_FOREIGN; - nData: Option := REGNAME_COPYTABLE_DATA; + nColumns: Option := asCopyTableColumns; + nKeys: Option := asCopyTableKeys; + nForeignKeys: Option := asCopyTableForeignKeys; + nData: Option := asCopyTableData; else raise Exception.Create(SUnhandledNodeIndex); end; if not (vsDisabled in Node.States) then - MainReg.WriteBool(Option, Node.CheckState in CheckedStates); + AppSettings.WriteBool(Option, Node.CheckState in CheckedStates); Node := TreeElements.GetNextSibling(Node); end; // Store recent filters if MemoFilter.Enabled and (MemoFilter.GetTextLen > 0) then begin - OpenRegistry; - Values := TStringList.Create; NewValues := TStringList.Create; NewValues.Add(MemoFilter.Text); - MainReg.GetValueNames(Values); - for i:=0 to Values.Count-1 do begin - if Pos(REGPREFIX_COPYTABLE_FILTERS, Values[i]) <> 1 then - continue; - Filter := MainReg.ReadString(Values[i]); + for i:=1 to 20 do begin + Filter := AppSettings.ReadString(asCopyTableRecentFilter, IntToStr(i)); + if IsEmpty(Filter) then + Continue; if NewValues.IndexOf(Filter) = -1 then NewValues.Add(Filter); - MainReg.DeleteValue(Values[i]); + AppSettings.DeleteValue(asCopyTableRecentFilter, IntToStr(i)); end; for i:=0 to NewValues.Count-1 do begin - if i = 20 then - break; - MainReg.WriteString(REGPREFIX_COPYTABLE_FILTERS+IntToStr(i), NewValues[i]); + AppSettings.WriteString(asCopyTableRecentFilter, NewValues[i], IntToStr(i)); end; end; Action := caFree; @@ -292,7 +282,7 @@ end; procedure TCopyTableForm.TreeElementsInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var - Option: String; + Option: TAppSettingIndex; ChildCount: Integer; begin // First three upper nodes mostly have child nodes @@ -300,17 +290,17 @@ begin case Sender.GetNodeLevel(Node) of 0: begin case Node.Index of - nColumns: begin Option := REGNAME_COPYTABLE_COLUMNS; ChildCount := FColumns.Count; end; - nKeys: begin Option := REGNAME_COPYTABLE_KEYS; ChildCount := FKeys.Count; end; - nForeignKeys: begin Option := REGNAME_COPYTABLE_FOREIGN; ChildCount := FForeignKeys.Count; end; - nData: begin Option := REGNAME_COPYTABLE_DATA; ChildCount := -1; end; + nColumns: begin Option := asCopyTableColumns; ChildCount := FColumns.Count; end; + nKeys: begin Option := asCopyTableKeys; ChildCount := FKeys.Count; end; + nForeignKeys: begin Option := asCopyTableForeignKeys; ChildCount := FForeignKeys.Count; end; + nData: begin Option := asCopyTableData; ChildCount := -1; end; else raise Exception.Create(SUnhandledNodeIndex); end; if ChildCount > 0 then Include(InitialStates, ivsHasChildren); if (ChildCount = 0) or ((Node.Index = nData) and (FDBObj.Rows = 0)) then Node.States := Node.States + [vsDisabled] - else if GetRegValue(Option, True) then + else if AppSettings.ReadBool(Option) then Node.CheckState := csCheckedNormal; (Sender as TVirtualStringTree).OnChecked(Sender, Node); end; diff --git a/source/createdatabase.pas b/source/createdatabase.pas index 7baf74bb..db78b799 100644 --- a/source/createdatabase.pas +++ b/source/createdatabase.pas @@ -273,9 +273,9 @@ begin AllDatabases[i] := editDBname.Text else AllDatabases.Add(editDBname.Text); - OpenRegistry(FConnection.Parameters.SessionPath); + AppSettings.SessionPath := FConnection.Parameters.SessionPath; FConnection.Parameters.AllDatabasesStr := ImplodeStr(';', AllDatabases); - MainReg.WriteString(REGNAME_DATABASES, FConnection.Parameters.AllDatabasesStr); + AppSettings.WriteString(asDatabases, FConnection.Parameters.AllDatabasesStr); end; end; diff --git a/source/dbconnection.pas b/source/dbconnection.pas index cae65377..ed6c2551 100644 --- a/source/dbconnection.pas +++ b/source/dbconnection.pas @@ -608,21 +608,21 @@ uses helpers, loginform; constructor TConnectionParameters.Create; begin inherited Create; - FNetType := ntMySQL_TCPIP; + FNetType := TNetType(AppSettings.GetDefaultInt(asNetType)); FIsFolder := False; - FHostname := DEFAULT_HOST; - FUsername := DEFAULT_USER; + FHostname := AppSettings.GetDefaultString(asHost); + FUsername := AppSettings.GetDefaultString(asUser); FPassword := ''; - FPort := DEFAULT_PORT; - FSSHPlinkExe := GetRegValue(REGNAME_PLINKEXE, ''); - FSSHPort := DEFAULT_SSHPORT; - FSSHTimeout := DEFAULT_SSHTIMEOUT; + FPort := AppSettings.GetDefaultInt(asPort); + FSSHPlinkExe := AppSettings.ReadString(asPlinkExecutable); + FSSHPort := AppSettings.GetDefaultInt(asSSHtunnelPort); + FSSHTimeout := AppSettings.GetDefaultInt(asSSHtunnelTimeout); FSSHLocalPort := FPort + 1; FSSLPrivateKey := ''; FSSLCertificate := ''; FSSLCACertificate := ''; FStartupScriptFilename := ''; - FSessionColor := DEFAULT_TREEBACKGROUND; + FSessionColor := AppSettings.GetDefaultInt(asTreeBackground); FLastConnect := 0; FCounter := 0; FServerVersion := ''; @@ -632,49 +632,49 @@ end; constructor TConnectionParameters.Create(SessionRegPath: String); var DummyDate: TDateTime; - RegKey: String; begin // Parameters from stored registry key Create; - RegKey := REGPATH + REGKEY_SESSIONS + '\' + SessionRegPath; + + if not AppSettings.SessionPathExists(SessionRegPath) then + raise Exception.Create('Error: Session "'+SessionRegPath+'" not found in registry.'); + FSessionPath := SessionRegPath; + AppSettings.SessionPath := SessionRegPath; - if not Mainreg.KeyExists(RegKey) then - raise Exception.Create('Error: Session "'+SessionName+'" not found in registry.'); - - MainReg.OpenKey(RegKey, True); - if MainReg.ValueExists(REGNAME_SESSIONFOLDER) then begin + if AppSettings.ValueExists(asSessionFolder) then begin FIsFolder := True; end else begin - FSessionColor := GetRegValue(REGNAME_TREEBACKGROUND, DEFAULT_TREEBACKGROUND, SessionRegPath); - FNetType := TNetType(GetRegValue(REGNAME_NETTYPE, Integer(ntMySQL_TCPIP), SessionRegPath)); - FHostname := GetRegValue(REGNAME_HOST, '', SessionRegPath); - FUsername := GetRegValue(REGNAME_USER, '', SessionRegPath); - FPassword := decrypt(GetRegValue(REGNAME_PASSWORD, '', SessionRegPath)); - FLoginPrompt := GetRegValue(REGNAME_LOGINPROMPT, False, SessionRegPath); - FWindowsAuth := GetRegValue(REGNAME_WINDOWSAUTH, False, SessionRegPath); - FPort := StrToIntDef(GetRegValue(REGNAME_PORT, '', SessionRegPath), DEFAULT_PORT); - FAllDatabases := GetRegValue(REGNAME_DATABASES, '', SessionRegPath); - FSSHHost := GetRegValue(REGNAME_SSHHOST, '', SessionRegPath); - FSSHPort := GetRegValue(REGNAME_SSHPORT, DEFAULT_SSHPORT, SessionRegPath); - FSSHUser := GetRegValue(REGNAME_SSHUSER, '', SessionRegPath); - FSSHPassword := decrypt(GetRegValue(REGNAME_SSHPASSWORD, '', SessionRegPath)); - FSSHTimeout := GetRegValue(REGNAME_SSHTIMEOUT, DEFAULT_SSHTIMEOUT, SessionRegPath); - FSSHPrivateKey := GetRegValue(REGNAME_SSHKEY, '', SessionRegPath); - FSSHLocalPort := GetRegValue(REGNAME_SSHLOCALPORT, 0, SessionRegPath); - FSSHPlinkExe := GetRegValue(REGNAME_PLINKEXE, ''); - FSSLPrivateKey := GetRegValue(REGNAME_SSL_KEY, '', SessionRegPath); + FSessionColor := AppSettings.ReadInt(asTreeBackground); + FNetType := TNetType(AppSettings.ReadInt(asNetType)); + FHostname := AppSettings.ReadString(asHost); + FUsername := AppSettings.ReadString(asUser); + FPassword := decrypt(AppSettings.ReadString(asPassword)); + FLoginPrompt := AppSettings.ReadBool(asLoginPrompt); + FWindowsAuth := AppSettings.ReadBool(asWindowsAuth); + FPort := MakeInt(AppSettings.ReadString(asPort)); + FAllDatabases := AppSettings.ReadString(asDatabases); + FSSHHost := AppSettings.ReadString(asSSHtunnelHost); + FSSHPort := AppSettings.ReadInt(asSSHtunnelHostPort); + FSSHUser := AppSettings.ReadString(asSSHtunnelUser); + FSSHPassword := decrypt(AppSettings.ReadString(asSSHtunnelPassword)); + FSSHTimeout := AppSettings.ReadInt(asSSHtunnelTimeout); + FSSHPrivateKey := AppSettings.ReadString(asSSHtunnelPrivateKey); + FSSHLocalPort := AppSettings.ReadInt(asSSHtunnelPort); + FSSLPrivateKey := AppSettings.ReadString(asSSLKey); // Auto-activate SSL for sessions created before UseSSL was introduced: - FWantSSL := GetRegValue(REGNAME_SSL_ACTIVE, FSSLPrivateKey<>'', SessionRegPath); - FSSLCertificate := GetRegValue(REGNAME_SSL_CERT, '', SessionRegPath); - FSSLCACertificate := GetRegValue(REGNAME_SSL_CA, '', SessionRegPath); - FStartupScriptFilename := GetRegValue(REGNAME_STARTUPSCRIPT, '', SessionRegPath); - FCompressed := GetRegValue(REGNAME_COMPRESSED, DEFAULT_COMPRESSED, SessionRegPath); - FLocalTimeZone := GetRegValue(REGNAME_LOCALTIMEZONE, DEFAULT_LOCALTIMEZONE, SessionRegPath); - FServerVersion := GetRegValue(REGNAME_SERVERVERSION_FULL, '', SessionRegPath); + FWantSSL := AppSettings.ReadBool(asSSLActive, '', FSSLPrivateKey<>''); + FSSLCertificate := AppSettings.ReadString(asSSLCert); + FSSLCACertificate := AppSettings.ReadString(asSSLCA); + FStartupScriptFilename := AppSettings.ReadString(asStartupScriptFilename); + FCompressed := AppSettings.ReadBool(asCompressed); + FLocalTimeZone := AppSettings.ReadBool(asLocalTimeZone); + FServerVersion := AppSettings.ReadString(asServerVersionFull); DummyDate := 0; - FLastConnect := StrToDateTimeDef(GetRegValue(REGNAME_LASTCONNECT, '', SessionRegPath), DummyDate); - FCounter := GetRegValue(REGNAME_CONNECTCOUNT, 0, SessionRegPath); + FLastConnect := StrToDateTimeDef(AppSettings.ReadString(asLastConnect), DummyDate); + FCounter := AppSettings.ReadInt(asConnectCount); + AppSettings.ResetPath; + FSSHPlinkExe := AppSettings.ReadString(asPlinkExecutable); end; end; @@ -684,39 +684,37 @@ var IsNew: Boolean; begin // Save current values to registry - OpenRegistry; - MainReg.OpenKey(REGKEY_SESSIONS, False); - IsNew := not MainReg.KeyExists(FSessionPath); - MainReg.OpenKey(FSessionPath, True); + IsNew := not AppSettings.SessionPathExists(FSessionPath); + AppSettings.SessionPath := FSessionPath; if IsNew then - MainReg.WriteString(REGNAME_SESSIONCREATED, DateTimeToStr(Now)); + AppSettings.WriteString(asSessionCreated, DateTimeToStr(Now)); if FIsFolder then - MainReg.WriteBool(REGNAME_SESSIONFOLDER, True) + AppSettings.WriteBool(asSessionFolder, True) else begin - MainReg.WriteString(REGNAME_HOST, FHostname); - MainReg.WriteBool(REGNAME_WINDOWSAUTH, FWindowsAuth); - MainReg.WriteString(REGNAME_USER, FUsername); - MainReg.WriteString(REGNAME_PASSWORD, encrypt(FPassword)); - MainReg.WriteBool(REGNAME_LOGINPROMPT, FLoginPrompt); - MainReg.WriteString(REGNAME_PORT, IntToStr(FPort)); - MainReg.WriteInteger(REGNAME_NETTYPE, Integer(FNetType)); - MainReg.WriteBool(REGNAME_COMPRESSED, FCompressed); - MainReg.WriteBool(REGNAME_LOCALTIMEZONE, FLocalTimeZone); - MainReg.WriteString(REGNAME_DATABASES, FAllDatabases); - MainReg.WriteString(REGNAME_STARTUPSCRIPT, FStartupScriptFilename); - MainReg.WriteString(REGNAME_SSHHOST, FSSHHost); - MainReg.WriteInteger(REGNAME_SSHPORT, FSSHPort); - MainReg.WriteString(REGNAME_SSHUSER, FSSHUser); - MainReg.WriteString(REGNAME_SSHPASSWORD, encrypt(FSSHPassword)); - MainReg.WriteInteger(REGNAME_SSHTIMEOUT, FSSHTimeout); - MainReg.WriteString(REGNAME_SSHKEY, FSSHPrivateKey); - MainReg.WriteInteger(REGNAME_SSHLOCALPORT, FSSHLocalPort); - MainReg.WriteBool(REGNAME_SSL_ACTIVE, FWantSSL); - MainReg.WriteString(REGNAME_SSL_KEY, FSSLPrivateKey); - MainReg.WriteString(REGNAME_SSL_CERT, FSSLCertificate); - MainReg.WriteString(REGNAME_SSL_CA, FSSLCACertificate); - OpenRegistry; - MainReg.WriteString(REGNAME_PLINKEXE, FSSHPlinkExe); + AppSettings.WriteString(asHost, FHostname); + AppSettings.WriteBool(asWindowsAuth, FWindowsAuth); + AppSettings.WriteString(asUser, FUsername); + AppSettings.WriteString(asPassword, encrypt(FPassword)); + AppSettings.WriteBool(asLoginPrompt, FLoginPrompt); + AppSettings.WriteString(asPort, IntToStr(FPort)); + AppSettings.WriteInt(asNetType, Integer(FNetType)); + AppSettings.WriteBool(asCompressed, FCompressed); + AppSettings.WriteBool(asLocalTimeZone, FLocalTimeZone); + AppSettings.WriteString(asDatabases, FAllDatabases); + AppSettings.WriteString(asStartupScriptFilename, FStartupScriptFilename); + AppSettings.WriteString(asSSHtunnelHost, FSSHHost); + AppSettings.WriteInt(asSSHtunnelHostPort, FSSHPort); + AppSettings.WriteString(asSSHtunnelUser, FSSHUser); + AppSettings.WriteString(asSSHtunnelPassword, encrypt(FSSHPassword)); + AppSettings.WriteInt(asSSHtunnelTimeout, FSSHTimeout); + AppSettings.WriteString(asSSHtunnelPrivateKey, FSSHPrivateKey); + AppSettings.WriteInt(asSSHtunnelPort, FSSHLocalPort); + AppSettings.WriteBool(asSSLActive, FWantSSL); + AppSettings.WriteString(asSSLKey, FSSLPrivateKey); + AppSettings.WriteString(asSSLCert, FSSLCertificate); + AppSettings.WriteString(asSSLCA, FSSLCACertificate); + AppSettings.ResetPath; + AppSettings.WriteString(asPlinkExecutable, FSSHPlinkExe); end; end; @@ -1344,8 +1342,8 @@ end; procedure TDBConnection.DoAfterConnect; begin - OpenRegistry(FParameters.SessionPath); - MainReg.WriteString(REGNAME_SERVERVERSION_FULL, FServerVersionUntouched); + AppSettings.SessionPath := FParameters.SessionPath; + AppSettings.WriteString(asServerVersionFull, FServerVersionUntouched); FParameters.ServerVersion := FServerVersionUntouched; if Assigned(FOnConnected) then FOnConnected(Self, FDatabase); diff --git a/source/editvar.pas b/source/editvar.pas index 2aa5dcd3..16bac896 100644 --- a/source/editvar.pas +++ b/source/editvar.pas @@ -57,16 +57,15 @@ procedure TfrmEditVariable.FormCreate(Sender: TObject); begin InheritFont(Font); SetWindowSizeGrip(Handle, True); - Width := GetRegValue(REGNAME_EDITVARWINWIDTH, Width); - Height := GetRegValue(REGNAME_EDITVARWINHEIGHT, Height); + Width := AppSettings.ReadInt(asEditVarWindowWidth); + Height := AppSettings.ReadInt(asEditVarWindowHeight); end; procedure TfrmEditVariable.FormDestroy(Sender: TObject); begin - OpenRegistry; - MainReg.WriteInteger(REGNAME_EDITVARWINWIDTH, Width); - MainReg.WriteInteger(REGNAME_EDITVARWINHEIGHT, Height); + AppSettings.WriteInt(asEditVarWindowWidth, Width); + AppSettings.WriteInt(asEditVarWindowHeight, Height); end; diff --git a/source/exportgrid.pas b/source/exportgrid.pas index 0127c670..ab2452ab 100644 --- a/source/exportgrid.pas +++ b/source/exportgrid.pas @@ -85,19 +85,18 @@ uses main, helpers, dbconnection, mysql_structures; procedure TfrmExportGrid.FormCreate(Sender: TObject); begin InheritFont(Font); - OpenRegistry; - editFilename.Text := GetRegValue(REGNAME_GEXP_FILENAME, editFilename.Text); - radioOutputCopyToClipboard.Checked := GetRegValue(REGNAME_GEXP_OUTPUTCOPY, radioOutputCopyToClipboard.Checked); - radioOutputFile.Checked := GetRegValue(REGNAME_GEXP_OUTPUTFILE, radioOutputFile.Checked); - FRecentFiles := Explode(DELIM, GetRegValue(REGNAME_GEXP_RECENTFILES, '')); + editFilename.Text := AppSettings.ReadString(asGridExportFilename); + radioOutputCopyToClipboard.Checked := AppSettings.ReadBool(asGridExportOutputCopy); + radioOutputFile.Checked := AppSettings.ReadBool(asGridExportOutputFile); + FRecentFiles := Explode(DELIM, AppSettings.ReadString(asGridExportRecentFiles)); comboEncoding.Items.Assign(MainForm.FileEncodings); comboEncoding.Items.Delete(0); // Remove "Auto detect" - comboEncoding.ItemIndex := GetRegValue(REGNAME_GEXP_ENCODING, 4); - grpFormat.ItemIndex := GetRegValue(REGNAME_GEXP_FORMAT, grpFormat.ItemIndex); - chkColumnHeader.Checked := GetRegValue(REGNAME_GEXP_COLUMNNAMES, chkColumnHeader.Checked); - FCSVSeparator := GetRegValue(REGNAME_GEXP_SEPARATOR, editSeparator.Text); - FCSVEncloser := GetRegValue(REGNAME_GEXP_ENCLOSER, editEncloser.Text); - FCSVTerminator := GetRegValue(REGNAME_GEXP_TERMINATOR, editTerminator.Text); + comboEncoding.ItemIndex := AppSettings.ReadInt(asGridExportEncoding); + grpFormat.ItemIndex := AppSettings.ReadInt(asGridExportFormat); + chkColumnHeader.Checked := AppSettings.ReadBool(asGridExportColumnNames); + FCSVSeparator := AppSettings.ReadString(asGridExportSeparator); + FCSVEncloser := AppSettings.ReadString(asGridExportEncloser); + FCSVTerminator := AppSettings.ReadString(asGridExportTerminator); ValidateControls(Sender); end; @@ -106,17 +105,17 @@ procedure TfrmExportGrid.FormDestroy(Sender: TObject); begin // Store settings if ModalResult = mrOK then begin - MainReg.WriteBool(REGNAME_GEXP_OUTPUTCOPY, radioOutputCopyToClipboard.Checked); - MainReg.WriteBool(REGNAME_GEXP_OUTPUTFILE, radioOutputFile.Checked); - MainReg.WriteString(REGNAME_GEXP_FILENAME, editFilename.Text); - MainReg.WriteString(REGNAME_GEXP_RECENTFILES, ImplodeStr(DELIM, FRecentFiles)); - MainReg.WriteInteger(REGNAME_GEXP_ENCODING, comboEncoding.ItemIndex); - MainReg.WriteInteger(REGNAME_GEXP_FORMAT, grpFormat.ItemIndex); - MainReg.WriteInteger(REGNAME_GEXP_SELECTION, grpSelection.ItemIndex); - MainReg.WriteBool(REGNAME_GEXP_COLUMNNAMES, chkColumnHeader.Checked); - MainReg.WriteString(REGNAME_GEXP_SEPARATOR, FCSVSeparator); - MainReg.WriteString(REGNAME_GEXP_ENCLOSER, FCSVEncloser); - MainReg.WriteString(REGNAME_GEXP_TERMINATOR, FCSVTerminator); + AppSettings.WriteBool(asGridExportOutputCopy, radioOutputCopyToClipboard.Checked); + AppSettings.WriteBool(asGridExportOutputFile, radioOutputFile.Checked); + AppSettings.WriteString(asGridExportFilename, editFilename.Text); + AppSettings.WriteString(asGridExportRecentFiles, ImplodeStr(DELIM, FRecentFiles)); + AppSettings.WriteInt(asGridExportEncoding, comboEncoding.ItemIndex); + AppSettings.WriteInt(asGridExportFormat, grpFormat.ItemIndex); + AppSettings.WriteInt(asGridExportSelection, grpSelection.ItemIndex); + AppSettings.WriteBool(asGridExportColumnNames, chkColumnHeader.Checked); + AppSettings.WriteString(asGridExportSeparator, FCSVSeparator); + AppSettings.WriteString(asGridExportEncloser, FCSVEncloser); + AppSettings.WriteString(asGridExportTerminator, FCSVTerminator); end; end; @@ -149,7 +148,7 @@ begin end; grpSelection.Items.Add('Selection ('+FormatNumber(Grid.SelectedCount)+' rows, '+FormatByteNumber(SelectionSize)+')'); grpSelection.Items.Add('Complete ('+FormatNumber(Grid.RootNodeCount)+' rows, '+FormatByteNumber(AllSize)+')'); - grpSelection.ItemIndex := GetRegValue(REGNAME_GEXP_SELECTION, grpSelection.ItemIndex); + grpSelection.ItemIndex := AppSettings.ReadInt(asGridExportSelection); end; diff --git a/source/grideditlinks.pas b/source/grideditlinks.pas index 1f5191aa..b853b7cc 100644 --- a/source/grideditlinks.pas +++ b/source/grideditlinks.pas @@ -527,8 +527,7 @@ end; destructor TDateTimeEditorLink.Destroy; begin - OpenRegistry; - Mainreg.WriteInteger(REGPREFIX_DATEEDITOR_CURSOR+IntToStr(Integer(Datatype)), FMaskEdit.SelStart); + AppSettings.WriteInt(asDateTimeEditorCursorPos, FMaskEdit.SelStart, IntToStr(Integer(Datatype))); FreeAndNil(FTimer); FreeAndNil(FUpDown); FreeAndNil(FMaskEdit); @@ -544,7 +543,7 @@ begin FPanel.Show; FMaskEdit.SetFocus; // Focus very last segment of date - FMaskEdit.SelStart := GetRegValue(REGPREFIX_DATEEDITOR_CURSOR+IntToStr(Integer(Datatype)), Length(FMaskEdit.Text)-1); + FMaskEdit.SelStart := AppSettings.ReadInt(asDateTimeEditorCursorPos, IntToStr(Integer(Datatype))); FMaskEdit.SelLength := 1; end; end; @@ -883,8 +882,8 @@ begin FPanel.Hide; FPanel.Parent := FParentForm; FPanel.ParentBackground := False; - FPanel.Width := GetRegValue(REGNAME_SETEDITORWIDTH, DEFAULT_SETEDITORWIDTH); - FPanel.Height := GetRegValue(REGNAME_SETEDITORHEIGHT, DEFAULT_SETEDITORHEIGHT); + FPanel.Width := AppSettings.ReadInt(asSetEditorWidth); + FPanel.Height := AppSettings.ReadInt(asSetEditorHeight); SetWindowSizeGrip(FPanel.Handle, True); FPanel.OnResize := PanelResize; FPanel.OnExit := DoEndEdit; @@ -908,8 +907,8 @@ end; destructor TSetEditorLink.Destroy; begin - Mainreg.WriteInteger(REGNAME_SETEDITORWIDTH, FPanel.Width); - Mainreg.WriteInteger(REGNAME_SETEDITORHEIGHT, FPanel.Height); + AppSettings.WriteInt(asSetEditorWidth, FPanel.Width); + AppSettings.WriteInt(asSetEditorHeight, FPanel.Height); FreeAndNil(FPanel); inherited; end; diff --git a/source/helpers.pas b/source/helpers.pas index 3f46c446..e592c231 100644 --- a/source/helpers.pas +++ b/source/helpers.pas @@ -130,6 +130,106 @@ type procedure LogFromOutside(Msg: String; Category: TDBLogCategory); end; + TAppSettingDataType = (adInt, adBool, adString); + TAppSettingIndex = (asHiddenColumns, asFilter, asSort, asDisplayedColumnsSorted, asLastSessions, + asLastActiveSession, asAutoReconnect, asRestoreLastUsedDB, asLastUsedDB, asTreeBackground, + asFontName, asFontSize, asTabWidth, asDataFontName, asDataFontSize, + asLogsqlnum, asLogsqlwidth, asSessionLogsDirectory, asLogHorizontalScrollbar, asSQLColActiveLine, + asMaxColWidth, asDatagridMaximumRows, asDatagridRowsPerStep, asGridRowLineCount, asRememberFilters, + asLogToFile, asMainWinMaximized, asMainWinLeft, asMainWinTop, asMainWinWidth, + asMainWinHeight, asMainWinOnMonitor, asToolBar2Left, asToolBar2Top, asToolBarDataLeft, + asToolBarDataTop, asToolBarQueryLeft, asToolBarQueryTop, asQuerymemoheight, asDbtreewidth, + asDataPreviewHeight, asDataPreviewEnabled, asLogHeight, asQueryhelperswidth, asStopOnErrorsInBatchMode, + asWrapLongLines, asDisplayBLOBsAsText, asSingleQueries, asMemoEditorWidth, asMemoEditorHeight, + asMemoEditorWrap, asDelimiter, asSQLHelpWindowLeft, asSQLHelpWindowTop, asSQLHelpWindowWidth, + asSQLHelpWindowHeight, asSQLHelpPnlLeftWidth, asSQLHelpPnlRightTopHeight, asTableEditorTabsHeight, asHost, + asUser, asPassword, asWindowsAuth, asLoginPrompt, asPort, + asPlinkExecutable, asSSHtunnelHost, asSSHtunnelHostPort, asSSHtunnelPort, asSSHtunnelUser, + asSSHtunnelPassword, asSSHtunnelTimeout, asSSHtunnelPrivateKey, asSSLActive, asSSLKey, + asSSLCert, asSSLCA, asNetType, asCompressed, asLocalTimeZone, + asStartupScriptFilename, asDatabases, asDatabaseFilter, asExportSQLCreateDatabases, asExportSQLDropDatabases, + asExportSQLCreateTables, asExportSQLDropTables, asExportSQLDataHow, asExportSQLFilenames, asExportSQLDirectories, + asExportSQLDatabase, asExportSQLServerDatabase, asExportSQLOutput, asGridExportOutputCopy, asGridExportOutputFile, + asGridExportFilename, asGridExportRecentFiles, asGridExportEncoding, asGridExportFormat, asGridExportSelection, + asGridExportColumnNames, asGridExportSeparator, asGridExportEncloser, asGridExportTerminator, asCSVImportSeparator, + asCSVImportEncloser, asCSVImportTerminator, asCSVImportFieldEscaper, asCSVImportWindowWidth, asCSVImportWindowHeight, + asCSVImportFilename, asCSVImportFieldsEnclosedOptionally, asCSVImportIgnoreLines, asCSVImportLowPriority, asCSVImportLocalNumbers, + asCSVImportTruncateTable, asCSVImportDuplicateHandling, asCSVImportParseMethod, asUpdatecheck, asUpdatecheckBuilds, + asUpdatecheckInterval, asUpdatecheckLastrun, asTableToolsWindowWidth, asTableToolsWindowHeight, asTableToolsTreeWidth, + asTableToolsFindText, asTableToolsDatatype, asTableToolsFindCaseSensitive, asFileImportWindowWidth, asFileImportWindowHeight, + asEditVarWindowWidth, asEditVarWindowHeight, asUsermanagerWindowWidth, asUsermanagerWindowHeight, asUsermanagerListWidth, + asSelectDBOWindowWidth, asSelectDBOWindowHeight, asSessionManagerListWidth, asSessionManagerWindowWidth, asSessionManagerWindowHeight, + asCopyTableWindowHeight, asCopyTableWindowWidth, asCopyTableColumns, asCopyTableKeys, asCopyTableForeignKeys, + asCopyTableData, asCopyTableRecentFilter, asServerVersion, asServerVersionFull, asLastConnect, + asConnectCount, asRefusedCount, asSessionCreated, asDoUsageStatistics, + asLastUsageStatisticCall, asDisplayBars, asBarColor, asMySQLBinaries, asPromptSaveFileOnTabClose, + asCompletionProposal, asTabsToSpaces, asFilterPanel, asAllowMultipleInstances, asFindDialogSearchHistory, + asFindDialogReplaceHistory, asMaxQueryResults, asSetEditorWidth, asSetEditorHeight, asLogErrors, + asLogUserSQL, asLogSQL, asLogInfos, asLogDebug, asFieldColorNumeric, + asFieldColorReal, asFieldColorText, asFieldColorBinary, asFieldColorDatetime, asFieldColorSpatial, + asFieldColorOther, asFieldEditorBinary, asFieldEditorDatetime, asFieldEditorDatetimePrefill, asFieldEditorEnum, + asFieldEditorSet, asFieldNullBackground, asGroupTreeObjects, asDisplayObjectSizeColumn, asSQLfile, + asActionShortcut1, asActionShortcut2, asHighlighterForeground, asHighlighterBackground, asHighlighterStyle, + asListColWidths, asListColsVisible, asListColPositions, asListColSort, asSessionFolder, + asRecentFilter, asDateTimeEditorCursorPos); + TAppSetting = record + Name: String; + Session: Boolean; + DefaultInt, CurrentInt: Integer; + DefaultBool, CurrentBool: Boolean; + DefaultString, CurrentString: String; + Synced: Boolean; + end; + TAppSettings = class(TObject) + private + FReads, FWrites: Integer; + FBasePath: String; + FSessionPath: String; + FRegistry: TRegistry; + FPortableMode: Boolean; + FSettingsFile: String; + FSettings: Array[TAppSettingIndex] of TAppSetting; + procedure InitSetting(Index: TAppSettingIndex; Name: String; + DefaultInt: Integer=0; DefaultBool: Boolean=False; DefaultString: String=''; + Session: Boolean=False); + procedure SetSessionPath(Value: String); + procedure PrepareRegistry; + procedure Read(Index: TAppSettingIndex; FormatName: String; + DataType: TAppSettingDataType; var I: Integer; var B: Boolean; var S: String; + DI: Integer; DB: Boolean; DS: String); + procedure Write(Index: TAppSettingIndex; FormatName: String; + DataType: TAppSettingDataType; I: Integer; B: Boolean; S: String); + public + constructor Create; + destructor Destroy; override; + function ReadInt(Index: TAppSettingIndex; FormatName: String=''; Default: Integer=0): Integer; + function ReadBool(Index: TAppSettingIndex; FormatName: String=''; Default: Boolean=False): Boolean; + function ReadString(Index: TAppSettingIndex; FormatName: String=''; Default: String=''): String; overload; + function ReadString(ValueName: String): String; overload; + procedure WriteInt(Index: TAppSettingIndex; Value: Integer; FormatName: String=''); + procedure WriteBool(Index: TAppSettingIndex; Value: Boolean; FormatName: String=''); + procedure WriteString(Index: TAppSettingIndex; Value: String; FormatName: String=''); overload; + procedure WriteString(ValueName, Value: String); overload; + function GetDefaultInt(Index: TAppSettingIndex): Integer; + function GetDefaultString(Index: TAppSettingIndex): String; + function GetValueName(Index: TAppSettingIndex): String; + function GetValueNames: TStringList; + function GetKeyNames: TStringList; + function GetSessionNames(ParentPath: String; var Folders: TStringList): TStringList; + procedure GetSessionPaths(ParentPath: String; var Sessions: TStringList); + function DeleteValue(Index: TAppSettingIndex; FormatName: String=''): Boolean; overload; + function DeleteValue(ValueName: String): Boolean; overload; + procedure DeleteCurrentKey; + procedure MoveCurrentKey(TargetPath: String); + function ValueExists(Index: TAppSettingIndex): Boolean; + function SessionPathExists(SessionPath: String): Boolean; + function IsEmptyKey: Boolean; + procedure ResetPath; + property SessionPath: String read FSessionPath write SetSessionPath; + property PortableMode: Boolean read FPortableMode; + procedure ImportSettings(Filename: String); + procedure ExportSettings(Filename: String); + end; {$I const.inc} @@ -156,6 +256,10 @@ type function RemoveNulChars(Text: String): String; function fixNewlines(txt: String): String; function GetShellFolder(CSIDL: integer): string; + // Common directories + function DirnameCommonAppData: String; + function DirnameUserAppData: String; + function DirnameSnippets: String; function goodfilename( str: String ): String; function FormatNumber( str: String; Thousands: Boolean=True): String; Overload; function UnformatNumber(Val: String): String; @@ -182,12 +286,6 @@ type function GetTextHeight(Font: TFont): Integer; function ColorAdjustBrightness(Col: TColor; Shift: SmallInt): TColor; function ComposeOrderClause(Cols: TOrderColArray): String; - procedure OpenRegistry(SessionPath: String = ''); - function GetRegValue(ValueName: String; DefaultValue: Integer; SessionPath: String=''): Integer; overload; - function GetRegValue(ValueName: String; DefaultValue: Boolean; SessionPath: String=''): Boolean; overload; - function GetRegValue(ValueName: String; DefaultValue: String; SessionPath: String=''): String; overload; - function GetSessionNames(ParentPath: String; var Folders: TStringList): TStringList; - procedure GetSessionPaths(ParentPath: String; var Sessions: TStringList); procedure DeInitializeVTNodes(Sender: TBaseVirtualTree); function ListIndexByRegExpr(List: TStrings; Expression: String): Integer; function FindNode(VT: TVirtualStringTree; idx: Cardinal; ParentNode: PVirtualNode): PVirtualNode; @@ -208,9 +306,6 @@ type function KeyPressed(Code: Integer): Boolean; function GeneratePassword(Len: Integer): String; procedure InvalidateVT(VT: TVirtualStringTree; RefreshTag: Integer; ImmediateRepaint: Boolean); - procedure HandlePortableSettings(StartupMode: Boolean); - procedure ImportSettings(Filename: String); - procedure ExportSettings(Filename: String); function CharAtPos(Str: String; Pos: Integer): Char; function CompareAnyNode(Text1, Text2: String): Integer; function StringListCompareAnythingAsc(List: TStringList; Index1, Index2: Integer): Integer; @@ -227,9 +322,7 @@ type function GetHTMLCharsetByEncoding(Encoding: TEncoding): String; var - MainReg: TRegistry; - RegPath: String = '\Software\' + APPNAME + '\'; - PortableMode: Boolean = False; + AppSettings: TAppSettings; MutexHandle: THandle = 0; DecimalSeparatorSystemdefault: Char; @@ -709,6 +802,26 @@ begin end; +function DirnameCommonAppData: String; +begin + // "All users" folder for HeidiSQL's data (All Users\Application Data) + Result := GetShellFolder(CSIDL_COMMON_APPDATA) + '\' + APPNAME + '\'; +end; + + +function DirnameUserAppData: String; +begin + // User folder for HeidiSQL's data (\Application Data) + Result := GetShellFolder(CSIDL_APPDATA) + '\' + APPNAME + '\'; +end; + + +function DirnameSnippets: String; +begin + // Folder for snippets + Result := DirnameCommonAppData + 'Snippets\' +end; + {*** Remove special characters from a filename @@ -1486,93 +1599,6 @@ begin end; -{** - Init main registry object and open desired key - Outsoureced from GetRegValue() to avoid redundant code - in these 3 overloaded methods. -} -procedure OpenRegistry(SessionPath: String = ''); -var - folder : String; -begin - if MainReg = nil then begin - MainReg := TRegistry.Create; - HandlePortableSettings(True); - end; - folder := RegPath; - if SessionPath <> '' then - folder := folder + REGKEY_SESSIONS + '\' + SessionPath; - if MainReg.CurrentPath <> folder then - MainReg.OpenKey(folder, true); -end; - - -function GetRegValue(ValueName: String; DefaultValue: Integer; SessionPath: String=''): Integer; -begin - // Read a numeric user setting value from registry - Result := DefaultValue; - OpenRegistry(SessionPath); - if MainReg.ValueExists(ValueName) then - Result := MainReg.ReadInteger(ValueName); -end; - - -function GetRegValue(ValueName: String; DefaultValue: Boolean; SessionPath: String=''): Boolean; -begin - // Read a boolean user setting value from registry - Result := DefaultValue; - OpenRegistry(SessionPath); - if MainReg.ValueExists(ValueName) then - Result := MainReg.ReadBool(ValueName); -end; - - -function GetRegValue(ValueName: String; DefaultValue: String; SessionPath: String=''): String; -begin - // Read a text user setting value from registry - Result := DefaultValue; - OpenRegistry(SessionPath); - if MainReg.ValueExists(ValueName) then - Result := MainReg.ReadString(ValueName); -end; - - -function GetSessionNames(ParentPath: String; var Folders: TStringList): TStringList; -var - i: Integer; - CurPath: String; -begin - Result := TStringlist.Create; - OpenRegistry; - CurPath := RegPath + REGKEY_SESSIONS + '\' + ParentPath; - MainReg.OpenKey(CurPath, False); - MainReg.GetKeyNames(Result); - for i:=Result.Count-1 downto 0 do begin - MainReg.OpenKey(CurPath+'\'+Result[i], False); - if MainReg.ValueExists(REGNAME_SESSIONFOLDER) then begin - Folders.Add(Result[i]); - Result.Delete(i); - end; - end; -end; - - -procedure GetSessionPaths(ParentPath: String; var Sessions: TStringList); -var - Folders, Names: TStringList; - i: Integer; -begin - Folders := TStringList.Create; - Names := GetSessionNames(ParentPath, Folders); - for i:=0 to Names.Count-1 do - Sessions.Add(ParentPath+Names[i]); - for i:=0 to Folders.Count-1 do - GetSessionPaths(ParentPath+Folders[i]+'\', Sessions); - Names.Free; - Folders.Free; -end; - - procedure DeInitializeVTNodes(Sender: TBaseVirtualTree); var Node: PVirtualNode; @@ -2202,176 +2228,6 @@ begin end; -procedure ImportSettings(Filename: String); -var - Content, Name, Value, KeyPath: String; - Lines, Segments: TStringList; - i: Integer; - DataType: TRegDataType; -begin - // Load registry settings from file - Content := ReadTextfile(FileName, nil); - Lines := Explode(CRLF, Content); - for i:=0 to Lines.Count-1 do begin - // Each line has 3 segments: reg path | data type | value. Continue if explode finds less or more than 3. - Segments := Explode(DELIMITER, Lines[i]); - if Segments.Count <> 3 then - continue; - KeyPath := RegPath + ExtractFilePath(Segments[0]); - Name := ExtractFileName(Segments[0]); - DataType := TRegDataType(StrToInt(Segments[1])); - MainReg.OpenKey(KeyPath, True); - if MainReg.ValueExists(Name) then - Continue; // Don't touch value if already there - Value := ''; - if Segments.Count >= 3 then - Value := Segments[2]; - case DataType of - rdString: begin - Value := StringReplace(Value, CHR13REPLACEMENT, #13, [rfReplaceAll]); - Value := StringReplace(Value, CHR10REPLACEMENT, #10, [rfReplaceAll]); - MainReg.WriteString(Name, Value); - end; - rdInteger: - MainReg.WriteInteger(Name, MakeInt(Value)); - rdBinary, rdUnknown, rdExpandString: - ErrorDialog(Name+' has an unsupported data type.'); - end; - Segments.Free; - end; - Lines.Free; -end; - - -procedure ExportSettings(Filename: String); -var - Content, Value: String; - DataType: TRegDataType; - - procedure ReadKeyToContent(Path: String); - var - Names: TStringList; - i: Integer; - SubPath: String; - begin - // Recursively read values in keys and their subkeys into "content" variable - MainReg.OpenKey(Path, True); - SubPath := Copy(Path, Length(RegPath)+1, MaxInt); - Names := TStringList.Create; - MainReg.GetValueNames(Names); - for i:=0 to Names.Count-1 do begin - DataType := MainReg.GetDataType(Names[i]); - Content := Content + - SubPath + Names[i] + DELIMITER + - IntToStr(Integer(DataType)) + DELIMITER; - case DataType of - rdString: begin - Value := MainReg.ReadString(Names[i]); - Value := StringReplace(Value, #13, CHR13REPLACEMENT, [rfReplaceAll]); - Value := StringReplace(Value, #10, CHR10REPLACEMENT, [rfReplaceAll]); - end; - rdInteger: - Value := IntToStr(MainReg.ReadInteger(Names[i])); - rdBinary, rdUnknown, rdExpandString: - ErrorDialog(Names[i]+' has an unsupported data type.'); - end; - Content := Content + Value + CRLF; - end; - Names.Clear; - MainReg.GetKeyNames(Names); - for i:=0 to Names.Count-1 do - ReadKeyToContent(Path + Names[i] + '\'); - Names.Free; - end; - -begin - // Save registry settings to file - Content := ''; - ReadKeyToContent(RegPath); - SaveUnicodeFile(FileName, Content); -end; - - -procedure HandlePortableSettings(StartupMode: Boolean); -var - FileName: String; - AllKeys: TStringList; - i: Integer; - Proc: TProcessEntry32; - ProcRuns: Boolean; - SnapShot: THandle; - rx: TRegExpr; -begin - // Export registry keys and values into textfile, for portable reasons - - // Use filename from command line. If not given, use file in directory of executable. - rx := TRegExpr.Create; - rx.Expression := '^\-\-?psettings\=(.+)$'; - for i:=1 to ParamCount do begin - if rx.Exec(ParamStr(i)) then begin - Filename := rx.Match[1]; - break; - end; - end; - if Filename = '' then - Filename := ExtractFilePath(ParamStr(0)) + 'portable_settings.txt'; - if not FileExists(FileName) then - Exit; - - // Open the right key - if StartupMode then begin - RegPath := '\Software\' + APPNAME + ' Portable '+IntToStr(GetCurrentProcessId)+'\'; - PortableMode := True; - end else begin - // Do not work like a portable on exit, if at application start we didn't either - if not PortableMode then - Exit; - end; - - Screen.Cursor := crHourGlass; - try - // Both ImportSettings and ExportSettings rely on RegPath pointing to the right reg key - if StartupMode then begin - ImportSettings(Filename); - end else begin - // Application closes - ExportSettings(Filename); - MainReg.CloseKey; - MainReg.DeleteKey(RegPath); - - // Remove dead keys from instances which didn't close clean, e.g. because of an AV - SnapShot := CreateToolhelp32Snapshot(TH32CS_SnapProcess, 0); - Proc.dwSize := Sizeof(Proc); - MainReg.OpenKeyReadOnly('\Software\'); - AllKeys := TStringList.Create; - MainReg.GetKeyNames(AllKeys); - rx.Expression := '^' + QuoteRegExprMetaChars(APPNAME) + ' Portable (\d+)$'; - for i:=0 to AllKeys.Count-1 do begin - if not rx.Exec(AllKeys[i]) then - Continue; - ProcRuns := False; - if Process32First(SnapShot, Proc) then while True do begin - ProcRuns := rx.Match[1] = IntToStr(Proc.th32ProcessID); - if ProcRuns or (not Process32Next(SnapShot, Proc)) then - break; - end; - if not ProcRuns then - MainReg.DeleteKey(AllKeys[i]); - end; - MainReg.CloseKey; - CloseHandle(SnapShot); - AllKeys.Free; - rx.Free; - end; - except - On E:Exception do - ErrorDialog(E.Message); - end; - Screen.Cursor := crDefault; - -end; - - function CharAtPos(Str: String; Pos: Integer): Char; begin // Access char in string without causing access violation @@ -2699,7 +2555,7 @@ begin Synchronize(BeforeQuery); try FConnection.LockedByThread := Self; - DoStoreResult := ResultCount < Mainform.prefMaxQueryResults; + DoStoreResult := ResultCount < AppSettings.ReadInt(asMaxQueryResults); FConnection.Query(SQL, DoStoreResult, lcUserFiredSQL); Inc(ResultCount, FConnection.ResultCount); FBatchPosition := i; @@ -2971,6 +2827,733 @@ end; +{ TAppSettings } + +constructor TAppSettings.Create; +var + rx: TRegExpr; + i: Integer; +begin + inherited; + FRegistry := TRegistry.Create; + FReads := 0; + FWrites := 0; + + // Use filename from command line. If not given, use file in directory of executable. + rx := TRegExpr.Create; + rx.Expression := '^\-\-?psettings\=(.+)$'; + for i:=1 to ParamCount do begin + if rx.Exec(ParamStr(i)) then begin + FSettingsFile := rx.Match[1]; + break; + end; + end; + if FSettingsFile = '' then + FSettingsFile := ExtractFilePath(ParamStr(0)) + 'portable_settings.txt'; + if FileExists(FSettingsFile) then begin + FPortableMode := True; + FBasePath := '\Software\' + APPNAME + ' Portable '+IntToStr(GetCurrentProcessId)+'\'; + try + ImportSettings(FSettingsFile); + except + on E:Exception do + ErrorDialog(E.Message); + end; + end else begin + FPortableMode := False; + FBasePath := '\Software\' + APPNAME + '\'; + FSettingsFile := ''; + end; + + PrepareRegistry; + + InitSetting(asHiddenColumns, 'HiddenColumns', 0, False, '', True); + InitSetting(asFilter, 'Filter', 0, False, '', True); + InitSetting(asSort, 'Sort', 0, False, '', True); + InitSetting(asDisplayedColumnsSorted, 'DisplayedColumnsSorted', 0, False); + InitSetting(asLastSessions, 'LastSessions', 0, False, ''); + InitSetting(asLastActiveSession, 'LastActiveSession', 0, False, ''); + InitSetting(asAutoReconnect, 'AutoReconnect', 0, False); + InitSetting(asRestoreLastUsedDB, 'RestoreLastUsedDB', 0, True); + InitSetting(asLastUsedDB, 'lastUsedDB', 0, False, ''); + InitSetting(asTreeBackground, 'TreeBackground', clNone, False, '', True); + InitSetting(asFontName, 'FontName', 0, False, 'Courier New'); + InitSetting(asFontSize, 'FontSize', 9); + InitSetting(asTabWidth, 'TabWidth', 3); + InitSetting(asDataFontName, 'DataFontName', 0, False, 'Tahoma'); + InitSetting(asDataFontSize, 'DataFontSize', 8); + InitSetting(asLogsqlnum, 'logsqlnum', 300); + InitSetting(asLogsqlwidth, 'logsqlwidth', 2000); + InitSetting(asSessionLogsDirectory, 'SessionLogsDirectory', 0, False, DirnameUserAppData + 'Sessionlogs\'); + InitSetting(asLogHorizontalScrollbar, 'LogHorizontalScrollbar', 0, False); + InitSetting(asSQLColActiveLine, 'SQLColActiveLine', 0, False, 'clNone'); + InitSetting(asMaxColWidth, 'MaxColWidth', 300); + InitSetting(asDatagridMaximumRows, 'DatagridMaximumRows', 100000); + InitSetting(asDatagridRowsPerStep, 'DatagridRowsPerStep', 1000); + InitSetting(asGridRowLineCount, 'GridRowLineCount', 1); + InitSetting(asRememberFilters, 'RememberFilters', 0, True); + InitSetting(asLogToFile, 'LogToFile', 0, False); + InitSetting(asMainWinMaximized, 'MainWinMaximized', 0, False); + InitSetting(asMainWinLeft, 'MainWinLeft', 100); + InitSetting(asMainWinTop, 'MainWinTop', 100); + InitSetting(asMainWinWidth, 'MainWinWidth', 800); + InitSetting(asMainWinHeight, 'MainWinHeight', 600); + InitSetting(asMainWinOnMonitor, 'MainWinOnMonitor', 1); + InitSetting(asToolBar2Left, 'ToolBar2Left', 11); + InitSetting(asToolBar2Top, 'ToolBar2Top', 2); + InitSetting(asToolBarDataLeft, 'ToolBarDataLeft', 343); + InitSetting(asToolBarDataTop, 'ToolBarDataTop', 2); + InitSetting(asToolBarQueryLeft, 'ToolBarQueryLeft', 494); + InitSetting(asToolBarQueryTop, 'ToolBarQueryTop', 2); + InitSetting(asQuerymemoheight, 'querymemoheight', 100); + InitSetting(asDbtreewidth, 'dbtreewidth', 170); + InitSetting(asDataPreviewHeight, 'DataPreviewHeight', 100); + InitSetting(asDataPreviewEnabled, 'DataPreviewEnabled', 0, False); + InitSetting(asLogHeight, 'sqloutheight', 80); + InitSetting(asQueryhelperswidth, 'queryhelperswidth', 200); + InitSetting(asStopOnErrorsInBatchMode, 'StopOnErrorsInBatchMode', 0, True); + InitSetting(asWrapLongLines, 'WrapLongLines', 0, False); + InitSetting(asDisplayBLOBsAsText, 'DisplayBLOBsAsText', 0, False); + InitSetting(asSingleQueries, 'SingleQueries', 0, True); + InitSetting(asMemoEditorWidth, 'MemoEditorWidth', 100); + InitSetting(asMemoEditorHeight, 'MemoEditorHeight', 100); + InitSetting(asMemoEditorWrap, 'MemoEditorWrap', 0, False); + InitSetting(asDelimiter, 'Delimiter', 0, False, ';'); + InitSetting(asSQLHelpWindowLeft, 'SQLHelp_WindowLeft', 0); + InitSetting(asSQLHelpWindowTop, 'SQLHelp_WindowTop', 0); + InitSetting(asSQLHelpWindowWidth, 'SQLHelp_WindowWidth', 600); + InitSetting(asSQLHelpWindowHeight, 'SQLHelp_WindowHeight', 400); + InitSetting(asSQLHelpPnlLeftWidth, 'SQLHelp_PnlLeftWidth', 150); + InitSetting(asSQLHelpPnlRightTopHeight, 'SQLHelp_PnlRightTopHeight', 150); + InitSetting(asTableEditorTabsHeight, 'TableEditorTabsHeight', 150); + InitSetting(asHost, 'Host', 0, False, '127.0.0.1', True); + InitSetting(asUser, 'User', 0, False, 'root', True); + InitSetting(asPassword, 'Password', 0, False, '', True); + InitSetting(asWindowsAuth, 'WindowsAuth', 0, False, '', True); + InitSetting(asLoginPrompt, 'LoginPrompt', 0, False, '', True); + InitSetting(asPort, 'Port', 0, False, '3306', True); + InitSetting(asPlinkExecutable, 'PlinkExecutable', 0, False, ''); + InitSetting(asSSHtunnelHost, 'SSHtunnelHost', 0, False, '', True); + InitSetting(asSSHtunnelHostPort, 'SSHtunnelHostPort', 22, False, '', True); + InitSetting(asSSHtunnelPort, 'SSHtunnelPort', 0, False, '', True); + InitSetting(asSSHtunnelUser, 'SSHtunnelUser', 0, False, '', True); + InitSetting(asSSHtunnelPassword, 'SSHtunnelPassword', 0, False, '', True); + InitSetting(asSSHtunnelTimeout, 'SSHtunnelTimeout', 4, False, '', True); + InitSetting(asSSHtunnelPrivateKey, 'SSHtunnelPrivateKey', 0, False, '', True); + InitSetting(asSSLActive, 'SSL_Active', 0, False, '', True); + InitSetting(asSSLKey, 'SSL_Key', 0, False, '', True); + InitSetting(asSSLCert, 'SSL_Cert', 0, False, '', True); + InitSetting(asSSLCA, 'SSL_CA', 0, False, '', True); + InitSetting(asNetType, 'NetType', Integer(ntMySQL_TCPIP), False, '', True); + InitSetting(asCompressed, 'Compressed', 0, False, '', True); + InitSetting(asLocalTimeZone, 'LocalTimeZone', 0, False, '', True); + InitSetting(asStartupScriptFilename, 'StartupScriptFilename', 0, False, '', True); + InitSetting(asDatabases, 'Databases', 0, False, '', True); + InitSetting(asDatabaseFilter, 'DatabaseFilter', 0, False, ''); + InitSetting(asExportSQLCreateDatabases, 'ExportSQL_CreateDatabases', 0, False); + InitSetting(asExportSQLDropDatabases, 'ExportSQL_DropDatabases', 0, False); + InitSetting(asExportSQLCreateTables, 'ExportSQL_CreateTables', 0, False); + InitSetting(asExportSQLDropTables, 'ExportSQL_DropTables', 0, False); + InitSetting(asExportSQLDataHow, 'ExportSQL_DataHow', 0); + InitSetting(asExportSQLFilenames, 'ExportSQL_Filenames', 0, False, ''); + InitSetting(asExportSQLDirectories, 'ExportSQL_Directories', 0, False, ''); + InitSetting(asExportSQLDatabase, 'ExportSQL_Database', 0, False, ''); + InitSetting(asExportSQLServerDatabase, 'ExportSQL_ServerDatabase', 0, False, ''); + InitSetting(asExportSQLOutput, 'ExportSQL_Output', 0); + InitSetting(asGridExportOutputCopy, 'GridExportOutputCopy', 0, True); + InitSetting(asGridExportOutputFile, 'GridExportOutputFile', 0, False); + InitSetting(asGridExportFilename, 'GridExportFilename', 0, False, ''); + InitSetting(asGridExportRecentFiles, 'GridExportRecentFiles', 0, False, ''); + InitSetting(asGridExportEncoding, 'GridExportEncoding', 4); + InitSetting(asGridExportFormat, 'GridExportFormat', 0); + InitSetting(asGridExportSelection, 'GridExportSelection', 1); + InitSetting(asGridExportColumnNames, 'GridExportColumnNames', 0, True); + InitSetting(asGridExportSeparator, 'GridExportSeparator', 0, False, ';'); + InitSetting(asGridExportEncloser, 'GridExportEncloser', 0, False, ''); + InitSetting(asGridExportTerminator, 'GridExportTerminator', 0, False, '\r\n'); + InitSetting(asCSVImportSeparator, 'CSVSeparatorV2', 0, False, ';'); + InitSetting(asCSVImportEncloser, 'CSVEncloserV2', 0, False, '"'); + InitSetting(asCSVImportTerminator, 'CSVTerminator', 0, False, '\r\n'); + InitSetting(asCSVImportFieldEscaper, 'CSVImportFieldEscaperV2', 0, False, '"'); + InitSetting(asCSVImportWindowWidth, 'CSVImportWindowWidth', 530); + InitSetting(asCSVImportWindowHeight, 'CSVImportWindowHeight', 530); + InitSetting(asCSVImportFilename, 'loadfilename', 0, False, ''); + InitSetting(asCSVImportFieldsEnclosedOptionally, 'CSVImportFieldsEnclosedOptionallyV2', 0, True); + InitSetting(asCSVImportIgnoreLines, 'CSVImportIgnoreLines', 1); + InitSetting(asCSVImportLowPriority, 'CSVImportLowPriority', 0, True); + InitSetting(asCSVImportLocalNumbers, 'CSVImportLocalNumbers', 0, False); + InitSetting(asCSVImportTruncateTable, 'CSVImportTruncateTable', 0, False); + InitSetting(asCSVImportDuplicateHandling, 'CSVImportDuplicateHandling', 2); + InitSetting(asCSVImportParseMethod, 'CSVImportParseMethod', 0); + InitSetting(asUpdatecheck, 'Updatecheck', 0, False); + InitSetting(asUpdatecheckBuilds, 'UpdatecheckBuilds', 0, False); + InitSetting(asUpdatecheckInterval, 'UpdatecheckInterval', 3); + InitSetting(asUpdatecheckLastrun, 'UpdatecheckLastrun', 0, False, '2000-01-01'); + InitSetting(asTableToolsWindowWidth, 'TableTools_WindowWidth', 560); + InitSetting(asTableToolsWindowHeight, 'TableTools_WindowHeight', 420); + InitSetting(asTableToolsTreeWidth, 'TableTools_TreeWidth', 150); + InitSetting(asTableToolsFindText, 'TableTools_FindText', 0, False, ''); + InitSetting(asTableToolsDatatype, 'TableTools_Datatype', 0); + InitSetting(asTableToolsFindCaseSensitive, 'TableTools_FindCaseSensitive', 0, False); + InitSetting(asFileImportWindowWidth, 'FileImport_WindowWidth', 530); + InitSetting(asFileImportWindowHeight, 'FileImport_WindowHeight', 530); + InitSetting(asEditVarWindowWidth, 'EditVar_WindowWidth', 300); + InitSetting(asEditVarWindowHeight, 'EditVar_WindowHeight', 260); + InitSetting(asUsermanagerWindowWidth, 'Usermanager_WindowWidth', 500); + InitSetting(asUsermanagerWindowHeight, 'Usermanager_WindowHeight', 400); + InitSetting(asUsermanagerListWidth, 'Usermanager_ListWidth', 180); + InitSetting(asSelectDBOWindowWidth, 'SelectDBO_WindowWidth', 250); + InitSetting(asSelectDBOWindowHeight, 'SelectDBO_WindowHeight', 350); + InitSetting(asSessionManagerListWidth, 'SessionManager_ListWidth', 170); + InitSetting(asSessionManagerWindowWidth, 'SessionManager_WindowWidth', 500); + InitSetting(asSessionManagerWindowHeight, 'SessionManager_WindowHeight', 400); + InitSetting(asCopyTableWindowHeight, 'CopyTable_WindowHeight', 340); + InitSetting(asCopyTableWindowWidth, 'CopyTable_WindowWidth', 380); + InitSetting(asCopyTableColumns, 'CopyTable_Columns', 0, True); + InitSetting(asCopyTableKeys, 'CopyTable_Keys', 0, True); + InitSetting(asCopyTableForeignKeys, 'CopyTable_ForeignKeys', 0, True); + InitSetting(asCopyTableData, 'CopyTable_Data', 0, True); + InitSetting(asCopyTableRecentFilter, 'CopyTable_RecentFilter_%s', 0, False, ''); + InitSetting(asServerVersion, 'ServerVersion', 0, False, '', True); + InitSetting(asServerVersionFull, 'ServerVersionFull', 0, False, '', True); + InitSetting(asLastConnect, 'LastConnect', 0, False, '2000-01-01', True); + InitSetting(asConnectCount, 'ConnectCount', 0, False, '', True); + InitSetting(asRefusedCount, 'RefusedCount', 0, False, '', True); + InitSetting(asSessionCreated, 'SessionCreated', 0, False, '', True); + InitSetting(asDoUsageStatistics, 'DoUsageStatistics', 0, False); + InitSetting(asLastUsageStatisticCall, 'LastUsageStatisticCall', 0, False, '2000-01-01'); + InitSetting(asDisplayBars, 'DisplayBars', 0, true); + InitSetting(asBarColor, 'BarColor', $00BBFFDD); + InitSetting(asMySQLBinaries, 'MySQL_Binaries', 0, False, ''); + InitSetting(asPromptSaveFileOnTabClose, 'PromptSaveFileOnTabClose', 0, True); + InitSetting(asCompletionProposal, 'CompletionProposal', 0, True); + InitSetting(asTabsToSpaces, 'TabsToSpaces', 0, False); + InitSetting(asFilterPanel, 'FilterPanel', 0, False); + InitSetting(asAllowMultipleInstances, 'AllowMultipleInstances', 0, True); + InitSetting(asFindDialogSearchHistory, 'FindDialogSearchHistory', 0, False, ''); + InitSetting(asFindDialogReplaceHistory, 'FindDialogReplaceHistory', 0, False, ''); + InitSetting(asMaxQueryResults, 'MaxQueryResults', 10); + InitSetting(asSetEditorWidth, 'SetEditorWidth', 100); + InitSetting(asSetEditorHeight, 'SetEditorHeight', 130); + InitSetting(asLogErrors, 'LogErrors', 0, True); + InitSetting(asLogUserSQL, 'LogUserSQL', 0, True); + InitSetting(asLogSQL, 'LogSQL', 0, True); + InitSetting(asLogInfos, 'LogInfos', 0, True); + InitSetting(asLogDebug, 'LogDebug', 0, False); + InitSetting(asFieldColorNumeric, 'FieldColor_Numeric', $00FF0000); + InitSetting(asFieldColorReal, 'FieldColor_Real', $00FF0048); + InitSetting(asFieldColorText, 'FieldColor_Text', $00008000); + InitSetting(asFieldColorBinary, 'FieldColor_Binary', $00800080); + InitSetting(asFieldColorDatetime, 'FieldColor_Datetime', $00000080); + InitSetting(asFieldColorSpatial, 'FieldColor_Spatial', $00808000); + InitSetting(asFieldColorOther, 'FieldColor_Other', $00008080); + InitSetting(asFieldEditorBinary, 'FieldEditor_Binary', 0, True); + InitSetting(asFieldEditorDatetime, 'FieldEditor_Datetime', 0, True); + InitSetting(asFieldEditorDatetimePrefill, 'FieldEditor_Datetime_Prefill', 0, True); + InitSetting(asFieldEditorEnum, 'FieldEditor_Enum', 0, True); + InitSetting(asFieldEditorSet, 'FieldEditor_Set', 0, True); + InitSetting(asFieldNullBackground, 'Field_NullBackground', $00FF00FF); + InitSetting(asGroupTreeObjects, 'GroupTreeObjects', 0, False); + InitSetting(asDisplayObjectSizeColumn, 'DisplayObjectSizeColumn', 0, True); + InitSetting(asActionShortcut1, 'Shortcut1_%s', 0); + InitSetting(asActionShortcut2, 'Shortcut2_%s', 0); + InitSetting(asHighlighterForeground, 'SQL Attr %s Foreground', 0); + InitSetting(asHighlighterBackground, 'SQL Attr %s Background', 0); + InitSetting(asHighlighterStyle, 'SQL Attr %s Style', 0); + InitSetting(asSQLfile, 'SQLFile%s', 0, False, ''); + InitSetting(asListColWidths, 'ColWidths_%s', 0, False, ''); + InitSetting(asListColsVisible, 'ColsVisible_%s', 0, False, ''); + InitSetting(asListColPositions, 'ColPositions_%s', 0, False, ''); + InitSetting(asListColSort, 'ColSort_%s', 0, False, ''); + InitSetting(asSessionFolder, 'Folder', 0, False); + InitSetting(asRecentFilter, '', 0, False, ''); + InitSetting(asDateTimeEditorCursorPos, 'DateTimeEditor_CursorPos_Type%s', 0); +end; + + +destructor TAppSettings.Destroy; +var + AllKeys: TStringList; + i: Integer; + Proc: TProcessEntry32; + ProcRuns: Boolean; + SnapShot: THandle; + rx: TRegExpr; +begin + // Export settings into textfile in portable mode. + if FPortableMode then try + ExportSettings(FSettingsFile); + FRegistry.CloseKey; + FRegistry.DeleteKey(FBasePath); + + // Remove dead keys from instances which didn't close clean, e.g. because of an AV + SnapShot := CreateToolhelp32Snapshot(TH32CS_SnapProcess, 0); + Proc.dwSize := Sizeof(Proc); + FRegistry.OpenKeyReadOnly('\Software\'); + AllKeys := TStringList.Create; + FRegistry.GetKeyNames(AllKeys); + rx := TRegExpr.Create; + rx.Expression := '^' + QuoteRegExprMetaChars(APPNAME) + ' Portable (\d+)$'; + for i:=0 to AllKeys.Count-1 do begin + if not rx.Exec(AllKeys[i]) then + Continue; + ProcRuns := False; + if Process32First(SnapShot, Proc) then while True do begin + ProcRuns := rx.Match[1] = IntToStr(Proc.th32ProcessID); + if ProcRuns or (not Process32Next(SnapShot, Proc)) then + break; + end; + if not ProcRuns then + FRegistry.DeleteKey(AllKeys[i]); + end; + FRegistry.CloseKey; + CloseHandle(SnapShot); + AllKeys.Free; + rx.Free; + except + on E:Exception do + ErrorDialog(E.Message); + end; + FRegistry.Free; + inherited; +end; + + +procedure TAppSettings.InitSetting(Index: TAppSettingIndex; Name: String; + DefaultInt: Integer=0; DefaultBool: Boolean=False; DefaultString: String=''; + Session: Boolean=False); +begin + FSettings[Index].Name := Name; + FSettings[Index].Session := Session; + FSettings[Index].DefaultInt := DefaultInt; + FSettings[Index].DefaultBool := DefaultBool; + FSettings[Index].DefaultString := DefaultString; + FSettings[Index].Synced := False; +end; + + +procedure TAppSettings.SetSessionPath(Value: String); +begin + // Following calls may want to read or write some session specific setting + FSessionPath := Value; + PrepareRegistry; +end; + + +procedure TAppSettings.ResetPath; +begin + SessionPath := ''; +end; + + +procedure TAppSettings.PrepareRegistry; +var + Folder: String; +begin + // Open the wanted registry path + Folder := FBasePath; + if FSessionPath <> '' then + Folder := Folder + REGKEY_SESSIONS + '\' + FSessionPath; + if '\'+FRegistry.CurrentPath <> Folder then + FRegistry.OpenKey(Folder, True); +end; + + +function TAppSettings.GetValueNames: TStringList; +begin + PrepareRegistry; + Result := TStringList.Create; + FRegistry.GetValueNames(Result); +end; + + +function TAppSettings.GetValueName(Index: TAppSettingIndex): String; +begin + Result := FSettings[Index].Name; +end; + + +function TAppSettings.GetKeyNames: TStringList; +begin + PrepareRegistry; + Result := TStringList.Create; + FRegistry.GetKeyNames(Result); +end; + + +function TAppSettings.DeleteValue(Index: TAppSettingIndex; FormatName: String=''): Boolean; +var + ValueName: String; +begin + PrepareRegistry; + ValueName := GetValueName(Index); + if FormatName <> '' then + ValueName := Format(ValueName, [FormatName]); + Result := FRegistry.DeleteValue(ValueName); +end; + + +function TAppSettings.DeleteValue(ValueName: String): Boolean; +begin + Result := FRegistry.DeleteValue(ValueName); +end; + + +procedure TAppSettings.DeleteCurrentKey; +var + KeyPath: String; +begin + PrepareRegistry; + if IsEmpty(FSessionPath) then + raise Exception.Create('No path set, won''t delete root key '+FRegistry.CurrentPath) + else begin + KeyPath := REGKEY_SESSIONS + '\' + FSessionPath; + ResetPath; + FRegistry.DeleteKey(KeyPath); + end; +end; + + +procedure TAppSettings.MoveCurrentKey(TargetPath: String); +var + KeyPath: String; +begin + PrepareRegistry; + if IsEmpty(FSessionPath) then + raise Exception.Create('No path set, won''t move root key '+FRegistry.CurrentPath) + else begin + KeyPath := REGKEY_SESSIONS + '\' + FSessionPath; + ResetPath; + FRegistry.MoveKey(KeyPath, TargetPath, True); + end; +end; + + +function TAppSettings.ValueExists(Index: TAppSettingIndex): Boolean; +var + ValueName: String; +begin + PrepareRegistry; + ValueName := GetValueName(Index); + Result := FRegistry.ValueExists(ValueName); +end; + + +function TAppSettings.SessionPathExists(SessionPath: String): Boolean; +begin + Result := FRegistry.KeyExists(FBasePath + REGKEY_SESSIONS + '\' + SessionPath); +end; + + +function TAppSettings.IsEmptyKey: Boolean; +var + TestList: TStringList; +begin + TestList := GetValueNames; + Result := (not FRegistry.HasSubKeys) and (TestList.Count = 0); + TestList.Free; +end; + + +function TAppSettings.GetDefaultInt(Index: TAppSettingIndex): Integer; +begin + // Return default integer value + Result := FSettings[Index].DefaultInt; +end; + + +function TAppSettings.GetDefaultString(Index: TAppSettingIndex): String; +begin + // Return default string value + Result := FSettings[Index].DefaultString; +end; + + +procedure TAppSettings.Read(Index: TAppSettingIndex; FormatName: String; + DataType: TAppSettingDataType; var I: Integer; var B: Boolean; var S: String; + DI: Integer; DB: Boolean; DS: String); +var + ValueName: String; +begin + // Read user setting value from registry + I := FSettings[Index].DefaultInt; + B := FSettings[Index].DefaultBool; + S := FSettings[Index].DefaultString; + if DI<>0 then I := DI; + if DB<>False then B := DB; + if DS<>'' then S := DS; + ValueName := FSettings[Index].Name; + if FormatName <> '' then + ValueName := Format(ValueName, [FormatName]); + if FSettings[Index].Session and IsEmpty(FSessionPath) then + raise Exception.Create('Attempt to read session setting without session path'); + if (not FSettings[Index].Session) and IsNotEmpty(FSessionPath) then + FSessionPath := ''; + PrepareRegistry; + if FSettings[Index].Synced then begin + case DataType of + adInt: I := FSettings[Index].CurrentInt; + adBool: B := FSettings[Index].CurrentBool; + adString: S := FSettings[Index].CurrentString; + else raise Exception.CreateFmt(SUnsupportedSettingsDatatype, [FSettings[Index].Name]); + end; + end else if FRegistry.ValueExists(ValueName) then begin + Inc(FReads); + case DataType of + adInt: I := FRegistry.ReadInteger(ValueName); + adBool: B := FRegistry.ReadBool(ValueName); + adString: S := FRegistry.ReadString(ValueName); + else raise Exception.CreateFmt(SUnsupportedSettingsDatatype, [FSettings[Index].Name]); + end; + end; + if (FormatName = '') and (FSessionPath = '') then begin + FSettings[Index].Synced := True; + FSettings[Index].CurrentInt := I; + FSettings[Index].CurrentBool := B; + FSettings[Index].CurrentString := S; + end; +end; + + +function TAppSettings.ReadInt(Index: TAppSettingIndex; FormatName: String=''; Default: Integer=0): Integer; +var + S: String; + B: Boolean; +begin + Read(Index, FormatName, adInt, Result, B, S, Default, False, ''); +end; + + +function TAppSettings.ReadBool(Index: TAppSettingIndex; FormatName: String=''; Default: Boolean=False): Boolean; +var + I: Integer; + S: String; +begin + Read(Index, FormatName, adBool, I, Result, S, 0, Default, ''); +end; + + +function TAppSettings.ReadString(Index: TAppSettingIndex; FormatName: String=''; Default: String=''): String; +var + I: Integer; + B: Boolean; +begin + Read(Index, FormatName, adString, I, B, Result, 0, False, Default); +end; + + +function TAppSettings.ReadString(ValueName: String): String; +begin + PrepareRegistry; + Result := FRegistry.ReadString(ValueName); +end; + + +procedure TAppSettings.Write(Index: TAppSettingIndex; FormatName: String; + DataType: TAppSettingDataType; I: Integer; B: Boolean; S: String); +var + ValueName: String; + SameAsDefault, SameAsCurrent: Boolean; +begin + // Write user setting value to registry + ValueName := FSettings[Index].Name; + if FormatName <> '' then + ValueName := Format(ValueName, [FormatName]); + if FSettings[Index].Session and IsEmpty(FSessionPath) then + raise Exception.Create('Attempt to write session setting without session path'); + if (not FSettings[Index].Session) and IsNotEmpty(FSessionPath) then + FSessionPath := ''; + PrepareRegistry; + case DataType of + adInt: begin + SameAsDefault := I = FSettings[Index].DefaultInt; + SameAsCurrent := FSettings[Index].Synced and (I = FSettings[Index].CurrentInt); + if (not SameAsDefault) and (not SameAsCurrent) then begin + FRegistry.WriteInteger(ValueName, I); + Inc(FWrites); + FSettings[Index].CurrentInt := I; + end; + end; + adBool: begin + SameAsDefault := B = FSettings[Index].DefaultBool; + SameAsCurrent := FSettings[Index].Synced and (B = FSettings[Index].CurrentBool); + if (not SameAsDefault) and (not SameAsCurrent) then begin + FRegistry.WriteBool(ValueName, B); + Inc(FWrites); + FSettings[Index].CurrentBool := B; + end; + end; + adString: begin + SameAsDefault := S = FSettings[Index].DefaultString; + SameAsCurrent := FSettings[Index].Synced and (S = FSettings[Index].CurrentString); + if (not SameAsDefault) and (not SameAsCurrent) then begin + FRegistry.WriteString(ValueName, S); + Inc(FWrites); + FSettings[Index].CurrentString := S; + end; + end; + else + raise Exception.CreateFmt(SUnsupportedSettingsDatatype, [FSettings[Index].Name]); + end; + if SameAsDefault and FRegistry.ValueExists(ValueName) then + FRegistry.DeleteValue(ValueName); + if (FormatName = '') and (FSessionPath = '') then + FSettings[Index].Synced := True; +end; + + +procedure TAppSettings.WriteInt(Index: TAppSettingIndex; Value: Integer; FormatName: String=''); +begin + Write(Index, FormatName, adInt, Value, False, ''); +end; + + +procedure TAppSettings.WriteBool(Index: TAppSettingIndex; Value: Boolean; FormatName: String=''); +begin + Write(Index, FormatName, adBool, 0, Value, ''); +end; + + +procedure TAppSettings.WriteString(Index: TAppSettingIndex; Value: String; FormatName: String=''); +begin + Write(Index, FormatName, adString, 0, False, Value); +end; + + +procedure TAppSettings.WriteString(ValueName, Value: String); +begin + PrepareRegistry; + FRegistry.WriteString(ValueName, Value); +end; + + +function TAppSettings.GetSessionNames(ParentPath: String; var Folders: TStringList): TStringList; +var + i: Integer; + CurPath: String; +begin + ResetPath; + CurPath := FBasePath + REGKEY_SESSIONS + '\' + ParentPath; + FRegistry.OpenKey(CurPath, False); + Result := TStringList.Create; + FRegistry.GetKeyNames(Result); + for i:=Result.Count-1 downto 0 do begin + FRegistry.OpenKey(CurPath+'\'+Result[i], False); + if ValueExists(asSessionFolder) then begin + Folders.Add(Result[i]); + Result.Delete(i); + end; + end; +end; + + +procedure TAppSettings.GetSessionPaths(ParentPath: String; var Sessions: TStringList); +var + Folders, Names: TStringList; + i: Integer; +begin + Folders := TStringList.Create; + Names := GetSessionNames(ParentPath, Folders); + for i:=0 to Names.Count-1 do + Sessions.Add(ParentPath+Names[i]); + for i:=0 to Folders.Count-1 do + GetSessionPaths(ParentPath+Folders[i]+'\', Sessions); + Names.Free; + Folders.Free; +end; + + +procedure TAppSettings.ImportSettings(Filename: String); +var + Content, Name, Value, KeyPath: String; + Lines, Segments: TStringList; + i: Integer; + DataType: TRegDataType; +begin + // Load registry settings from file + Content := ReadTextfile(FileName, nil); + Lines := Explode(CRLF, Content); + for i:=0 to Lines.Count-1 do begin + // Each line has 3 segments: reg path | data type | value. Continue if explode finds less or more than 3. + Segments := Explode(DELIMITER, Lines[i]); + if Segments.Count <> 3 then + continue; + KeyPath := FBasePath + ExtractFilePath(Segments[0]); + Name := ExtractFileName(Segments[0]); + DataType := TRegDataType(StrToInt(Segments[1])); + FRegistry.OpenKey(KeyPath, True); + if FRegistry.ValueExists(Name) then + Continue; // Don't touch value if already there + Value := ''; + if Segments.Count >= 3 then + Value := Segments[2]; + case DataType of + rdString: begin + Value := StringReplace(Value, CHR13REPLACEMENT, #13, [rfReplaceAll]); + Value := StringReplace(Value, CHR10REPLACEMENT, #10, [rfReplaceAll]); + FRegistry.WriteString(Name, Value); + end; + rdInteger: + FRegistry.WriteInteger(Name, MakeInt(Value)); + rdBinary, rdUnknown, rdExpandString: + ErrorDialog(Name+' has an unsupported data type.'); + end; + Segments.Free; + end; + Lines.Free; +end; + + +procedure TAppSettings.ExportSettings(Filename: String); +var + Content, Value: String; + DataType: TRegDataType; + + procedure ReadKeyToContent(Path: String); + var + Names: TStringList; + i: Integer; + SubPath: String; + begin + // Recursively read values in keys and their subkeys into "content" variable + FRegistry.OpenKey(Path, True); + SubPath := Copy(Path, Length(FBasePath)+1, MaxInt); + Names := TStringList.Create; + FRegistry.GetValueNames(Names); + for i:=0 to Names.Count-1 do begin + DataType := FRegistry.GetDataType(Names[i]); + Content := Content + + SubPath + Names[i] + DELIMITER + + IntToStr(Integer(DataType)) + DELIMITER; + case DataType of + rdString: begin + Value := FRegistry.ReadString(Names[i]); + Value := StringReplace(Value, #13, CHR13REPLACEMENT, [rfReplaceAll]); + Value := StringReplace(Value, #10, CHR10REPLACEMENT, [rfReplaceAll]); + end; + rdInteger: + Value := IntToStr(FRegistry.ReadInteger(Names[i])); + rdBinary, rdUnknown, rdExpandString: + ErrorDialog(Names[i]+' has an unsupported data type.'); + end; + Content := Content + Value + CRLF; + end; + Names.Clear; + FRegistry.GetKeyNames(Names); + for i:=0 to Names.Count-1 do + ReadKeyToContent(Path + Names[i] + '\'); + Names.Free; + end; + +begin + // Save registry settings to file + Content := ''; + ReadKeyToContent(FBasePath); + SaveUnicodeFile(FileName, Content); +end; + + + end. diff --git a/source/insertfiles.pas b/source/insertfiles.pas index 5807f230..5de3e3b5 100644 --- a/source/insertfiles.pas +++ b/source/insertfiles.pas @@ -139,9 +139,8 @@ end; procedure TfrmInsertFiles.FormDestroy(Sender: TObject); begin - OpenRegistry; - MainReg.WriteInteger(REGNAME_FILEIMPORTWINWIDTH, Width); - MainReg.WriteInteger(REGNAME_FILEIMPORTWINHEIGHT, Height); + AppSettings.WriteInt(asFileImportWindowWidth, Width); + AppSettings.WriteInt(asFileImportWindowHeight, Height); MainForm.SaveListSetup(ListColumns); MainForm.SaveListSetup(listFiles); end; @@ -149,8 +148,8 @@ end; procedure TfrmInsertFiles.FormShow(Sender: TObject); begin - Width := GetRegValue(REGNAME_FILEIMPORTWINWIDTH, Width); - Height := GetRegValue(REGNAME_FILEIMPORTWINHEIGHT, Height); + Width := AppSettings.ReadInt(asFileImportWindowWidth); + Height := AppSettings.ReadInt(asFileImportWindowHeight); FConnection := Mainform.ActiveConnection; Caption := FConnection.Parameters.SessionName + ' - ' + MainForm.actInsertFiles.Caption; comboDBs.Items.Clear; diff --git a/source/loaddata.pas b/source/loaddata.pas index e6069cb2..eb3400f8 100644 --- a/source/loaddata.pas +++ b/source/loaddata.pas @@ -95,41 +95,40 @@ begin InheritFont(Font); SetWindowSizeGrip(Handle, True); // Restore settings - Width := GetRegValue(REGNAME_CSV_WINDOWWIDTH, Width); - Height := GetRegValue(REGNAME_CSV_WINDOWHEIGHT, Height); - editFilename.Text := GetRegValue(REGNAME_CSV_FILENAME, ''); - editFieldTerminator.Text := GetRegValue(REGNAME_CSV_SEPARATOR, DEFAULT_CSV_SEPARATOR); - editFieldEncloser.Text := GetRegValue(REGNAME_CSV_ENCLOSER, DEFAULT_CSV_ENCLOSER); - editLineTerminator.Text := GetRegValue(REGNAME_CSV_TERMINATOR, DEFAULT_CSV_TERMINATOR); - chkFieldsEnclosedOptionally.Checked := GetRegValue(REGNAME_CSV_ENCLOPTION, chkFieldsEnclosedOptionally.Checked); - editFieldEscaper.Text := GetRegValue(REGNAME_CSV_ESCAPER, editFieldEscaper.Text); - updownIgnoreLines.Position := GetRegValue(REGNAME_CSV_IGNORELINES, updownIgnoreLines.Position); - chkLowPriority.Checked := GetRegValue(REGNAME_CSV_LOWPRIO, chkLowPriority.Checked); - chkLocalNumbers.Checked := GetRegValue(REGNAME_CSV_LOCALNUMBERS, chkLocalNumbers.Checked); - chkTruncateTable.Checked := GetRegValue(REGNAME_CSV_TRUNCATETABLE, chkTruncateTable.Checked); - grpDuplicates.ItemIndex := GetRegValue(REGNAME_CSV_DUPLICATES, grpDuplicates.ItemIndex); - grpParseMethod.ItemIndex := GetRegValue(REGNAME_CSV_PARSEMETHOD, grpParseMethod.ItemIndex); + Width := AppSettings.ReadInt(asCSVImportWindowWidth); + Height := AppSettings.ReadInt(asCSVImportWindowHeight); + editFilename.Text := AppSettings.ReadString(asCSVImportFilename); + editFieldTerminator.Text := AppSettings.ReadString(asCSVImportSeparator); + editFieldEncloser.Text := AppSettings.ReadString(asCSVImportEncloser); + editLineTerminator.Text := AppSettings.ReadString(asCSVImportTerminator); + chkFieldsEnclosedOptionally.Checked := AppSettings.ReadBool(asCSVImportFieldsEnclosedOptionally); + editFieldEscaper.Text := AppSettings.ReadString(asCSVImportFieldEscaper); + updownIgnoreLines.Position := AppSettings.ReadInt(asCSVImportIgnoreLines); + chkLowPriority.Checked := AppSettings.ReadBool(asCSVImportLowPriority); + chkLocalNumbers.Checked := AppSettings.ReadBool(asCSVImportLocalNumbers); + chkTruncateTable.Checked := AppSettings.ReadBool(asCSVImportTruncateTable); + grpDuplicates.ItemIndex := AppSettings.ReadInt(asCSVImportDuplicateHandling); + grpParseMethod.ItemIndex := AppSettings.ReadInt(asCSVImportParseMethod); end; procedure Tloaddataform.FormDestroy(Sender: TObject); begin // Save settings - OpenRegistry; - MainReg.WriteInteger(REGNAME_CSV_WINDOWWIDTH, Width); - MainReg.WriteInteger(REGNAME_CSV_WINDOWHEIGHT, Height); - MainReg.WriteString(REGNAME_CSV_FILENAME, editFilename.Text); - MainReg.WriteString(REGNAME_CSV_SEPARATOR, editFieldTerminator.Text); - MainReg.WriteString(REGNAME_CSV_ENCLOSER, editFieldEncloser.Text); - MainReg.WriteString(REGNAME_CSV_TERMINATOR, editLineTerminator.Text); - MainReg.WriteBool(REGNAME_CSV_ENCLOPTION, chkFieldsEnclosedOptionally.Checked); - MainReg.WriteString(REGNAME_CSV_ESCAPER, editFieldEscaper.Text); - MainReg.WriteInteger(REGNAME_CSV_IGNORELINES, updownIgnoreLines.Position); - MainReg.WriteBool(REGNAME_CSV_LOWPRIO, chkLowPriority.Checked); - MainReg.WriteBool(REGNAME_CSV_LOCALNUMBERS, chkLocalNumbers.Checked); - MainReg.WriteBool(REGNAME_CSV_TRUNCATETABLE, chkTruncateTable.Checked); - MainReg.WriteInteger(REGNAME_CSV_DUPLICATES, grpDuplicates.ItemIndex); - MainReg.WriteInteger(REGNAME_CSV_PARSEMETHOD, grpParseMethod.ItemIndex); + AppSettings.WriteInt(asCSVImportWindowWidth, Width); + AppSettings.WriteInt(asCSVImportWindowHeight, Height); + AppSettings.WriteString(asCSVImportFilename, editFilename.Text); + AppSettings.WriteString(asCSVImportSeparator, editFieldTerminator.Text); + AppSettings.WriteString(asCSVImportEncloser, editFieldEncloser.Text); + AppSettings.WriteString(asCSVImportTerminator, editLineTerminator.Text); + AppSettings.WriteBool(asCSVImportFieldsEnclosedOptionally, chkFieldsEnclosedOptionally.Checked); + AppSettings.WriteString(asCSVImportFieldEscaper, editFieldEscaper.Text); + AppSettings.WriteInt(asCSVImportIgnoreLines, updownIgnoreLines.Position); + AppSettings.WriteBool(asCSVImportLowPriority, chkLowPriority.Checked); + AppSettings.WriteBool(asCSVImportLocalNumbers, chkLocalNumbers.Checked); + AppSettings.WriteBool(asCSVImportTruncateTable, chkTruncateTable.Checked); + AppSettings.WriteInt(asCSVImportDuplicateHandling, grpDuplicates.ItemIndex); + AppSettings.WriteInt(asCSVImportParseMethod, grpParseMethod.ItemIndex); end; diff --git a/source/main.pas b/source/main.pas index f45519e9..4c98e69f 100644 --- a/source/main.pas +++ b/source/main.pas @@ -82,8 +82,8 @@ type private FMaxDuration: Cardinal; public + constructor Create(SessionPath: String); property MaxDuration: Cardinal read FMaxDuration; - function ReadItem(RegValue: String): TQueryHistoryItem; end; TQueryHistoryItemComparer = class(TComparer) function Compare(const Left, Right: TQueryHistoryItem): Integer; override; @@ -923,11 +923,6 @@ type FCommandStatsQueryCount: Int64; FCommandStatsServerUptime: Integer; - // Common directories - FDirnameCommonAppData: String; - FDirnameUserAppData: String; - FDirnameSnippets: String; - procedure ParseCommandLineParameters(Parameters: TStringlist); procedure SetDelimiter(Value: String); procedure DisplayRowCountStats(Sender: TBaseVirtualTree); @@ -957,33 +952,6 @@ type FileEncodings: TStringList; ImportSettingsDone: Boolean; - // Variables set by preferences dialog - prefRememberFilters: Boolean; - prefLogsqlnum: Integer; - prefLogSqlWidth: Integer; - prefDirnameSessionLogs: String; - prefMaxColWidth: Integer; - prefGridRowcountStep: Integer; - prefGridRowcountMax: Integer; - prefGridRowsLineCount: Word; - prefLogToFile: Boolean; - prefLogErrors: Boolean; - prefLogUserSQL: Boolean; - prefLogSQL: Boolean; - prefLogInfos: Boolean; - prefLogDebug: Boolean; - prefEnableBinaryEditor: Boolean; - prefEnableDatetimeEditor: Boolean; - prefPrefillDateTime: Boolean; - prefEnableEnumEditor: Boolean; - prefEnableSetEditor: Boolean; - prefNullColorDefault: TColor; - prefNullBG: TColor; - prefDisplayBars: Boolean; - prefBarColor: TColor; - prefCompletionProposal: Boolean; - prefMaxQueryResults: Integer; - // Data grid related stuff DataGridHiddenColumns: TStringList; DataGridSortColumns: TOrderColArray; @@ -1249,16 +1217,15 @@ begin FreeAndNil(FSearchReplaceDialog); // Save opened session names in root folder - OpenRegistry; OpenSessions := ''; for Connection in Connections do OpenSessions := OpenSessions + Connection.Parameters.SessionPath + DELIM; Delete(OpenSessions, Length(OpenSessions)-Length(DELIM)+1, Length(DELIM)); - MainReg.WriteString(REGNAME_LASTSESSIONS, OpenSessions); + AppSettings.WriteString(asLastSessions, OpenSessions); if Assigned(ActiveConnection) then - MainReg.WriteString(REGNAME_LASTACTIVESESSION, ActiveConnection.Parameters.SessionPath); + AppSettings.WriteString(asLastActiveSession, ActiveConnection.Parameters.SessionPath); - // Some grid editors access the registry - be sure these are gone before freeing MainReg + // Some grid editors access the registry - be sure these are gone before freeing AppSettings QueryTabs.Clear; DataGrid.EndEditNode; @@ -1269,36 +1236,35 @@ begin Connections.Clear; // Save various settings - OpenRegistry; - MainReg.WriteInteger(REGNAME_TOOLBAR2LEFT, ToolBarStandard.Left); - MainReg.WriteInteger(REGNAME_TOOLBAR2TOP, ToolBarStandard.Top); - MainReg.WriteInteger(REGNAME_TOOLBARDATALEFT, ToolBarData.Left); - MainReg.WriteInteger(REGNAME_TOOLBARDATATOP, ToolBarData.Top); - MainReg.WriteInteger(REGNAME_TOOLBARQUERYLEFT, ToolBarQuery.Left); - MainReg.WriteInteger(REGNAME_TOOLBARQUERYTOP, ToolBarQuery.Top); - MainReg.WriteBool(REGNAME_STOPONERRORSINBATCH, actQueryStopOnErrors.Checked); - MainReg.WriteBool(REGNAME_BLOBASTEXT, actBlobAsText.Checked); - MainReg.WriteString(REGNAME_DELIMITER, FDelimiter); - MainReg.WriteInteger(REGNAME_QUERYMEMOHEIGHT, pnlQueryMemo.Height); - MainReg.WriteInteger(REGNAME_QUERYHELPERSWIDTH, treeQueryHelpers.Width); - MainReg.WriteInteger(REGNAME_DBTREEWIDTH, pnlLeft.width); - MainReg.WriteBool(REGNAME_GROUPOBJECTS, actGroupObjects.Checked); - MainReg.WriteString(REGNAME_DATABASE_FILTER, comboDBFilter.Items.Text); - MainReg.WriteInteger(REGNAME_PREVIEW_HEIGHT, pnlPreview.Height); - MainReg.WriteBool(REGNAME_PREVIEW_ENABLED, actDataPreview.Checked); - MainReg.WriteInteger(REGNAME_SQLOUTHEIGHT, SynMemoSQLLog.Height); - MainReg.WriteBool(REGNAME_FILTERACTIVE, pnlFilterVT.Tag=Integer(True)); - MainReg.WriteBool(REGNAME_WRAPLINES, actQueryWordWrap.Checked); - MainReg.WriteBool(REGNAME_SINGLEQUERIES, actSingleQueries.Checked); - MainReg.WriteBool(REGNAME_LOG_HORIZONTALSCROLLBAR, actLogHorizontalScrollbar.Checked); - MainReg.WriteBool(REGNAME_WINMAXIMIZED, WindowState=wsMaximized); - MainReg.WriteInteger(REGNAME_WINONMONITOR, Monitor.MonitorNum); + AppSettings.WriteInt(asToolbar2Left, ToolBarStandard.Left); + AppSettings.WriteInt(asToolBar2Top, ToolBarStandard.Top); + AppSettings.WriteInt(asToolBarDataLeft, ToolBarData.Left); + AppSettings.WriteInt(asToolBarDataTop, ToolBarData.Top); + AppSettings.WriteInt(asToolBarQueryLeft, ToolBarQuery.Left); + AppSettings.WriteInt(asToolBarQueryTop, ToolBarQuery.Top); + AppSettings.WriteBool(asStopOnErrorsInBatchMode, actQueryStopOnErrors.Checked); + AppSettings.WriteBool(asDisplayBLOBsAsText, actBlobAsText.Checked); + AppSettings.WriteString(asDelimiter, FDelimiter); + AppSettings.WriteInt(asQuerymemoheight, pnlQueryMemo.Height); + AppSettings.WriteInt(asQueryhelperswidth, treeQueryHelpers.Width); + AppSettings.WriteInt(asDbtreewidth, pnlLeft.width); + AppSettings.WriteBool(asGroupTreeObjects, actGroupObjects.Checked); + AppSettings.WriteString(asDatabaseFilter, comboDBFilter.Items.Text); + AppSettings.WriteInt(asDataPreviewHeight, pnlPreview.Height); + AppSettings.WriteBool(asDataPreviewEnabled, actDataPreview.Checked); + AppSettings.WriteInt(asLogHeight, SynMemoSQLLog.Height); + AppSettings.WriteBool(asFilterPanel, pnlFilterVT.Tag=Integer(True)); + AppSettings.WriteBool(asWrapLongLines, actQueryWordWrap.Checked); + AppSettings.WriteBool(asSingleQueries, actSingleQueries.Checked); + AppSettings.WriteBool(asLogHorizontalScrollbar, actLogHorizontalScrollbar.Checked); + AppSettings.WriteBool(asMainWinMaximized, WindowState=wsMaximized); + AppSettings.WriteInt(asMainWinOnMonitor, Monitor.MonitorNum); // Window dimensions are only valid when WindowState is normal. if WindowState = wsNormal then begin - MainReg.WriteInteger(REGNAME_WINLEFT, Left); - MainReg.WriteInteger(REGNAME_WINTOP, Top); - MainReg.WriteInteger(REGNAME_WINWIDTH, Width); - MainReg.WriteInteger(REGNAME_WINHEIGHT, Height); + AppSettings.WriteInt(asMainWinLeft, Left); + AppSettings.WriteInt(asMainWinTop, Top); + AppSettings.WriteInt(asMainWinWidth, Width); + AppSettings.WriteInt(asMainWinHeight, Height); end; SaveListSetup(ListDatabases); SaveListSetup(ListVariables); @@ -1307,15 +1273,10 @@ begin SaveListSetup(ListCommandStats); SaveListSetup(ListTables); - if prefLogToFile then + if AppSettings.ReadBool(asLogToFile) then DeactivateFileLogging; - if MainReg <> nil then begin - MainReg.CloseKey; - // Export settings into textfile in portable mode. - HandlePortableSettings(False); - MainReg.Free; - end; + AppSettings.Free; end; @@ -1347,7 +1308,6 @@ var wine_nt_to_unix_file_name: procedure(p1:pointer; p2:pointer); stdcall; begin caption := APPNAME; - setLocales; // Detect version dwInfoSize := GetFileVersionInfoSize(PChar(Application.ExeName), dwWnd); @@ -1386,16 +1346,10 @@ begin Supports(TaskbarList, IID_ITaskbarList4, TaskbarList4); end; - // "All users" folder for HeidiSQL's data (All Users\Application Data) - FDirnameCommonAppData := GetShellFolder(CSIDL_COMMON_APPDATA) + '\' + APPNAME + '\'; - - // User folder for HeidiSQL's data (\Application Data) - FDirnameUserAppData := GetShellFolder(CSIDL_APPDATA) + '\' + APPNAME + '\'; // Ensure directory exists - ForceDirectories(FDirnameUserAppData); + ForceDirectories(DirnameUserAppData); - // Folder which contains snippet-files - FDirnameSnippets := FDirnameCommonAppData + 'Snippets\'; + // Load snippet filenames SetSnippetFilenames; // SQLFiles-History @@ -1444,7 +1398,7 @@ begin end; FunctionCategories.Free; - Delimiter := GetRegValue(REGNAME_DELIMITER, DEFAULT_DELIMITER); + Delimiter := AppSettings.ReadString(asDelimiter); // Delphi work around to force usage of Vista's default font (other OSes will be unaffected) if (Win32MajorVersion >= 6) and (Screen.Fonts.IndexOf(VistaFont) >= 0) then begin @@ -1500,100 +1454,71 @@ begin FixVT(treeQueryHelpers); // Window position - Left := GetRegValue(REGNAME_WINLEFT, Left); - Top := GetRegValue(REGNAME_WINTOP, Top); + Left := AppSettings.ReadInt(asMainWinLeft); + Top := AppSettings.ReadInt(asMainWinTop); // .. dimensions - Width := GetRegValue(REGNAME_WINWIDTH, Width); - Height := GetRegValue(REGNAME_WINHEIGHT, Height); + Width := AppSettings.ReadInt(asMainWinWidth); + Height := AppSettings.ReadInt(asMainWinHeight); // ... state - if GetRegValue(REGNAME_WINMAXIMIZED, WindowState=wsMaximized) then + if AppSettings.ReadBool(asMainWinMaximized) then WindowState := wsMaximized; // ... and monitor placement - MonitorIndex := GetRegValue(REGNAME_WINONMONITOR, Monitor.MonitorNum); + AppSettings.ReadInt(asMainWinOnMonitor); + MonitorIndex := AppSettings.ReadInt(asMainWinOnMonitor); MonitorIndex := Max(0, MonitorIndex); MonitorIndex := Min(Screen.MonitorCount-1, MonitorIndex); MakeFullyVisible(Screen.Monitors[MonitorIndex]); // Position of Toolbars - ToolBarStandard.Left := GetRegValue(REGNAME_TOOLBAR2LEFT, ToolBarStandard.Left); - ToolBarStandard.Top := GetRegValue(REGNAME_TOOLBAR2TOP, ToolBarStandard.Top); - ToolBarData.Left := GetRegValue(REGNAME_TOOLBARDATALEFT, ToolBarData.Left); - ToolBarData.Top := GetRegValue(REGNAME_TOOLBARDATATOP, ToolBarData.Top); - ToolBarQuery.Left := GetRegValue(REGNAME_TOOLBARQUERYLEFT, ToolBarQuery.Left); - ToolBarQuery.Top := GetRegValue(REGNAME_TOOLBARQUERYTOP, ToolBarQuery.Top); - actQueryStopOnErrors.Checked := GetRegValue(REGNAME_STOPONERRORSINBATCH, DEFAULT_STOPONERRORSINBATCH); - actBlobAsText.Checked := GetRegValue(REGNAME_BLOBASTEXT, DEFAULT_BLOBASTEXT); - actQueryWordWrap.Checked := GetRegValue(REGNAME_WRAPLINES, actQueryWordWrap.Checked); - actSingleQueries.Checked := GetRegValue(REGNAME_SINGLEQUERIES, actSingleQueries.Checked); - actBatchInOneGo.Checked := not GetRegValue(REGNAME_SINGLEQUERIES, actSingleQueries.Checked); + ToolBarStandard.Left := AppSettings.ReadInt(asToolbar2Left); + ToolBarStandard.Top := AppSettings.ReadInt(asToolbar2Top); + ToolBarData.Left := AppSettings.ReadInt(asToolbarDataLeft); + ToolBarData.Top := AppSettings.ReadInt(asToolbarDataTop); + ToolBarQuery.Left := AppSettings.ReadInt(asToolBarQueryLeft); + ToolBarQuery.Top := AppSettings.ReadInt(asToolBarQueryTop); + actQueryStopOnErrors.Checked := AppSettings.ReadBool(asStopOnErrorsInBatchMode); + actBlobAsText.Checked := AppSettings.ReadBool(asDisplayBLOBsAsText); + actQueryWordWrap.Checked := AppSettings.ReadBool(asWrapLongLines); + actSingleQueries.Checked := AppSettings.ReadBool(asSingleQueries); + actBatchInOneGo.Checked := not AppSettings.ReadBool(asSingleQueries); - pnlQueryMemo.Height := GetRegValue(REGNAME_QUERYMEMOHEIGHT, pnlQueryMemo.Height); - treeQueryHelpers.Width := GetRegValue(REGNAME_QUERYHELPERSWIDTH, treeQueryHelpers.Width); - pnlLeft.Width := GetRegValue(REGNAME_DBTREEWIDTH, pnlLeft.Width); - pnlPreview.Height := GetRegValue(REGNAME_PREVIEW_HEIGHT, pnlPreview.Height); - if GetRegValue(REGNAME_PREVIEW_ENABLED, actDataPreview.Checked) and (not actDataPreview.Checked) then + pnlQueryMemo.Height := AppSettings.ReadInt(asQuerymemoheight); + treeQueryHelpers.Width := AppSettings.ReadInt(asQueryhelperswidth); + pnlLeft.Width := AppSettings.ReadInt(asDbtreewidth); + pnlPreview.Height := AppSettings.ReadInt(asDataPreviewHeight); + if AppSettings.ReadBool(asDataPreviewEnabled) then actDataPreviewExecute(actDataPreview); - SynMemoSQLLog.Height := Max(GetRegValue(REGNAME_SQLOUTHEIGHT, SynMemoSQLLog.Height), spltTopBottom.MinSize); + SynMemoSQLLog.Height := Max(AppSettings.ReadInt(asLogHeight), spltTopBottom.MinSize); // Force status bar position to below log memo StatusBar.Top := SynMemoSQLLog.Top + SynMemoSQLLog.Height; - prefMaxColWidth := GetRegValue(REGNAME_MAXCOLWIDTH, DEFAULT_MAXCOLWIDTH); - prefGridRowcountMax := GetRegValue(REGNAME_MAXTOTALROWS, DEFAULT_MAXTOTALROWS); - prefGridRowcountStep := GetRegValue(REGNAME_ROWSPERSTEP, DEFAULT_ROWSPERSTEP); - prefGridRowsLineCount := GetRegValue(REGNAME_GRIDROWSLINECOUNT, DEFAULT_GRIDROWSLINECOUNT); - actDataShowNext.Hint := 'Show next '+FormatNumber(prefGridRowcountStep)+' rows ...'; + actDataShowNext.Hint := 'Show next '+FormatNumber(AppSettings.ReadInt(asDatagridRowsPerStep))+' rows ...'; actAboutBox.Caption := 'About '+APPNAME+' '+AppVersion; - // Fix registry entry from older versions which can have 0 here which makes no sense - // since the autosetting was removed - if prefMaxColWidth <= 0 then - prefMaxColWidth := DEFAULT_MAXCOLWIDTH; - prefLogsqlnum := GetRegValue(REGNAME_LOGSQLNUM, DEFAULT_LOGSQLNUM); - prefLogSqlWidth := GetRegValue(REGNAME_LOGSQLWIDTH, DEFAULT_LOGSQLWIDTH); - prefDirnameSessionLogs := GetRegValue(REGNAME_LOGDIR, FDirnameUserAppData + 'Sessionlogs\'); // Activate logging - if GetRegValue(REGNAME_LOGTOFILE, DEFAULT_LOGTOFILE) then + if AppSettings.ReadBool(asLogToFile) then ActivateFileLogging; - prefRememberFilters := GetRegValue(REGNAME_REMEMBERFILTERS, DEFAULT_REMEMBERFILTERS); - if GetRegValue(REGNAME_LOG_HORIZONTALSCROLLBAR, SynMemoSQLLog.ScrollBars = ssBoth) then + if AppSettings.ReadBool(asLogHorizontalScrollbar) then actLogHorizontalScrollbar.Execute; - prefLogErrors := GetRegValue(REGNAME_LOG_ERRORS, DEFAULT_LOG_ERRORS); - prefLogUserSQL := GetRegValue(REGNAME_LOG_USERSQL, DEFAULT_LOG_USERSQL); - prefLogSQL := GetRegValue(REGNAME_LOG_SQL, DEFAULT_LOG_SQL); - prefLogInfos := GetRegValue(REGNAME_LOG_INFOS, DEFAULT_LOG_INFOS); - prefLogDebug := GetRegValue(REGNAME_LOG_DEBUG, DEFAULT_LOG_DEBUG); - prefDisplayBars := GetRegValue(REGNAME_DISPLAYBARS, DEFAULT_DISPLAYBARS); - prefBarColor := GetRegValue(REGNAME_BARCOLOR, DEFAULT_BARCOLOR); - prefCompletionProposal := GetRegValue(REGNAME_COMPLETIONPROPOSAL, DEFAULT_COMPLETIONPROPOSAL); - prefMaxQueryResults := GetRegValue(REGNAME_MAXQUERYRESULTS, DEFAULT_MAXQUERYRESULTS); // Data-Font: - datafontname := GetRegValue(REGNAME_DATAFONTNAME, DEFAULT_DATAFONTNAME); - datafontsize := GetRegValue(REGNAME_DATAFONTSIZE, DEFAULT_DATAFONTSIZE); - DataGrid.Font.Name := datafontname; - QueryGrid.Font.Name := datafontname; - DataGrid.Font.Size := datafontsize; - QueryGrid.Font.Size := datafontsize; - FixVT(DataGrid, prefGridRowsLineCount); - FixVT(QueryGrid, prefGridRowsLineCount); + DataGrid.Font.Name := AppSettings.ReadString(asDataFontName); + QueryGrid.Font.Name := AppSettings.ReadString(asDataFontName); + DataGrid.Font.Size := AppSettings.ReadInt(asDataFontSize); + QueryGrid.Font.Size := AppSettings.ReadInt(asDataFontSize); + FixVT(DataGrid, AppSettings.ReadInt(asGridRowLineCount)); + FixVT(QueryGrid, AppSettings.ReadInt(asGridRowLineCount)); // Load color settings - DatatypeCategories[dtcInteger].Color := GetRegValue(REGNAME_FIELDCOLOR_INTEGER, DEFAULT_FIELDCOLOR_INTEGER); - DatatypeCategories[dtcReal].Color := GetRegValue(REGNAME_FIELDCOLOR_REAL, DEFAULT_FIELDCOLOR_REAL); - DatatypeCategories[dtcText].Color := GetRegValue(REGNAME_FIELDCOLOR_TEXT, DEFAULT_FIELDCOLOR_TEXT); - DatatypeCategories[dtcBinary].Color := GetRegValue(REGNAME_FIELDCOLOR_BINARY, DEFAULT_FIELDCOLOR_BINARY); - DatatypeCategories[dtcTemporal].Color := GetRegValue(REGNAME_FIELDCOLOR_DATETIME, DEFAULT_FIELDCOLOR_DATETIME); - DatatypeCategories[dtcSpatial].Color := GetRegValue(REGNAME_FIELDCOLOR_SPATIAL, DEFAULT_FIELDCOLOR_SPATIAL); - DatatypeCategories[dtcOther].Color := GetRegValue(REGNAME_FIELDCOLOR_OTHER, DEFAULT_FIELDCOLOR_OTHER); - prefNullBG := GetRegValue(REGNAME_BG_NULL, DEFAULT_BG_NULL); + DatatypeCategories[dtcInteger].Color := AppSettings.ReadInt(asFieldColorNumeric); + DatatypeCategories[dtcReal].Color := AppSettings.ReadInt(asFieldColorReal); + DatatypeCategories[dtcText].Color := AppSettings.ReadInt(asFieldColorText); + DatatypeCategories[dtcBinary].Color := AppSettings.ReadInt(asFieldColorBinary); + DatatypeCategories[dtcTemporal].Color := AppSettings.ReadInt(asFieldColorDatetime); + DatatypeCategories[dtcSpatial].Color := AppSettings.ReadInt(asFieldColorSpatial); + DatatypeCategories[dtcOther].Color := AppSettings.ReadInt(asFieldColorOther); CalcNullColors; - // Editor enablings - prefEnableBinaryEditor := GetRegValue(REGNAME_FIELDEDITOR_BINARY, DEFAULT_FIELDEDITOR_BINARY); - prefEnableDatetimeEditor := GetRegValue(REGNAME_FIELDEDITOR_DATETIME, DEFAULT_FIELDEDITOR_DATETIME); - prefPrefillDateTime := GetRegValue(REGNAME_PREFILL_DATETIME, DEFAULT_PREFILL_DATETIME); - prefEnableEnumEditor := GetRegValue(REGNAME_FIELDEDITOR_ENUM, DEFAULT_FIELDEDITOR_ENUM); - prefEnableSetEditor := GetRegValue(REGNAME_FIELDEDITOR_SET, DEFAULT_FIELDEDITOR_SET); // Database tree options - actGroupObjects.Checked := GetRegValue(REGNAME_GROUPOBJECTS, DEFAULT_GROUPOBJECTS); - menuShowSizeColumn.Checked := GetRegValue(REGNAME_SIZECOL_TREE, DEFAULT_SIZECOL_TREE); + actGroupObjects.Checked := AppSettings.ReadBool(asGroupTreeObjects); + menuShowSizeColumn.Checked := AppSettings.ReadBool(asDisplayObjectSizeColumn); if menuShowSizeColumn.Checked then DBtree.Header.Columns[1].Options := DBtree.Header.Columns[1].Options + [coVisible] else @@ -1610,7 +1535,7 @@ begin // Shortcuts for i:=0 to ActionList1.ActionCount-1 do begin Action := TAction(ActionList1.Actions[i]); - Action.ShortCut := GetRegValue(REGPREFIX_SHORTCUT1+Action.Name, Action.ShortCut); + Action.ShortCut := AppSettings.ReadInt(asActionShortcut1, Action.Name, Action.ShortCut); end; // Place progressbar on the statusbar @@ -1631,7 +1556,7 @@ begin // Filter panel ImageListMain.GetBitmap(134, btnCloseFilterPanel.Glyph); - if GetRegValue(REGNAME_FILTERACTIVE, DEFAULT_FILTERACTIVE) then + if AppSettings.ReadBool(asFilterPanel) then actFilterPanelExecute(nil); lblFilterVTInfo.Caption := ''; @@ -1644,7 +1569,7 @@ begin FConnections.OnNotify := ConnectionsNotify; // Load database filter items. Was previously bound to sessions before multi connections were implemented - comboDBFilter.Items.Text := GetRegValue(REGNAME_DATABASE_FILTER, ''); + comboDBFilter.Items.Text := AppSettings.ReadString(asDatabaseFilter); if comboDBFilter.Items.Count > 0 then comboDBFilter.ItemIndex := 0 else @@ -1668,7 +1593,7 @@ var UpdatecheckInterval, i: Integer; DefaultLastrunDate, LastActiveSession: String; frm : TfrmUpdateCheck; - Connected, DecideForStatistic: Boolean; + Connected: Boolean; StatsCall: THttpDownload; SessionPaths: TStringlist; DlgResult: TModalResult; @@ -1678,17 +1603,17 @@ begin DefaultLastrunDate := '2000-01-01'; // Do an updatecheck if checked in settings - if GetRegValue(REGNAME_DO_UPDATECHECK, DEFAULT_DO_UPDATECHECK) then begin + if AppSettings.ReadBool(asUpdatecheck) then begin try - LastUpdatecheck := StrToDateTime( GetRegValue(REGNAME_LAST_UPDATECHECK, DefaultLastrunDate) ); + LastUpdatecheck := StrToDateTime(AppSettings.ReadString(asUpdatecheckLastrun)); except - LastUpdatecheck := StrToDateTime( DefaultLastrunDate ); + LastUpdatecheck := StrToDateTime(DefaultLastrunDate); end; - UpdatecheckInterval := GetRegValue(REGNAME_UPDATECHECK_INTERVAL, DEFAULT_UPDATECHECK_INTERVAL); + UpdatecheckInterval := AppSettings.ReadInt(asUpdatecheckInterval); if DaysBetween(Now, LastUpdatecheck) >= UpdatecheckInterval then begin frm := TfrmUpdateCheck.Create(Self); frm.AutoClose := True; - frm.CheckForBuildsInAutoMode := GetRegValue(REGNAME_DO_UPDATECHECK_BUILDS, DEFAULT_DO_UPDATECHECK_BUILDS); + frm.CheckForBuildsInAutoMode := AppSettings.ReadBool(asUpdatecheckBuilds); frm.ShowModal; FreeAndNil(frm); end; @@ -1696,14 +1621,14 @@ begin // Get all session names SessionPaths := TStringList.Create; - GetSessionPaths('', SessionPaths); + AppSettings.GetSessionPaths('', SessionPaths); // Call user statistics if checked in settings - if GetRegValue(REGNAME_DO_STATISTICS, DEFAULT_DO_STATISTICS) then begin + if AppSettings.ReadBool(asDoUsageStatistics) then begin try - LastStatsCall := StrToDateTime( GetRegValue(REGNAME_LAST_STATSCALL, DefaultLastrunDate) ); + LastStatsCall := StrToDateTime(AppSettings.ReadString(asLastUsageStatisticCall)); except - LastStatsCall := StrToDateTime( DefaultLastrunDate ); + LastStatsCall := StrToDateTime(DefaultLastrunDate); end; if DaysBetween(Now, LastStatsCall) >= 30 then begin // Report used SVN revision @@ -1711,19 +1636,20 @@ begin StatsCall.URL := APPDOMAIN + 'savestats.php?c=' + IntToStr(AppVerRevision); // Enumerate actively used server versions for i:=0 to SessionPaths.Count-1 do begin + AppSettings.SessionPath := SessionPaths[i]; try - LastConnect := StrToDateTime(GetRegValue(REGNAME_LASTCONNECT, DefaultLastrunDate, SessionPaths[i])); + LastConnect := StrToDateTime(AppSettings.ReadString(asLastConnect)); except LastConnect := StrToDateTime(DefaultLastrunDate); end; if LastConnect > LastStatsCall then begin - StatsCall.URL := StatsCall.URL + '&s[]=' + IntToStr(GetRegValue(REGNAME_SERVERVERSION, 0, SessionPaths[i])); + StatsCall.URL := StatsCall.URL + '&s[]=' + IntToStr(AppSettings.ReadInt(asServerVersion)); end; end; + AppSettings.ResetPath; try StatsCall.SendRequest(''); - OpenRegistry; - MainReg.WriteString(REGNAME_LAST_STATSCALL, DateTimeToStr(Now)); + AppSettings.WriteString(asLastUsageStatisticCall, DateTimeToStr(Now)); except // Silently ignore it when the url could not be called over the network. end; @@ -1731,18 +1657,8 @@ begin end; end; - // Ask if we shall activate statistic calls. Would be used by noone otherwise. - OpenRegistry; - if not Mainreg.ValueExists(REGNAME_DO_STATISTICS) then begin - DecideForStatistic := MessageDialog(APPNAME + ' has a new statistics feature: If activated, server and client versions '+ - 'are reported once per month and displayed on heidisql.com.'+CRLF+CRLF+'Activate this feature?', - mtConfirmation, [mbYes, mbNo]) = mrYes; - Mainreg.WriteBool(REGNAME_DO_STATISTICS, DecideForStatistic); - end; - Connected := False; - OpenRegistry; CmdlineParameters := TStringList.Create; for i:=1 to ParamCount do CmdlineParameters.Add(ParamStr(i)); @@ -1750,11 +1666,11 @@ begin if Assigned(FCmdlineConnectionParams) then begin // Minimal parameter for command line mode is hostname Connected := InitConnection(FCmdlineConnectionParams, True, Connection); - end else if GetRegValue(REGNAME_AUTORECONNECT, DEFAULT_AUTORECONNECT) then begin + end else if AppSettings.ReadBool(asAutoReconnect) then begin // Auto connection via preference setting // Do not autoconnect if we're in commandline mode and the connection was not successful - LastSessions := Explode(DELIM, GetRegValue(REGNAME_LASTSESSIONS, '')); - LastActiveSession := GetRegValue(REGNAME_LASTACTIVESESSION, ''); + LastSessions := Explode(DELIM, AppSettings.ReadString(asLastSessions)); + LastActiveSession := AppSettings.ReadString(asLastActiveSession); for i:=LastSessions.Count-1 downto 0 do begin if SessionPaths.IndexOf(LastSessions[i]) = -1 then LastSessions.Delete(i); @@ -1949,15 +1865,16 @@ begin end; // Remove filters if unwanted - if not prefRememberFilters then begin - OpenRegistry(Item.Parameters.SessionPath); - Keys := TStringList.Create; - MainReg.GetKeyNames(Keys); + if not AppSettings.ReadBool(asRememberFilters) then begin + AppSettings.SessionPath := Item.Parameters.SessionPath; + Keys := AppSettings.GetKeyNames; rx := TRegExpr.Create; rx.Expression := '.+'+QuoteRegExprMetaChars(DELIM)+'.+'; for i:=0 to Keys.Count-1 do begin - if rx.Exec(Keys[i]) then - MainReg.DeleteKey(Keys[i]); + if rx.Exec(Keys[i]) then begin + AppSettings.SessionPath := Item.Parameters.SessionPath + '\' + Keys[i]; + AppSettings.DeleteCurrentKey; + end; end; rx.Free; end; @@ -1967,8 +1884,8 @@ begin RefreshHelperNode(HELPERNODE_COLUMNS); // Last chance to access connection related properties before disconnecting - OpenRegistry(Item.Parameters.SessionPath); - MainReg.WriteString(REGNAME_LASTUSEDDB, Item.Database); + AppSettings.SessionPath := Item.Parameters.SessionPath; + AppSettings.WriteString(asLastUsedDB, Item.Database); // Disconnect Item.Active := False; @@ -2172,7 +2089,7 @@ begin // All sessions SessionPaths := TStringList.Create; - GetSessionPaths('', SessionPaths); + AppSettings.GetSessionPaths('', SessionPaths); for i:=0 to SessionPaths.Count-1 do begin item := TMenuItem.Create(menuConnections); item.Caption := SessionPaths[i]; @@ -2199,7 +2116,7 @@ begin // Add all sessions to submenu menuConnectTo.Clear; SessionPaths := TStringList.Create; - GetSessionPaths('', SessionPaths); + AppSettings.GetSessionPaths('', SessionPaths); for i:=0 to SessionPaths.Count-1 do begin Item := TMenuItem.Create(menuConnectTo); Item.Caption := SessionPaths[i]; @@ -2233,7 +2150,7 @@ begin Dialog.Filter := 'Textfiles (*.txt)|*.txt|All files (*.*)|*.*'; Dialog.Options := Dialog.Options + [ofOverwritePrompt]; if Dialog.Execute then try - ExportSettings(Dialog.FileName); + AppSettings.ExportSettings(Dialog.FileName); MessageDialog('Settings successfully exported to '+Dialog.FileName, mtInformation, [mbOK]); except on E:Exception do @@ -2256,7 +2173,7 @@ begin if LowerCase(ExtractFileExt(Dialog.FileName)) = 'reg' then ShellExec('regedit.exe', '', '"'+Dialog.FileName+'"') else begin - ImportSettings(Dialog.FileName); + AppSettings.ImportSettings(Dialog.FileName); MessageDialog('Settings successfully restored from '+Dialog.FileName, mtInformation, [mbOK]); end; ImportSettingsDone := True; @@ -2401,15 +2318,14 @@ end; procedure TMainForm.FinishedQueryExecution(Thread: TQueryThread); var Tab, WarningsTab: TQueryTab; - MetaInfo, ErroneousSQL, RegName, RegItem, MsgTitle, MsgText: String; + MetaInfo, ErroneousSQL, RegName, MsgTitle, MsgText: String; ProfileAllTime: Extended; ProfileNode: PVirtualNode; - AllRegItems: TStringList; History: TQueryHistory; HistoryItem: TQueryHistoryItem; Warnings: TDBQuery; HistoryNum, MaxWarnings, RegItemsSize: Integer; - DoDelete: Boolean; + DoDelete, ValueFound: Boolean; MinDate: TDateTime; procedure GoToErrorPos(Err: String); @@ -2526,32 +2442,30 @@ begin // Assume that a bunch of up to 5 queries is not a batch. if IsEmpty(Thread.ErrorMessage) and (Thread.Batch.Count <= 5) and (Thread.Batch.Size <= SIZE_MB) then begin ShowStatusMsg('Updating query history ...'); - OpenRegistry(Thread.Connection.Parameters.SessionPath); - MainReg.OpenKey(REGKEY_QUERYHISTORY, true); // Load all items so we can clean up - AllRegItems := TStringList.Create; - MainReg.GetValueNames(AllRegItems); - History := TQueryHistory.Create; - for RegItem in AllRegItems do begin - History.ReadItem(RegItem); - end; + History := TQueryHistory.Create(Thread.Connection.Parameters.SessionPath); // Find lowest unused item number HistoryNum := 0; while True do begin Inc(HistoryNum); RegName := IntToStr(HistoryNum); - if AllRegItems.IndexOf(RegName) = -1 then + ValueFound := False; + for HistoryItem in History do begin + if HistoryItem.RegValue = HistoryNum then begin + ValueFound := True; + Break; + end; + end; + if not ValueFound then break; end; - // Sort by date - History.Sort(TQueryHistoryItemComparer.Create); - // Delete identical history items to avoid spam // Delete old items // Delete items which exceed a max datasize barrier + AppSettings.SessionPath := Thread.Connection.Parameters.SessionPath + '\' + REGKEY_QUERYHISTORY; MinDate := IncDay(Now, -30); RegItemsSize := Thread.Batch.Size; for HistoryItem in History do begin @@ -2560,16 +2474,15 @@ begin or (HistoryItem.Time < MinDate) or (RegItemsSize > SIZE_MB); if DoDelete then - MainReg.DeleteValue(IntToStr(HistoryItem.RegValue)); + AppSettings.DeleteValue(IntToStr(HistoryItem.RegValue)); end; History.Free; // Store history item and closing registry key to ensure writing has finished - MainReg.WriteString(RegName, DateTimeToStr(Now) + DELIM + + AppSettings.WriteString(RegName, DateTimeToStr(Now) + DELIM + Thread.Connection.Database + DELIM + IntToStr(Thread.QueryTime+Thread.QueryNetTime) + DELIM + Thread.Batch.SQL); - MainReg.CloseKey; RefreshHelperNode(HELPERNODE_HISTORY); end; @@ -2925,7 +2838,7 @@ begin cmd := 'mysql.exe'; sep := '\'; end; - path := GetRegValue(REGNAME_MYSQLBINARIES, DEFAULT_MYSQLBINARIES); + path := AppSettings.ReadString(asMySQLBinaries); if (Length(path)>0) and (path[Length(path)] <> sep) then path := path + sep; if not FileExists(path+cmd, true) then begin @@ -3084,7 +2997,7 @@ begin RunFileDialog.ShowModal; RunFileDialog.Free; // Add filename to history menu - if Pos(MainForm.FDirnameSnippets, Filenames[i]) = 0 then + if Pos(DirnameSnippets, Filenames[i]) = 0 then MainForm.AddOrRemoveFromQueryLoadHistory(Filenames[i], True, True); end; end; @@ -3150,7 +3063,7 @@ end; } function TMainform.InitConnection(Params: TConnectionParameters; ActivateMe: Boolean; var Connection: TDBConnection): Boolean; var - SessionExists, RestoreLastActiveDatabase: Boolean; + RestoreLastActiveDatabase: Boolean; StartupScript, LastActiveDatabase: String; StartupBatch: TSQLBatch; Query: TSQLSentence; @@ -3170,13 +3083,12 @@ begin end; // attempt to establish connection - SessionExists := MainReg.KeyExists(REGPATH + REGKEY_SESSIONS + '\' + Params.SessionPath); if not Connection.Active then begin // attempt failed - if SessionExists then begin + if AppSettings.SessionPathExists(Params.SessionPath) then begin // Save "refused" counter - OpenRegistry(Params.SessionPath); - MainReg.WriteInteger(REGNAME_REFUSEDCOUNT, GetRegValue(REGNAME_REFUSEDCOUNT, 0, Params.SessionPath)+1); + AppSettings.SessionPath := Params.SessionPath; + AppSettings.WriteInt(asRefusedCount, AppSettings.ReadInt(asRefusedCount)+1); end; Result := False; FreeAndNil(Connection); @@ -3185,19 +3097,20 @@ begin Result := True; FConnections.Add(Connection); - if SessionExists then begin + if AppSettings.SessionPathExists(Params.SessionPath) then begin // Save "connected" counter - OpenRegistry(Params.SessionPath); - MainReg.WriteInteger(REGNAME_CONNECTCOUNT, GetRegValue(REGNAME_CONNECTCOUNT, 0, Params.SessionPath)+1); + AppSettings.SessionPath := Params.SessionPath; + AppSettings.WriteInt(asConnectCount, AppSettings.ReadInt(asConnectCount)+1); // Save server version - Mainreg.WriteInteger(REGNAME_SERVERVERSION, Connection.ServerVersionInt); - Mainreg.WriteString(REGNAME_LASTCONNECT, DateTimeToStr(Now)); + AppSettings.WriteInt(asServerVersion, Connection.ServerVersionInt); + AppSettings.WriteString(asLastConnect, DateTimeToStr(Now)); end; if ActivateMe then begin // Set focus on last uses db. If not wanted or db is gone, go to root node at least - RestoreLastActiveDatabase := GetRegValue(REGNAME_RESTORELASTUSEDDB, DEFAULT_RESTORELASTUSEDDB); - LastActiveDatabase := GetRegValue(REGNAME_LASTUSEDDB, '', Params.SessionPath); + RestoreLastActiveDatabase := AppSettings.ReadBool(asRestoreLastUsedDB); + AppSettings.SessionPath := Params.SessionPath; + LastActiveDatabase := AppSettings.ReadString(asLastUsedDB); if RestoreLastActiveDatabase and (Connection.AllDatabases.IndexOf(LastActiveDatabase) >- 1) then begin SetActiveDatabase(LastActiveDatabase, Connection); DBNode := FindDBNode(DBtree, Connection, LastActiveDatabase); @@ -3706,7 +3619,7 @@ begin if Copy( snippetname, Length(snippetname)-4, 4 ) <> '.sql' then snippetname := snippetname + '.sql'; // cleanup snippetname from special characters - snippetname := FDirnameSnippets + goodfilename(snippetname); + snippetname := DirnameSnippets + goodfilename(snippetname); if FileExists( snippetname ) then begin if MessageDialog('Overwrite existing snippet '+snippetname+'?', mtConfirmation, [mbOK, mbCancel]) <> mrOK then @@ -3727,8 +3640,8 @@ begin end; if LB <> '' then Text := StringReplace(Text, CRLF, LB, [rfReplaceAll]); - if not DirectoryExists(FDirnameSnippets) then - ForceDirectories(FDirnameSnippets); + if not DirectoryExists(DirnameSnippets) then + ForceDirectories(DirnameSnippets); SaveUnicodeFile( snippetname, Text ); FillPopupQueryLoad; SetSnippetFilenames; @@ -3779,7 +3692,7 @@ begin // Recent files j := 0; for i:=0 to 19 do begin - sqlFilename := GetRegValue( 'SQLFile'+IntToStr(i), '' ); + sqlFilename := AppSettings.ReadString(asSQLfile, IntToStr(i)); if sqlFilename = '' then continue; inc(j); @@ -3816,15 +3729,11 @@ end; procedure TMainform.PopupQueryLoadRemoveAllFiles(Sender: TObject); var - Values: TStringList; i: Integer; begin - Values := TStringList.Create; - OpenRegistry; - MainReg.GetValueNames(Values); - for i:=0 to Values.Count-1 do begin - if Pos('SQLFile', Values[i]) = 1 then - MainReg.DeleteValue(Values[i]); + for i:=0 to 20 do begin + if not AppSettings.DeleteValue(asSQLfile, IntToStr(i)) then + break; end; FillPopupQueryLoad; end; @@ -3841,7 +3750,7 @@ begin Filename := (Sender as TMenuItem).Caption; Filename := StripHotkey(Filename); if Pos('\', Filename) = 0 then // assuming we load a snippet - Filename := FDirnameSnippets + Filename + '.sql' + Filename := DirnameSnippets + Filename + '.sql' else begin // assuming we load a file from the recent-list p := Pos(' ', Filename) + 1; filename := Copy(Filename, p, Length(Filename)); @@ -3859,27 +3768,25 @@ end; procedure TMainform.AddOrRemoveFromQueryLoadHistory(Filename: String; AddIt: Boolean; CheckIfFileExists: Boolean); var - i : Integer; - Values, newfilelist : TStringList; - savedfilename : String; + i: Integer; + newfilelist: TStringList; + savedfilename: String; begin // Add or remove filename to/from history, avoiding duplicates newfilelist := TStringList.create; - Values := TStringList.create; - OpenRegistry; - MainReg.GetValueNames( Values ); + AppSettings.ResetPath; // Add new filename if AddIt then newfilelist.Add( filename ); // Add all other filenames - for i:=0 to Values.Count-1 do begin - if Pos( 'SQLFile', Values[i] ) <> 1 then - continue; - savedfilename := GetRegValue( Values[i], '' ); - MainReg.DeleteValue( Values[i] ); + for i:=0 to 20 do begin + savedfilename := AppSettings.ReadString(asSQLfile, IntToStr(i)); + if IsEmpty(savedfilename) then + Break; + AppSettings.DeleteValue(asSQLfile, IntToStr(i)); if CheckIfFileExists and (not FileExists( savedfilename )) then continue; if (savedfilename <> filename) and (newfilelist.IndexOf(savedfilename)=-1) then @@ -3890,7 +3797,7 @@ begin for i := 0 to newfilelist.Count-1 do begin if i >= 20 then break; - MainReg.WriteString( 'SQLFile'+IntToStr(i), newfilelist[i] ); + AppSettings.WriteString(asSQLfile, newfilelist[i], IntToStr(i)); end; end; @@ -3951,8 +3858,8 @@ end; procedure TMainForm.actApplyFilterExecute(Sender: TObject); var - i, nr: Integer; - OldNumbers, Filters: TStringList; + i: Integer; + Filters: TStringList; val: String; begin // If filter box is empty but filter generator box not, most users expect @@ -3963,27 +3870,21 @@ begin if SynMemoFilter.GetTextLen > 0 then begin // Recreate recent filters list Filters := TStringList.Create; - OldNumbers := TStringList.Create; Filters.Add(Trim(SynMemoFilter.Text)); - MainReg.OpenKey(GetRegKeyTable+'\'+REGNAME_FILTERS, True); - MainReg.GetValueNames(OldNumbers); - OldNumbers.CustomSort(StringListCompareAnythingAsc); + AppSettings.SessionPath := GetRegKeyTable+'\'+REGKEY_RECENTFILTERS; // Add old filters - for i := 0 to OldNumbers.Count - 1 do begin - nr := MakeInt(OldNumbers[i]); - if nr = 0 then continue; // Not a valid entry, ignore that - val := MainReg.ReadString(OldNumbers[i]); + for i:=1 to 20 do begin + val := AppSettings.ReadString(asRecentFilter, IntToStr(i)); + if IsEmpty(val) then + Continue; if Filters.IndexOf(val) = -1 then Filters.Add(val); - MainReg.DeleteValue(OldNumbers[i]); + AppSettings.DeleteValue(asRecentFilter, IntToStr(i)); end; - for i := 1 to Filters.Count do begin - MainReg.WriteString(IntToStr(i), Filters[i-1]); - // Avoid too much registry spam with mega old filters - if i = 20 then break; - end; - FreeAndNil(OldNumbers); + for i:=0 to Filters.Count-1 do + AppSettings.WriteString(asRecentFilter, Filters[i], IntToStr(i+1)); FreeAndNil(Filters); + AppSettings.ResetPath; end; // Keep current column widths on "Quick filter" clicks, don't keep them on "Apply filter" clicks if (Sender is TMenuItem) and ((Sender as TMenuItem).GetParentMenu = popupDataGrid) then begin @@ -4059,7 +3960,7 @@ var begin Grid := ActiveGrid; // Be sure to have all rows - if (Grid = DataGrid) and (DatagridWantedRowCount < prefGridRowcountMax) then + if (Grid = DataGrid) and (DatagridWantedRowCount < AppSettings.ReadInt(asDatagridMaximumRows)) then actDataShowAll.Execute; Node := Grid.GetLast; if Assigned(Node) then @@ -4145,11 +4046,12 @@ begin cs.Dialog.Color := ActiveConnection.Parameters.SessionColor; // Add custom colors from all sessions SessionPaths := TStringList.Create; - GetSessionPaths('', SessionPaths); + AppSettings.GetSessionPaths('', SessionPaths); CharPostfix := 'A'; for i:=0 to SessionPaths.Count-1 do begin - Col := GetRegValue(REGNAME_TREEBACKGROUND, clDefault, SessionPaths[i]); - if Col <> clDefault then begin + AppSettings.SessionPath := SessionPaths[i]; + Col := AppSettings.ReadInt(asTreeBackground); + if Col <> clNone then begin ColString := IntToHex(ColorToRgb(Col), 6); if not ValueExists(ColString) then begin cs.Dialog.CustomColors.Add('Color'+CharPostfix+'='+ColString); @@ -4161,8 +4063,8 @@ begin end; if cs.Execute then begin ActiveConnection.Parameters.SessionColor := cs.Dialog.Color; - OpenRegistry(ActiveConnection.Parameters.SessionPath); - MainReg.WriteInteger(REGNAME_TREEBACKGROUND, cs.Dialog.Color); + AppSettings.SessionPath := ActiveConnection.Parameters.SessionPath; + AppSettings.WriteInt(asTreeBackground, cs.Dialog.Color); end; end; @@ -4173,7 +4075,7 @@ end; procedure TMainForm.LogSQL(Msg: String; Category: TDBLogCategory=lcInfo; Connection: TDBConnection=nil); var snip, IsSQL: Boolean; - Len, i: Integer; + Len, i, MaxLineWidth: Integer; Sess: String; begin if csDestroying in ComponentState then @@ -4181,22 +4083,23 @@ begin // Log only wanted events case Category of - lcError: if not prefLogErrors then Exit; - lcUserFiredSQL: if not prefLogUserSQL then Exit; - lcSQL: if not prefLogSQL then Exit; - lcInfo: if not prefLogInfos then Exit; - lcDebug: if not prefLogDebug then Exit; + lcError: if not AppSettings.ReadBool(asLogErrors) then Exit; + lcUserFiredSQL: if not AppSettings.ReadBool(asLogUserSQL) then Exit; + lcSQL: if not AppSettings.ReadBool(asLogSQL) then Exit; + lcInfo: if not AppSettings.ReadBool(asLogInfos) then Exit; + lcDebug: if not AppSettings.ReadBool(asLogDebug) then Exit; end; // Shorten very long messages Len := Length(Msg); - snip := (prefLogSqlWidth > 0) and (Len > prefLogSqlWidth); + MaxLineWidth := AppSettings.ReadInt(asLogsqlwidth); + snip := (MaxLineWidth > 0) and (Len > MaxLineWidth); IsSQL := Category in [lcSQL, lcUserFiredSQL]; if snip then begin Msg := - Copy(Msg, 0, prefLogSqlWidth) + + Copy(Msg, 0, MaxLineWidth) + '/* large SQL query ('+FormatByteNumber(Len)+'), snipped at ' + - FormatNumber(prefLogSqlWidth) + + FormatNumber(MaxLineWidth) + ' characters */'; end else if (not snip) and IsSQL then Msg := Msg + Delimiter; @@ -4207,7 +4110,7 @@ begin // Delete first line(s) in SQL log and adjust LineNumberStart in gutter i := 0; - while SynMemoSQLLog.Lines.Count > prefLogsqlnum do begin + while SynMemoSQLLog.Lines.Count > AppSettings.ReadInt(asLogsqlnum) do begin SynMemoSQLLog.Lines.Delete(0); Inc(i); end; @@ -4220,7 +4123,7 @@ begin SynMemoSQLLog.Repaint; // Log to file? - if prefLogToFile then + if AppSettings.ReadBool(asLogToFile) then try Sess := ''; if Assigned(Connection) then @@ -4241,8 +4144,8 @@ var begin // Show next X rows in datagrid OldRowCount := DatagridWantedRowCount; - Inc(DatagridWantedRowCount, prefGridRowcountStep); - DataGridWantedRowCount := Min(DataGridWantedRowCount, prefGridRowcountMax); + Inc(DatagridWantedRowCount, AppSettings.ReadInt(asDatagridRowsPerStep)); + DataGridWantedRowCount := Min(DataGridWantedRowCount, AppSettings.ReadInt(asDatagridMaximumRows)); InvalidateVT(DataGrid, VTREE_NOTLOADED, True); SelectNode(DataGrid, OldRowCount); end; @@ -4251,7 +4154,7 @@ end; procedure TMainForm.actDataShowAllExecute(Sender: TObject); begin // Remove LIMIT clause - DatagridWantedRowCount := prefGridRowcountMax; + DatagridWantedRowCount := AppSettings.ReadInt(asDatagridMaximumRows); InvalidateVT(DataGrid, VTREE_NOTLOADED, True); end; @@ -4299,7 +4202,7 @@ var vt: TVirtualStringTree; Select: String; RefreshingData, IsKeyColumn: Boolean; - i, Offset, ColLen, ColWidth, VisibleColumns: Integer; + i, Offset, ColLen, ColWidth, VisibleColumns, MaximumRows: Integer; KeyCols, ColWidths, WantedColumnOrgnames: TStringList; WantedColumns: TTableColumnList; c: TTableColumn; @@ -4519,12 +4422,13 @@ begin vt.UpdateScrollBars(True); ValidateControls(Sender); DisplayRowCountStats(vt); - actDataShowNext.Enabled := (vt.RootNodeCount = DatagridWantedRowCount) and (DatagridWantedRowCount < prefGridRowcountMax); + MaximumRows := AppSettings.ReadInt(asDatagridMaximumRows); + actDataShowNext.Enabled := (vt.RootNodeCount = DatagridWantedRowCount) and (DatagridWantedRowCount < MaximumRows); actDataShowAll.Enabled := actDataShowNext.Enabled; EnumerateRecentFilters; ColWidths.Free; - if Integer(vt.RootNodeCount) = prefGridRowcountMax then - LogSQL('Browsing is currently limited to a maximum of '+FormatNumber(prefGridRowcountMax)+' rows. To see more rows, increase this maximum in Tools > Preferences > Data .', lcInfo); + if Integer(vt.RootNodeCount) = MaximumRows then + LogSQL('Browsing is currently limited to a maximum of '+FormatNumber(MaximumRows)+' rows. To see more rows, increase this maximum in Tools > Preferences > Data .', lcInfo); end; vt.Tag := VTREE_LOADED; @@ -4592,7 +4496,7 @@ var Idx: PCardinal; begin // Display multiline grid rows - if prefGridRowsLineCount = DEFAULT_GRIDROWSLINECOUNT then + if AppSettings.ReadInt(asGridRowLineCount) = 1 then Exclude(Node.States, vsMultiLine) else Include(Node.States, vsMultiLine); @@ -5038,7 +4942,7 @@ begin Conn := ActiveConnection; Editor := Proposal.Form.CurrentEditor; Editor.GetHighlighterAttriAtRowColEx(Editor.PrevWordPos, Token, TokenTypeInt, Start, Attri); - CanExecute := prefCompletionProposal and + CanExecute := AppSettings.ReadBool(asCompletionProposal) and (not (TtkTokenKind(TokenTypeInt) in [tkString, tkComment])); if not CanExecute then Exit; @@ -5208,7 +5112,7 @@ begin // Display hint on function and procedure parameters // Activated in preferences? - if not prefCompletionProposal then begin + if not AppSettings.ReadBool(asCompletionProposal) then begin CanExecute := False; Exit; end; @@ -5491,7 +5395,7 @@ begin 1: case Tree.FocusedNode.Parent.Index of HELPERNODE_SNIPPETS: - Text := ReadTextFile(FDirnameSnippets + Tree.Text[Tree.FocusedNode, 0] + '.sql', nil); + Text := ReadTextFile(DirnameSnippets + Tree.Text[Tree.FocusedNode, 0] + '.sql', nil); HELPERNODE_HISTORY: Text := ''; else begin @@ -6198,7 +6102,7 @@ begin if not Assigned(ActiveQueryHelpers.FocusedNode) then Exit; - snippetfile := FDirnameSnippets + ActiveQueryHelpers.Text[ActiveQueryHelpers.FocusedNode, 0] + '.sql'; + snippetfile := DirnameSnippets + ActiveQueryHelpers.Text[ActiveQueryHelpers.FocusedNode, 0] + '.sql'; if MessageDialog('Delete snippet file?', snippetfile, mtConfirmation, [mbOk, mbCancel]) = mrOk then begin Screen.Cursor := crHourGlass; @@ -6220,7 +6124,7 @@ end; } procedure TMainForm.menuInsertSnippetAtCursorClick(Sender: TObject); begin - ActiveQueryTab.LoadContents(FDirnameSnippets + ActiveQueryHelpers.Text[ActiveQueryHelpers.FocusedNode, 0] + '.sql', False, nil); + ActiveQueryTab.LoadContents(DirnameSnippets + ActiveQueryHelpers.Text[ActiveQueryHelpers.FocusedNode, 0] + '.sql', False, nil); end; @@ -6229,7 +6133,7 @@ end; } procedure TMainForm.menuLoadSnippetClick(Sender: TObject); begin - ActiveQueryTab.LoadContents(FDirnameSnippets + ActiveQueryHelpers.Text[ActiveQueryHelpers.FocusedNode, 0] + '.sql', True, nil); + ActiveQueryTab.LoadContents(DirnameSnippets + ActiveQueryHelpers.Text[ActiveQueryHelpers.FocusedNode, 0] + '.sql', True, nil); end; @@ -6241,14 +6145,14 @@ begin // Normally the snippets folder is created at installation. But it sure // can be the case that it has been deleted or that the application was // not installed properly. Ask if we should create the folder now. - if DirectoryExists(FDirnameSnippets) then - ShellExec('', FDirnameSnippets) + if DirectoryExists(DirnameSnippets) then + ShellExec('', DirnameSnippets) else - if MessageDialog('Snippets folder does not exist', 'The folder "'+FDirnameSnippets+'" is normally created when you install '+appname+'.' + CRLF + CRLF + 'Shall it be created now?', + if MessageDialog('Snippets folder does not exist', 'The folder "'+DirnameSnippets+'" is normally created when you install '+appname+'.' + CRLF + CRLF + 'Shall it be created now?', mtWarning, [mbYes, mbNo]) = mrYes then try Screen.Cursor := crHourglass; - ForceDirectories(FDirnameSnippets); + ForceDirectories(DirnameSnippets); finally Screen.Cursor := crDefault; end; @@ -6260,18 +6164,16 @@ var Values: TStringList; begin // Clear query history items in registry - OpenRegistry(ActiveConnection.Parameters.SessionPath); - MainReg.OpenKey(REGKEY_QUERYHISTORY, True); - Values := TStringList.Create; - MainReg.GetValueNames(Values); + AppSettings.SessionPath := ActiveConnection.Parameters.SessionPath + '\' + REGKEY_QUERYHISTORY; + Values := AppSettings.GetValueNames; if MessageDialog('Clear query history?', FormatNumber(Values.Count)+' history items will be deleted.', mtConfirmation, [mbYes, mbNo]) = mrYes then begin Screen.Cursor := crHourglass; - OpenRegistry(ActiveConnection.Parameters.SessionPath); - MainReg.DeleteKey(REGKEY_QUERYHISTORY); + AppSettings.DeleteCurrentKey;; RefreshHelperNode(HELPERNODE_HISTORY); Screen.Cursor := crDefault; end; Values.Free; + AppSettings.ResetPath; end; @@ -6410,11 +6312,11 @@ begin if not Assigned(OwnerForm) then Exit; Regname := OwnerForm.Name + '.' + List.Name; - OpenRegistry; - MainReg.WriteString( REGPREFIX_COLWIDTHS + Regname, ColWidths ); - MainReg.WriteString( REGPREFIX_COLSVISIBLE + Regname, ColsVisible ); - MainReg.WriteString( REGPREFIX_COLPOS + Regname, ColPos ); - MainReg.WriteString( REGPREFIX_COLSORT + Regname, IntToStr(List.Header.SortColumn) + ',' + IntToStr(Integer(List.Header.SortDirection))); + AppSettings.ResetPath; + AppSettings.WriteString(asListColWidths, ColWidths, Regname); + AppSettings.WriteString(asListColsVisible, ColsVisible, Regname); + AppSettings.WriteString(asListColPositions, ColPos, Regname); + AppSettings.WriteString(asListColSort, IntToStr(List.Header.SortColumn) + ',' + IntToStr(Integer(List.Header.SortDirection)), RegName); end; @@ -6435,7 +6337,7 @@ begin // Column widths OwnerForm := GetParentFormOrFrame(List); Regname := OwnerForm.Name + '.' + List.Name; - Value := GetRegValue(REGPREFIX_COLWIDTHS + Regname, ''); + Value := AppSettings.ReadString(asListColWidths, Regname); if Value <> '' then begin ValueList := Explode( ',', Value ); for i := 0 to ValueList.Count - 1 do @@ -6448,7 +6350,7 @@ begin end; // Column visibility - Value := GetRegValue(REGPREFIX_COLSVISIBLE + Regname, ''); + Value := AppSettings.ReadString(asListColsVisible, Regname); if Value <> '' then begin ValueList := Explode( ',', Value ); for i:=0 to List.Header.Columns.Count-1 do begin @@ -6460,7 +6362,7 @@ begin end; // Column position - Value := GetRegValue(REGPREFIX_COLPOS + Regname, ''); + Value := AppSettings.ReadString(asListColPositions, Regname); if Value <> '' then begin ValueList := Explode( ',', Value ); for i := 0 to ValueList.Count - 1 do @@ -6473,7 +6375,7 @@ begin end; // Sort column and direction - Value := GetRegValue(REGPREFIX_COLSORT + Regname, ''); + Value := AppSettings.ReadString(asListColSort, Regname); if Value <> '' then begin ValueList := Explode(',', Value); if ValueList.Count = 2 then begin @@ -6495,21 +6397,25 @@ end; } procedure TMainForm.ActivateFileLogging; var - LogfilePattern : String; + LogfilePattern, LogDir: String; i : Integer; begin + if AppSettings.ReadBool(asLogToFile) then + Exit; + // Ensure directory exists - if prefDirnameSessionLogs[Length(prefDirnameSessionLogs)] <> '\' then - prefDirnameSessionLogs := prefDirnameSessionLogs + '\'; - ForceDirectories(prefDirnameSessionLogs); + LogDir := AppSettings.ReadString(asSessionLogsDirectory); + if LogDir[Length(LogDir)] <> '\' then + LogDir := LogDir + '\'; + ForceDirectories(LogDir); // Determine free filename LogfilePattern := '%.6u.log'; i := 1; - FFileNameSessionLog := prefDirnameSessionLogs + goodfilename(Format(LogfilePattern, [i])); + FFileNameSessionLog := LogDir + goodfilename(Format(LogfilePattern, [i])); while FileExists(FFileNameSessionLog) do begin inc(i); - FFileNameSessionLog := prefDirnameSessionLogs + goodfilename(Format(LogfilePattern, [i])); + FFileNameSessionLog := LogDir + goodfilename(Format(LogfilePattern, [i])); end; // Create file handle for writing @@ -6523,12 +6429,12 @@ begin if IOResult <> 0 then begin ErrorDialog('Error opening session log file', FFileNameSessionLog+CRLF+CRLF+'Logging is disabled now.'); - prefLogToFile := False; + AppSettings.WriteBool(asLogToFile, False); end else - prefLogToFile := True; + AppSettings.WriteBool(asLogToFile, True); // Update popupMenu items - menuLogToFile.Checked := prefLogToFile; - menuOpenLogFolder.Enabled := prefLogToFile; + menuLogToFile.Checked := AppSettings.ReadBool(asLogToFile); + menuOpenLogFolder.Enabled := AppSettings.ReadBool(asLogToFile); end; @@ -6538,15 +6444,17 @@ end; } procedure TMainForm.DeactivateFileLogging; begin - prefLogToFile := False; + if not AppSettings.ReadBool(asLogToFile) then + Exit; + AppSettings.WriteBool(asLogToFile, False); {$I-} // Supress errors CloseFile(FFileHandleSessionLog); {$I+} // Reset IOResult so later checks in ActivateFileLogging doesn't get an old value IOResult; // Update popupMenu items - menuLogToFile.Checked := prefLogToFile; - menuOpenLogFolder.Enabled := prefLogToFile; + menuLogToFile.Checked := AppSettings.ReadBool(asLogToFile); + menuOpenLogFolder.Enabled := AppSettings.ReadBool(asLogToFile); end; @@ -6594,20 +6502,17 @@ end; } procedure TMainForm.menuLogToFileClick(Sender: TObject); var - OldprefLogToFile: Boolean; + WasActivated: Boolean; begin - OldprefLogToFile := prefLogToFile; - if not prefLogToFile then + WasActivated := AppSettings.ReadBool(asLogToFile); + if not WasActivated then ActivateFileLogging else DeactivateFileLogging; // Save option - if prefLogToFile <> OldprefLogToFile then - begin - OpenRegistry; - MainReg.WriteBool('LogToFile', prefLogToFile); - end; + AppSettings.ResetPath; + AppSettings.WriteBool(asLogToFile, not WasActivated); end; @@ -6616,7 +6521,7 @@ end; } procedure TMainForm.menuOpenLogFolderClick(Sender: TObject); begin - ShellExec('', prefDirnameSessionLogs); + ShellExec('', AppSettings.ReadString(asSessionLogsDirectory)); end; @@ -6670,7 +6575,7 @@ procedure TMainForm.PaintColorBar(Value, Max: Extended; TargetCanvas: TCanvas; C var BarWidth, CellWidth: Integer; begin - if not prefDisplayBars then + if not AppSettings.ReadBool(asDisplayBars) then Exit; // Add minimal margin to cell edges @@ -6680,7 +6585,7 @@ begin // Avoid division by zero, when max is 0 - very rare case but reported in issue #2196. if (Value > 0) and (Max > 0) then begin BarWidth := Round(CellWidth / Max * Value); - TargetCanvas.Brush.Color := prefBarColor; + TargetCanvas.Brush.Color := AppSettings.ReadInt(asBarColor); TargetCanvas.Pen.Color := ColorAdjustBrightness(TargetCanvas.Brush.Color, -40); TargetCanvas.RoundRect(CellRect.Left, CellRect.Top, CellRect.Left+BarWidth, CellRect.Bottom, 2, 2); end; @@ -8112,7 +8017,7 @@ begin TypeCat := Results.DataType(Column).Category; if Assigned(EditLink) then // Editor was created above, do nothing now - else if (Results.DataType(Column).Index = dtEnum) and prefEnableEnumEditor then begin + else if (Results.DataType(Column).Index = dtEnum) and AppSettings.ReadBool(asFieldEditorEnum) then begin EnumEditor := TEnumEditorLink.Create(VT); EnumEditor.DataType := Results.DataType(Column).Index; EnumEditor.ValueList := Results.ValueList(Column); @@ -8123,14 +8028,14 @@ begin InplaceEditor.MaxLength := Results.MaxLength(Column); InplaceEditor.ButtonVisible := True; EditLink := InplaceEditor; - end else if (TypeCat in [dtcBinary, dtcSpatial]) and prefEnableBinaryEditor then begin + end else if (TypeCat in [dtcBinary, dtcSpatial]) and AppSettings.ReadBool(asFieldEditorBinary) then begin HexEditor := THexEditorLink.Create(VT); HexEditor.DataType := Results.DataType(Column).Index; HexEditor.MaxLength := Results.MaxLength(Column); EditLink := HexEditor; - end else if (TypeCat = dtcTemporal) and prefEnableDatetimeEditor then begin + end else if (TypeCat = dtcTemporal) and AppSettings.ReadBool(asFieldEditorDatetime) then begin // Ensure date/time editor starts with a non-empty text value - if (Results.Col(Column) = '') and prefPrefillDateTime then begin + if (Results.Col(Column) = '') and AppSettings.ReadBool(asFieldEditorDatetimePrefill) then begin case Results.DataType(Column).Index of dtDate: NowText := DateToStr(Now); dtTime: NowText := TimeToStr(Now); @@ -8141,7 +8046,7 @@ begin DateTimeEditor := TDateTimeEditorLink.Create(VT); DateTimeEditor.DataType := Results.DataType(Column).Index; EditLink := DateTimeEditor; - end else if (Results.DataType(Column).Index = dtSet) and prefEnableSetEditor then begin + end else if (Results.DataType(Column).Index = dtSet) and AppSettings.ReadBool(asFieldEditorSet) then begin SetEditor := TSetEditorLink.Create(VT); SetEditor.DataType := Results.DataType(Column).Index; SetEditor.ValueList := Results.ValueList(Column); @@ -8166,8 +8071,8 @@ begin DBtree.Header.Columns[1].Options := DBtree.Header.Columns[1].Options + [coVisible] else DBtree.Header.Columns[1].Options := DBtree.Header.Columns[1].Options - [coVisible]; - OpenRegistry; - MainReg.WriteBool(REGNAME_SIZECOL_TREE, NewVal); + AppSettings.ResetPath; + AppSettings.WriteBool(asDisplayObjectSizeColumn, NewVal); end; @@ -8226,7 +8131,7 @@ begin end; // text margins and minimal extra space ColTextWidth := ColTextWidth + Tree.TextMargin*2 + 20; - ColTextWidth := Min(ColTextWidth, prefMaxColWidth); + ColTextWidth := Min(ColTextWidth, AppSettings.ReadInt(asMaxColWidth)); Col.Width := ColTextWidth; end; @@ -8249,8 +8154,8 @@ begin cl := clHighlight else if vsSelected in Node.States then cl := $00DDDDDD - else if (prefNullBG <> clNone) and r.IsNull(Column) then - cl := prefNullBG; + else if r.IsNull(Column) then + cl := AppSettings.ReadInt(asFieldNullBackground); if cl <> clNone then begin TargetCanvas.Brush.Color := cl; TargetCanvas.FillRect(CellRect); @@ -8262,11 +8167,8 @@ procedure TMainForm.HandleDataGridAttributes(RefreshingData: Boolean); var rx: TRegExpr; idx, i: Integer; - TestList: TStringList; Sort, KeyName, FocusedCol, CellFocus, Filter: String; begin - OpenRegistry; - MainReg.OpenKey(GetRegKeyTable, True); actDataResetSorting.Enabled := False; // Clear filter, column names and sort structure if gr if not Assigned(DataGridHiddenColumns) then begin @@ -8298,44 +8200,46 @@ begin SetLength(DataGridSortColumns, 0); DataGridWantedRowCount := 0; while DataGridFocusedNodeIndex >= DataGridWantedRowCount do - Inc(DataGridWantedRowCount, prefGridRowcountStep); + Inc(DataGridWantedRowCount, AppSettings.ReadInt(asDatagridRowsPerStep)); end else begin // Save current attributes if grid gets refreshed + AppSettings.SessionPath := GetRegKeyTable; if DataGridHiddenColumns.Count > 0 then - MainReg.WriteString(REGNAME_HIDDENCOLUMNS, DataGridHiddenColumns.DelimitedText) - else if MainReg.ValueExists(REGNAME_HIDDENCOLUMNS) then - MainReg.DeleteValue(REGNAME_HIDDENCOLUMNS); + AppSettings.WriteString(asHiddenColumns, DataGridHiddenColumns.DelimitedText) + else if AppSettings.ValueExists(asHiddenColumns) then + AppSettings.DeleteValue(asHiddenColumns); if SynMemoFilter.GetTextLen > 0 then - MainReg.WriteString(REGNAME_FILTER, SynMemoFilter.Text) - else if MainReg.ValueExists(REGNAME_FILTER) then - MainReg.DeleteValue(REGNAME_FILTER); + AppSettings.WriteString(asFilter, SynMemoFilter.Text) + else if AppSettings.ValueExists(asFilter) then + AppSettings.DeleteValue(asFilter); for i := 0 to High(DataGridSortColumns) do Sort := Sort + IntToStr(DataGridSortColumns[i].SortDirection) + '_' + DataGridSortColumns[i].ColumnName + DELIM; if Sort <> '' then - MainReg.WriteString(REGNAME_SORT, Sort) - else if MainReg.ValueExists(REGNAME_SORT) then - MainReg.DeleteValue(REGNAME_SORT); + AppSettings.WriteString(asSort, Sort) + else if AppSettings.ValueExists(asSort) then + AppSettings.DeleteValue(asSort); end; // Auto remove registry spam if table folder is empty - TestList := TStringList.Create; - MainReg.GetValueNames(TestList); - if (not MainReg.HasSubKeys) and (TestList.Count = 0) then - MainReg.DeleteKey(GetRegKeyTable); + if AppSettings.SessionPathExists(GetRegKeyTable) then begin + AppSettings.SessionPath := GetRegKeyTable; + if AppSettings.IsEmptyKey then + AppSettings.DeleteCurrentKey; + end; // Do nothing if table was not filtered yet - if not MainReg.OpenKey(GetRegKeyTable, False) then + if not AppSettings.SessionPathExists(GetRegKeyTable) then Exit; // Columns - if MainReg.ValueExists(REGNAME_HIDDENCOLUMNS) then - DataGridHiddenColumns.DelimitedText := MainReg.ReadString(REGNAME_HIDDENCOLUMNS); + if AppSettings.ValueExists(asHiddenColumns) then + DataGridHiddenColumns.DelimitedText := AppSettings.ReadString(asHiddenColumns); // Set filter, without changing cursor position - if MainReg.ValueExists(REGNAME_FILTER) then begin - Filter := MainReg.ReadString(REGNAME_FILTER); + if AppSettings.ValueExists(asFilter) then begin + Filter := AppSettings.ReadString(asFilter); if SynMemoFilter.Text <> Filter then begin SynMemoFilter.Text := Filter; SynMemoFilter.Modified := True; @@ -8345,12 +8249,12 @@ begin end; // Sort - if MainReg.ValueExists(REGNAME_SORT) then begin + if AppSettings.ValueExists(asSort) then begin SetLength(DataGridSortColumns, 0); rx := TRegExpr.Create; rx.Expression := '\b(\d)_(.+)\'+DELIM; rx.ModifierG := False; - if rx.Exec(MainReg.ReadString(REGNAME_SORT)) then while true do begin + if rx.Exec(AppSettings.ReadString(asSort)) then while true do begin idx := Length(DataGridSortColumns); // Check if column exists, could be renamed or deleted for i:=0 to SelectedTableColumns.Count-1 do begin @@ -8367,13 +8271,15 @@ begin end; actDataResetSorting.Enabled := Length(DataGridSortColumns) > 0; end; + + AppSettings.ResetPath; end; function TMainForm.GetRegKeyTable: String; begin // Return the slightly complex registry path to \Servers\CustomFolder\ActiveServer\curdb|curtable - Result := REGPATH + REGKEY_SESSIONS + '\' + ActiveDbObj.Connection.Parameters.SessionPath + '\' + + Result := ActiveDbObj.Connection.Parameters.SessionPath + '\' + ActiveDatabase + DELIM + ActiveDbObj.Name; end; @@ -8907,7 +8813,7 @@ var i: Integer; item: TMenuItem; rx: TRegExpr; - capt: String; + capt, Path: String; begin // Reset menu and combobox menuRecentFilters.Enabled := False; @@ -8915,17 +8821,18 @@ begin menuRecentFilters.Delete(i); comboRecentFilters.Items.Clear; // Enumerate recent filters from registry - if MainReg.OpenKey(GetRegKeyTable+'\'+REGNAME_FILTERS, False) then begin - flt := TStringList.Create; + Path := GetRegKeyTable+'\'+REGKEY_RECENTFILTERS; + if AppSettings.SessionPathExists(Path) then begin + AppSettings.SessionPath := Path; + flt := AppSettings.GetValueNames; rx := TRegExpr.Create; rx.Expression := '\s+'; - MainReg.GetValueNames(flt); - for i := 0 to flt.Count - 1 do begin - // Legacy releases seem to store some integers here - if MainReg.GetDataType(flt[i]) <> rdString then + for i:=0 to flt.Count-1 do begin + // Previously introduced bugs stored some other settings here, see issue #2127 + if flt[i] <> IntToStr(MakeInt(flt[i])) then continue; item := TMenuItem.Create(popupFilter); - capt := MainReg.ReadString(flt[i]); + capt := AppSettings.ReadString(flt[i]); capt := rx.Replace(capt, ' ', True); item.Hint := capt; item.Caption := sstr(capt, 50); @@ -8936,6 +8843,7 @@ begin end; FreeAndNil(rx); FreeAndNil(flt); + AppSettings.ResetPath; menuRecentFilters.Enabled := menuRecentFilters.Count > 0; end; comboRecentFilters.Visible := comboRecentFilters.Items.Count > 0; @@ -8953,18 +8861,22 @@ end; procedure TMainForm.LoadRecentFilter(Sender: TObject); var key: Integer; + Path: String; begin // Event handler for both dynamic popup menu items and filter combobox if Sender is TMenuItem then key := (Sender as TMenuItem).Tag else key := (Sender as TComboBox).ItemIndex+1; - if MainReg.OpenKey(GetRegKeyTable+'\'+REGNAME_FILTERS, False) then begin + Path := GetRegKeyTable+'\'+REGKEY_RECENTFILTERS; + if AppSettings.SessionPathExists(Path) then begin + AppSettings.SessionPath := Path; SynMemoFilter.UndoList.AddGroupBreak; SynMemoFilter.BeginUpdate; SynMemoFilter.SelectAll; - SynMemoFilter.SelText := MainReg.ReadString(IntToStr(key)); + SynMemoFilter.SelText := AppSettings.ReadString(IntToStr(key)); SynMemoFilter.EndUpdate; + AppSettings.ResetPath; end; end; @@ -9628,7 +9540,7 @@ var begin // Set window caption and taskbar text Cap := DBtree.Path(DBtree.FocusedNode, 0, ttNormal, '\') + ' - ' + APPNAME; - if PortableMode then + if AppSettings.PortableMode then Cap := Cap + ' Portable'; Cap := Cap + ' ' + AppVersion; Caption := Cap; @@ -9697,7 +9609,7 @@ var Tab: TQueryTab; begin Tab := QueryTabs[PageIndex-tabQuery.PageIndex]; - if (not Tab.Memo.Modified) or (not GetRegValue(REGNAME_PROMPTFILESAVE, DEFAULT_PROMPTFILESAVE)) then + if (not Tab.Memo.Modified) or (not AppSettings.ReadBool(asPromptSaveFileOnTabClose)) then Result := True else begin // Unhide tabsheet so the user sees the memo content @@ -9783,8 +9695,6 @@ var i, j: Integer; Editors: TObjectList; BaseEditor, Editor: TSynMemo; - FontName: String; - FontSize, TabWidth: Integer; KeyStroke: TSynEditKeyStroke; ActiveLineColor: TColor; Attri: TSynHighlighterAttributes; @@ -9814,14 +9724,11 @@ begin if Assigned(FPreferencesDialog) then Editors.Add(FPreferencesDialog.SynMemoSQLSample); - FontName := GetRegValue(REGNAME_FONTNAME, DEFAULT_FONTNAME); - FontSize := GetRegValue(REGNAME_FONTSIZE, DEFAULT_FONTSIZE); - TabWidth := GetRegValue(REGNAME_TABWIDTH, DEFAULT_TABWIDTH); - if GetRegValue(REGNAME_TABSTOSPACES, DEFAULT_TABSTOSPACES) then + if AppSettings.ReadBool(asTabsToSpaces) then BaseEditor.Options := BaseEditor.Options + [eoTabsToSpaces] else BaseEditor.Options := BaseEditor.Options - [eoTabsToSpaces]; - ActiveLineColor := StringToColor(GetRegValue(REGNAME_SQLCOLACTIVELINE, ColorToString(DEFAULT_SQLCOLACTIVELINE))); + ActiveLineColor := StringToColor(AppSettings.ReadString(asSQLColActiveLine)); for i:=0 to Editors.Count-1 do begin // See issue #2651: if Editors[i]=nil then @@ -9830,10 +9737,10 @@ begin if Editor = nil then continue; LogSQL('Setting up TSynMemo "'+Editor.Name+'"', lcDebug); - Editor.Font.Name := FontName; - Editor.Font.Size := FontSize; - Editor.Gutter.Font.Name := FontName; - Editor.Gutter.Font.Size := FontSize; + Editor.Font.Name := AppSettings.ReadString(asFontName); + Editor.Font.Size := AppSettings.ReadInt(asFontSize); + Editor.Gutter.Font.Name := Editor.Font.Name; + Editor.Gutter.Font.Size := Editor.Font.Size; Editor.Gutter.AutoSize := BaseEditor.Gutter.AutoSize; Editor.Gutter.DigitCount := BaseEditor.Gutter.DigitCount; Editor.Gutter.LeftOffset := BaseEditor.Gutter.LeftOffset; @@ -9845,18 +9752,20 @@ begin Editor.Options := BaseEditor.Options; if Editor = SynMemoSQLLog then Editor.Options := Editor.Options + [eoRightMouseMovesCursor]; - Editor.TabWidth := TabWidth; + Editor.TabWidth := AppSettings.ReadInt(asTabWidth); Editor.MaxScrollWidth := BaseEditor.MaxScrollWidth; Editor.WantTabs := BaseEditor.WantTabs; Editor.OnPaintTransient := BaseEditor.OnPaintTransient; // Shortcuts if Editor = BaseEditor then for j:=0 to Editor.Keystrokes.Count-1 do begin KeyStroke := Editor.Keystrokes[j]; - Shortcut1 := GetRegValue(REGPREFIX_SHORTCUT1+EditorCommandToCodeString(Keystroke.Command), KeyStroke.ShortCut); - Shortcut2 := GetRegValue(REGPREFIX_SHORTCUT2+EditorCommandToCodeString(Keystroke.Command), KeyStroke.ShortCut2); + Shortcut1 := AppSettings.ReadInt(asActionShortcut1, EditorCommandToCodeString(Keystroke.Command)); + Shortcut2 := AppSettings.ReadInt(asActionShortcut2, EditorCommandToCodeString(Keystroke.Command)); try - Keystroke.ShortCut := Shortcut1; - Keystroke.ShortCut2 := Shortcut2; + if Shortcut1<>0 then + Keystroke.ShortCut := Shortcut1; + if Shortcut2<>0 then + Keystroke.ShortCut2 := Shortcut2; except on E:ESynKeyError do begin LogSQL('Could not apply SynEdit keystroke shortcut "'+ShortCutToText(Shortcut1)+'"' + @@ -9870,9 +9779,9 @@ begin // Highlighting for i:=0 to SynSQLSyn1.AttrCount - 1 do begin Attri := SynSQLSyn1.Attribute[i]; - Attri.Foreground := GetRegValue(REGPREFIX_SQLATTRI+Attri.FriendlyName+REGPOSTFIX_SQL_FG, Attri.Foreground); - Attri.Background := GetRegValue(REGPREFIX_SQLATTRI+Attri.FriendlyName+REGPOSTFIX_SQL_BG, Attri.Background); - Attri.IntegerStyle := GetRegValue(REGPREFIX_SQLATTRI+Attri.FriendlyName+REGPOSTFIX_SQL_STYLE, Attri.IntegerStyle); + Attri.Foreground := AppSettings.ReadInt(asHighlighterForeground, Attri.FriendlyName, Attri.Foreground); + Attri.Background := AppSettings.ReadInt(asHighlighterBackground, Attri.FriendlyName, Attri.Background); + Attri.IntegerStyle := AppSettings.ReadInt(asHighlighterStyle, Attri.FriendlyName, Attri.IntegerStyle); end; end; @@ -10016,7 +9925,7 @@ var begin if CellPaintMode=cpmPaint then begin DBObj := Sender.GetNodeData(Node); - if DbObj.Connection.Parameters.SessionColor <> DEFAULT_TREEBACKGROUND then begin + if DbObj.Connection.Parameters.SessionColor <> AppSettings.GetDefaultInt(asTreeBackground) then begin TargetCanvas.Brush.Color := DbObj.Connection.Parameters.SessionColor; TargetCanvas.FillRect(CellRect); end; @@ -10587,11 +10496,11 @@ end; procedure TMainForm.treeQueryHelpersInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); var - Values: TStringList; - v, QueryDay: String; + QueryDay: String; History: TQueryHistory; Item: TQueryHistoryItem; Tab: TQueryTab; + i: Integer; begin Tab := GetQueryTabByHelpers(Sender); case Sender.GetNodeLevel(Node) of @@ -10616,21 +10525,13 @@ begin if not Assigned(Tab.HistoryDays) then Tab.HistoryDays := TStringList.Create; Tab.HistoryDays.Clear; - OpenRegistry(ActiveConnection.Parameters.SessionPath); - MainReg.OpenKey(REGKEY_QUERYHISTORY, true); - Values := TStringList.Create; - MainReg.GetValueNames(Values); - History := TQueryHistory.Create; - for v in Values do begin - Item := History.ReadItem(v); - if Assigned(Item) then begin - QueryDay := DateToStr(Item.Time); - if Tab.HistoryDays.IndexOf(QueryDay) = -1 then - Tab.HistoryDays.Add(QueryDay); - end; + History := TQueryHistory.Create(ActiveConnection.Parameters.SessionPath); + for Item in History do begin + QueryDay := DateToStr(Item.Time); + if Tab.HistoryDays.IndexOf(QueryDay) = -1 then + Tab.HistoryDays.Add(QueryDay); end; History.Free; - Values.Free; Tab.HistoryDays.CustomSort(StringListCompareAnythingDesc); ChildCount := Tab.HistoryDays.Count; end; @@ -10639,23 +10540,14 @@ begin end; 1: case Node.Parent.Index of HELPERNODE_HISTORY: begin - History := TQueryHistory.Create; + History := TQueryHistory.Create(ActiveConnection.Parameters.SessionPath); Tab.HistoryDays.Objects[Node.Index] := History; - OpenRegistry(ActiveConnection.Parameters.SessionPath); - MainReg.OpenKey(REGKEY_QUERYHISTORY, true); - Values := TStringList.Create; - MainReg.GetValueNames(Values); - for v in Values do begin - Item := History.ReadItem(v); - if Assigned(Item) then begin - QueryDay := DateToStr(Item.Time); - if QueryDay <> Tab.HistoryDays[Node.Index] then - History.Remove(Item); - end; + for i:=History.Count-1 downto 0 do begin + QueryDay := DateToStr(History[i].Time); + if QueryDay <> Tab.HistoryDays[Node.Index] then + History.Delete(i); end; - History.Sort(TQueryHistoryItemComparer.Create); ChildCount := History.Count; - Values.Free; end; else ChildCount := 0; end; @@ -10674,7 +10566,7 @@ begin FSnippetFilenames := TStringList.Create; FSnippetFilenames.Clear; try - Files := TDirectory.GetFiles(FDirnameSnippets, '*.sql'); + Files := TDirectory.GetFiles(DirnameSnippets, '*.sql'); for i:=0 to Length(Files)-1 do begin Snip := ExtractFilename(Files[i]); Snip := Copy(Snip, 1, Length(Snip)-4); @@ -10982,7 +10874,7 @@ begin MainForm.LogSQL('Loading file "'+Filename+'" ('+FormatByteNumber(Filesize)+') into query tab #'+IntToStr(Number)+' ...', lcInfo); try Content := ReadTextfile(Filename, Encoding); - if Pos(MainForm.FDirnameSnippets, Filename) = 0 then + if Pos(DirnameSnippets, Filename) = 0 then MainForm.AddOrRemoveFromQueryLoadHistory(Filename, True, True); MainForm.FillPopupQueryLoad; Memo.UndoList.AddGroupBreak; @@ -11113,7 +11005,7 @@ begin Grid.OnNewText := OrgGrid.OnNewText; Grid.OnPaintText := OrgGrid.OnPaintText; Grid.OnStartOperation := OrgGrid.OnStartOperation; - FixVT(Grid, Mainform.prefGridRowsLineCount); + FixVT(Grid, AppSettings.ReadInt(asGridRowLineCount)); end; destructor TResultTab.Destroy; @@ -11129,31 +11021,39 @@ end; { TQueryHistory } -function TQueryHistory.ReadItem(RegValue: String): TQueryHistoryItem; +constructor TQueryHistory.Create(SessionPath: String); var - i, p: Integer; + ValueNames: TStringList; + i, j, p: Integer; Raw: String; + Item: TQueryHistoryItem; begin - i := StrToIntDef(RegValue, -1); - // Prevent from running into serious errors when registry has some non-numeric value - if i=-1 then begin - Result := nil; - Exit; + AppSettings.SessionPath := SessionPath + '\' + REGKEY_QUERYHISTORY; + ValueNames := AppSettings.GetValueNames; + for i:=0 to ValueNames.Count-1 do begin + j := StrToIntDef(ValueNames[i], -1); + // Prevent from running into serious errors when registry has some non-numeric value + if i<>-1 then begin + Item := TQueryHistoryItem.Create; + Item.RegValue := j; + Raw := AppSettings.ReadString(ValueNames[i]); + p := Pos(DELIM, Raw); + Item.Time := StrToDateTime(Copy(Raw, 1, p-1)); + System.Delete(Raw, 1, p); + p := Pos(DELIM, Raw); + Item.Database := Copy(Raw, 1, p-1); + System.Delete(Raw, 1, p); + p := Pos(DELIM, Raw); + Item.Duration := StrToIntDef(Copy(Raw, 1, p-1), 0); + FMaxDuration := Max(FMaxDuration, Item.Duration); + Item.SQL := Copy(Raw, p+1, Length(Raw)); + Add(Item); + end; end; - Result := TQueryHistoryItem.Create; - Result.RegValue := i; - Raw := MainReg.ReadString(RegValue); - p := Pos(DELIM, Raw); - Result.Time := StrToDateTime(Copy(Raw, 1, p-1)); - System.Delete(Raw, 1, p); - p := Pos(DELIM, Raw); - Result.Database := Copy(Raw, 1, p-1); - System.Delete(Raw, 1, p); - p := Pos(DELIM, Raw); - Result.Duration := StrToIntDef(Copy(Raw, 1, p-1), 0); - FMaxDuration := Max(FMaxDuration, Result.Duration); - Result.SQL := Copy(Raw, p+1, Length(Raw)); - Add(Result); + // Sort by date + Sort(TQueryHistoryItemComparer.Create); + ValueNames.Free; + AppSettings.ResetPath; end; diff --git a/source/options.pas b/source/options.pas index 55794003..25bd4992 100644 --- a/source/options.pas +++ b/source/options.pas @@ -205,69 +205,64 @@ var begin Screen.Cursor := crHourGlass; - // Open registry key - OpenRegistry; - // Save values - MainReg.WriteBool(REGNAME_AUTORECONNECT, chkAutoReconnect.Checked); - MainReg.WriteBool(REGNAME_MULTI_INSTANCES, chkAllowMultiInstances.Checked); - MainReg.WriteBool(REGNAME_RESTORELASTUSEDDB, chkRestoreLastDB.Checked); - MainReg.WriteBool(REGNAME_PROMPTFILESAVE, chkAskFileSave.Checked); - MainReg.WriteString(REGNAME_FONTNAME, comboSQLFontName.Text); - MainReg.WriteInteger(REGNAME_FONTSIZE, updownSQLFontSize.Position); - MainReg.WriteInteger(REGNAME_TABWIDTH, updownSQLTabWidth.Position); - MainReg.WriteInteger(REGNAME_LOGSQLNUM, updownLogLines.Position); - MainReg.WriteInteger(REGNAME_LOGSQLWIDTH, updownLogSnip.Position); - MainReg.WriteString(REGNAME_LOGDIR, editLogDir.Text); - MainReg.WriteBool(REGNAME_LOG_ERRORS, chkLogEventErrors.Checked); - MainReg.WriteBool(REGNAME_LOG_USERSQL, chkLogEventUserFiredSQL.Checked); - MainReg.WriteBool(REGNAME_LOG_SQL, chkLogEventSQL.Checked); - MainReg.WriteBool(REGNAME_LOG_INFOS, chkLogEventInfo.Checked); - MainReg.WriteBool(REGNAME_LOG_DEBUG, chkLogEventDebug.Checked); + AppSettings.WriteBool(asAutoReconnect, chkAutoReconnect.Checked); + AppSettings.WriteBool(asAllowMultipleInstances, chkAllowMultiInstances.Checked); + AppSettings.WriteBool(asRestoreLastUsedDB, chkRestoreLastDB.Checked); + AppSettings.WriteBool(asPromptSaveFileOnTabClose, chkAskFileSave.Checked); + AppSettings.WriteString(asFontName, comboSQLFontName.Text); + AppSettings.WriteInt(asFontSize, updownSQLFontSize.Position); + AppSettings.WriteInt(asTabWidth, updownSQLTabWidth.Position); + AppSettings.WriteInt(asLogsqlnum, updownLogLines.Position); + AppSettings.WriteInt(asLogsqlwidth, updownLogSnip.Position); + AppSettings.WriteString(asSessionLogsDirectory, editLogDir.Text); + AppSettings.WriteBool(asLogErrors, chkLogEventErrors.Checked); + AppSettings.WriteBool(asLogUserSQL, chkLogEventUserFiredSQL.Checked); + AppSettings.WriteBool(asLogSQL, chkLogEventSQL.Checked); + AppSettings.WriteBool(asLogInfos, chkLogEventInfo.Checked); + AppSettings.WriteBool(asLogDebug, chkLogEventDebug.Checked); for i:=0 to SynSQLSynSQLSample.AttrCount - 1 do begin Attri := SynSQLSynSQLSample.Attribute[i]; - MainReg.WriteInteger(REGPREFIX_SQLATTRI+Attri.FriendlyName+REGPOSTFIX_SQL_FG, Attri.Foreground); - MainReg.WriteInteger(REGPREFIX_SQLATTRI+Attri.FriendlyName+REGPOSTFIX_SQL_BG, Attri.Background); - MainReg.WriteInteger(REGPREFIX_SQLATTRI+Attri.FriendlyName+REGPOSTFIX_SQL_STYLE, Attri.IntegerStyle); + AppSettings.WriteInt(asHighlighterForeground, Attri.Foreground, Attri.FriendlyName); + AppSettings.WriteInt(asHighlighterBackground, Attri.Background, Attri.FriendlyName); + AppSettings.WriteInt(asHighlighterStyle, Attri.IntegerStyle, Attri.FriendlyName); end; - MainReg.WriteString(REGNAME_SQLCOLACTIVELINE, ColorToString(SynMemoSQLSample.ActiveLineColor)); + AppSettings.WriteString(asSQLColActiveLine, ColorToString(SynMemoSQLSample.ActiveLineColor)); - MainReg.WriteInteger(REGNAME_MAXCOLWIDTH, updownMaxColWidth.Position); - Mainform.prefGridRowcountStep := StrToIntDef(editGridRowCountStep.Text, DEFAULT_ROWSPERSTEP); - Mainform.prefGridRowcountMax := StrToIntDef(editGridRowCountMax.Text, DEFAULT_MAXTOTALROWS); - MainReg.WriteInteger(REGNAME_ROWSPERSTEP, Mainform.prefGridRowcountStep); - MainReg.WriteInteger(REGNAME_MAXTOTALROWS, Mainform.prefGridRowcountMax); - MainReg.WriteInteger(REGNAME_GRIDROWSLINECOUNT, updownGridRowsLineCount.Position); - MainReg.WriteString(REGNAME_DATAFONTNAME, comboDataFontName.Text); - MainReg.WriteInteger(REGNAME_DATAFONTSIZE, updownDataFontSize.Position); - MainReg.WriteBool(REGNAME_LOGTOFILE, chkLogToFile.Checked); - MainReg.WriteBool(REGNAME_DO_UPDATECHECK, chkUpdatecheck.Checked); - MainReg.WriteBool(REGNAME_DO_UPDATECHECK_BUILDS, chkUpdatecheckBuilds.Checked); - MainReg.WriteInteger(REGNAME_UPDATECHECK_INTERVAL, updownUpdatecheckInterval.Position); - MainReg.WriteBool(REGNAME_DO_STATISTICS, chkDoStatistics.Checked); - MainReg.WriteBool(REGNAME_DISPLAYBARS, chkColorBars.Checked); - MainReg.WriteInteger(REGNAME_BARCOLOR, cboxColorBars.Selected); - MainReg.WriteString(REGNAME_MYSQLBINARIES, editMySQLBinaries.Text); - MainReg.WriteInteger(REGNAME_MAXQUERYRESULTS, updownMaxQueryResults.Position); + AppSettings.WriteInt(asMaxColWidth, updownMaxColWidth.Position); + AppSettings.WriteInt(asDatagridRowsPerStep, StrToIntDef(editGridRowCountStep.Text, -1)); + AppSettings.WriteInt(asDatagridMaximumRows, StrToIntDef(editGridRowCountMax.Text, -1)); + AppSettings.WriteInt(asGridRowLineCount, updownGridRowsLineCount.Position); + AppSettings.WriteString(asDataFontName, comboDataFontName.Text); + AppSettings.WriteInt(asDataFontSize, updownDataFontSize.Position); + AppSettings.WriteBool(asLogToFile, chkLogToFile.Checked); + AppSettings.WriteBool(asUpdatecheck, chkUpdatecheck.Checked); + AppSettings.WriteBool(asUpdatecheckBuilds, chkUpdatecheckBuilds.Checked); + AppSettings.WriteInt(asUpdatecheckInterval, updownUpdatecheckInterval.Position); + AppSettings.WriteBool(asDoUsageStatistics, chkDoStatistics.Checked); + AppSettings.WriteBool(asDisplayBars, chkColorBars.Checked); + AppSettings.WriteInt(asBarColor, cboxColorBars.Selected); + AppSettings.WriteString(asMySQLBinaries, editMySQLBinaries.Text); + AppSettings.WriteInt(asMaxQueryResults, updownMaxQueryResults.Position); // Save color settings - MainReg.WriteInteger(REGNAME_FIELDCOLOR_INTEGER, FGridTextColors[dtcInteger]); - MainReg.WriteInteger(REGNAME_FIELDCOLOR_REAL, FGridTextColors[dtcReal]); - MainReg.WriteInteger(REGNAME_FIELDCOLOR_TEXT, FGridTextColors[dtcText]); - MainReg.WriteInteger(REGNAME_FIELDCOLOR_BINARY, FGridTextColors[dtcBinary]); - MainReg.WriteInteger(REGNAME_FIELDCOLOR_DATETIME, FGridTextColors[dtcTemporal]); - MainReg.WriteInteger(REGNAME_FIELDCOLOR_SPATIAL, FGridTextColors[dtcSpatial]); - MainReg.WriteInteger(REGNAME_FIELDCOLOR_OTHER, FGridTextColors[dtcOther]); - MainReg.WriteInteger(REGNAME_BG_NULL, cboxNullBackground.Selected); + AppSettings.WriteInt(asFieldColorNumeric, FGridTextColors[dtcInteger]); + AppSettings.WriteInt(asFieldColorReal, FGridTextColors[dtcReal]); + AppSettings.WriteInt(asFieldColorText, FGridTextColors[dtcText]); + AppSettings.WriteInt(asFieldColorBinary, FGridTextColors[dtcBinary]); + AppSettings.WriteInt(asFieldColorDatetime, FGridTextColors[dtcTemporal]); + AppSettings.WriteInt(asFieldColorSpatial, FGridTextColors[dtcSpatial]); + AppSettings.WriteInt(asFieldColorOther, FGridTextColors[dtcOther]); + AppSettings.WriteInt(asFieldNullBackground, cboxNullBackground.Selected); // Editor enablings - MainReg.WriteBool(REGNAME_FIELDEDITOR_BINARY, chkEditorBinary.Checked); - MainReg.WriteBool(REGNAME_FIELDEDITOR_DATETIME, chkEditorDatetime.Checked); - MainReg.WriteBool(REGNAME_PREFILL_DATETIME, chkPrefillDatetime.Checked); - MainReg.WriteBool(REGNAME_FIELDEDITOR_ENUM, chkEditorEnum.Checked); - MainReg.WriteBool(REGNAME_FIELDEDITOR_SET, chkEditorSet.Checked); - MainReg.WriteBool(REGNAME_REMEMBERFILTERS, chkRememberFilters.Checked); + AppSettings.WriteBool(asFieldEditorBinary, chkEditorBinary.Checked); + AppSettings.WriteBool(asFieldEditorDatetime, chkEditorDatetime.Checked); + AppSettings.WriteBool(asFieldEditorDatetimePrefill, chkPrefillDatetime.Checked); + AppSettings.WriteBool(asFieldEditorEnum, chkEditorEnum.Checked); + AppSettings.WriteBool(asFieldEditorSet, chkEditorSet.Checked); + AppSettings.WriteBool(asRememberFilters, chkRememberFilters.Checked); - MainReg.WriteBool(REGNAME_COMPLETIONPROPOSAL, chkCompletionProposal.Checked); - MainReg.WriteBool(REGNAME_TABSTOSPACES, chkTabsToSpaces.Checked); + AppSettings.WriteBool(asCompletionProposal, chkCompletionProposal.Checked); + AppSettings.WriteBool(asTabsToSpaces, chkTabsToSpaces.Checked); // Shortcuts CatNode := TreeShortcutItems.GetFirst; @@ -278,12 +273,12 @@ begin // Save modified shortcuts if Assigned(Data.KeyStroke) then begin if Data.Shortcut1 <> Data.KeyStroke.ShortCut then - MainReg.WriteInteger(REGPREFIX_SHORTCUT1+EditorCommandToCodeString(Data.KeyStroke.Command), Data.Shortcut1); + AppSettings.WriteInt(asActionShortcut1, Data.Shortcut1, EditorCommandToCodeString(Data.KeyStroke.Command)); if Data.Shortcut2 <> Data.KeyStroke.ShortCut2 then - MainReg.WriteInteger(REGPREFIX_SHORTCUT2+EditorCommandToCodeString(Data.KeyStroke.Command), Data.Shortcut2); + AppSettings.WriteInt(asActionShortcut2, Data.Shortcut2, EditorCommandToCodeString(Data.KeyStroke.Command)); end else begin if Data.Shortcut1 <> Data.Action.ShortCut then - MainReg.WriteInteger(REGPREFIX_SHORTCUT1+Data.Action.Name, Data.Shortcut1); + AppSettings.WriteInt(asActionShortcut1, Data.Shortcut1, Data.Action.Name); // Apply shortcut for this session Data.Action.ShortCut := Data.Shortcut1; end; @@ -297,31 +292,21 @@ begin // Set relevant properties in mainform Mainform.DataGrid.Font.Name := comboDataFontName.Text; Mainform.DataGrid.Font.Size := updownDataFontSize.Position; - Mainform.prefGridRowsLineCount := updownGridRowsLineCount.Position; - FixVT(Mainform.DataGrid, Mainform.prefGridRowsLineCount); + FixVT(Mainform.DataGrid, updownGridRowsLineCount.Position); for i:=Mainform.tabQuery.PageIndex to Mainform.PageControlMain.PageCount-1 do begin QueryTab := Mainform.QueryTabs[i-Mainform.tabQuery.PageIndex]; for j:=0 to QueryTab.ResultTabs.Count-1 do begin Grid := QueryTab.ResultTabs[j].Grid; Grid.Font.Name := comboDataFontName.Text; Grid.Font.Size := updownDataFontSize.Position; - FixVT(Grid, Mainform.prefGridRowsLineCount); + FixVT(Grid, updownGridRowsLineCount.Position); end; end; - Mainform.prefLogsqlnum := updownLogLines.Position; - Mainform.prefLogSqlWidth := updownLogSnip.Position; - Mainform.prefLogErrors := chkLogEventErrors.Checked; - Mainform.prefLogUserSQL := chkLogEventUserFiredSQL.Checked; - Mainform.prefLogSQL := chkLogEventSQL.Checked; - Mainform.prefLogInfos := chkLogEventInfo.Checked; - Mainform.prefLogDebug := chkLogEventDebug.Checked; - Mainform.prefDirnameSessionLogs := editLogDir.Text; if chkLogToFile.Checked then Mainform.ActivateFileLogging - else if Mainform.prefLogToFile then + else Mainform.DeactivateFileLogging; - Mainform.prefMaxColWidth := updownMaxColWidth.Position; DatatypeCategories[dtcInteger].Color := FGridTextColors[dtcInteger]; DatatypeCategories[dtcReal].Color := FGridTextColors[dtcReal]; DatatypeCategories[dtcText].Color := FGridTextColors[dtcText]; @@ -329,20 +314,9 @@ begin DatatypeCategories[dtcTemporal].Color := FGridTextColors[dtcTemporal]; DatatypeCategories[dtcSpatial].Color := FGridTextColors[dtcSpatial]; DatatypeCategories[dtcOther].Color := FGridTextColors[dtcOther]; - Mainform.prefNullBG := cboxNullBackground.Selected; Mainform.CalcNullColors; Mainform.DataGrid.Repaint; Mainform.QueryGrid.Repaint; - Mainform.prefEnableBinaryEditor := chkEditorBinary.Checked; - Mainform.prefEnableDatetimeEditor := chkEditorDatetime.Checked; - Mainform.prefPrefillDateTime := chkPrefillDateTime.Checked; - Mainform.prefEnableEnumEditor := chkEditorEnum.Checked; - Mainform.prefEnableSetEditor := chkEditorSet.Checked; - Mainform.prefRememberFilters := chkRememberFilters.Checked; - Mainform.prefDisplayBars := chkColorBars.Checked; - Mainform.prefBarColor := cboxColorBars.Selected; - Mainform.prefCompletionProposal := chkCompletionProposal.Checked; - Mainform.prefMaxQueryResults := updownMaxQueryResults.Position; Mainform.ListTables.Invalidate; Mainform.ListProcesses.Invalidate; Mainform.ListCommandStats.Invalidate; @@ -415,77 +389,72 @@ end; procedure Toptionsform.FormShow(Sender: TObject); -var - datafontname : String; - datafontsize : Integer; begin screen.Cursor := crHourGlass; // Read and display values - datafontname := GetRegValue(REGNAME_DATAFONTNAME, DEFAULT_DATAFONTNAME); - datafontsize := GetRegValue(REGNAME_DATAFONTSIZE, DEFAULT_DATAFONTSIZE); - chkAutoReconnect.Checked := GetRegValue(REGNAME_AUTORECONNECT, DEFAULT_AUTORECONNECT); - chkAllowMultiInstances.Checked := GetRegValue(REGNAME_MULTI_INSTANCES, DEFAULT_MULTI_INSTANCES); - chkRestoreLastDB.Checked := GetRegValue(REGNAME_RESTORELASTUSEDDB, DEFAULT_RESTORELASTUSEDDB); - chkUpdatecheck.Checked := GetRegValue(REGNAME_DO_UPDATECHECK, DEFAULT_DO_UPDATECHECK); - chkUpdatecheckBuilds.Checked := GetRegValue(REGNAME_DO_UPDATECHECK_BUILDS, DEFAULT_DO_UPDATECHECK_BUILDS); - updownUpdatecheckInterval.Position := GetRegValue(REGNAME_UPDATECHECK_INTERVAL, DEFAULT_UPDATECHECK_INTERVAL); + chkAutoReconnect.Checked := AppSettings.ReadBool(asAutoReconnect);; + chkAllowMultiInstances.Checked := AppSettings.ReadBool(asAllowMultipleInstances); + chkRestoreLastDB.Checked := AppSettings.ReadBool(asRestoreLastUsedDB); + chkUpdatecheck.Checked := AppSettings.ReadBool(asUpdatecheck); + chkUpdatecheckBuilds.Checked := AppSettings.ReadBool(asUpdatecheckBuilds); + updownUpdatecheckInterval.Position := AppSettings.ReadInt(asUpdatecheckInterval); chkUpdatecheckClick(Sender); - chkDoStatistics.Checked := GetRegValue(REGNAME_DO_STATISTICS, DEFAULT_DO_STATISTICS); - chkColorBars.Checked := GetRegValue(REGNAME_DISPLAYBARS, DEFAULT_DISPLAYBARS); - cboxColorBars.Selected := GetRegValue(REGNAME_BARCOLOR, DEFAULT_BARCOLOR); - editMySQLBinaries.Text := GetRegValue(REGNAME_MYSQLBINARIES, DEFAULT_MYSQLBINARIES); - chkAskFileSave.Checked := GetRegValue(REGNAME_PROMPTFILESAVE, DEFAULT_PROMPTFILESAVE); + chkDoStatistics.Checked := AppSettings.ReadBool(asDoUsageStatistics); + chkColorBars.Checked := AppSettings.ReadBool(asDisplayBars); + cboxColorBars.Selected := AppSettings.ReadInt(asBarColor); + editMySQLBinaries.Text := AppSettings.ReadString(asMySQLBinaries); + chkAskFileSave.Checked := AppSettings.ReadBool(asPromptSaveFileOnTabClose); // Logging - updownLogLines.Position := GetRegValue(REGNAME_LOGSQLNUM, DEFAULT_LOGSQLNUM); - updownLogSnip.Position := GetRegValue(REGNAME_LOGSQLWIDTH, DEFAULT_LOGSQLWIDTH); - chkLogToFile.Checked := GetRegValue(REGNAME_LOGTOFILE, DEFAULT_LOGTOFILE); - editLogDir.Text := GetRegValue(REGNAME_LOGDIR, Mainform.prefDirnameSessionLogs); - chkLogEventErrors.Checked := GetRegValue(REGNAME_LOG_ERRORS, DEFAULT_LOG_ERRORS); - chkLogEventUserFiredSQL.Checked := GetRegValue(REGNAME_LOG_USERSQL, DEFAULT_LOG_USERSQL); - chkLogEventSQL.Checked := GetRegValue(REGNAME_LOG_SQL, DEFAULT_LOG_SQL); - chkLogEventInfo.Checked := GetRegValue(REGNAME_LOG_INFOS, DEFAULT_LOG_INFOS); - chkLogEventDebug.Checked := GetRegValue(REGNAME_LOG_DEBUG, DEFAULT_LOG_DEBUG); + updownLogLines.Position := AppSettings.ReadInt(asLogsqlnum); + updownLogSnip.Position := AppSettings.ReadInt(asLogsqlwidth); + chkLogToFile.Checked := AppSettings.ReadBool(asLogToFile); + editLogDir.Text := AppSettings.ReadString(asSessionLogsDirectory); + chkLogEventErrors.Checked := AppSettings.ReadBool(asLogErrors); + chkLogEventUserFiredSQL.Checked := AppSettings.ReadBool(asLogUserSQL); + chkLogEventSQL.Checked := AppSettings.ReadBool(asLogSQL); + chkLogEventInfo.Checked := AppSettings.ReadBool(asLogInfos); + chkLogEventDebug.Checked := AppSettings.ReadBool(asLogDebug); // Default Column-Width in DBGrids: - updownMaxColWidth.Position := GetRegValue(REGNAME_MAXCOLWIDTH, DEFAULT_MAXCOLWIDTH); - editGridRowCountStep.Text := IntToStr(GetRegValue(REGNAME_ROWSPERSTEP, DEFAULT_ROWSPERSTEP)); - editGridRowCountMax.Text := IntToStr(GetRegValue(REGNAME_MAXTOTALROWS, DEFAULT_MAXTOTALROWS)); - updownGridRowsLineCount.Position := GetRegValue(REGNAME_GRIDROWSLINECOUNT, DEFAULT_GRIDROWSLINECOUNT); + updownMaxColWidth.Position := AppSettings.ReadInt(asMaxColWidth); + editGridRowCountStep.Text := IntToStr(AppSettings.ReadInt(asDatagridRowsPerStep)); + editGridRowCountMax.Text := IntToStr(AppSettings.ReadInt(asDatagridMaximumRows)); + updownGridRowsLineCount.Position := AppSettings.ReadInt(asGridRowLineCount); // SQL: Mainform.SetupSynEditors; comboSQLFontName.ItemIndex := comboSQLFontName.Items.IndexOf(SynMemoSQLSample.Font.Name); updownSQLFontSize.Position := SynMemoSQLSample.Font.Size; updownSQLTabWidth.Position := SynMemoSQLSample.TabWidth; - chkCompletionProposal.Checked := GetRegValue(REGNAME_COMPLETIONPROPOSAL, DEFAULT_COMPLETIONPROPOSAL); - chkTabsToSpaces.Checked := GetRegValue(REGNAME_TABSTOSPACES, DEFAULT_TABSTOSPACES); + chkCompletionProposal.Checked := AppSettings.ReadBool(asCompletionProposal); + chkTabsToSpaces.Checked := AppSettings.ReadBool(asTabsToSpaces); comboSQLColElementChange(Sender); // Data-Appearance: comboDataFontName.Items := Screen.Fonts; - comboDataFontName.ItemIndex := comboDataFontName.Items.IndexOf(datafontname); - updownDataFontSize.Position := datafontsize; - updownMaxQueryResults.Position := GetRegValue(REGNAME_MAXQUERYRESULTS, DEFAULT_MAXQUERYRESULTS); + comboDataFontName.ItemIndex := comboDataFontName.Items.IndexOf(AppSettings.ReadString(asDataFontName)); + updownDataFontSize.Position := AppSettings.ReadInt(asDataFontSize); + updownMaxQueryResults.Position := AppSettings.ReadINt(asMaxQueryResults); // Load color settings - FGridTextColors[dtcInteger] := GetRegValue(REGNAME_FIELDCOLOR_INTEGER, DEFAULT_FIELDCOLOR_INTEGER); - FGridTextColors[dtcReal] := GetRegValue(REGNAME_FIELDCOLOR_REAL, DEFAULT_FIELDCOLOR_REAL); - FGridTextColors[dtcText] := GetRegValue(REGNAME_FIELDCOLOR_TEXT, DEFAULT_FIELDCOLOR_TEXT); - FGridTextColors[dtcBinary] := GetRegValue(REGNAME_FIELDCOLOR_BINARY, DEFAULT_FIELDCOLOR_BINARY); - FGridTextColors[dtcTemporal] := GetRegValue(REGNAME_FIELDCOLOR_DATETIME, DEFAULT_FIELDCOLOR_DATETIME); - FGridTextColors[dtcSpatial] := GetRegValue(REGNAME_FIELDCOLOR_SPATIAL, DEFAULT_FIELDCOLOR_SPATIAL); - FGridTextColors[dtcOther] := GetRegValue(REGNAME_FIELDCOLOR_OTHER, DEFAULT_FIELDCOLOR_OTHER); + FGridTextColors[dtcInteger] := AppSettings.ReadInt(asFieldColorNumeric); + FGridTextColors[dtcReal] := AppSettings.ReadInt(asFieldColorReal); + FGridTextColors[dtcText] := AppSettings.ReadInt(asFieldColorText); + FGridTextColors[dtcBinary] := AppSettings.ReadInt(asFieldColorBinary); + FGridTextColors[dtcTemporal] := AppSettings.ReadInt(asFieldColorDatetime); + FGridTextColors[dtcSpatial] := AppSettings.ReadInt(asFieldColorSpatial); + FGridTextColors[dtcOther] := AppSettings.ReadInt(asFieldColorOther); comboGridTextColors.ItemIndex := 0; comboGridTextColors.OnSelect(comboGridTextColors); - cboxNullBackground.Selected := GetRegValue(REGNAME_BG_NULL, DEFAULT_BG_NULL); + cboxNullBackground.Selected := AppSettings.ReadInt(asFieldNullBackground); // Editor enablings - chkEditorBinary.Checked := GetRegValue(REGNAME_FIELDEDITOR_BINARY, DEFAULT_FIELDEDITOR_BINARY); - chkEditorDatetime.Checked := GetRegValue(REGNAME_FIELDEDITOR_DATETIME, DEFAULT_FIELDEDITOR_DATETIME); - chkPrefillDateTime.Checked := GetRegValue(REGNAME_PREFILL_DATETIME, DEFAULT_PREFILL_DATETIME); - chkEditorEnum.Checked := GetRegValue(REGNAME_FIELDEDITOR_ENUM, DEFAULT_FIELDEDITOR_ENUM); - chkEditorSet.Checked := GetRegValue(REGNAME_FIELDEDITOR_SET, DEFAULT_FIELDEDITOR_SET); - chkRememberFilters.Checked := GetRegValue(REGNAME_REMEMBERFILTERS, DEFAULT_REMEMBERFILTERS); + chkEditorBinary.Checked := AppSettings.ReadBool(asFieldEditorBinary); + chkEditorDatetime.Checked := AppSettings.ReadBool(asFieldEditorDatetime); + chkPrefillDateTime.Checked := AppSettings.ReadBool(asFieldEditorDatetimePrefill); + chkEditorEnum.Checked := AppSettings.ReadBool(asFieldEditorEnum); + chkEditorSet.Checked := AppSettings.ReadBool(asFieldEditorEnum); + chkRememberFilters.Checked := AppSettings.ReadBool(asRememberFilters); // Shortcuts TreeShortcutItems.ReinitChildren(nil, True); @@ -681,11 +650,10 @@ begin 'This also applies to automatic settings, e.g. toolbar positions.', mtConfirmation, [mbOK, mbCancel]) = mrCancel then Exit; - OpenRegistry; - ValueList := TStringlist.Create; - Mainreg.GetValueNames(ValueList); + AppSettings.ResetPath; + ValueList := AppSettings.GetValueNames; for i:=0 to ValueList.Count-1 do - Mainreg.DeleteValue(ValueList[i]); + AppSettings.DeleteValue(ValueList[i]); FormShow(Sender); end; diff --git a/source/routine_editor.pas b/source/routine_editor.pas index 137556b8..21bf830d 100644 --- a/source/routine_editor.pas +++ b/source/routine_editor.pas @@ -122,7 +122,6 @@ end; destructor TfrmRoutineEditor.Destroy; begin // Store GUI setup - OpenRegistry; Mainform.SaveListSetup(listParameters); inherited; end; diff --git a/source/searchreplace.pas b/source/searchreplace.pas index 1b8ff4b4..8d465ddc 100644 --- a/source/searchreplace.pas +++ b/source/searchreplace.pas @@ -49,8 +49,8 @@ uses helpers; procedure TfrmSearchReplace.FormCreate(Sender: TObject); begin - comboSearch.Items.Text := GetRegValue(REGNAME_SEARCHTEXT, ''); - comboReplace.Items.Text := GetRegValue(REGNAME_REPLACETEXT, ''); + comboSearch.Items.Text := AppSettings.ReadString(asFindDialogSearchHistory); + comboReplace.Items.Text := AppSettings.ReadString(asFindDialogReplaceHistory); comboSearch.Text := ''; comboReplace.Text := ''; if comboSearch.Items.Count > 0 then comboSearch.Text := comboSearch.Items[0]; @@ -104,9 +104,8 @@ end; procedure TfrmSearchReplace.FormDestroy(Sender: TObject); begin - OpenRegistry; - Mainreg.WriteString(REGNAME_SEARCHTEXT, comboSearch.Items.Text); - Mainreg.WriteString(REGNAME_REPLACETEXT, comboReplace.Items.Text); + AppSettings.WriteString(asFindDialogSearchHistory, comboSearch.Items.Text); + AppSettings.WriteString(asFindDialogReplaceHistory, comboReplace.Items.Text); end; diff --git a/source/selectdbobject.pas b/source/selectdbobject.pas index 287d5b5c..b232e624 100644 --- a/source/selectdbobject.pas +++ b/source/selectdbobject.pas @@ -62,8 +62,8 @@ end; procedure TfrmSelectDBObject.FormCreate(Sender: TObject); begin - Width := GetRegValue(REGNAME_SELECTDBO_WINWIDTH, Width); - Height := GetRegValue(REGNAME_SELECTDBO_WINHEIGHT, Height); + Width := AppSettings.ReadInt(asSelectDBOWindowWidth); + Height := AppSettings.ReadInt(asSelectDBOWindowHeight); SetWindowSizeGrip( Self.Handle, True ); InheritFont(Font); TreeDBO.TreeOptions := MainForm.DBtree.TreeOptions; @@ -73,9 +73,8 @@ end; procedure TfrmSelectDBObject.FormDestroy(Sender: TObject); begin - OpenRegistry; - MainReg.WriteInteger( REGNAME_SELECTDBO_WINWIDTH, Width ); - MainReg.WriteInteger( REGNAME_SELECTDBO_WINHEIGHT, Height ); + AppSettings.WriteInt(asSelectDBOWindowWidth, Width); + AppSettings.WriteInt(asSelectDBOWindowHeight, Height); end; diff --git a/source/sqlhelp.pas b/source/sqlhelp.pas index 87f0bef5..f57729df 100644 --- a/source/sqlhelp.pas +++ b/source/sqlhelp.pas @@ -82,12 +82,12 @@ begin // Set window-layout InheritFont(Font); SetWindowSizeGrip(Handle, True); - Top := GetRegValue( REGNAME_SQLHELPWINTOP, Top ); - Left := GetRegValue( REGNAME_SQLHELPWINLEFT, Left ); - Width := GetRegValue( REGNAME_SQLHELPWINWIDTH, Width ); - Height := GetRegValue( REGNAME_SQLHELPWINHEIGHT, Height ); - pnlLeft.Width := GetRegValue( REGNAME_SQLHELPPLWIDTH, pnlLeft.Width ); - memoDescription.Height := GetRegValue( REGNAME_SQLHELPPRHEIGHT, memoDescription.Height ); + Top := AppSettings.ReadInt(asSQLHelpWindowTop); + Left := AppSettings.ReadInt(asSQLHelpWindowLeft); + Width := AppSettings.ReadInt(asSQLHelpWindowWidth); + Height := AppSettings.ReadInt(asSQLHelpWindowHeight); + pnlLeft.Width := AppSettings.ReadInt(asSQLHelpPnlLeftWidth); + memoDescription.Height := AppSettings.ReadInt(asSQLHelpPnlRightTopHeight); Caption := DEFAULT_WINDOW_CAPTION; MainForm.SetupSynEditors; FixVT(treeTopics); @@ -259,13 +259,12 @@ end; procedure TfrmSQLhelp.FormDestroy(Sender: TObject); begin - OpenRegistry; - MainReg.WriteInteger( REGNAME_SQLHELPWINLEFT, Left ); - MainReg.WriteInteger( REGNAME_SQLHELPWINTOP, Top ); - MainReg.WriteInteger( REGNAME_SQLHELPWINWIDTH, Width ); - MainReg.WriteInteger( REGNAME_SQLHELPWINHEIGHT, Height ); - MainReg.WriteInteger( REGNAME_SQLHELPPLWIDTH, pnlLeft.Width ); - MainReg.WriteInteger( REGNAME_SQLHELPPRHEIGHT, memoDescription.Height ); + AppSettings.WriteInt(asSQLHelpWindowLeft, Left ); + AppSettings.WriteInt(asSQLHelpWindowTop, Top ); + AppSettings.WriteInt(asSQLHelpWindowWidth, Width ); + AppSettings.WriteInt(asSQLHelpWindowHeight, Height ); + AppSettings.WriteInt(asSQLHelpPnlLeftWidth, pnlLeft.Width ); + AppSettings.WriteInt(asSQLHelpPnlRightTopHeight, memoDescription.Height ); end; diff --git a/source/syncdb.pas b/source/syncdb.pas index 631ee3a1..07c6afe0 100644 --- a/source/syncdb.pas +++ b/source/syncdb.pas @@ -119,7 +119,7 @@ begin treeSource.ToggleNode(SessNode); SessionPaths := TStringList.Create; - GetSessionPaths('', SessionPaths); + AppSettings.GetSessionPaths('', SessionPaths); comboTargetServer.Items.Assign(SessionPaths); SessionPaths.Free; comboTargetServer.Items.Insert(0, 'Select server session ...'); diff --git a/source/table_editor.pas b/source/table_editor.pas index 3a9f291d..5da40261 100644 --- a/source/table_editor.pas +++ b/source/table_editor.pas @@ -210,7 +210,7 @@ uses main; constructor TfrmTableEditor.Create(AOwner: TComponent); begin inherited; - PageControlMain.Height := GetRegValue(REGNAME_TABLEEDITOR_TABSHEIGHT, DEFAULT_TABLEEDITOR_TABSHEIGHT); + PageControlMain.Height := AppSettings.ReadInt(asTableEditorTabsHeight); FixVT(listColumns); FixVT(treeIndexes); FixVT(listForeignKeys); @@ -236,8 +236,7 @@ end; destructor TfrmTableEditor.Destroy; begin // Store GUI setup - OpenRegistry; - MainReg.WriteInteger(REGNAME_TABLEEDITOR_TABSHEIGHT, PageControlMain.Height); + AppSettings.WriteInt(asTableEditorTabsHeight, PageControlMain.Height); Mainform.SaveListSetup(listColumns); Mainform.SaveListSetup(treeIndexes); Mainform.SaveListSetup(listForeignKeys); diff --git a/source/tabletools.pas b/source/tabletools.pas index c1893c87..14591019 100644 --- a/source/tabletools.pas +++ b/source/tabletools.pas @@ -181,29 +181,29 @@ var begin // Restore GUI setup InheritFont(Font); - Width := GetRegValue(REGNAME_TOOLSWINWIDTH, Width); - Height := GetRegValue(REGNAME_TOOLSWINHEIGHT, Height); - TreeObjects.Width := GetRegValue(REGNAME_TOOLSTREEWIDTH, TreeObjects.Width); + Width := AppSettings.ReadInt(asTableToolsWindowWidth); + Height := AppSettings.ReadInt(asTableToolsWindowHeight); + TreeObjects.Width := AppSettings.ReadInt(asTableToolsTreeWidth); // Find text tab - memoFindText.Text := GetRegValue(REGNAME_TOOLSFINDTEXT, ''); + memoFindText.Text := AppSettings.ReadString(asTableToolsFindText); comboDatatypes.Items.Add('All data types'); for dtc:=Low(DatatypeCategories) to High(DatatypeCategories) do comboDatatypes.Items.Add(DatatypeCategories[dtc].Name); - comboDatatypes.ItemIndex := GetRegValue(REGNAME_TOOLSDATATYPE, 0); - chkCaseSensitive.Checked := GetRegValue(REGNAME_TOOLSCASESENSITIVE, chkCaseSensitive.Checked); + comboDatatypes.ItemIndex := AppSettings.ReadInt(asTableToolsDatatype); + chkCaseSensitive.Checked := AppSettings.ReadBool(asTableToolsFindCaseSensitive); // SQL export tab - chkExportDatabasesCreate.Checked := GetRegValue(REGNAME_EXP_CREATEDB, chkExportDatabasesCreate.Checked); - chkExportDatabasesDrop.Checked := GetRegValue(REGNAME_EXP_DROPDB, chkExportDatabasesDrop.Checked); - chkExportTablesCreate.Checked := GetRegValue(REGNAME_EXP_CREATETABLE, chkExportTablesCreate.Checked); - chkExportTablesDrop.Checked := GetRegValue(REGNAME_EXP_DROPTABLE, chkExportTablesDrop.Checked); + chkExportDatabasesCreate.Checked := AppSettings.ReadBool(asExportSQLCreateDatabases); + chkExportDatabasesDrop.Checked := AppSettings.ReadBool(asExportSQLDropDatabases); + chkExportTablesCreate.Checked := AppSettings.ReadBool(asExportSQLCreateTables); + chkExportTablesDrop.Checked := AppSettings.ReadBool(asExportSQLDropTables); comboExportData.Items.Text := DATA_NO+CRLF +DATA_REPLACE+CRLF +DATA_INSERT+CRLF +DATA_INSERTNEW+CRLF +DATA_UPDATE; - comboExportData.ItemIndex := GetRegValue(REGNAME_EXP_DATAHOW, 0); + comboExportData.ItemIndex := AppSettings.ReadInt(asExportSQLDataHow); // Add hardcoded output options and session names from registry comboExportOutputType.Items.Text := OUTPUT_FILE+CRLF +OUTPUT_DIR+CRLF +OUTPUT_CLIPBOARD+CRLF +OUTPUT_DB; SessionPaths := TStringList.Create; - GetSessionPaths('', SessionPaths); + AppSettings.GetSessionPaths('', SessionPaths); for i:=0 to SessionPaths.Count-1 do begin if SessionPaths[i] <> Mainform.ActiveConnection.Parameters.SessionPath then comboExportOutputType.Items.Add(OUTPUT_SERVER+SessionPaths[i]); @@ -239,10 +239,9 @@ end; procedure TfrmTableTools.FormDestroy(Sender: TObject); begin // Save GUI setup - OpenRegistry; - MainReg.WriteInteger( REGNAME_TOOLSWINWIDTH, Width ); - MainReg.WriteInteger( REGNAME_TOOLSWINHEIGHT, Height ); - MainReg.WriteInteger( REGNAME_TOOLSTREEWIDTH, TreeObjects.Width); + AppSettings.WriteInt(asTableToolsWindowWidth, Width ); + AppSettings.WriteInt(asTableToolsWindowHeight, Height ); + AppSettings.WriteInt(asTableToolsTreeWidth, TreeObjects.Width); end; @@ -285,7 +284,7 @@ begin // Restore output option. Use Server preselection in tmSQLExport mode only, to avoid // unwanted connects in other modes. - idx := GetRegValue(REGNAME_EXP_OUTPUT, 0); + idx := AppSettings.ReadInt(asExportSQLOutput); if (idx = -1) or (idx >= comboExportOutputType.Items.Count) then idx := 0; if (copy(comboExportOutputType.Items[idx], 1, Length(OUTPUT_SERVER)) = OUTPUT_SERVER) @@ -325,33 +324,31 @@ end; procedure TfrmTableTools.SaveSettings(Sender: TObject); begin - OpenRegistry; - case ToolMode of tmFind: begin - MainReg.WriteString(REGNAME_TOOLSFINDTEXT, memoFindText.Text); - MainReg.WriteInteger(REGNAME_TOOLSDATATYPE, comboDatatypes.ItemIndex); - MainReg.WriteBool(REGNAME_TOOLSCASESENSITIVE, chkCaseSensitive.Checked); + AppSettings.WriteString(asTableToolsFindText, memoFindText.Text); + AppSettings.WriteInt(asTableToolsDatatype, comboDatatypes.ItemIndex); + AppSettings.WriteBool(asTableToolsFindCaseSensitive, chkCaseSensitive.Checked); end; tmSQLExport: begin - MainReg.WriteBool(REGNAME_EXP_CREATEDB, chkExportDatabasesCreate.Checked); - MainReg.WriteBool(REGNAME_EXP_DROPDB, chkExportDatabasesDrop.Checked); - MainReg.WriteBool(REGNAME_EXP_CREATETABLE, chkExportTablesCreate.Checked); - MainReg.WriteBool(REGNAME_EXP_DROPTABLE, chkExportTablesDrop.Checked); - MainReg.WriteInteger(REGNAME_EXP_DATAHOW, comboExportData.ItemIndex); - MainReg.WriteInteger(REGNAME_EXP_OUTPUT, comboExportOutputType.ItemIndex); + AppSettings.WriteBool(asExportSQLCreateDatabases, chkExportDatabasesCreate.Checked); + AppSettings.WriteBool(asExportSQLDropDatabases, chkExportDatabasesDrop.Checked); + AppSettings.WriteBool(asExportSQLCreateTables, chkExportTablesCreate.Checked); + AppSettings.WriteBool(asExportSQLDropTables, chkExportTablesDrop.Checked); + AppSettings.WriteInt(asExportSQLDataHow, comboExportData.ItemIndex); + AppSettings.WriteInt(asExportSQLOutput, comboExportOutputType.ItemIndex); if comboExportOutputType.Text = OUTPUT_FILE then begin comboExportOutputTarget.Items.Insert(0, comboExportOutputTarget.Text); - MainReg.WriteString(REGNAME_EXP_OUTFILES, comboExportOutputTarget.Items.Text); + AppSettings.WriteString(asExportSQLFilenames, comboExportOutputTarget.Items.Text); end else if comboExportOutputType.Text = OUTPUT_DIR then begin comboExportOutputTarget.Items.Insert(0, comboExportOutputTarget.Text); - MainReg.WriteString(REGNAME_EXP_OUTDIRS, comboExportOutputTarget.Items.Text); + AppSettings.WriteString(asExportSQLDirectories, comboExportOutputTarget.Items.Text); end else if comboExportOutputType.Text = OUTPUT_DB then begin - MainReg.WriteString(REGNAME_EXP_OUTDATABASE, comboExportOutputTarget.Text); + AppSettings.WriteString(asExportSQLDatabase, comboExportOutputTarget.Text); end else if copy(comboExportOutputType.Text, 1, Length(OUTPUT_SERVER)) = OUTPUT_SERVER then begin - MainReg.WriteString(REGNAME_EXP_OUTSERVERDB, comboExportOutputTarget.Text); + AppSettings.WriteString(asExportSQLServerDatabase, comboExportOutputTarget.Text); end; end; @@ -931,7 +928,7 @@ begin FreeAndNil(FTargetConnection); if comboExportOutputType.Text = OUTPUT_FILE then begin comboExportOutputTarget.Style := csDropDown; - comboExportOutputTarget.Items.Text := GetRegValue(REGNAME_EXP_OUTFILES, ''); + comboExportOutputTarget.Items.Text := AppSettings.ReadString(asExportSQLFilenames, ''); if comboExportOutputTarget.Items.Count > 0 then comboExportOutputTarget.ItemIndex := 0; lblExportOutputTarget.Caption := 'Filename:'; @@ -939,7 +936,7 @@ begin btnExportOutputTargetSelect.ImageIndex := 10; end else if comboExportOutputType.Text = OUTPUT_DIR then begin comboExportOutputTarget.Style := csDropDown; - comboExportOutputTarget.Items.Text := GetRegValue(REGNAME_EXP_OUTDIRS, ''); + comboExportOutputTarget.Items.Text := AppSettings.ReadString(asExportSQLDirectories, ''); if comboExportOutputTarget.Items.Count > 0 then comboExportOutputTarget.ItemIndex := 0; lblExportOutputTarget.Caption := 'Directory:'; @@ -965,7 +962,7 @@ begin comboExportOutputTarget.Items.Add(TreeObjects.Text[DBNode, 0]); DBNode := TreeObjects.GetNextSibling(DBNode); end; - comboExportOutputTarget.ItemIndex := comboExportOutputTarget.Items.IndexOf(GetRegValue(REGNAME_EXP_OUTDATABASE, '')); + comboExportOutputTarget.ItemIndex := comboExportOutputTarget.Items.IndexOf(AppSettings.ReadString(asExportSQLDatabase)); if comboExportOutputTarget.ItemIndex = -1 then comboExportOutputTarget.ItemIndex := 0; end else begin @@ -985,7 +982,7 @@ begin FTargetConnection.Active := True; comboExportOutputTarget.Items := FTargetConnection.AllDatabases; comboExportOutputTarget.Items.Insert(0, '[Same as on source server]'); - comboExportOutputTarget.ItemIndex := comboExportOutputTarget.Items.IndexOf(GetRegValue(REGNAME_EXP_OUTSERVERDB, '')); + comboExportOutputTarget.ItemIndex := comboExportOutputTarget.Items.IndexOf(AppSettings.ReadString(asExportSQLServerDatabase)); if comboExportOutputTarget.ItemIndex = -1 then comboExportOutputTarget.ItemIndex := 0; Screen.Cursor := crDefault; diff --git a/source/texteditor.pas b/source/texteditor.pas index 840808db..1f119342 100644 --- a/source/texteditor.pas +++ b/source/texteditor.pas @@ -168,19 +168,18 @@ end; procedure TfrmTextEditor.FormDestroy(Sender: TObject); begin - OpenRegistry; - MainReg.WriteInteger( REGNAME_EDITOR_WIDTH, Width ); - MainReg.WriteInteger( REGNAME_EDITOR_HEIGHT, Height ); - MainReg.WriteBool(REGNAME_EDITOR_WORDWRAP, btnWrap.Down); + AppSettings.WriteInt(asMemoEditorWidth, Width); + AppSettings.WriteInt(asMemoEditorHeight, Height); + AppSettings.WriteBool(asMemoEditorWrap, btnWrap.Down); end; procedure TfrmTextEditor.FormShow(Sender: TObject); begin // Restore form dimensions - Width := GetRegValue(REGNAME_EDITOR_WIDTH, DEFAULT_EDITOR_WIDTH); - Height := GetRegValue(REGNAME_EDITOR_HEIGHT, DEFAULT_EDITOR_HEIGHT); - if GetRegValue(REGNAME_EDITOR_WORDWRAP, btnWrap.Down) then + Width := AppSettings.ReadInt(asMemoEditorWidth); + Height := AppSettings.ReadInt(asMemoEditorHeight); + if AppSettings.ReadBool(asMemoEditorWrap) then btnWrap.Click; // Fix label position: lblTextLength.Top := tlbStandard.Top + (tlbStandard.Height-lblTextLength.Height) div 2; diff --git a/source/updatecheck.pas b/source/updatecheck.pas index 2d719b9d..6eb8a0fb 100644 --- a/source/updatecheck.pas +++ b/source/updatecheck.pas @@ -102,8 +102,7 @@ begin else if groupRelease.Enabled or btnBuild.Enabled then Status('Updates available.'); // Remember when we did the updatecheck to enable the automatic interval - OpenRegistry; - MainReg.WriteString(REGNAME_LAST_UPDATECHECK, DateTimeToStr(Now)); + AppSettings.WriteString(asUpdatecheckLastrun, DateTimeToStr(Now)); except // Do not popup errors, just display them in the status label on E:Exception do diff --git a/source/usermanager.pas b/source/usermanager.pas index 276e739a..46d12dd9 100644 --- a/source/usermanager.pas +++ b/source/usermanager.pas @@ -207,9 +207,9 @@ procedure TUserManagerForm.FormCreate(Sender: TObject); begin // Restore GUI setup InheritFont(Font); - Width := GetRegValue(REGNAME_USERMNGR_WINWIDTH, Width); - Height := GetRegValue(REGNAME_USERMNGR_WINHEIGHT, Height); - pnlLeft.Width := GetRegValue(REGNAME_USERMNGR_LISTWIDTH, pnlLeft.Width); + Width := AppSettings.ReadInt(asUsermanagerWindowWidth); + Height := AppSettings.ReadInt(asUsermanagerWindowHeight); + pnlLeft.Width := AppSettings.ReadInt(asUsermanagerListWidth); SetWindowSizeGrip( Self.Handle, True ); FixVT(listUsers); FixVT(treePrivs); @@ -223,10 +223,9 @@ end; procedure TUserManagerForm.FormDestroy(Sender: TObject); begin // FormDestroy: Save GUI setup - OpenRegistry; - MainReg.WriteInteger( REGNAME_USERMNGR_WINWIDTH, Width ); - MainReg.WriteInteger( REGNAME_USERMNGR_WINHEIGHT, Height ); - MainReg.WriteInteger( REGNAME_USERMNGR_LISTWIDTH, pnlLeft.Width ); + AppSettings.WriteInt(asUsermanagerWindowWidth, Width); + AppSettings.WriteInt(asUsermanagerWindowHeight, Height); + AppSettings.WriteInt(asUsermanagerListWidth, pnlLeft.Width); Mainform.SaveListSetup(listUsers); end;