text
stringlengths
14
6.51M
{$mode objfpc}{$H+}{$J-} uses SysUtils; type TGun = class end; TPlayer = class Gun1, Gun2: TGun; constructor Create; destructor Destroy; override; end; constructor TPlayer.Create; begin inherited; Gun1 := TGun.Create; raise Exception.Create('Підняття винятку з конструктора!'); Gun2 := TGun.Create; end; destructor TPlayer.Destroy; begin { у випадку, якщо в конструкторі стався збій, ми можемо мати Gun1 <> nil і Gun2 = nil зараз. Змиріться з цим. ...Насправді, у цьому випадку FreeAndNil справляється з цим без будь-яких додаткових зусиль з нашого боку, тому що FreeAndNil перевіряє, чи є екземпляр нульовим, перш ніж викликати його деструктор } FreeAndNil(Gun1); FreeAndNil(Gun2); inherited; end; begin try TPlayer.Create; except on E: Exception do WriteLn('Спіймано ' + E.ClassName + ': ' + E.Message); end; end.
unit Getter.DriveList.Fixed; interface uses Windows, Getter.DriveList; type TFixedDriveListGetter = class sealed(TDriveListGetter) protected function GetDriveTypeToGet: TDriveSet; override; end; implementation function TFixedDriveListGetter.GetDriveTypeToGet: TDriveSet; begin result := [DRIVE_FIXED, DRIVE_REMOVABLE]; end; end.
unit Matrices; interface uses Math, System.SysUtils, UVector; const MIN = 0; MAX = 10; Type _INDICE = MIN..MAX; Matriz = Object Private _Item : Array [MIN..MAX, MIN..MAX] of Integer; _Size : _INDICE; Public Procedure SetDimension(value : Integer); Procedure SetVaule(r, c : _INDICE; value : Integer); Procedure LoadRandom(utill : Integer); Function ReturnItems(r, c : Integer) : Integer; Function GetDimension() : Integer; Function Sumar(m2 : Matriz) : Matriz; Function Multiply(m2 : Matriz) : Matriz; Function GetMainDiagonal() : String; Function GetOppositeDiagonal() : String; Function GetMainAndOppositeDiagonalV1(vec : UVector.OBVector) : UVector.OBVector; Function GetMaxRowsAndCols(m2 : Matriz) : Integer; Function MultiplyMatrizByScalar(value : Integer) : Matriz; End; implementation Procedure Matriz.SetDimension(value : Integer); Begin _Size := value; End; Procedure Matriz.SetVaule(r, c : _INDICE; value : Integer); Begin _Item[r, c] := value; End; Procedure Matriz.LoadRandom(utill : Integer); // Carga aleatoria de la matriz Var rows, cols : _INDICE; Begin Randomize; for rows := MIN TO _Size DO for cols := MIN TO _Size DO Begin _Item[rows, cols] := Random(utill) + 1; End; End; Function Matriz.ReturnItems(r: Integer; c: Integer) : Integer; begin ReturnItems := _Item[r, c]; end; Function Matriz.GetDimension() : Integer; Begin GetDimension := _Size; End; Function Matriz.Sumar(m2 : Matriz) : Matriz; Var m3 : Matriz; rows, cols : Integer; Begin m3.Setdimension(m2.GetDimension()); for rows := MIN TO _Size DO for cols := MIN TO _Size DO Begin m3._Item[rows,cols] := _Item[rows,cols] + m2._Item[rows,cols]; End; Sumar := m3; End; Function Matriz.Multiply(m2 : Matriz) : Matriz; Var m3 : Matriz; rows, cols, cs, resu, resu1 : Integer; Begin m3.Setdimension(m2.GetDimension()); for rows := MIN TO _Size DO for cols := MIN TO _Size DO Begin resu := 0; resu1 := 0; for cs := MIN TO (_Size) DO Begin // NOTA: Puse dos variables para que no me de valores ERRONEOS // Por alguna razon daba ese error y no me daba los valores correspondientes // a la operacion resu := _Item[rows, cs] * (m2._Item[cs, cols]); resu1 := resu1 + resu; //FIN NOTA m3._Item[rows, cols] := resu1; End; End; Multiply := m3; End; Function Matriz.GetMainDiagonal() : String; Var i : Integer; MainDiagonal : String; Begin MainDiagonal := ''; for i := MIN TO _Size DO Begin MainDiagonal := MainDiagonal + IntToStr(_Item[i, i]); if (i <> _Size) Then MainDiagonal := MainDiagonal + ', '; End; MainDiagonal := MainDiagonal; GetMainDiagonal := MainDiagonal; End; Function Matriz.GetOppositeDiagonal() : String; Var rows, cols : Integer; OppositeDiagonal : String; Begin OppositeDiagonal := ''; cols := _Size; for rows := MIN TO _Size DO Begin OppositeDiagonal := OppositeDiagonal + IntToStr(_Item[rows, cols]); cols := cols - 1; if (rows <> _Size) Then OppositeDiagonal := OppositeDiagonal + ', '; End; GetOppositeDiagonal := OppositeDiagonal; End; Function Matriz.GetMainAndOppositeDiagonalV1(vec : UVector.OBVector) : UVector.OBVector; Var rows, cols : Integer; OppositeDiagonal : String; Begin OppositeDiagonal := ''; cols := _Size; for rows := MIN TO _Size DO Begin vec.CargarManualV1(0, rows, _Item[rows, rows]); vec.CargarManualV1(1, rows, _Item[rows, cols]); cols := cols - 1; End; //1 GetMainAndOppositeDiagonalV1 := vec; end; Function Matriz.GetMaxRowsAndCols(m2 : Matriz) : Integer; Var m3 : Matriz; rows, cols, maxRowsCols : Integer; Begin m3.Setdimension(m2.GetDimension()); maxRowsCols := 0; for rows := MIN TO _Size DO for cols := MIN TO _Size DO Begin m3._Item[rows,cols] := _Item[rows,cols] + m2._Item[rows,cols]; if (m3._Item[rows,cols] > maxRowsCols) Then maxRowsCols := m3._Item[rows,cols]; End; GetMaxRowsAndCols := maxRowsCols; End; Function Matriz.MultiplyMatrizByScalar(value : Integer) : Matriz; Var m3 : Matriz; rows, cols : Integer; Begin m3.Setdimension(_Size); for rows := MIN TO _Size DO for cols := MIN TO _Size DO Begin m3._Item[rows,cols] := _Item[rows,cols] * value; End; MultiplyMatrizByScalar := m3; End; end.
(* Filter: MM, 2020-04-01 *) (* ------ *) (* Simple filter program for text files *) (* ========================================================================= *) PROGRAM Filter; VAR stdOutput: TEXT; inputFileName, outputFileName: STRING; line: STRING; PROCEDURE CheckIOError(message: STRING); VAR error: INTEGER; BEGIN (* CheckIOError *) error := IOResult; IF (error <> 0) THEN BEGIN WriteLn('ERROR: ', message, '(Code: ', error, ')'); HALT; END; (* IF *) END; (* CheckIOError *) PROCEDURE TransformText(VAR s: STRING); BEGIN (* TransformText *) s := UpCase(s); END; (* TransformText *) BEGIN (* Filter *) stdOutput := output; IF (ParamCount > 0) THEN BEGIN //counts command line paramaters inputFileName := ParamStr(1); Assign(input, inputFileName); {$I-} Reset(input); CheckIOError('Cannot open input file.'); {$I+} END; (* IF *) IF (ParamCount > 1) THEN BEGIN outputFileName := ParamStr(2); Assign(output, outputFileName); {$I-} Rewrite(output); CheckIOError('Cannot write to output file.'); {$I+} END; (* IF *) REPEAT ReadLn(input, line); TransformText(line); WriteLn(output, line); UNTIL (Eof(input)); (* REPEAT *) IF (ParamCount > 0) THEN Close(input); IF (ParamCount > 1) THEN Close(output); output := stdOutput; WriteLn('Done!'); END. (* Filter *)
unit Firebird.SyntaxWords.Tests; interface {$M+} uses DUnitX.TestFramework; const {$REGION 'Firebird 2.5 Keywords'} Firebird25Keywords: TArray<String> = [ '!<', '^<', '^=', '^>', ',', ':=', '!=', '!>', '(', ')', '<', '<=', '<>', '=', '>', '>=', '||', '~<', '~=', '~>', 'ABS', 'ACCENT', 'ACOS', 'ACTION', 'ACTIVE', 'ADD', 'ADMIN', 'AFTER', 'ALL', 'ALTER', 'ALWAYS', 'AND', 'ANY', 'AS', 'ASC', 'ASCENDING', 'ASCII_CHAR', 'ASCII_VAL', 'ASIN', 'AT', 'ATAN', 'ATAN2', 'AUTO', 'AUTONOMOUS', 'AVG', 'BACKUP', 'BEFORE', 'BEGIN', 'BETWEEN', 'BIGINT', 'BIN_AND', 'BIN_NOT', 'BIN_OR', 'BIN_SHL', 'BIN_SHR', 'BIN_XOR', 'BIT_LENGTH', 'BLOB', 'BLOCK', 'BOTH', 'BREAK', 'BY', 'CALLER', 'CASCADE', 'CASE', 'CAST', 'CEIL', 'CEILING', 'CHAR', 'CHAR_LENGTH', 'CHAR_TO_UUID', 'CHARACTER', 'CHARACTER_LENGTH', 'CHECK', 'CLOSE', 'COALESCE', 'COLLATE', 'COLLATION', 'COLUMN', 'COMMENT', 'COMMIT', 'COMMITTED', 'COMMON', 'COMPUTED', 'CONDITIONAL', 'CONNECT', 'CONSTRAINT', 'CONTAINING', 'COS', 'COSH', 'COT', 'COUNT', 'CREATE', 'CROSS', 'CSTRING', 'CURRENT', 'CURRENT_CONNECTION', 'CURRENT_DATE', 'CURRENT_ROLE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_TRANSACTION', 'CURRENT_USER', 'CURSOR', 'DATA', 'DATABASE', 'DATE', 'DATEADD', 'DATEDIFF', 'DAY', 'DEC', 'DECIMAL', 'DECLARE', 'DECODE', 'DEFAULT', 'DELETE', 'DELETING', 'DESC', 'DESCENDING', 'DESCRIPTOR', 'DIFFERENCE', 'DISCONNECT', 'DISTINCT', 'DO', 'DOMAIN', 'DOUBLE', 'DROP', 'ELSE', 'END', 'ENTRY_POINT', 'ESCAPE', 'EXCEPTION', 'EXECUTE', 'EXISTS', 'EXIT', 'EXP', 'EXTERNAL', 'EXTRACT', 'FETCH', 'FILE', 'FILTER', 'FIRST', 'FIRSTNAME', 'FLOAT', 'FLOOR', 'FOR', 'FOREIGN', 'FREE_IT', 'FROM', 'FULL', 'FUNCTION', 'GDSCODE', 'GEN_ID', 'GEN_UUID', 'GENERATED', 'GENERATOR', 'GLOBAL', 'GRANT', 'GRANTED', 'GROUP', 'HASH', 'HAVING', 'HOUR', 'IF', 'IGNORE', 'IIF', 'IN', 'INACTIVE', 'INDEX', 'INNER', 'INPUT_TYPE', 'INSENSITIVE', 'INSERT', 'INSERTING', 'INT', 'INTEGER', 'INTO', 'IS', 'ISOLATION', 'JOIN', 'KEY', 'LAST', 'LASTNAME', 'LEADING', 'LEAVE', 'LEFT', 'LENGTH', 'LEVEL', 'LIKE', 'LIMBO', 'LIST', 'LN', 'LOCK', 'LOG', 'LOG10', 'LONG', 'LOWER', 'LPAD', 'MANUAL', 'MAPPING', 'MATCHED', 'MATCHING', 'MAX', 'MAXIMUM_SEGMENT', 'MAXVALUE', 'MERGE', 'MIDDLENAME', 'MILLISECOND', 'MIN', 'MINUTE', 'MINVALUE', 'MOD', 'MODULE_NAME', 'MONTH', 'NAMES', 'NATIONAL', 'NATURAL', 'NCHAR', 'NEXT', 'NO', 'NOT', 'NULL', 'NULLIF', 'NULLS', 'NUMERIC', 'OCTET_LENGTH', 'OF', 'ON', 'ONLY', 'OPEN', 'OPTION', 'OR', 'ORDER', 'OS_NAME', 'OUTER', 'OUTPUT_TYPE', 'OVERFLOW', 'OVERLAY', 'PAD', 'PAGE', 'PAGE_SIZE', 'PAGES', 'PARAMETER', 'PASSWORD', 'PI', 'PLACING', 'PLAN', 'POSITION', 'POST_EVENT', 'POWER', 'PRECISION', 'PRESERVE', 'PRIMARY', 'PRIVILEGES', 'PROCEDURE', 'PROTECTED', 'RAND', 'RDB$DB_KEY', 'READ', 'REAL', 'RECORD_VERSION', 'RECREATE', 'RECURSIVE', 'REFERENCES', 'RELEASE', 'REPLACE', 'REQUESTS', 'RESERV', 'RESERVING', 'RESTART', 'RESTRICT', 'RETAIN', 'RETURNING', 'RETURNING_VALUES', 'RETURNS', 'REVERSE', 'REVOKE', 'RIGHT', 'ROLE', 'ROLLBACK', 'ROUND', 'ROW_COUNT', 'ROWS', 'RPAD', 'SAVEPOINT', 'SCALAR_ARRAY', 'SCHEMA', 'SECOND', 'SEGMENT', 'SELECT', 'SENSITIVE', 'SEQUENCE', 'SET', 'SHADOW', 'SHARED', 'SIGN', 'SIMILAR', 'SIN', 'SINGULAR', 'SINH', 'SIZE', 'SKIP', 'SMALLINT', 'SNAPSHOT', 'SOME', 'SORT', 'SOURCE', 'SPACE', 'SQLCODE', 'SQLSTATE (2.5.1)', 'SQRT', 'STABILITY', 'START', 'STARTING', 'STARTS', 'STATEMENT', 'STATISTICS', 'SUB_TYPE', 'SUBSTRING', 'SUM', 'SUSPEND', 'TABLE', 'TAN', 'TANH', 'TEMPORARY', 'THEN', 'TIME', 'TIMEOUT', 'TIMESTAMP', 'TO', 'TRAILING', 'TRANSACTION', 'TRIGGER', 'TRIM', 'TRUNC', 'TWO_PHASE', 'TYPE', 'UNCOMMITTED', 'UNDO', 'UNION', 'UNIQUE', 'UPDATE', 'UPDATING', 'UPPER', 'USER', 'USING', 'UUID_TO_CHAR', 'VALUE', 'VALUES', 'VARCHAR', 'VARIABLE', 'VARYING', 'VIEW', 'WAIT', 'WEEK', 'WEEKDAY', 'WHEN', 'WHERE', 'WHILE', 'WITH', 'WORK', 'WRITE', 'YEAR', 'YEARDAY']; {$ENDREGION} type /// <summary> /// https://firebirdsql.org/refdocs/langrefupd25-reskeywords-full-keywords.html /// </summary> TFirebird25Syntax = record class function CompareArraysAreTheSame(left, right: TArray<string>): Boolean; static; function Find(const value:string): Boolean; function IsOperator(const input: string): Boolean; procedure Execute(); end; [TestFixture] TTestFirebird25Syntax = class public [Setup] procedure SetUp(); [TearDown] procedure TearDown(); published [Test] procedure Test_WordsCompare(); [Test] procedure Test_IsOperator(); [Test] [TestCase('Testcase1', 'EXTERNAL,True')] [TestCase('Testcase2', 'DECLARE,True')] [TestCase('Testcase3', 'Nathan,False')] procedure Test_Find(const Value: string; Expected: Boolean); end; {$M-} implementation uses System.SysUtils, // ONPParser, System.Generics.Collections, // Must appear after Classes, so that it can use the correct TCollectionNotification. System.Generics.Defaults; { TFirebird25Syntax } class function TFirebird25Syntax.CompareArraysAreTheSame(left, right: TArray<string>): Boolean; var Comparer: IComparer<TArray<string>>; begin // TArray.Sort<String>(Arr, TStringComparer.Ordinal); Comparer := TComparer<TArray<string>>.Default; Result := Comparer.Compare(left, right) = 0; end; procedure TFirebird25Syntax.Execute(); begin // for I := 0 to length(keyArray)-1 do // FCboAdjustmentReason.Properties.Items.AddObject(Referenzen[keyArray[I]].Code + ' ('+ Referenzen[keyArray[I]].CodeDescription+')', Referenzen[keyArray[I]].CopyToObject); // FCboAdjustmentReason.ItemIndex := 0; // TArray.Sort<TArray<string>>(Firebird25Keywords, TStringComparer.Ordinal.); // Firebird25Keywords. end; function TFirebird25Syntax.Find(const value: string): Boolean; var // KeyArray: TArray<String>; FoundIndex: Integer; begin // KeyArray := Firebird25Keywords; // TArray.Sort<String>(KeyArray); // Result := TArray.BinarySearch<String>(KeyArray, Value, FoundIndex, TStringComparer.Ordinal); Result := TArray.BinarySearch<String>(Firebird25Keywords, Value, FoundIndex, TStringComparer.Ordinal); end; function TFirebird25Syntax.IsOperator(const input: string): Boolean; const Ops: TArray<String> = ['-', '+', '*', '/']; var Each: string; begin for Each in Ops do if Each.Contains(input) then Exit(True); Result := False; end; { TTestFirebird25Syntax } procedure TTestFirebird25Syntax.SetUp(); begin //... end; procedure TTestFirebird25Syntax.TearDown(); begin //... end; procedure TTestFirebird25Syntax.Test_Find(const Value: string; Expected: Boolean); var Cut: TFirebird25Syntax; begin Assert.AreEqual(Expected, Cut.Find(Value)); end; procedure TTestFirebird25Syntax.Test_IsOperator; var Cut: TFirebird25Syntax; begin Assert.IsTrue(Cut.IsOperator('-')); Assert.IsTrue(Cut.IsOperator('+')); Assert.IsTrue(Cut.IsOperator('*')); Assert.IsTrue(Cut.IsOperator('/')); Assert.IsFalse(Cut.IsOperator(' ')); Assert.IsFalse(Cut.IsOperator('A')); Assert.IsFalse(Cut.IsOperator('')); end; procedure TTestFirebird25Syntax.Test_WordsCompare(); var Actual: Boolean; begin // Arrange... // Act... Actual := TFirebird25Syntax.CompareArraysAreTheSame(Firebird25Keywords, Firebird25Keywords); // Assert... Assert.IsTrue(Actual); end; initialization {$IFDEF VER320}TDUnitX.RegisterTestFixture(TTestFirebird25Syntax, 'Words');{$ENDIF} end.
unit frmAdminToolU; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, IBServices, StdCtrls, ActnList, Menus, Grids, ExtCtrls, DB, IBSQL, IBDatabase, IBDatabaseInfo; type TfrmAdminTool = class(TForm) PageControl1: TPageControl; tabUsers: TTabSheet; ActionList1: TActionList; MainMenu1: TMainMenu; Login1: TMenuItem; Logout1: TMenuItem; Login: TAction; Logout: TAction; tabBackup: TTabSheet; tabRestore: TTabSheet; tabValidate: TTabSheet; tabCertificates: TTabSheet; tabStatistics: TTabSheet; tabProperties: TTabSheet; lstUsers: TListView; srvUsers: TIBSecurityService; btnAdd: TButton; btnEdit: TButton; btnDelete: TButton; lstCertificates: TListView; srvLicense: TIBLicensingService; srvProperties: TIBServerProperties; Button1: TButton; btnRemove: TButton; AddCertificate: TAction; RemoveCertificate: TAction; GroupBox1: TGroupBox; lblCertificate: TLabel; sgBackupOptions: TStringGrid; btnOK: TButton; sgBackupFiles: TStringGrid; cbBackupOptions: TComboBox; pnlBackupOption: TPanel; Backup: TAction; srvBackup: TIBBackupService; Label1: TLabel; edtBackupName: TEdit; btnDatabaseLookup: TButton; dlgBackupRestore: TOpenDialog; lblOptions: TLabel; Button2: TButton; sgRestoreOptions: TStringGrid; pnlRestoreOptionName: TPanel; cbRestoreOptions: TComboBox; Label2: TLabel; sgRestoreFiles: TStringGrid; sgRestore: TStringGrid; Label3: TLabel; Label4: TLabel; Restore: TAction; srvRestore: TIBRestoreService; srvValidate: TIBValidationService; lblDatabaseName: TLabel; bvlLine1: TBevel; Label5: TLabel; Panel1: TPanel; sgValidateOptions: TStringGrid; cbValidateOptions: TComboBox; Button3: TButton; edtValidate: TEdit; pnlValidate: TPanel; Validate: TAction; Label6: TLabel; Label7: TLabel; Bevel1: TBevel; sgStats: TStringGrid; pnlStats: TPanel; cbStats: TComboBox; Button4: TButton; edtStatistics: TEdit; Statistics: TAction; srvStats: TIBStatisticalService; srvLog: TIBLogService; tabLog: TTabSheet; edLog: TRichEdit; srvConfig: TIBConfigService; Label8: TLabel; gbSummaryInfo: TGroupBox; lblDBOwner: TLabel; lblDBPages: TLabel; lblPageSize: TLabel; lvSecondaryFiles: TListView; stxDBOwner: TStaticText; stxDBPages: TStaticText; stxPageSize: TStaticText; sgProperties: TStringGrid; cbProperties: TComboBox; pnlProperties: TPanel; Label9: TLabel; edtProperties: TEdit; Button5: TButton; Button6: TButton; Lookup: TAction; Apply: TAction; dbProperties: TIBDatabase; trProperties: TIBTransaction; sqlFiles: TIBSQL; sqlOwner: TIBSQL; infoDB: TIBDatabaseInfo; procedure LogoutUpdate(Sender: TObject); procedure LoginExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure LogoutExecute(Sender: TObject); procedure LoginUpdate(Sender: TObject); procedure AddUserExecute(Sender: TObject); procedure LoggedInUpdate(Sender: TObject); procedure EditUserExecute(Sender: TObject); procedure DeleteUserUpdate(Sender: TObject); procedure DeleteUserExecute(Sender: TObject); procedure EditUserUpdate(Sender: TObject); procedure lstCertificatesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure AddCertificateExecute(Sender: TObject); procedure RemoveCertificateExecute(Sender: TObject); procedure sgFilesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure sgFilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure sgBackupOptionsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure sgBackupOptionsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure BackupExecute(Sender: TObject); procedure btnDatabaseLookupClick(Sender: TObject); procedure sgRestoreFilesDblClick(Sender: TObject); procedure sgRestoreOptionsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure RestoreExecute(Sender: TObject); procedure sgValidateOptionsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure ValidateExecute(Sender: TObject); procedure ValidateUpdate(Sender: TObject); procedure StatisticsExecute(Sender: TObject); procedure LookupUpdate(Sender: TObject); procedure sgPropertiesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure cbPropertiesChange(Sender: TObject); procedure LookupExecute(Sender: TObject); procedure ApplyExecute(Sender: TObject); procedure cbPropertiesExit(Sender: TObject); procedure cbStatsExit(Sender: TObject); procedure cbValidateOptionsExit(Sender: TObject); procedure cbRestoreOptionsExit(Sender: TObject); procedure cbBackupOptionsExit(Sender: TObject); procedure StatisticsUpdate(Sender: TObject); private { Private declarations } FLoggedIn : Boolean; procedure UpdateListView; procedure UpdateServer(Server, Protocol, User, password : String); procedure ShowLicense; procedure UpdateOptions(const Grid : TStringGrid; const Panel : TPanel; const Combo : TComboBox; const ACol, ARow: Integer); procedure SetupRestoreTab; procedure SetupBackupTab; procedure SetupValidateTab; procedure SetupStats; procedure SetupProperties; public { Public declarations } property LoggedIn : Boolean read FLoggedIn; end; var frmAdminTool: TfrmAdminTool; implementation uses frmLoginU, IBIntf, frmUserInformationU, typInfo, frmAddCertificateU, frmVerboseU; {$R *.dfm} const OPTION_NAME_COL = 0; OPTION_VALUE_COL = 1; FORMAT_ROW = 0; METADATA_ONLY_ROW = 1; GARBAGE_COLLECTION_ROW = 2; TRANSACTIONS_IN_LIMBO_ROW = 3; CHECKSUMS_ROW = 4; CONVERT_TO_TABLES_ROW = 5; VERBOSE_OUTPUT_ROW = 6; PAGE_SIZE_ROW = 0; OVERWRITE_ROW = 1; COMMIT_EACH_TABLE_ROW = 2; CREATE_SHADOW_FILES_ROW = 3; DEACTIVATE_INDICES_ROW = 4; VALIDITY_CONDITIONS_ROW = 5; USE_ALL_SPACE_ROW = 7; VALIDATE_RECORD_FRAGMENTS_ROW = 0; READ_ONLY_VALIDATION_ROW = 1; IGNORE_CHECKSUM_ERRORS_ROW = 2; STATISTICS_OPTION_ROW = 0; FORCED_WRITES_ROW = 0; SWEEP_INTERVAL_ROW = 1; READ_ONLY_ROW = 3; SQL_DIALECT_ROW = 2; FORCED_WRITES_TRUE = 'Enabled'; FORCED_WRITES_FALSE = 'Disabled'; READ_ONLY_TRUE = 'True'; READ_ONLY_FALSE = 'False'; SWEEP_INTERVAL_MIN = 0; SWEEP_INTERVAL_MAX = 200000; SQL_DIALECT1 = '1'; SQL_DIALECT2 = '2'; SQL_DIALECT3 = '3'; procedure TfrmAdminTool.LogoutUpdate(Sender: TObject); begin TAction(Sender).Enabled := FLoggedIn; end; procedure TfrmAdminTool.LoginExecute(Sender: TObject); var i : Integer; User, Password : String; begin with TfrmLogin.Create(self) do try { Try reading the default user name and password from the environment variables if they are set} i := GetEnvironmentVariable(PChar('ISC_USER'), PChar(User), 0); if i>0 then begin SetLength(User,i); GetEnvironmentVariable(PChar('ISC_USER'),PChar(User), i); end; i := GetEnvironmentVariable(PChar('ISC_PASSWORD'),Pchar(Password), 0); if i>0 then begin SetLength(Password,i); GetEnvironmentVariable(PChar('ISC_PASSWORD'),PChar(Password), i); end; edtUserName.Text := User; edtPassword.Text := Password; if ShowModal = mrOk then begin FLoggedIn := true; UpdateServer(edtServer.Text, cbxProtocol.Text, edtUserName.Text, edtPassword.Text); end; finally Free; end; end; procedure TfrmAdminTool.FormCreate(Sender: TObject); begin try CheckIBLoaded; except ShowMessage('Interbase Client not installed, aborting'); Application.Terminate; end; if GetIBClientVersion < 6 then begin ShowMessage('InterBase version less than 6 found, aborting'); Application.Terminate; end; SetupBackupTab; SetupRestoreTab; SetupValidateTab; SetupStats; SetupProperties; PageControl1.ActivePage := tabUsers; FLoggedIn := false; end; procedure TfrmAdminTool.LogoutExecute(Sender: TObject); begin FLoggedIn := false; end; procedure TfrmAdminTool.LoginUpdate(Sender: TObject); begin TAction(Sender).Enabled := not FLoggedIn; end; procedure TfrmAdminTool.AddUserExecute(Sender: TObject); begin with TfrmUserInformation.Create(Self) do try SecurityService := srvUsers; DisplayUser(''); if ShowModal = IDOK then UpdateListView; finally Free; end; end; procedure TfrmAdminTool.LoggedInUpdate(Sender: TObject); begin TAction(Sender).Enabled := LoggedIn; end; procedure TfrmAdminTool.EditUserExecute(Sender: TObject); begin with TfrmUserInformation.Create(self) do try SecurityService := srvUsers; DisplayUser(lstUsers.Selected.Caption); if ShowModal = IDOK then UpdateListView; finally Free; end; end; procedure TfrmAdminTool.DeleteUserUpdate(Sender: TObject); begin if not LoggedIn then TAction(Sender).Enabled := false else if not Assigned(lstUsers.Selected) then TAction(Sender).Enabled := false else TAction(Sender).Enabled := not (lstUsers.Selected.Caption = 'SYSDBA'); end; procedure TfrmAdminTool.DeleteUserExecute(Sender: TObject); begin if MessageDlg('Are you certain you wish to delete this user?', mtConfirmation, [mbYes, mbNo], 0) = IDNO then Exit; srvUsers.Active := true; srvUsers.UserName := lstUsers.Selected.Caption; srvUsers.DeleteUser; srvUsers.Active := false; UpdateListView; end; procedure TfrmAdminTool.UpdateListView; var I : Integer; begin with srvUsers do begin try Active := true; DisplayUsers; lstUsers.Items.BeginUpdate; lstUsers.Items.Clear; for I := 0 to UserInfoCount - 1 do begin with UserInfo[i] do begin with lstUsers.Items.Add do begin Caption := UserName; SubItems.Add(FirstName + ' ' + MiddleName + ' ' + LastName); SubItems.Add(IntToStr(UserId)); SubItems.Add(IntToStr(GroupId)); end; end; end; finally lstUsers.Items.EndUpdate; Active := false; end; end; end; procedure TfrmAdminTool.UpdateServer(Server, Protocol, User, password: String); var ProtocolEnum : TProtocol; begin ProtocolEnum := TProtocol(GetEnumValue(typeinfo(TProtocol), Protocol)); srvUsers.ServerName := Server; srvUsers.Protocol := ProtocolEnum; srvUsers.Params.Clear; srvUsers.Params.Values['user_name'] := User; srvUsers.Params.Values['password'] := Password; UpdateListView; with srvProperties do begin if Active then Active:= False; ServerName := Server; Protocol := ProtocolEnum; Params.Clear; Params.Values['user_name'] := User; Params.Values['password'] := Password; ShowLicense; end; with srvLicense do begin if Active then Active:= False; ServerName := Server; Protocol := ProtocolEnum; Params.Clear; Params.Values['user_name'] := User; Params.Values['password'] := Password; Active := true; end; srvBackup.ServerName := Server; srvBackup.Protocol := ProtocolEnum; srvBackup.Params.Clear; srvBackup.Params.Values['user_name'] := User; srvBackup.Params.Values['password'] := Password; srvRestore.ServerName := Server; srvRestore.Protocol := ProtocolEnum; srvRestore.Params.Clear; srvRestore.Params.Values['user_name'] := User; srvRestore.Params.Values['password'] := Password; srvValidate.ServerName := Server; srvValidate.Protocol := ProtocolEnum; srvValidate.Params.Clear; srvValidate.Params.Values['user_name'] := User; srvValidate.Params.Values['password'] := Password; srvStats.ServerName := Server; srvStats.Protocol := ProtocolEnum; srvStats.Params.Clear; srvStats.Params.Values['user_name'] := User; srvStats.Params.Values['password'] := Password; srvConfig.ServerName := Server; srvConfig.Protocol := ProtocolEnum; srvConfig.Params.Clear; srvConfig.Params.Values['user_name'] := User; srvConfig.Params.Values['password'] := Password; srvLog.ServerName := Server; srvLog.Protocol := ProtocolEnum; srvLog.Params.Clear; srvLog.Params.Values['user_name'] := User; srvLog.Params.Values['password'] := Password; srvLog.Attach; try srvLog.ServiceStart; edLog.Lines.Clear; while not srvLog.Eof do edLog.Lines.Add(srvLog.GetNextLine); finally srvLog.Detach; end; end; procedure TfrmAdminTool.EditUserUpdate(Sender: TObject); begin TAction(Sender).Enabled := Assigned(lstUsers.Selected) and LoggedIn; end; procedure TfrmAdminTool.lstCertificatesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin lblCertificate.Caption := srvProperties.LicenseInfo.Desc[Item.Index]; end; procedure TfrmAdminTool.AddCertificateExecute(Sender: TObject); begin with TfrmAddCertificate.Create(self) do try LicensingService := srvLicense; if ShowModal = mrOK then begin if not srvProperties.Active then srvProperties.Active := True; ShowLicense; end; finally Free; end; end; procedure TfrmAdminTool.ShowLicense; var counter : Integer; begin try lstCertificates.Items.Clear; lblCertificate.Caption := ''; if not srvProperties.Active then srvProperties.Active := true; //if there are no licenses, FetchLiceses fails and causes active to be false srvProperties.FetchLicenseInfo; with lstCertificates.Items do begin for counter:= 0 to High(srvProperties.LicenseInfo.Key) do with Add do begin Caption := srvProperties.LicenseInfo.ID[counter]; SubItems.Add(srvProperties.LicenseInfo.Key[counter]); end; end; lstCertificates.Items.Item[0].Selected := True; lstCertificates.itemfocused := lstCertificates.Items.Item[0]; except lblCertificate.Caption := 'Cannot get licensing info for current server'; end; end; procedure TfrmAdminTool.RemoveCertificateExecute(Sender: TObject); begin with srvLicense do begin Key := lstCertificates.Items.Item[lstCertificates.Selected.Index].SubItems[0]; RemoveLicense; ShowLicense; end; end; procedure TfrmAdminTool.sgFilesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); const INDENT = 2; var lLeft: integer; lText: string; SGrid : TStringGrid; begin SGrid := Sender as TStringGrid; with SGrid.canvas do begin if (ACol = 2) and (ARow <> 0) then begin font.color := clBlack; if brush.color = clHighlight then font.color := clWhite; lText := SGrid.Cells[ACol,ARow]; lLeft := Rect.Left + INDENT; TextRect(Rect, lLeft, Rect.top + INDENT, lText); end; end; end; procedure TfrmAdminTool.sgFilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var lKey : Word; SGrid : TStringGrid; begin SGrid := Sender as TStringGrid; if (Key = VK_TAB) and (ssCtrl in Shift) then begin if SGrid.Col < sgBackupFiles.ColCount - 1 then begin SGrid.Col := sgBackupFiles.Col + 1; end else begin if SGrid.Row = SGrid.RowCount - 1 then SGrid.RowCount := SGrid.RowCount + 1; SGrid.Col := 0; SGrid.Row := SGrid.Row + 1; end; end; if (Key = VK_RETURN) and (SGrid.Cells[SGrid.Col,SGrid.Row] <> '') then begin lKey := VK_TAB; sgFilesKeyDown(Self, lKey, [ssCtrl]); end; end; procedure TfrmAdminTool.sgBackupOptionsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); const INDENT = 2; var lLeft: integer; lText: string; begin with (Sender as TStringGrid).canvas do begin if ACol = OPTION_VALUE_COL then begin font.color := clBlue; if brush.color = clHighlight then font.color := clWhite; lText := (Sender as TStringGrid).Cells[ACol,ARow]; lLeft := Rect.Left + INDENT; TextRect(Rect, lLeft, Rect.top + INDENT, lText); end; end; end; procedure TfrmAdminTool.sgBackupOptionsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin cbBackupOptions.Items.Clear; case ARow of FORMAT_ROW: begin cbBackupOptions.Items.Add('Transportable'); cbBackupOptions.Items.Add('Non-Transportable'); end; METADATA_ONLY_ROW, GARBAGE_COLLECTION_ROW, CONVERT_TO_TABLES_ROW: begin cbBackupOptions.Items.Add('True'); cbBackupOptions.Items.Add('False'); end; TRANSACTIONS_IN_LIMBO_ROW, CHECKSUMS_ROW: begin cbBackupOptions.Items.Add('Process'); cbBackupOptions.Items.Add('Ignore'); end; VERBOSE_OUTPUT_ROW: begin cbBackupOptions.Items.Add('None'); cbBackupOptions.Items.Add('To Screen'); end; end; UpdateOptions(sgBackupOptions, pnlBackupOption, cbBackupOptions, ACol, ARow); end; procedure TfrmAdminTool.BackupExecute(Sender: TObject); var j: integer; lOptions: TBackupOptions; frmVerbose : TfrmVerbose; begin Screen.Cursor := crHourGlass; try srvBackup.Attach(); lOptions := []; if srvBackup.Active = true then begin if sgBackupOptions.Cells[OPTION_VALUE_COL,FORMAT_ROW] = 'Non-Transportable' then begin Include(lOptions, NonTransportable); end; if sgBackupOptions.Cells[OPTION_VALUE_COL,METADATA_ONLY_ROW] = 'True' then begin Include(lOptions, MetadataOnly); end; if sgBackupOptions.Cells[OPTION_VALUE_COL,GARBAGE_COLLECTION_ROW] = 'False' then begin Include(lOptions, NoGarbageCollection); end; if sgBackupOptions.Cells[OPTION_VALUE_COL,TRANSACTIONS_IN_LIMBO_ROW] = 'Ignore' then begin Include(lOptions, IgnoreLimbo); end; if sgBackupOptions.Cells[OPTION_VALUE_COL,CHECKSUMS_ROW] = 'True' then begin Include(lOptions, IgnoreChecksums); end; if sgBackupOptions.Cells[OPTION_VALUE_COL,CONVERT_TO_TABLES_ROW] = 'True' then begin Include(lOptions, ConvertExtTables); end; srvBackup.Options := lOptions; if (sgBackupOptions.Cells[OPTION_VALUE_COL,VERBOSE_OUTPUT_ROW] = 'To Screen') or (sgBackupOptions.Cells[OPTION_VALUE_COL,VERBOSE_OUTPUT_ROW] = 'To File') then begin srvBackup.Verbose := true; end; for j := 1 to sgBackupFiles.RowCount - 1 do begin if (sgBackupFiles.Cells[0,j] <> '') and (sgBackupFiles.Cells[1,j] <> '') then begin srvBackup.BackupFile.Add(Format('%s=%s',[sgBackupFiles.Cells[0,j], sgBackupFiles.Cells[1,j]])); end else if (sgBackupFiles.Cells[0,j] <> '') then begin srvBackup.BackupFile.Add(sgBackupFiles.Cells[0,j]); end; end; srvBackup.DatabaseName := edtBackupName.Text; srvBackup.ServiceStart; if srvBackup.Verbose then begin frmVerbose := TfrmVerbose.Create(self); frmVerbose.Show; while not srvBackup.Eof do begin Application.ProcessMessages; frmVerbose.edOutput.Lines.Add(srvBackup.GetNextLine) end; end else while srvBackup.IsServiceRunning do begin Application.ProcessMessages; end; end; finally if srvBackup.Active then srvBackup.Detach(); Screen.Cursor := crDefault; end; end; procedure TfrmAdminTool.btnDatabaseLookupClick(Sender: TObject); begin dlgBackupRestore.Options := [ofHideReadOnly, ofNoNetworkButton, ofEnableSizing]; dlgBackupRestore.DefaultExt := '*.gdb'; dlgBackupRestore.Filter := '(*.gdb) InterBase Database|*.gdb|(*.*) All Files|*.*'; if dlgBackupRestore.Execute then edtBackupName.Text := dlgBackupRestore.FileName; end; procedure TfrmAdminTool.sgRestoreFilesDblClick(Sender: TObject); var i : integer; begin If srvBackup.Protocol <> LOCAL then begin ShowMessage('Can Only broswe local machine'); Exit; end; dlgBackupRestore.Options := [ofHideReadOnly, ofNoNetworkButton, ofEnableSizing, ofAllowMultiSelect, ofFileMustExist]; dlgBackupRestore.Filter := 'Backup files (*.gbk)|*.gbk|All files (*.*)|*.*'; dlgBackupRestore.FilterIndex := 1; if dlgBackupRestore.Execute then begin if sgRestoreFiles.RowCount < dlgBackupRestore.Files.Count then sgRestoreFiles.RowCount := dlgBackupRestore.Files.Count; for i:= 0 to dlgBackupRestore.Files.Count - 1 do sgRestoreFiles.Cells[0, i+1] := dlgBackupRestore.Files.Strings[i]; end; end; procedure TfrmAdminTool.SetupRestoreTab; begin sgRestoreFiles.Cells[0,0] := 'Filename(s)'; sgRestore.Cells[0,0] := 'Filename(s)'; sgRestore.Cells[1,0] := 'Pages'; sgRestoreOptions.RowCount := 8; sgRestoreOptions.Cells[OPTION_NAME_COL,PAGE_SIZE_ROW] := 'Page Size (Bytes)'; sgRestoreOptions.Cells[OPTION_VALUE_COL,PAGE_SIZE_ROW] := '4096'; sgRestoreOptions.Cells[OPTION_NAME_COL,OVERWRITE_ROW] := 'Overwrite'; sgRestoreOptions.Cells[OPTION_VALUE_COL,OVERWRITE_ROW] := 'False'; sgRestoreOptions.Cells[OPTION_NAME_COL,COMMIT_EACH_TABLE_ROW] := 'Commit After Each Table'; sgRestoreOptions.Cells[OPTION_VALUE_COL,COMMIT_EACH_TABLE_ROW] := 'False'; sgRestoreOptions.Cells[OPTION_NAME_COL,CREATE_SHADOW_FILES_ROW] := 'Create Shadow Files'; sgRestoreOptions.Cells[OPTION_VALUE_COL,CREATE_SHADOW_FILES_ROW] := 'True'; sgRestoreOptions.Cells[OPTION_NAME_COL,DEACTIVATE_INDICES_ROW] := 'Deactivate Indices'; sgRestoreOptions.Cells[OPTION_VALUE_COL,DEACTIVATE_INDICES_ROW] := 'False'; sgRestoreOptions.Cells[OPTION_NAME_COL,VALIDITY_CONDITIONS_ROW] := 'Validity Conditions'; sgRestoreOptions.Cells[OPTION_VALUE_COL,VALIDITY_CONDITIONS_ROW] := 'Restore'; sgRestoreOptions.Cells[OPTION_NAME_COL,USE_ALL_SPACE_ROW] := 'Use All Space'; sgRestoreOptions.Cells[OPTION_VALUE_COL,USE_ALL_SPACE_ROW] := 'False'; sgRestoreOptions.Cells[OPTION_NAME_COL,VERBOSE_OUTPUT_ROW] := 'Verbose Output'; sgRestoreOptions.Cells[OPTION_VALUE_COL,VERBOSE_OUTPUT_ROW] := 'To Screen'; pnlRestoreOptionName.Caption := 'Page Size (Bytes)'; cbRestoreOptions.Items.Add('1024'); cbRestoreOptions.Items.Add('2048'); cbRestoreOptions.Items.Add('4096'); cbRestoreOptions.Items.Add('8192'); cbRestoreOptions.ItemIndex := 2; end; procedure TfrmAdminTool.SetupBackupTab; begin sgBackupOptions.DefaultRowHeight := cbBackupOptions.Height; sgBackupFiles.Cells[0,0] := 'Filename(s)'; sgBackupFiles.Cells[1,0] := 'Size(Bytes)'; sgBackupOptions.Cells[OPTION_NAME_COL,FORMAT_ROW] := 'Format'; sgBackupOptions.Cells[OPTION_VALUE_COL,FORMAT_ROW] := 'Transportable'; sgBackupOptions.Cells[OPTION_NAME_COL,METADATA_ONLY_ROW] := 'Metadata Only'; sgBackupOptions.Cells[OPTION_VALUE_COL,METADATA_ONLY_ROW] := 'False'; sgBackupOptions.Cells[OPTION_NAME_COL,GARBAGE_COLLECTION_ROW] := 'Garbage Collection'; sgBackupOptions.Cells[OPTION_VALUE_COL,GARBAGE_COLLECTION_ROW] := 'True'; sgBackupOptions.Cells[OPTION_NAME_COL,TRANSACTIONS_IN_LIMBO_ROW] := 'Transactions in Limbo'; sgBackupOptions.Cells[OPTION_VALUE_COL,TRANSACTIONS_IN_LIMBO_ROW] := 'Process'; sgBackupOptions.Cells[OPTION_NAME_COL,CHECKSUMS_ROW] := 'Checksums'; sgBackupOptions.Cells[OPTION_VALUE_COL,CHECKSUMS_ROW] := 'Process'; sgBackupOptions.Cells[OPTION_NAME_COL,CONVERT_TO_TABLES_ROW] := 'Convert to Tables'; sgBackupOptions.Cells[OPTION_VALUE_COL,CONVERT_TO_TABLES_ROW] := 'False'; sgBackupOptions.Cells[OPTION_NAME_COL,VERBOSE_OUTPUT_ROW] := 'Verbose Output'; sgBackupOptions.Cells[OPTION_VALUE_COL,VERBOSE_OUTPUT_ROW] := 'To Screen'; pnlBackupOption.Caption := 'Format'; cbBackupOptions.Items.Add('Transportable'); cbBackupOptions.Items.Add('Non-Transportable'); cbBackupOptions.ItemIndex := 0; end; procedure TfrmAdminTool.sgRestoreOptionsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin cbRestoreOptions.Items.Clear; case ARow of PAGE_SIZE_ROW: begin cbRestoreOptions.Items.Add('1024'); cbRestoreOptions.Items.Add('2048'); cbRestoreOptions.Items.Add('4096'); cbRestoreOptions.Items.Add('8192'); end; OVERWRITE_ROW, COMMIT_EACH_TABLE_ROW, CREATE_SHADOW_FILES_ROW, DEACTIVATE_INDICES_ROW, USE_ALL_SPACE_ROW: begin cbRestoreOptions.Items.Add('True'); cbRestoreOptions.Items.Add('False'); end; VALIDITY_CONDITIONS_ROW: begin cbRestoreOptions.Items.Add('Restore'); cbRestoreOptions.Items.Add('Ignore'); end; VERBOSE_OUTPUT_ROW: begin cbRestoreOptions.Items.Add('None'); cbRestoreOptions.Items.Add('To Screen'); end; end; UpdateOptions(sgRestoreOptions, pnlRestoreOptionName, cbRestoreOptions, ACol, ARow); end; procedure TfrmAdminTool.RestoreExecute(Sender: TObject); var j: integer; lOptions: TRestoreOptions; frmVerbose : TfrmVerbose; begin Screen.Cursor := crHourglass; try lOptions := []; srvRestore.Attach; if srvRestore.Active = true then begin if sgRestoreOptions.Cells[OPTION_VALUE_COL,OVERWRITE_ROW] = 'True' then Include(lOptions, Replace) else Include(lOptions, CreateNewDB); if sgRestoreOptions.Cells[OPTION_VALUE_COL,COMMIT_EACH_TABLE_ROW] = 'True' then Include(lOptions, OneRelationAtATime); if sgRestoreOptions.Cells[OPTION_VALUE_COL,CREATE_SHADOW_FILES_ROW] = 'False' then Include(lOptions, NoShadow); if sgRestoreOptions.Cells[OPTION_VALUE_COL,DEACTIVATE_INDICES_ROW] = 'True' then Include(lOptions, DeactivateIndexes); if sgRestoreOptions.Cells[OPTION_VALUE_COL,VALIDITY_CONDITIONS_ROW] = 'False' then Include(lOptions, NoValidityCheck); srvRestore.Options := lOptions; srvRestore.PageSize := StrToInt(sgRestoreOptions.Cells[OPTION_VALUE_COL,PAGE_SIZE_ROW]); if (sgRestoreOptions.Cells[OPTION_VALUE_COL,VERBOSE_OUTPUT_ROW] = 'To Screen') or (sgRestoreOptions.Cells[OPTION_VALUE_COL,VERBOSE_OUTPUT_ROW] = 'To File') then srvRestore.Verbose := true; for j := 1 to sgRestoreFiles.RowCount - 1 do if sgRestoreFiles.Cells[0,j] <> '' then srvRestore.BackupFile.Add(Format('%s',[sgRestoreFiles.Cells[0,j]])); for j := 1 to sgRestore.RowCount - 1 do begin if (sgRestore.Cells[0,j] <> '') and (sgRestore.Cells[1,j] <> '')then srvRestore.DatabaseName.Add(Format('%s=%s',[sgRestore.Cells[0,j],sgRestore.Cells[1,j]])) else srvRestore.DatabaseName.Add(sgRestore.Cells[0,j]); end; srvRestore.ServiceStart; if srvRestore.Verbose then begin frmVerbose := TfrmVerbose.Create(self); frmVerbose.Show; while not srvRestore.Eof do begin Application.ProcessMessages; frmVerbose.edOutput.Lines.Add(srvRestore.GetNextLine) end; end else while srvRestore.IsServiceRunning do begin Application.ProcessMessages; end; end; finally if srvRestore.Active then srvRestore.Detach(); Screen.Cursor := crDefault; end; end; procedure TfrmAdminTool.SetupValidateTab; begin sgValidateOptions.Cells[OPTION_NAME_COL,VALIDATE_RECORD_FRAGMENTS_ROW] := 'Validate Record Fragments'; sgValidateOptions.Cells[OPTION_VALUE_COL,VALIDATE_RECORD_FRAGMENTS_ROW] := 'False'; sgValidateOptions.Cells[OPTION_NAME_COL,READ_ONLY_VALIDATION_ROW] := 'Read Only Validation'; sgValidateOptions.Cells[OPTION_VALUE_COL,READ_ONLY_VALIDATION_ROW] := 'False'; sgValidateOptions.Cells[OPTION_NAME_COL,IGNORE_CHECKSUM_ERRORS_ROW] := 'Ignore Checksum Errors'; sgValidateOptions.Cells[OPTION_VALUE_COL,IGNORE_CHECKSUM_ERRORS_ROW] := 'False'; pnlValidate.Caption := 'Validate Record Fragments'; cbValidateOptions.Items.Add('True'); cbValidateOptions.Items.Add('False'); cbValidateOptions.ItemIndex := 1; end; procedure TfrmAdminTool.sgValidateOptionsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin UpdateOptions(sgValidateOptions, pnlValidate, cbValidateOptions, ACol, ARow); end; procedure TfrmAdminTool.UpdateOptions(const Grid: TStringGrid; const Panel: TPanel; const Combo: TComboBox; const ACol, ARow: Integer); var lR, lName : TRect; begin Panel.Caption := Grid.Cells[OPTION_NAME_COL, ARow]; if ACol = OPTION_NAME_COL then Combo.ItemIndex := Combo.Items.IndexOf(Grid.Cells[ACol+1,ARow]) else if ACol = OPTION_VALUE_COL then Combo.ItemIndex := Combo.Items.IndexOf(Grid.Cells[ACol,ARow]); Combo.Tag := ARow; if ACol = OPTION_NAME_COL then begin lName := Grid.CellRect(ACol, ARow); lR := Grid.CellRect(ACol + 1, ARow); end else begin lName := Grid.CellRect(ACol - 1, ARow); lR := Grid.CellRect(ACol, ARow); end; // lName := sgOptions.CellRect(ACol, ARow); lName.Left := lName.Left + Grid.Left; lName.Right := lName.Right + Grid.Left; lName.Top := lName.Top + Grid.Top; lName.Bottom := lName.Bottom + Grid.Top; Panel.Left := lName.Left + 1; Panel.Top := lName.Top + 1; Panel.Width := (lName.Right + 1) - lName.Left; Panel.Height := (lName.Bottom + 1) - lName.Top; // lR := sgOptions.CellRect(ACol, ARow); lR.Left := lR.Left + Grid.Left; lR.Right := lR.Right + Grid.Left; lR.Top := lR.Top + Grid.Top; lR.Bottom := lR.Bottom + Grid.Top; Combo.Left := lR.Left + 1; Combo.Top := lR.Top + 1; Combo.Width := (lR.Right + 1) - lR.Left; Combo.Height := (lR.Bottom + 1) - lR.Top; Combo.SetFocus; end; procedure TfrmAdminTool.ValidateExecute(Sender: TObject); var lValidateOptions : TValidateOptions; frmVerbose : TfrmVerbose; begin lValidateOptions := []; Screen.Cursor := crHourGlass; try srvValidate.Attach; // if successfully attached to server if srvValidate.Active = true then begin case srvValidate.Protocol of TCP : srvValidate.DatabaseName := Format('%s:%s',[srvValidate.ServerName,edtValidate.Text]); NamedPipe : srvValidate.DatabaseName := Format('\\%s\%s',[srvValidate.ServerName,edtValidate.Text]); SPX : srvValidate.DatabaseName := Format('%s@%s',[srvValidate.ServerName,edtValidate.Text]); Local : srvValidate.DatabaseName := edtValidate.Text; end; // determine which options have been selected Include (lValidateOptions, ValidateDB); if sgValidateOptions.Cells[1,VALIDATE_RECORD_FRAGMENTS_ROW] = 'True' then Include(lValidateOptions, ValidateFull); if sgValidateOptions.Cells[1,READ_ONLY_VALIDATION_ROW] = 'True' then Include(lValidateOptions, CheckDB); if sgValidateOptions.Cells[1,IGNORE_CHECKSUM_ERRORS_ROW] = 'True' then Include(lValidateOptions, IgnoreChecksum); srvValidate.Options := lValidateOptions; srvValidate.ServiceStart; Application.ProcessMessages; frmVerbose := TfrmVerbose.Create(self); frmVerbose.Show; frmVerbose.edOutput.Lines.Add('Database - ' + edtValidate.Text); while not srvValidate.Eof do begin Application.ProcessMessages; frmVerbose.edOutput.Lines.Add(Trim(srvValidate.GetNextLine)); end; if frmVerbose.edOutput.Lines.Count = 2 then frmVerbose.edOutput.Lines.Add('No database validation errors were found.'); end; finally Screen.Cursor := crDefault; if srvValidate.Active then srvValidate.Detach(); end; end; procedure TfrmAdminTool.ValidateUpdate(Sender: TObject); begin TAction(Sender).Enabled := (edtValidate.Text <> '') and LoggedIn; end; procedure TfrmAdminTool.SetupStats; begin sgStats.DefaultRowHeight := cbStats.Height; sgStats.RowCount := 1; sgStats.Cells[OPTION_NAME_COL,STATISTICS_OPTION_ROW] := 'Show data for:'; sgStats.Cells[OPTION_VALUE_COL,STATISTICS_OPTION_ROW] := 'All Options'; pnlStats.Caption := 'Show data for:'; cbStats.Items.Add('All Options'); cbStats.Items.Add('Data Pages'); cbStats.Items.Add('Database Log'); cbStats.Items.Add('Header Page'); cbStats.Items.Add('Index Pages'); cbStats.Items.Add('System Relations'); cbStats.ItemIndex := 0; end; procedure TfrmAdminTool.StatisticsExecute(Sender: TObject); var lDBStatisticsOptions: TStatOptions; frmVerbose : TfrmVerbose; begin Screen.Cursor := crHourGlass; srvStats.Attach; try // if successfully attached to server if srvStats.Active = true then begin // assign database details srvStats.DatabaseName := edtStatistics.Text; lDBStatisticsOptions := []; // determine which options have been selected case cbStats.ItemIndex of 1: Include(lDBStatisticsOptions, DataPages); 2: Include(lDBStatisticsOptions, DbLog); 3: Include(lDBStatisticsOptions, HeaderPages); 4: Include(lDBStatisticsOptions, IndexPages); 5: Include(lDBStatisticsOptions, SystemRelations); end; // assign validation options srvStats.Options := lDBStatisticsOptions; srvStats.ServiceStart; frmVerbose := TfrmVerbose.Create(self); frmVerbose.Show; frmVerbose.edOutput.Lines.Add('Database Stats - ' + edtStatistics.Text); while not srvStats.Eof do begin Application.ProcessMessages; frmVerbose.edOutput.Lines.Add(Trim(srvStats.GetNextLine)); end; frmVerbose.edOutput.Lines.Add('Done'); end; finally Screen.Cursor := crDefault; if srvStats.Active then srvStats.Detach(); end; end; procedure TfrmAdminTool.LookupUpdate(Sender: TObject); begin TAction(Sender).Enabled := (edtProperties.Text <> '') and LoggedIn; end; procedure TfrmAdminTool.SetupProperties; begin sgProperties.Cells[OPTION_NAME_COL,FORCED_WRITES_ROW] := 'Forced Writes'; pnlProperties.Caption := sgProperties.Cells[OPTION_NAME_COL,FORCED_WRITES_ROW]; sgProperties.Cells[OPTION_NAME_COL,SWEEP_INTERVAL_ROW] := 'Sweep Interval'; sgProperties.Cells[OPTION_NAME_COL,SQL_DIALECT_ROW] := 'Database Dialect'; sgProperties.Cells[OPTION_NAME_COL,READ_ONLY_ROW] := 'Read Only'; cbProperties.Items.Add(FORCED_WRITES_TRUE); cbProperties.Items.Add(FORCED_WRITES_FALSE); cbProperties.Tag := FORCED_WRITES_ROW; end; procedure TfrmAdminTool.sgPropertiesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin cbProperties.Items.Clear; case ARow of FORCED_WRITES_ROW: begin cbProperties.Style := csDropDown; cbProperties.Items.Add(FORCED_WRITES_TRUE); cbProperties.Items.Add(FORCED_WRITES_FALSE); cbProperties.Tag := FORCED_WRITES_ROW; end; SWEEP_INTERVAL_ROW: begin cbProperties.Style := csSimple; cbProperties.Text := sgProperties.Cells[OPTION_VALUE_COL,SWEEP_INTERVAL_ROW]; cbProperties.Tag := SWEEP_INTERVAL_ROW; end; READ_ONLY_ROW: begin cbProperties.Style := csDropDown; cbProperties.Items.Add(READ_ONLY_TRUE); cbProperties.Items.Add(READ_ONLY_FALSE); cbProperties.Tag := READ_ONLY_ROW; end; SQL_DIALECT_ROW: begin cbProperties.Style := csDropDown; cbProperties.Items.Add(SQL_DIALECT1); cbProperties.Items.Add(SQL_DIALECT2); cbProperties.Items.Add(SQL_DIALECT3); if Lookup.Enabled then cbProperties.ItemIndex := StrToInt(sgProperties.Cells[OPTION_VALUE_COL,SQL_DIALECT_ROW])-1; cbProperties.Tag := SQL_DIALECT_ROW; end; end; UpdateOptions(sgProperties, pnlProperties, cbProperties, ACol, ARow); end; procedure TfrmAdminTool.cbPropertiesChange(Sender: TObject); begin Apply.Enabled := true; end; procedure TfrmAdminTool.LookupExecute(Sender: TObject); var lListItem: TListItem; dummy : Boolean; begin case srvConfig.Protocol of TCP : dbProperties.DatabaseName := Format('%s:%s',[srvConfig.ServerName,edtProperties.Text]); NamedPipe : dbProperties.DatabaseName := Format('\\%s\%s',[srvConfig.ServerName,edtProperties.Text]); SPX : dbProperties.DatabaseName := Format('%s@%s',[srvConfig.ServerName,edtProperties.Text]); Local : dbProperties.DatabaseName := edtProperties.Text; end; srvConfig.DatabaseName := edtProperties.Text; dbProperties.Params.Clear; dbProperties.Params.Assign(srvConfig.Params); dbProperties.Connected := true; trProperties.StartTransaction; stxPageSize.Caption := IntToStr(infoDB.PageSize); // get page size from ib info object stxDBPages.Caption := IntToStr(infoDB.Allocation); // get number of pages allocated sgProperties.Cells[OPTION_VALUE_COL,SWEEP_INTERVAL_ROW] := IntToStr(infoDB.SweepInterval); if infoDB.ForcedWrites <> 0 then // True sgProperties.Cells[OPTION_VALUE_COL,FORCED_WRITES_ROW] := FORCED_WRITES_TRUE else // False sgProperties.Cells[OPTION_VALUE_COL,FORCED_WRITES_ROW] := FORCED_WRITES_FALSE; if infoDB.ReadOnly <> 0 then // True sgProperties.Cells[OPTION_VALUE_COL,READ_ONLY_ROW] := READ_ONLY_TRUE else // False sgProperties.Cells[OPTION_VALUE_COL,READ_ONLY_ROW] := READ_ONLY_FALSE; sgProperties.Cells[OPTION_VALUE_COL,SQL_DIALECT_ROW] := IntToStr(infoDB.DBSQLDialect); sqlFiles.ExecQuery; while not sqlFiles.Eof do begin lListItem := lvSecondaryFiles.Items.Add; lListItem.Caption := sqlFiles.Fields[0].AsString; lListItem.SubItems.Add(sqlFiles.Fields[1].AsString); sqlFiles.Next; end; sqlFiles.Close; sqlOwner.ExecQuery; stxDBOwner.Caption := sqlOwner.Fields[0].AsString; sqlOwner.Close; trProperties.Commit; dbProperties.Close; sgPropertiesSelectCell(sgProperties, 1, cbProperties.Tag, Dummy); end; procedure TfrmAdminTool.ApplyExecute(Sender: TObject); var FW, RO, SW, SD : Integer; begin Screen.Cursor := crHourGlass; try srvConfig.Attach(); dbProperties.Connected := true; FW := infoDB.ForcedWrites; RO := infoDB.ReadOnly; SW := infoDB.SweepInterval; SD := infoDB.DBSQLDialect; dbProperties.Connected := false; if srvConfig.Active then // if attached successfully begin if (sgProperties.Cells[OPTION_VALUE_COL,READ_ONLY_ROW] = READ_ONLY_FALSE) and (RO = 1) then srvConfig.SetReadOnly(False) else if (sgProperties.Cells[OPTION_VALUE_COL,READ_ONLY_ROW] = READ_ONLY_TRUE) and (RO = 0) then srvConfig.SetReadOnly(true); while srvConfig.IsServiceRunning do Application.ProcessMessages; // Set sweep interval if changed if StrToInt(sgProperties.Cells[OPTION_VALUE_COL,SWEEP_INTERVAL_ROW]) <> SW then begin srvConfig.SetSweepInterval(StrToInt(sgProperties.Cells[OPTION_VALUE_COL,SWEEP_INTERVAL_ROW])); while srvConfig.IsServiceRunning do Application.ProcessMessages; end; // Set SQL Dialect if changed if StrToInt(sgProperties.Cells[OPTION_VALUE_COL,SQL_DIALECT_ROW]) <> SD then begin srvConfig.SetDBSqlDialect(StrToInt(sgProperties.Cells[OPTION_VALUE_COL,SQL_DIALECT_ROW])); while srvConfig.IsServiceRunning do Application.ProcessMessages; end; // Set forced writes if changed if (sgProperties.Cells[OPTION_VALUE_COL,FORCED_WRITES_ROW] = FORCED_WRITES_TRUE) and (FW = 0) then srvConfig.SetAsyncMode(false) else if (sgProperties.Cells[OPTION_VALUE_COL,FORCED_WRITES_ROW] = FORCED_WRITES_FALSE) and (FW = 1) then srvConfig.SetAsyncMode(true); while srvConfig.IsServiceRunning do Application.ProcessMessages; end; Apply.Enabled := false; finally if srvConfig.Active then srvConfig.Detach(); Screen.Cursor := crDefault; end; end; procedure TfrmAdminTool.cbPropertiesExit(Sender: TObject); begin sgProperties.Cells[OPTION_VALUE_COL,cbProperties.Tag] := cbProperties.Text; end; procedure TfrmAdminTool.cbStatsExit(Sender: TObject); begin sgStats.Cells[OPTION_VALUE_COL,0] := cbStats.Text; end; procedure TfrmAdminTool.cbValidateOptionsExit(Sender: TObject); begin sgValidateOptions.Cells[OPTION_VALUE_COL,cbValidateOptions.Tag] := cbValidateOptions.Text; end; procedure TfrmAdminTool.cbRestoreOptionsExit(Sender: TObject); begin sgRestoreOptions.Cells[OPTION_VALUE_COL,cbRestoreOptions.Tag] := cbRestoreOptions.Text; end; procedure TfrmAdminTool.cbBackupOptionsExit(Sender: TObject); begin sgBackupOptions.Cells[OPTION_VALUE_COL,cbBackupOptions.Tag] := cbBackupOptions.Text; end; procedure TfrmAdminTool.StatisticsUpdate(Sender: TObject); begin TAction(Sender).Enabled := (edtStatistics.Text <> '') and LoggedIn; end; end.
unit UnitTask; {$mode objfpc}{$H+} interface const TMAX = 2137; type Task = record id : LongInt; // identyfikator ExecutionTime : LongInt; // czas wykonania AvailabilityTime : LongInt; // minimalny czas dostępności (algorytm go uzupełni) CommenceTime : LongInt; // czas faktyczny wykonania (j.w.) AssignedMachine : LongInt; // przypisana maszyna (j.w.) ArrivalTime : LongInt; FinishTime : LongInt; DueDate : LongInt; ModifiedDueDate : LongInt; GraphPosX : LongInt; GraphPosY : LongInt; PrevTasks : array of LongInt; // wymagane taski NextTasks : array of LongInt; // taski wychodzące Visited : Boolean; // używane do sprawdzania cyklicznosci i do sygnalizowania przerwań RowID : LongInt; ReadyToGo : LongInt; // sygnał ten daje możliwość wystartowania, jak wszystkie wymagane taski zostały wykonane (wtedy musi być równy 0, jak >0 to jeszcze są jakieś taski do wykonania) end; type TaskDB = record Content : array of Task; MachinesCount : LongInt; HasCycles : Boolean; Latency : LongInt; end; type TTasks = array of Task; type TLongInts = array of LongInt; function loadDBFromFile(filename : String) : TaskDB; procedure printDBContent(db : TaskDB); procedure dropDB(var db : TaskDB); function applyCPM(var db : TaskDB) : LongInt; function applyLiu(var db : TaskDB) : LongInt; procedure drawSchedule(db : TaskDB; maxl : LongInt; filename : String); procedure drawGraph(db : TaskDB; filename : String); implementation uses Classes, SysUtils, Math; // ========== Utils function table_min(tab : TLongInts) : LongInt; var i : LongInt; s : LongInt; begin s := tab[0]; for i := 1 to Length(tab)-1 do if (tab[i] < s) then s := tab[i]; table_min := s; end; function table_max(tab : TLongInts) : LongInt; var i : LongInt; s : LongInt; begin s := tab[0]; for i := 1 to Length(tab)-1 do if (tab[i] > s) then s := tab[i]; table_max := s; end; function table_empty(tab : TLongInts) : Boolean; var i : LongInt; s : Boolean; begin s := true; for i := 0 to Length(tab)-1 do if (tab[i] <> -1) then s := false; table_empty := s; end; function max2(x, y : LongInt) : LongInt; begin if (x > y) then max2 := x else max2 := y; end; // ========== DB Management function buildTask(id, execution_time, arrival_time, due_date : LongInt) : Task; var pom : Task; begin pom.id := id; pom.ExecutionTime := execution_time; pom.AvailabilityTime := -1; pom.ArrivalTime := arrival_time; pom.CommenceTime := -1; pom.AssignedMachine := -2; pom.DueDate := due_date; pom.ModifiedDueDate := TMAX; pom.GraphPosX := -1; pom.GraphPosY := -1; SetLength(pom.PrevTasks, 0); SetLength(pom.NextTasks, 0); pom.Visited := false; pom.RowID := -1; pom.FinishTime := -1; pom.ReadyToGo := 0; buildTask := pom; end; procedure addDependency(var destination : Task; var origin : Task); var i, j : LongInt; begin i := Length(destination.PrevTasks); j := Length(origin.NextTasks); SetLength(destination.PrevTasks, i+1); SetLength(origin.NextTasks, j+1); destination.PrevTasks[i] := origin.id; origin.NextTasks[j] := destination.id; end; function getTaskDBAddress(db : TaskDB; id : LongInt) : LongInt; var found : Boolean; index : LongInt; i : Task; begin found := false; index := Length(db.Content)-1; while index >= 0 do begin if (db.Content[index].id = id) then begin found := true; break; end; Dec(index); end; if not (found) then getTaskDBAddress := -1 else getTaskDBAddress := index; end; function getTaskByID(db : TaskDB; id : LongInt) : Task; begin getTaskByID := db.Content[getTaskDBAddress(db, id)]; end; function getAllSubTasks(db : TaskDB; id : LongInt) : TTasks; var pom : TTasks; j : LongInt; tl : Task; begin j := 0; for tl in db.Content do begin if (id = tl.id) then begin SetLength(pom, j+1); pom[j] := tl; Inc(j); end; end; getAllSubTasks := pom; end; procedure replaceTaskByID(var db : TaskDB; newtask : Task); begin db.Content[getTaskDBAddress(db, newtask.id)] := newtask; end; function setTasks(filename : String) : TaskDB; var db : TaskDB; pom : array of Task; fp : Text; L : TStrings; line : String; i : LongInt; begin i := 0; SetLength(pom, i); assignfile(fp, filename); reset(fp); L := TStringlist.Create; L.Delimiter := ' '; L.StrictDelimiter := false; while not eof(fp) do begin readln(fp, line); L.DelimitedText := line; if (L[0] = 'add') and (L[1] = 'task') and (L[3] = 'that') and (L[4] = 'lasts') and (L[6] = 'arrives') and (L[7] = 'at') and (L[9] = 'and') and (L[10] = 'is') and (L[11] = 'expected') and (L[12] = 'at') then begin SetLength(pom, i+1); pom[i] := buildTask(StrToInt(L[2]), StrToInt(L[5]), StrToInt(L[8]), StrToInt(L[13])); pom[i].ReadyToGo := 0; pom[i].RowID := i; pom[i].FinishTime := -1; Inc(i); end; end; L.Free; closefile(fp); db.Content := pom; db.MachinesCount := 1; db.Latency := 0; SetLength(pom, 0); setTasks := db; end; procedure buildDependencies(var db : TaskDB; filename : String); var fp : Text; L : TStrings; line : String; destination : Task; origin : Task; begin assignfile(fp, filename); reset(fp); L := TStringlist.Create; L.Delimiter := ' '; L.StrictDelimiter := false; while not eof(fp) do begin readln(fp, line); L.DelimitedText := line; if (L[0] = 'make') and (L[1] = 'task') and (L[3] = 'dependent') and (L[4] = 'on') and (L[5] = 'task') then begin destination := getTaskByID(db, StrToInt(L[2])); origin := getTaskByID(db, StrToInt(L[6])); addDependency(destination, origin); Inc(destination.ReadyToGo); replaceTaskByID(db, destination); replaceTaskByID(db, origin); end; end; L.Free; closefile(fp); end; function allVisited(db : TaskDB) : Boolean; var tk : Task; s : Boolean; begin s := true; for tk in db.Content do if not (tk.Visited) then s := false; allVisited := s; end; function table_allVisited(db : TTasks) : Boolean; var tk : Task; s : Boolean; begin s := true; for tk in db do if not (tk.Visited) then s := false; table_allVisited := s; end; procedure table_unvisit(var db : TTasks); var i : LongInt; begin for i := 0 to Length(db)-1 do db[i].Visited := false; end; function extractMostUrgent(tab : TTasks) : Task; var pom, tk : Task; begin pom := tab[0]; for tk in tab do if (tk.ModifiedDueDate < pom.ModifiedDueDate) then pom := tk; extractMostUrgent := pom; end; function extractMostUrgentAddr(tab : TTasks) : LongInt; var pom : Task; tk, res : LongInt; begin pom := tab[0]; res := tab[0].RowID; for tk := 1 to Length(tab)-1 do if (tab[tk].ModifiedDueDate < pom.ModifiedDueDate) then res := tab[tk].RowID; extractMostUrgentAddr := res; end; function getAllNextTasks(db : TaskDB; tk : Task) : TTasks; var pom : TTasks; i, j : LongInt; tl : Task; begin SetLength(pom, Length(tk.NextTasks)); j := 0; for i in tk.NextTasks do begin tl := getTaskByID(db, i); pom[j] := tl; j := j + 1; end; getAllNextTasks := pom; end; procedure appendNewTaskToDB(var db : TaskDB; tk : Task); var x : LongInt; begin x := Length(db.Content); SetLength(db.Content, x+1); tk.RowID := x; db.Content[x] := tk; end; function getAvailableTasks(db : TaskDB; ctime : LongInt) : TTasks; var pom : TTasks; j : LongInt; tl : Task; begin j := 0; for tl in db.Content do begin if (tl.AvailabilityTime <= ctime) and (tl.ArrivalTime <= ctime) and (tl.ReadyToGo <= 0) and (not (tl.Visited)) then begin SetLength(pom, j+1); pom[j] := tl; Inc(j); end; end; getAvailableTasks := pom; end; function getAllIDs(db : TaskDB) : TLongInts; var pom : TLongInts; i : Task; j : LongInt; begin SetLength(pom, Length(db.Content)); j := 0; for i in db.Content do begin pom[j] := i.id; j := j + 1; end; getAllIDs := pom; end; function getAllPrevTasks(db : TaskDB; tk : Task) : TTasks; var pom : TTasks; i, j : LongInt; tl : Task; begin SetLength(pom, Length(tk.PrevTasks)); j := 0; for i in tk.PrevTasks do begin tl := getTaskByID(db, i); pom[j] := tl; j := j + 1; end; getAllPrevTasks := pom; end; function hasCycles(var db : TaskDB) : Boolean; var queue : array of Task; lcursor : LongInt; rcursor : LongInt; i, j, k : LongInt; index : LongInt; tk, tl : Task; tks, tls : TTasks; answer : Boolean; begin SetLength(queue, Length(db.Content)); lcursor := 0; rcursor := 0; for i := 0 to Length(db.Content)-1 do if Length(db.Content[i].PrevTasks) = 0 then begin if (rcursor = Length(queue)) then SetLength(queue, rcursor+1); db.Content[i].Visited := true; queue[rcursor] := db.Content[i]; Inc(rcursor); end; while (lcursor < rcursor) or (rcursor = Length(db.Content)-1) do begin tk := queue[lcursor]; Inc(lcursor); tks := getAllNextTasks(db, tk); for tl in tks do begin if (table_allVisited(getAllPrevTasks(db, tl))) then begin index := getTaskDBAddress(db, tl.id); if (rcursor = Length(queue)) then SetLength(queue, rcursor+1); db.Content[index].Visited := true; queue[rcursor] := db.Content[index]; Inc(rcursor); end; end; end; answer := not (allVisited(db)); SetLength(queue, 0); hasCycles := answer; end; function loadDBFromFile(filename : String) : TaskDB; var db : TaskDB; TaskEbx : Task; begin db := setTasks(filename); buildDependencies(db, filename); if (hasCycles(db)) then begin writeln('ERROR: Graph contains cyclic dependencies!'); db.HasCycles := true; end else begin db.HasCycles := false; end; loadDBFromFile := db; end; procedure printDBContent(db : TaskDB); var dep, ava : String; com, ass : String; sch, fin : String; lat : String; tk : Task; i : LongInt; begin for tk in db.Content do begin if (Length(tk.PrevTasks) = 0) then begin dep := ', is independent'; end else begin dep := ', is dependent on ['; for i in tk.PrevTasks do dep := dep + ' ' + IntToStr(i); dep := dep + ' ]' end; if (tk.DueDate = -1) then begin sch := ''; end else begin sch := ', is expected to be finished at '+IntToStr(tk.DueDate); end; if (tk.AvailabilityTime = -1) then begin ava := ''; end else begin if (tk.AvailabilityTime = 0) then ava := ' and begins immediately at best' //if (tk.AvailabilityTime = tk.ExecutionTime) then ava := ' and begins immediately at best' else ava := ' and begins at ' + IntToStr(tk.AvailabilityTime) + ' at best'; end; if (tk.CommenceTime = -1) then begin com := ''; end else begin com := ', but in fact it begins at '+IntToStr(tk.CommenceTime); end; if (tk.FinishTime = -1) then begin fin := ''; lat := ''; end else begin fin := ' and finishes at '+IntToStr(tk.FinishTime); lat := ', so its latency is '+IntToStr(tk.FinishTime-tk.DueDate); end; if (tk.AssignedMachine = -2) then begin ass := ''; end else begin ass := '. This task is assigned to a machine no. '+IntToStr(tk.AssignedMachine); end; writeln('The task ', tk.id, ' lasts ', tk.ExecutionTime, sch, dep, ava, com, fin, lat, ass, '.'); end; end; procedure dropDB(var db : TaskDB); begin SetLength(db.Content, 0); end; // ============ CPM and Schedule Building function findCriticalPath(var db : TaskDB; var tk : Task) : LongInt; var i : LongInt; pom : Task; tab : array of LongInt; s : LongInt; begin SetLength(tab, Length(tk.PrevTasks)); for i := 0 to Length(tk.PrevTasks)-1 do begin pom := getTaskByID(db, tk.PrevTasks[i]); tab[i] := pom.ExecutionTime + pom.AvailabilityTime; end; s := table_max(tab); SetLength(tab, 0); findCriticalPath := s; end; function applyCPM(var db : TaskDB) : LongInt; var i, j : LongInt; tab : array of LongInt; maxs : array of LongInt; begin SetLength(tab, Length(db.Content)); SetLength(maxs, Length(db.Content)); for i := 0 to Length(db.Content)-1 do tab[i] := db.Content[i].id; for i in tab do begin j := getTaskDBAddress(db, i); if Length(db.Content[j].PrevTasks) = 0 then begin db.Content[j].AvailabilityTime := 0; maxs[j] := db.Content[j].ExecutionTime; end else begin db.Content[j].AvailabilityTime := max2(db.Content[j].ArrivalTime, findCriticalPath(db, db.Content[j])); maxs[j] := db.Content[j].ExecutionTime + db.Content[j].AvailabilityTime; end; end; applyCPM := table_max(maxs); end; procedure setModifiedDueDates(var db : TaskDB); var i, j : LongInt; tk : Task; times : TLongInts; begin for i := 0 to Length(db.Content)-1 do begin j := 1; SetLength(times, j); times[0] := db.Content[i].DueDate; for tk in getAllNextTasks(db, db.Content[i]) do begin SetLength(times, j+1); times[j] := tk.DueDate; Inc(j); end; db.Content[i].ModifiedDueDate := table_min(times); SetLength(times, 0); end; end; procedure sortByModifiedDueDate(var tab : TTasks); var i, j : LongInt; pom : Task; begin for j := Length(tab)-1 downto 1 do for i := 0 to j-1 do if (tab[i].ModifiedDueDate > tab[i+1].ModifiedDueDate) then begin pom := tab[i]; tab[i] := tab[i+1]; tab[i+1] := pom; end; //writeln('sorted'); end; procedure setSemaphoreDown(var db : TaskDB; id : Integer); var pom : Task; tk : Task; index : LongInt; begin pom := getTaskByID(db, id); //writeln('before'); //writeln('addr ', getTaskDBAddress(db, id)); //writeln('state ', db.Content[getTaskDBAddress(db, id)].ReadyToGo); //for index in pom.NextTasks do // Dec(db.Content[getTaskDBAddress(db, index)].ReadyToGo); Dec(db.Content[getTaskDBAddress(db, id)].ReadyToGo); //writeln('after'); //writeln('addr ', getTaskDBAddress(db, id)); //writeln('state ', db.Content[getTaskDBAddress(db, id)].ReadyToGo); end; function applyLiu(var db : TaskDB) : LongInt; var criticalpath : LongInt; TimeCursor : LongInt; TaskEax : Task; TaskEbx : Task; IntEax : LongInt; IntEbx : LongInt; Progress : LongInt; latency : LongInt; bonus : LongInt; xd : TLongInts; begin criticalpath := applyCPM(db); //printDBContent(db); latency := -TMAX; table_unvisit(db.Content); setModifiedDueDates(db); //sortByModifiedDueDate(db.Content); TimeCursor := 0; repeat //writeln('time: ', TimeCursor); //for TaskEbx in db.Content do write(' ', TaskEbx.ModifiedDueDate:7); //writeln(); //for TaskEbx in db.Content do write(' ', TaskEbx.Visited:7); //writeln(); //for TaskEbx in db.Content do write(' ', TaskEbx.ReadyToGo:7); //writeln(); if Length(getAvailableTasks(db, TimeCursor)) > 0 then begin IntEax := extractMostUrgentAddr(getAvailableTasks(db, TimeCursor)); //writeln(IntEax); //writeln(db.Content[IntEax].id); db.Content[IntEax].Visited := true; db.Content[IntEax].CommenceTime := TimeCursor; db.Content[IntEax].AssignedMachine := 1; Progress := 1; while (Progress < db.Content[IntEax].ExecutionTime) do begin if Length(getAvailableTasks(db, TimeCursor+Progress)) > 0 then // jeżeli już jest jakiś bardziej pilny task begin IntEbx := extractMostUrgentAddr(getAvailableTasks(db, TimeCursor+Progress)); if (db.Content[IntEbx].ModifiedDueDate < db.Content[IntEax].ModifiedDueDate) and (db.Content[IntEbx].id <> db.Content[IntEax].id) then begin TaskEax := db.Content[IntEax]; TaskEax.AvailabilityTime := TimeCursor+Progress; TaskEax.ArrivalTime := TimeCursor+Progress; TaskEax.ExecutionTime := db.Content[IntEax].ExecutionTime-Progress; TaskEax.Visited := false; appendNewTaskToDB(db, TaskEax); db.Content[IntEax].ExecutionTime := Progress; break; end; end; Inc(Progress); end; if (TimeCursor+Progress-db.Content[IntEax].DueDate > latency) then latency := TimeCursor+Progress-db.Content[IntEax].DueDate; db.Content[IntEax].FinishTime := TimeCursor+Progress; if (table_allVisited(getAllSubTasks(db, db.Content[IntEax].id))) then // jeżeli wszytkie podzadania już zostały odwiedzone i wykonane for IntEbx in db.Content[IntEax].NextTasks do begin //writeln('intebx - ', IntEbx); //writeln('addr - ', getTaskDBAddress(db, IntEbx)); //Dec(db.Content[getTaskDBAddress(db, IntEbx)].ReadyToGo); setSemaphoreDown(db, IntEbx); end; Inc(TimeCursor, Progress); end else begin Inc(TimeCursor); end; until table_allVisited(db.Content); db.Latency := latency; // done applyLiu := TimeCursor; end; // ========== Schedule Generation function buildCPMSchedule(var db : TaskDB; maxl : LongInt; cpucount : LongInt) : LongInt; var sched : array of array of Integer; i, j : LongInt; index, jndex : LongInt; assigned : Boolean; cursor : LongInt; usedcpus : LongInt; s, xsize : LongInt; expanded : Boolean; maxs : array of LongInt; begin SetLength(sched, 0, 0); SetLength(maxs, Length(db.Content)); xsize := maxl; expanded := false; if (cpucount <= 0) then // whether a count of CPUs is unbounded begin //writeln('lots of PCs'); usedcpus := 1; SetLength(sched, usedcpus, maxl); for i := 0 to maxl-1 do sched[usedcpus-1][i] := 0; //writeln('OK'); //for tk in db.Content do for index := 1 to Length(db.Content) do begin //writeln('OK ', index); //writeln('CPUs ', usedcpus); jndex := getTaskDBAddress(db, index); //writeln('Index: ', jndex); assigned := false; cursor := db.Content[jndex].AvailabilityTime; for i := 0 to usedcpus-1 do if (sched[i][cursor] = 0) then begin for j := 0 to db.Content[jndex].ExecutionTime-1 do sched[i][cursor+j] := 1; db.Content[jndex].CommenceTime := cursor; db.Content[jndex].AssignedMachine := i+1; assigned := true; break; end; if not assigned then begin Inc(usedcpus); SetLength(sched, usedcpus, maxl); for i := 0 to maxl-1 do sched[usedcpus-1][i] := 0; for j := 0 to db.Content[jndex].ExecutionTime-1 do sched[usedcpus-1][cursor+j] := 1; db.Content[jndex].CommenceTime := cursor; db.Content[jndex].AssignedMachine := usedcpus; assigned := true; end; end; db.MachinesCount := usedcpus; //writeln('Done'); end else begin // or is fixed SetLength(sched, cpucount, xsize); for i := 0 to cpucount-1 do for j := 0 to maxl-1 do sched[i][j] := 0; //for index := 1 to Length(db.Content) do for index in getAllIDs(db) do begin //writeln(index); jndex := getTaskDBAddress(db, index); assigned := false; cursor := db.Content[jndex].AvailabilityTime; repeat for i := 0 to cpucount-1 do if (sched[i][cursor] <> 1) then begin if (cursor + db.Content[jndex].ExecutionTime + 1 > xsize) then begin //write(xsize); xsize := cursor + db.Content[jndex].ExecutionTime + 1; SetLength(sched, cpucount, xsize); //writeln('expands to ', xsize); expanded := true; end; for j := 0 to db.Content[jndex].ExecutionTime-1 do sched[i][cursor+j] := 1; db.Content[jndex].CommenceTime := cursor; db.Content[jndex].AssignedMachine := i+1; assigned := true; break; end; Inc(cursor); if (cursor = xsize) then break; until assigned; end; end; SetLength(sched, 0, 0); if expanded then xsize := xsize - 1; buildCPMSchedule := xsize; end; procedure drawSchedule(db : TaskDB; maxl : LongInt; filename : String); var fp : Text; schedSizeX : LongInt; schedSizeY : LongInt; i : LongInt; CPUCount : LongInt; tk : Task; TaskX, TaskY : LongInt; TaskLength : LongInt; begin CPUCount := db.MachinesCount; schedSizeX := maxl*100 + 200; schedSizeY := CPUCount*100 + 200; assignfile(fp, filename); rewrite(fp); writeln(fp, '<svg xmlns="http://www.w3.org/2000/svg" width="',schedSizeX,'" height="',schedSizeY,'" viewBox="0 0 ',schedSizeX,' ',schedSizeY,'">'); writeln(fp, '<rect width="',schedSizeX,'" height="',schedSizeY,'" style="fill:rgb(255,255,255);stroke-width:0;stroke:rgb(0,0,0)" />'); //writeln(fp, '<text x="20" y="50" font-family="Verdana" font-size="25" style="font-weight:bold">CPU</text>'); writeln(fp, '<text x="10" y="',CPUCount*100+150,'" font-family="Verdana" font-size="25" style="font-weight:bold">Czas</text>'); for i := 1 to CPUCount do writeln(fp, '<text x="10" y="',i*100+55,'" font-family="Verdana" font-size="20">CPU ',i,'</text>'); for i := 0 to maxl do begin writeln(fp, '<text x="',i*100+100,'" y="',CPUCount*100+150,'" font-family="Verdana" font-size="20">',i,'</text>'); writeln(fp, '<line x1="',i*100+100,'" y1="80" x2="',i*100+100,'" y2="',CPUCount*100+120,'" style="stroke:rgb(0,0,0);stroke-width:1" />'); end; for tk in db.Content do begin TaskX := tk.CommenceTime*100+100; TaskY := tk.AssignedMachine*100; TaskLength := tk.ExecutionTime*100; //writeln('Task ',tk.id:3,': ', TaskX, ' ', TaskY, ' ', TaskLength); writeln(fp, '<rect x="',TaskX,'" y="',TaskY,'" width="',TaskLength,'" height="100" style="fill:rgb(128,128,255);stroke-width:2;stroke:rgb(0,0,0)" />'); writeln(fp, '<text x="',TaskX+10,'" y="',TaskY+60,'" font-family="Verdana" font-size="18" fill="white">Task ',tk.id,'</text>'); end; writeln(fp, '</svg>'); closefile(fp); writeln('A schedule image has been generated to the file "', filename, '".'); end; procedure drawGraph(db : TaskDB; filename : String); var fp : Text; schedSizeX : LongInt; schedSizeY : LongInt; i : LongInt; MiddleX : LongInt; MiddleY : LongInt; tk, tl : Task; TaskX, TaskY : LongInt; atan : Extended; angle : LongInt; posX, posY : LongInt; begin schedSizeX := 1000; schedSizeY := 1000; MiddleX := schedSizeX div 2; MiddleY := schedSizeY div 2; for i := 0 to Length(db.Content)-1 do begin db.Content[i].GraphPosX := MiddleX - trunc((MiddleX-150)*(cos(i/(Length(db.Content)) *2*pi()+0.01))); db.Content[i].GraphPosY := MiddleY - trunc((MiddleY-150)*(sin(i/(Length(db.Content)) *2*pi()+0.01))); end; assignfile(fp, filename); rewrite(fp); writeln(fp, '<svg xmlns="http://www.w3.org/2000/svg" width="',schedSizeX,'" height="',schedSizeY,'" viewBox="0 0 ',schedSizeX,' ',schedSizeY,'">'); writeln(fp, '<rect width="',schedSizeX,'" height="',schedSizeY,'" style="fill:rgb(255,255,255);stroke-width:0;stroke:rgb(0,0,0)" />'); for tk in db.Content do begin for i := 0 to Length(tk.PrevTasks)-1 do begin tl := getTaskByID(db, tk.PrevTasks[i]); atan := (1.0 * tk.GraphPosX - tl.GraphPosX)/(1.0 * tk.GraphPosY - tl.GraphPosY); angle := trunc(radtodeg(arctan(atan))) - 90; if (angle < 0) then angle := 360 - angle; writeln(fp, '<line x1="',tk.GraphPosX,'" y1="',tk.GraphPosY,'" x2="',tl.GraphPosX,'" y2="',tl.GraphPosY,'" style="stroke:rgb(0,0,0);stroke-width:2" />'); if (tk.GraphPosY < tl.GraphPosY) then writeln(fp, '<polygon points="2,7 0,0 11,7 0,14" transform="translate(',tk.GraphPosX+trunc(50*cos(degtorad(angle))),' ',tk.GraphPosY+trunc(50*sin(degtorad(angle))),') rotate(',angle+180,' 0 0) translate(-2 -7)" stroke="black" fill="black" />') else writeln(fp, '<polygon points="2,7 0,0 11,7 0,14" transform="translate(',tk.GraphPosX-trunc(50*cos(degtorad(angle))),' ',tk.GraphPosY-trunc(50*sin(degtorad(angle))),') rotate(',angle,' 0 0) translate(-2 -7)" stroke="black" fill="black" />'); end; end; for i := 0 to Length(db.Content)-1 do begin tk := db.Content[i]; if (i*4 < (Length(db.Content))) or (i*4.0/3 > (Length(db.Content))) then posX := tk.GraphPosX-130 else posX := tk.GraphPosX+30; if (i*2 < (Length(db.Content))) then posY := tk.GraphPosY-50 else posY := tk.GraphPosY+60; writeln(fp, '<circle cx="',tk.GraphPosX,'" cy="',tk.GraphPosY,'" r="40" stroke="black" stroke-width="3" fill="#008844" />'); writeln(fp, '<text x="',posX,'" y="',posY,'" font-family="Verdana" font-size="24" fill="black">Task ',tk.id,'</text>'); writeln(fp, '<text x="',tk.GraphPosX-10,'" y="',tk.GraphPosY+10,'" font-family="Verdana" font-size="24" fill="white">',tk.ExecutionTime,'</text>'); end; writeln(fp, '</svg>'); closefile(fp); writeln('A graph image has been generated to the file "', filename, '".'); end; end.
// @davidberneda // 2017 unit VariableStream; interface { TVariableStream class, to store data items of different lengths (sizes). For example: "Strings" (each string needs a different number of bytes) It also works with any other variable type, like "arrays of..." any type. } uses Classes, SysUtils; type TIndex=Integer; TSize=Integer; TOneOrMore=1..High(TIndex); TIndexRec=packed record public Position : TIndex; Size : TSize; end; TStreamClass=class of TStream; TVariableStream=class private FCount, FLast : TIndex; FData, FIndex : TStream; function BytesAt(const Index: TIndex):TBytes; procedure CheckIndex(const Index: TIndex); function IndexAt(const Index: TIndex):TIndexRec; procedure RaiseBadIndex(const Index:TIndex); procedure WriteIndexAt(const Index: TIndex; const ARec:TIndexRec); protected FUserOwned : Boolean; public Constructor Create(const AIndex,AData:TStream); overload; virtual; Constructor Create(const AClass:TStreamClass); overload; virtual; Destructor Destroy; override; procedure Clear; procedure Trim; property Count:TIndex read FCount; end; TVariableStream<T>=class abstract(TVariableStream) private procedure Put(const Index: TIndex; const Value: T); procedure WriteData(const ARec: TIndexRec; const Value:T); protected function DataBytesOf(const Value:T):TBytes; virtual; abstract; function DataSize(const Value:T):TSize; virtual; abstract; function Get(const Index: TIndex): T; virtual; abstract; public function Append(const Value:T):TIndex; procedure Delete(const Index:TIndex; const ACount:TOneOrMore=1); property Items[const Index:TIndex]:T read Get write Put; default; end; EVariableStreamException=class(Exception); // Example: // Strings of variable length TStringsStream=class(TVariableStream<String>) protected function DataBytesOf(const Value:String):TBytes; override; function DataSize(const Value:String):TSize; override; function Get(const Index: TIndex): String; override; public Encoding : TEncoding; Constructor Create(const AIndex,AData:TStream); override; end; implementation { TVariableStream } Constructor TVariableStream.Create(const AIndex, AData: TStream); begin inherited Create; FIndex:=AIndex; FData:=AData; FCount:=FIndex.Size div SizeOf(TIndexRec); FLast:=FData.Size; end; Constructor TVariableStream.Create(const AClass: TStreamClass); begin Create(AClass.Create,AClass.Create); end; Destructor TVariableStream.Destroy; var tmp : TSize; begin tmp:=Count*SizeOf(TIndexRec); if FIndex.Size<>tmp then FIndex.Size:=tmp; if not FUserOwned then begin FIndex.Free; FData.Free; end; inherited; end; procedure TVariableStream.Clear; begin FData.Size:=0; FIndex.Size:=0; FCount:=0; FLast:=0; end; procedure TVariableStream.RaiseBadIndex(const Index:TIndex); begin raise EVariableStreamException.CreateFmt('Bad Index: ',[Index]); end; procedure TVariableStream.Trim; begin FIndex.Size:=Count*SizeOf(TIndexRec); // Data: // ??? end; procedure TVariableStream.CheckIndex(const Index: TIndex); begin if (Index<0) or (Count<=Index) then RaiseBadIndex(Index); end; function TVariableStream.IndexAt(const Index: TIndex):TIndexRec; var P : ^TIndexRec; begin FIndex.Position:=Index*SizeOf(TIndexRec); P:=@result; FIndex.Read(P^,SizeOf(TIndexRec)); end; function TVariableStream.BytesAt(const Index: TIndex):TBytes; var tmp : TIndexRec; begin CheckIndex(Index); tmp:=IndexAt(Index); if tmp.Size=0 then result:=nil else begin SetLength(result,tmp.Size); FData.Position:=tmp.Position; FData.Read(result,tmp.Size); end; end; procedure TVariableStream.WriteIndexAt(const Index: TIndex; const ARec:TIndexRec); begin FIndex.Position:=Index*SizeOf(TIndexRec); FIndex.Write(ARec,SizeOf(TIndexRec)); end; { TVariableStream<T> } function TVariableStream<T>.Append(const Value: T): TIndex; var tmp : TIndexRec; begin tmp.Position:=FLast; tmp.Size:=DataSize(Value); WriteIndexAt(Count,tmp); Inc(FCount); WriteData(tmp,Value); Inc(FLast,tmp.Size); end; procedure TVariableStream<T>.WriteData(const ARec: TIndexRec; const Value:T); begin FData.Position:=ARec.Position; FData.WriteData(DataBytesOf(Value),ARec.Size); end; procedure TVariableStream<T>.Delete(const Index: TIndex; const ACount:TOneOrMore=1); var tmp : Array of TIndexRec; tmpSize : TSize; begin CheckIndex(Index); FIndex.Position:=(Index+ACount)*SizeOf(TIndexRec); SetLength(tmp,Count-ACount); tmpSize:=(Count-ACount)*SizeOf(TIndexRec); FIndex.ReadData(tmp,tmpSize); FIndex.Position:=Index*SizeOf(TIndexRec); FIndex.WriteData(tmp,tmpSize); Dec(FCount,ACount); end; procedure TVariableStream<T>.Put(const Index: TIndex; const Value: T); var tmp : TIndexRec; tmpSize : TSize; tmpBigger : Boolean; begin CheckIndex(Index); tmp:=IndexAt(Index); tmpSize:=DataSize(Value); tmpBigger:=tmpSize>tmp.Size; if tmpBigger then tmp.Position:=FLast; tmp.Size:=tmpSize; WriteIndexAt(Index,tmp); WriteData(tmp,Value); if tmpBigger then Inc(FLast,tmp.Size); end; { TStringsStream } Constructor TStringsStream.Create(const AIndex,AData:TStream); begin inherited; Encoding:=TEncoding.Default; end; function TStringsStream.DataBytesOf(const Value: String): TBytes; begin result:=Encoding.GetBytes(Value); end; function TStringsStream.DataSize(const Value: String): TSize; begin result:=Encoding.GetByteCount(Value); end; function TStringsStream.Get(const Index: TIndex): String; begin result:=Encoding.GetString(BytesAt(Index)); end; end.
unit fOrdersUnhold; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ORFn, ORCtrls, VA508AccessibilityManager; type TfrmUnholdOrders = class(TfrmAutoSz) Label1: TLabel; lstOrders: TCaptionListBox; cmdOK: TButton; cmdCancel: TButton; procedure FormCreate(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); private OKPressed: Boolean; end; function ExecuteUnholdOrders(SelectedList: TList): Boolean; implementation {$R *.DFM} uses rOrders, uConst, uCore; function ExecuteUnholdOrders(SelectedList: TList): Boolean; var frmUnholdOrders: TfrmUnholdOrders; OriginalID: string; i: Integer; begin Result := False; if SelectedList.Count = 0 then Exit; frmUnholdOrders := TfrmUnholdOrders.Create(Application); try ResizeFormToFont(TForm(frmUnholdOrders)); with SelectedList do for i := 0 to Count - 1 do frmUnholdOrders.lstOrders.Items.Add(TOrder(Items[i]).Text); frmUnholdOrders.ShowModal; if frmUnholdOrders.OKPressed then begin with SelectedList do for i := 0 to Count - 1 do begin OriginalID := TOrder(Items[i]).ID; ReleaseOrderHold(TOrder(Items[i])); TOrder(Items[i]).ActionOn := OriginalID + '=UH'; SendMessage(Application.MainForm.Handle, UM_NEWORDER, ORDER_ACT, Integer(Items[i])); end; Result := True; end else with SelectedList do for i := 0 to Count - 1 do UnlockOrder(TOrder(Items[i]).ID); finally frmUnholdOrders.Release; end; end; procedure TfrmUnholdOrders.FormCreate(Sender: TObject); begin inherited; OKPressed := False; end; procedure TfrmUnholdOrders.cmdOKClick(Sender: TObject); begin inherited; OKPressed := True; Close; end; procedure TfrmUnholdOrders.cmdCancelClick(Sender: TObject); begin inherited; Close; end; end.
namespace RemObjects.Elements.System; interface uses Foundation; type __ElementsBoxedStructDestructor = public procedure (o: ^Void); __ElementsBoxedStruct = public class(NSObject) // We're explicitly NOT implementing INSCopying and INSCoding private fValue: ^Void; fDtor: __ElementsBoxedStructDestructor; public constructor (aValue: ^Void; aDtor: __ElementsBoxedStructDestructor); // Presume already "copied" & malloced finalizer; method description: String; override; class method boxedStructWithValue(aValue: ^Void; aDtor: __ElementsBoxedStructDestructor): __ElementsBoxedStruct; class method valueForStruct(aStruct: Object; aDtor: __ElementsBoxedStructDestructor): ^Void; // property Dtor: __ElementsBoxedStructDestructor read fDtor; property Value: ^Void read fValue; operator Equal(object1: __ElementsBoxedStruct; object2: id): Boolean; operator Equal(object1: id; object2: __ElementsBoxedStruct): Boolean; operator NotEqual(object1: __ElementsBoxedStruct; object2: id): Boolean; operator NotEqual(object1: id; object2: __ElementsBoxedStruct): Boolean; { INSObject } method isEqual(object: id): Boolean; override; method isEqualTo(object: id): Boolean; reintroduce; { INSCopying } method copyWithZone(zone: ^NSZone): not nullable id; method mutableCopyWithZone(zone: ^NSZone): not nullable id; { INSCoding } method encodeWithCoder(aCoder: not nullable NSCoder); method initWithCoder(aDecoder: not nullable NSCoder): nullable InstanceType; end; __ElementsBoxedChar = public class(NSObject, INSCopying, INSCoding) private method stringValue: NSString; public constructor withChar(aChar: Char); class method boxedCharWithChar(aChar: Char): __ElementsBoxedChar; method description: String; override; property charValue: Char; readonly; property stringValue: NSString read stringValue; operator Implicit(aValue: __ElementsBoxedChar): NSNumber; operator Implicit(aValue: __ElementsBoxedChar): Char; operator Equal(object1: __ElementsBoxedChar; object2: id): Boolean; operator Equal(object1: id; object2: __ElementsBoxedChar): Boolean; operator NotEqual(object1: __ElementsBoxedChar; object2: id): Boolean; operator NotEqual(object1: id; object2: __ElementsBoxedChar): Boolean; { INSObject } method isEqual(object: id): Boolean; override; method isEqualTo(object: id): Boolean; reintroduce; method isGreaterThan(object: id): Boolean; reintroduce; method isGreaterThanOrEqualTo(object: id): Boolean; reintroduce; method isLessThan(object: id): Boolean; reintroduce; method isLessThanOrEqualTo(object: id): Boolean; reintroduce; { INSCopying } method copyWithZone(zone: ^NSZone): not nullable id; method mutableCopyWithZone(zone: ^NSZone): not nullable id; { INSCoding } method encodeWithCoder(aCoder: not nullable NSCoder); method initWithCoder(aDecoder: not nullable NSCoder): nullable InstanceType; end; __ElementsBoxedAnsiChar = public class(NSObject, INSCopying, INSCoding) private method stringValue: NSString; public constructor withAnsiChar(aAnsiChar: AnsiChar); class method boxedAnsiCharWithAnsiChar(aAnsiChar: AnsiChar): __ElementsBoxedAnsiChar; method description: String; override; property ansiCharValue: AnsiChar; readonly; property stringValue: NSString read stringValue; operator Implicit(aValue: __ElementsBoxedAnsiChar): NSNumber; operator Implicit(aValue: __ElementsBoxedAnsiChar): AnsiChar; operator Equal(object1: __ElementsBoxedAnsiChar; object2: id): Boolean; operator Equal(object1: id; object2: __ElementsBoxedAnsiChar): Boolean; operator NotEqual(object1: __ElementsBoxedAnsiChar; object2: id): Boolean; operator NotEqual(object1: id; object2: __ElementsBoxedAnsiChar): Boolean; { INSObject } method isEqual(object: id): Boolean; override; method isEqualTo(object: id): Boolean; reintroduce; method isGreaterThan(object: id): Boolean; reintroduce; method isGreaterThanOrEqualTo(object: id): Boolean; reintroduce; method isLessThan(object: id): Boolean; reintroduce; method isLessThanOrEqualTo(object: id): Boolean; reintroduce; { INSCopying } method copyWithZone(zone: ^NSZone): not nullable id; method mutableCopyWithZone(zone: ^NSZone): not nullable id; { INSCoding } method encodeWithCoder(aCoder: not nullable NSCoder); method initWithCoder(aDecoder: not nullable NSCoder): nullable InstanceType; end; implementation { __ElementsBoxedChar } constructor __ElementsBoxedChar withChar(aChar: Char); begin charValue := aChar; end; method __ElementsBoxedChar.description: String; begin result := NSString.stringWithFormat("%c", charValue); end; operator __ElementsBoxedChar.Implicit(aValue: __ElementsBoxedChar): NSNumber; begin result := NSNumber.numberWithUnsignedInt(aValue.charValue as Int16); end; operator __ElementsBoxedChar.Implicit(aValue: __ElementsBoxedChar): Char; begin result := aValue.charValue; end; operator __ElementsBoxedChar.Equal(object1: __ElementsBoxedChar; object2: id): Boolean; begin if not assigned(object1) then exit not assigned(object2); result := object1.isEqualTo(object2); end; operator __ElementsBoxedChar.Equal(object1: id; object2: __ElementsBoxedChar): Boolean; begin if not assigned(object2) then exit not assigned(object1); result := object2.isEqualTo(object1); end; operator __ElementsBoxedChar.NotEqual(object1: __ElementsBoxedChar; object2: id): Boolean; begin if not assigned(object1) then exit assigned(object2); result := not object1.isEqualTo(object2); end; operator __ElementsBoxedChar.NotEqual(object1: id; object2: __ElementsBoxedChar): Boolean; begin if not assigned(object2) then exit assigned(object1); result := not object2.isEqualTo(object1); end; class method __ElementsBoxedChar.boxedCharWithChar(aChar: Char): __ElementsBoxedChar; begin exit new __ElementsBoxedChar withChar(aChar); end; method __ElementsBoxedChar.stringValue: NSString; begin var char := charValue; result := NSString.stringWithCharacters(@char) length(1); end; method __ElementsBoxedChar.isEqual(object: id): Boolean; begin result := isEqualTo(object) end; method __ElementsBoxedChar.isEqualTo(object: id): Boolean; begin result := ((object is __ElementsBoxedChar) and (charValue = (object as __ElementsBoxedChar).charValue)) or ((object is __ElementsBoxedAnsiChar) and (charValue = Char((object as __ElementsBoxedAnsiChar).ansiCharValue))) or ((object is NSString) and (stringValue = (object as NSString))); end; method __ElementsBoxedChar.isGreaterThan(object: id): Boolean; begin result := ((object is __ElementsBoxedChar) and (charValue > (object as __ElementsBoxedChar).charValue)) or ((object is __ElementsBoxedAnsiChar) and (charValue > Char((object as __ElementsBoxedAnsiChar).ansiCharValue))) or ((object is NSString) and (stringValue > (object as NSString))); end; method __ElementsBoxedChar.isGreaterThanOrEqualTo(object: id): Boolean; begin result := ((object is __ElementsBoxedChar) and (charValue >= (object as __ElementsBoxedChar).charValue)) or ((object is __ElementsBoxedAnsiChar) and (charValue >= Char((object as __ElementsBoxedAnsiChar).ansiCharValue))) or ((object is NSString) and (stringValue >= (object as NSString))); end; method __ElementsBoxedChar.isLessThan(object: id): Boolean; begin result := ((object is __ElementsBoxedChar) and (charValue < (object as __ElementsBoxedChar).charValue)) or ((object is __ElementsBoxedAnsiChar) and (charValue < Char((object as __ElementsBoxedAnsiChar).ansiCharValue))) or ((object is NSString) and (stringValue < (object as NSString))); end; method __ElementsBoxedChar.isLessThanOrEqualTo(object: id): Boolean; begin result := ((object is __ElementsBoxedChar) and (charValue <= (object as __ElementsBoxedChar).charValue)) or ((object is __ElementsBoxedAnsiChar) and (charValue <= Char((object as __ElementsBoxedAnsiChar).ansiCharValue))) or ((object is NSString) and (stringValue <= (object as NSString))); end; method __ElementsBoxedChar.copyWithZone(zone: ^NSZone): not nullable id; begin result := __ElementsBoxedChar.allocWithZone(zone).initWithChar(charValue) as not nullable; end; method __ElementsBoxedChar.mutableCopyWithZone(zone: ^NSZone): not nullable id; begin result := __ElementsBoxedChar.allocWithZone(zone).initWithChar(charValue) as not nullable; end; method __ElementsBoxedChar.initWithCoder(aDecoder: not nullable NSCoder): nullable instancetype; begin var len: NSUInteger; var ch: ^Char := ^Char(aDecoder.decodeBytesWithReturnedLength(var len)); charValue := ch^; end; method __ElementsBoxedChar.encodeWithCoder(aCoder: not nullable NSCoder); begin var ch := charValue; aCoder.encodeBytes(@ch) length(2); end; { __ElementsBoxedAnsiChar } constructor __ElementsBoxedAnsiChar withAnsiChar(aAnsiChar: AnsiChar); begin ansiCharValue := aAnsiChar; end; method __ElementsBoxedAnsiChar.description: String; begin result := NSString.stringWithFormat("%c", ansiCharValue); end; operator __ElementsBoxedAnsiChar.Implicit(aValue: __ElementsBoxedAnsiChar): NSNumber; begin result := NSNumber.numberWithUnsignedChar(aValue.ansiCharValue as Byte); end; operator __ElementsBoxedAnsiChar.Implicit(aValue: __ElementsBoxedAnsiChar): AnsiChar; begin result := aValue.ansiCharValue; end; operator __ElementsBoxedAnsiChar.Equal(object1: __ElementsBoxedAnsiChar; object2: id): Boolean; begin if not assigned(object1) then exit not assigned(object2); result := object1.isEqualTo(object2); end; operator __ElementsBoxedAnsiChar.Equal(object1: id; object2: __ElementsBoxedAnsiChar): Boolean; begin if not assigned(object2) then exit not assigned(object1); result := object2.isEqualTo(object1); end; operator __ElementsBoxedAnsiChar.NotEqual(object1: __ElementsBoxedAnsiChar; object2: id): Boolean; begin if not assigned(object1) then exit assigned(object2); result := not object1.isEqualTo(object2); end; operator __ElementsBoxedAnsiChar.NotEqual(object1: id; object2: __ElementsBoxedAnsiChar): Boolean; begin if not assigned(object2) then exit assigned(object1); result := not object2.isEqualTo(object1); end; method __ElementsBoxedAnsiChar.stringValue: NSString; begin var char := Char(ansiCharValue); result := NSString.stringWithCharacters(@char) length(1); end; method __ElementsBoxedAnsiChar.isEqual(object: id): Boolean; begin result := isEqualTo(object) end; method __ElementsBoxedAnsiChar.isEqualTo(object: id): Boolean; begin result := ((object is __ElementsBoxedAnsiChar) and (ansiCharValue = (object as __ElementsBoxedAnsiChar).ansiCharValue)) or ((object is __ElementsBoxedChar) and (Char(ansiCharValue) = (object as __ElementsBoxedChar).charValue)) or ((object is NSString) and (stringValue = (object as NSString))); end; method __ElementsBoxedAnsiChar.isGreaterThan(object: id): Boolean; begin result := ((object is __ElementsBoxedChar) and (ansiCharValue > (object as __ElementsBoxedAnsiChar).ansiCharValue)) or ((object is __ElementsBoxedChar) and (Char(ansiCharValue) > (object as __ElementsBoxedChar).charValue)) or ((object is NSString) and (stringValue > (object as NSString))); end; method __ElementsBoxedAnsiChar.isGreaterThanOrEqualTo(object: id): Boolean; begin result := ((object is __ElementsBoxedChar) and (ansiCharValue >= (object as __ElementsBoxedAnsiChar).ansiCharValue)) or ((object is __ElementsBoxedChar) and (Char(ansiCharValue) >= (object as __ElementsBoxedChar).charValue)) or ((object is NSString) and (stringValue >= (object as NSString))); end; method __ElementsBoxedAnsiChar.isLessThan(object: id): Boolean; begin result := ((object is __ElementsBoxedChar) and (ansiCharValue < (object as __ElementsBoxedAnsiChar).ansiCharValue)) or ((object is __ElementsBoxedChar) and (Char(ansiCharValue) < (object as __ElementsBoxedChar).charValue)) or ((object is NSString) and (stringValue < (object as NSString))); end; method __ElementsBoxedAnsiChar.isLessThanOrEqualTo(object: id): Boolean; begin result := ((object is __ElementsBoxedChar) and (ansiCharValue <= (object as __ElementsBoxedAnsiChar).ansiCharValue)) or ((object is __ElementsBoxedChar) and (Char(ansiCharValue) <= (object as __ElementsBoxedChar).charValue)) or ((object is NSString) and (stringValue <= (object as NSString))); end; class method __ElementsBoxedAnsiChar.boxedAnsiCharWithAnsiChar(aAnsiChar: AnsiChar): __ElementsBoxedAnsiChar; begin exit new __ElementsBoxedAnsiChar withAnsiChar(aAnsiChar); end; method __ElementsBoxedAnsiChar.copyWithZone(zone: ^NSZone): not nullable id; begin result := __ElementsBoxedAnsiChar.allocWithZone(zone).initWithAnsiChar(ansiCharValue) as not nullable; end; method __ElementsBoxedAnsiChar.mutableCopyWithZone(zone: ^NSZone): not nullable id; begin result := __ElementsBoxedAnsiChar.allocWithZone(zone).initWithAnsiChar(ansiCharValue) as not nullable; end; method __ElementsBoxedAnsiChar.initWithCoder(aDecoder: not nullable NSCoder): nullable instancetype; begin var len: NSUInteger; var ch: ^AnsiChar := ^AnsiChar(aDecoder.decodeBytesWithReturnedLength(var len)); ansiCharValue := ch^; end; method __ElementsBoxedAnsiChar.encodeWithCoder(aCoder: not nullable NSCoder); begin var ch := ansiCharValue; aCoder.encodeBytes(@ch) length(2); end; { __ElementsBoxedStruct } constructor __ElementsBoxedStruct(aValue: ^Void; aDtor: __ElementsBoxedStructDestructor); begin fValue := aValue; fDtor := aDtor; end; finalizer __ElementsBoxedStruct; begin if fDtor <> nil then fDtor(fValue); free(fValue); end; method __ElementsBoxedStruct.description: String; begin result := "<Boxed Struct Type>" end; class method __ElementsBoxedStruct.boxedStructWithValue(aValue: ^Void; aDtor: __ElementsBoxedStructDestructor): __ElementsBoxedStruct; begin exit new __ElementsBoxedStruct(aValue, aDtor); end; class method __ElementsBoxedStruct.valueForStruct(aStruct: Object; aDtor: __ElementsBoxedStructDestructor): ^Void; begin var lSelf := __ElementsBoxedStruct(aStruct); if lSelf.Dtor <> aDtor then raise new NSException withName('InvalidCastException') reason ('Destructor does not match for boxed struct') userInfo(nil); exit lSelf.fValue; end; { INSObject } method __ElementsBoxedStruct.isEqual(object: id): Boolean; begin if object is __ElementsBoxedStruct then begin if (object as __ElementsBoxedStruct).Value = Value then exit true; // exact same pointer? then thye must be equal {$HINT need to call isEqual on the boxed struct, if implemented} end; result := false; end; method __ElementsBoxedStruct.isEqualTo(object: id): Boolean; begin result := isEqual(object); end; operator __ElementsBoxedStruct.Equal(object1: __ElementsBoxedStruct; object2: id): Boolean; begin if not assigned(object1) then exit not assigned(object2); result := object1.isEqual(object2); end; operator __ElementsBoxedStruct.Equal(object1: id; object2: __ElementsBoxedStruct): Boolean; begin if not assigned(object2) then exit not assigned(object1); result := object2.isEqual(object1); end; operator __ElementsBoxedStruct.NotEqual(object1: __ElementsBoxedStruct; object2: id): Boolean; begin if not assigned(object1) then exit assigned(object2); result := not object1.isEqual(object2); end; operator __ElementsBoxedStruct.NotEqual(object1: id; object2: __ElementsBoxedStruct): Boolean; begin if not assigned(object2) then exit assigned(object1); result := not object2.isEqual(object1); end; method __ElementsBoxedStruct.copyWithZone(zone: ^NSZone): not nullable id; begin exit self; end; method __ElementsBoxedStruct.mutableCopyWithZone(zone: ^NSZone): not nullable id; begin exit self; end; method __ElementsBoxedStruct.initWithCoder(aDecoder: not nullable NSCoder): nullable instancetype; begin raise new NSException("Encoding/decoding is not supported for boxed structs.") end; method __ElementsBoxedStruct.encodeWithCoder(aCoder: not nullable NSCoder); begin raise new NSException("Encoding/decoding is not supported for boxed structs.") end; end.
unit UnitFormDataTable; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.grids, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, server_data_types, System.Generics.Collections; type TMeregedRow = record Text: string; Row: integer; end; TFormDataTable = class(TForm) StringGrid2: TStringGrid; procedure StringGrid2DrawCell(Sender: TObject; ACol, ARow: integer; Rect: TRect; State: TGridDrawState); procedure StringGrid2DblClick(Sender: TObject); procedure StringGrid2TopLeftChanged(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } FMeregedRows: TArray<TMeregedRow>; FCells: TArray<TArray<TCell>>; public { Public declarations } procedure SetTable(ATable: TArray < TArray < TCell >> ); end; // var // FormDataTable: TFormDataTable; implementation {$R *.dfm} uses types, StrUtils, stringgridutils, UnitFormPopup, app, services, stringutils; function coord(x, y: integer): TCoord; begin result.x := x; result.y := y; end; procedure TFormDataTable.FormCreate(Sender: TObject); begin with StringGrid2 do begin ColCount := 10; RowCount := 2; FixedCols := 1; FixedRows := 1; Cells[0, 0] := 'a'; Cells[1, 1] := 'b'; Cells[2, 2] := 'c'; end; end; procedure TFormDataTable.FormShow(Sender: TObject); begin // end; procedure TFormDataTable.StringGrid2DblClick(Sender: TObject); begin FormPopup.ShowStringGridCellText(StringGrid2); end; procedure TFormDataTable.StringGrid2DrawCell(Sender: TObject; ACol, ARow: integer; Rect: TRect; State: TGridDrawState); var grd: TStringGrid; cnv: TCanvas; AMergeRect: TMeregedRow; not_used: double; begin grd := StringGrid2; cnv := grd.Canvas; cnv.Font.Assign(grd.Font); cnv.Brush.Color := clWhite; if gdSelected in State then cnv.Brush.Color := clGradientInactiveCaption else if gdFixed in State then cnv.Brush.Color := cl3DLight; cnv.Font.Color := clBlack; cnv.Pen.Color := $00BCBCBC; cnv.Pen.Width := -1; if ACol > 0 then for AMergeRect in FMeregedRows do if ARow = AMergeRect.Row then begin cnv.Brush.Color := clInfoBk; cnv.Font.Color := clNavy; cnv.Font.Style := [fsBold]; StringGrid_DrawMeregedCell(grd, AMergeRect.Text, AMergeRect.Row, Rect); exit; end; if (ACol > 0) ANd (ARow > 0) then begin if length(FCells[ARow][ACol].Color) > 0 then cnv.Font.Color := StringToColor(FCells[ARow][ACol].Color); end; DrawCellText(StringGrid2, ACol, ARow, Rect, TAlignment(FCells[ARow][ACol].Alignment), StringGrid2.Cells[ACol, ARow]); StringGrid_DrawCellBounds(cnv, ACol, ARow, Rect); end; procedure TFormDataTable.StringGrid2TopLeftChanged(Sender: TObject); var ACol, ARow: integer; begin with StringGrid2 do begin for ACol := LeftCol to LeftCol + VisibleColCount - 1 do for ARow := TopRow to TopRow + VisibleRowCount - 1 do Cells[ACol, ARow] := Cells[ACol, ARow]; for ACol := 0 to LeftCol + VisibleColCount - 1 do Cells[ACol, 0] := Cells[ACol, 0]; for ARow := TopRow to TopRow + VisibleRowCount - 1 do Cells[0, ARow] := Cells[0, ARow]; end; end; procedure TFormDataTable.SetTable(ATable: TArray < TArray < TCell >> ); var _row: TArray<TCell>; ACol, ARow, I: integer; s: string; begin FCells := ATable; FMeregedRows := []; StringGrid_Clear(StringGrid2); with StringGrid2 do begin ColCount := length(ATable[0]); RowCount := length(ATable); if RowCount > 1 then FixedRows := 1; for I := 0 to length(ATable[0]) - 1 do Cells[I, 0] := ATable[0][I].Text; ARow := 0; for _row in ATable do begin if length(_row) = 1 then begin SetLength(FMeregedRows, length(FMeregedRows) + 1); FMeregedRows[length(FMeregedRows) - 1].Row := ARow; FMeregedRows[length(FMeregedRows) - 1].Text := _row[0].Text; end else for ACol := 0 to ColCount - 1 do Cells[ACol, ARow] := _row[ACol].Text; ARow := ARow + 1; end; end; StringGrid_SetupColumnsWidth(StringGrid2); end; end.
unit UnProgramador1; interface Uses SQLExpr, Classes, SysUtils; Const CT_VersaoBancoProgramador1 = 209; Type TRBFunProgramador1 = class private procedure AtualizaTabela(VpaNumAtualizacao : Integer); public Aux : TSQLQuery; constructor cria(VpaBaseDados : TSQLConnection ); destructor destroy;override; procedure AtualizaBanco; function AtualizaBanco1(VpaNumAtualizacao: integer): string; end; implementation uses FunSql, ConstMsg; { TRBFunProgramador1 } {******************************************************************************} procedure TRBFunProgramador1.AtualizaBanco; begin AdicionaSQLAbreTabela(Aux,'Select I_ULT_PR1 from Cfg_Geral '); if Aux.FieldByName('I_ULT_PR1').AsInteger < CT_VersaoBancoProgramador1 Then AtualizaTabela(Aux.FieldByName('I_ULT_PR1').AsInteger); Aux.Close; end; {******************************************************************************} constructor TRBFunProgramador1.cria(VpaBaseDados: TSQLConnection); begin inherited create; Aux := TSQLQuery.Create(nil); Aux.SQLConnection := VpaBaseDados; end; {******************************************************************************} destructor TRBFunProgramador1.destroy; begin aux.Free; inherited; end; {******************************************************************************} procedure TRBFunProgramador1.AtualizaTabela(VpaNumAtualizacao: Integer); var VpfSemErros : Boolean; VpfErro : String; begin VpfSemErros := true; // FAbertura.painelTempo1.Execute('Atualizando o Banco de Dados. Aguarde...'); repeat Try if VpaNumAtualizacao < 1 Then begin VpfErro := '1'; ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 1'); end; if VpaNumAtualizacao < 2 Then begin VpfErro := '2'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD C_ALT_GCA CHAR(1) NULL'); ExecutaComandoSql(Aux,'UPDATE CFG_PRODUTO SET C_ALT_GCA = ''T'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 2'); end; if VpaNumAtualizacao < 3 Then begin VpfErro := '3'; ExecutaComandoSql(Aux,'ALTER TABLE TABELAIMPORTACAO ADD INDIMPORTAR CHAR(1) NULL'); ExecutaComandoSql(Aux,'UPDATE TABELAIMPORTACAO SET INDIMPORTAR = ''S'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 3'); end; if VpaNumAtualizacao < 4 then begin VpfErro := '4'; ExecutaComandoSql(Aux,'update TABELAIMPORTACAO set DESCAMPODATA = ''D_DAT_ALT'''+ ' Where CODTABELA = 31'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 4'); end; if VpaNumAtualizacao < 5 then begin VpfErro := '5'; ExecutaComandoSql(Aux,'ALTER TABLE ESTAGIOPRODUCAO ADD DATALT DATE NULL'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(33,3200,''ESTAGIOPRODUCAO'',''CADASTRO DE ESTAGIOS PRODUCAO'',''DATALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(33,1,''CODEST'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 5'); end; if VpaNumAtualizacao < 6 then begin VpfErro := '6'; ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(34,3300,''CADUNIDADE'',''CADASTRO DE UNIDADES DE MEDIDA'',''D_ULT_ALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(34,1,''C_COD_UNI'',3)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 6'); end; if VpaNumAtualizacao < 7 then begin VpfErro := '7'; ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(35,3400,''MOVINDICECONVERSAO'',''CADASTRO DE INDICE DE DE CONVERSAO UM'',''D_ULT_ALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(35,1,''C_UNI_COV'',3)'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(35,2,''C_UNI_ATU'',3)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 7'); end; if VpaNumAtualizacao < 8 then begin VpfErro := '8'; ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(36,3500,''CADCLASSIFICACAO'',''CADASTRO DE CLASSIFICACAO'',''D_ULT_ALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(36,1,''I_COD_EMP'',1)'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(36,2,''C_COD_CLA'',3)'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(36,3,''C_TIP_CLA'',3)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 8'); end; if VpaNumAtualizacao < 9 then begin VpfErro := '9'; ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(37,3500,''CADMOEDAS'',''CADASTRO DE MOEDAS'',''D_ULT_ALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(37,1,''I_COD_MOE'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 9'); end; if VpaNumAtualizacao < 10 then begin VpfErro := '10'; ExecutaComandoSql(Aux,'ALTER TABLE PRINCIPIOATIVO ADD DATULTIMAALTERACAO DATE'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(38,3600,''PRINCIPIOATIVO'',''CADASTRO DE PRINCIPIO ATIVO'',''DATULTIMAALTERACAO'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(38,1,''CODPRINCIPIO'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 10'); end; if VpaNumAtualizacao < 11 then begin VpfErro := '11'; ExecutaComandoSql(Aux,'ALTER TABLE MAQUINA ADD DATALT DATE'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(39,3700,''MAQUINA'',''CADASTRO DE MAQUINA'',''DATALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(39,1,''CODMAQ'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 11'); end; if VpaNumAtualizacao < 12 then begin VpfErro := '12'; ExecutaComandoSql(Aux,'ALTER TABLE CADTIPOFUNDO ADD D_ULT_ALT DATE'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(40,3800,''CADTIPOFUNDO'',''CADASTRO DE TIPO DE FUNDO'',''D_ULT_ALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(40,1,''I_COD_FUN'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 12'); end; if VpaNumAtualizacao < 13 then begin VpfErro := '13'; ExecutaComandoSql(Aux,'ALTER TABLE TIPOEMENDA ADD DATALT DATE'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(41,3900,''TIPOEMENDA'',''CADASTRO DE TIPO DE EMENDA'',''DATALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(41,1,''CODEME'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 13'); end; if VpaNumAtualizacao < 15 then begin VpfErro := '15'; ExecutaComandoSql(Aux,'ALTER TABLE TIPOCORTE ADD DATALT DATE'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(42,4000,''TIPOCORTE'',''CADASTRO DE TIPO DE CORTE'',''DATALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(42,1,''CODCORTE'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 15'); end; if VpaNumAtualizacao < 16 then begin VpfErro := '16'; ExecutaComandoSql(Aux,'ALTER TABLE EMBALAGEM ADD DAT_ULTIMA_ALTERACAO DATE'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(43,4100,''EMBALAGEM'',''CADASTRO DE EMBALAGEM'',''DAT_ULTIMA_ALTERACAO'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(43,1,''COD_EMBALAGEM'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 16'); end; if VpaNumAtualizacao < 17 then begin VpfErro := '17'; ExecutaComandoSql(Aux,'ALTER TABLE ACONDICIONAMENTO ADD DATULTIMAALTERACAO DATE'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(44,4200,''ACONDICIONAMENTO'',''CADASTRO DE ACONDICIONAMENTO'',''DATULTIMAALTERACAO'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(44,1,''CODACONDICIONAMENTO'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 17'); end; if VpaNumAtualizacao < 18 then begin VpfErro := '18'; ExecutaComandoSql(Aux,'ALTER TABLE COMPOSICAO ADD DATULTIMAALTERACAO DATE'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(45,4300,''COMPOSICAO'',''CADASTRO DE COMPOSICAO'',''DATULTIMAALTERACAO'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(45,1,''CODCOMPOSICAO'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 18'); end; if VpaNumAtualizacao < 19 then begin VpfErro := '19'; ExecutaComandoSql(Aux,'ALTER TABLE REPRESENTADA ADD DATULTIMAALTERACAO DATE'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(46,4400,''REPRESENTADA'',''CADASTRO DE REPRESENTADA'',''DATULTIMAALTERACAO'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(46,1,''CODREPRESENTADA'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 19'); end; if VpaNumAtualizacao < 20 then begin VpfErro := '20'; ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(47,4500,''CADMOEDAS'',''CADASTRO DE MOEDAS'',''D_ULT_ALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(47,1,''I_COD_MOE'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 20'); end; if VpaNumAtualizacao < 21 then begin VpfErro := '21'; ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' + ' VALUES(48,4600,''CADPRODUTOS'',''CADASTRO DE PRODUTOS'',''D_ULT_ALT'', ''S'')'); ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' + ' VALUES(48,1,''I_SEQ_PRO'',1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 21'); end; if VpaNumAtualizacao < 22 then begin VpfErro := '22'; ExecutaComandoSql(Aux,' ALTER TABLE CADPRODUTOS ADD (C_SIS_TEA VARCHAR2(10) NULL, ' + ' C_BCM_TEA VARCHAR2(10) NULL, ' + ' C_IND_PRE CHAR(1) NULL) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 22'); end; if VpaNumAtualizacao < 23 then begin VpfErro := '23'; ExecutaComandoSql(Aux,' CREATE TABLE PROCESSOPRODUCAO ( ' + ' CODPROCESSOPRODUCAO NUMBER(10,0) NOT NULL, ' + ' DESPROCESSOPRODUCAO VARCHAR2(80) NULL, ' + ' CODESTAGIO NUMBER(10,0) NULL REFERENCES ESTAGIOPRODUCAO(CODEST), ' + ' QTDPRODUCAOHORA NUMBER(11,4) NULL, ' + ' INDCONFIGURACAO CHAR(1) NULL, ' + ' DESTEMPOCONFIGURACAO VARCHAR2(7) NULL,' + ' PRIMARY KEY (CODPROCESSOPRODUCAO))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 23'); end; if VpaNumAtualizacao < 24 then begin VpfErro := '24'; ExecutaComandoSql(Aux,' CREATE TABLE AMOSTRAPRODUTO ( ' + ' CODAMOSTRA NUMBER(10) NOT NULL, ' + ' SEQAMOSTRAPRODUTO NUMBER(10) NOT NULL, ' + ' CODESTAGIO NUMBER(10), ' + ' CODPROCESSOPRODUCAO NUMBER(10), ' + ' QTDPRODUCAOHORA NUMBER(11,4), ' + ' INDCONFIGURACAO CHAR(1), ' + ' DESTEMPOCONFIGURACAO VARCHAR2(7), ' + ' PRIMARY KEY (CODAMOSTRA, SEQAMOSTRAPRODUTO), ' + ' FOREIGN KEY (CODAMOSTRA) REFERENCES AMOSTRA (CODAMOSTRA), ' + ' FOREIGN KEY (CODESTAGIO) REFERENCES ESTAGIOPRODUCAO (CODEST) ) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 24'); end; if VpaNumAtualizacao < 25 then begin VpfErro := '25'; ExecutaComandoSql(Aux,' ALTER TABLE CADPRODUTOS MODIFY L_DES_FUN VARCHAR2(2000)'); ExecutaComandoSql(Aux,' ALTER TABLE CADPRODUTOS MODIFY L_INF_DIS VARCHAR2(2000)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 25'); end; if VpaNumAtualizacao < 26 then begin VpfErro := '26'; ExecutaComandoSql(Aux,' CREATE TABLE APLICACAO (' + ' CODAPLICACAO NUMBER(10,0), ' + ' NOMAPLICACAO VARCHAR2(60), ' + ' PRIMARY KEY(CODAPLICACAO) ' + ' )'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 26'); end; if VpaNumAtualizacao < 27 then begin VpfErro := '27'; ExecutaComandoSql(Aux,' CREATE TABLE PROPOSTAPRODUTOCLIENTE (' + ' CODFILIAL NUMBER(10,0) NOT NULL, ' + ' SEQPROPOSTA NUMBER(10,0) NOT NULL, ' + ' SEQITEM NUMBER(10,0) NOT NULL,' + ' SEQPRODUTO NUMBER(10,0), ' + ' CODEMBALAGEM NUMBER(10,0), ' + ' CODAPLICACAO NUMBER(10,0), ' + ' DESPRODUCAO VARCHAR2(50), ' + ' DESSENTIDOPASSAGEM VARCHAR2(50), ' + ' DESDIAMETROTUBO VARCHAR2(50), ' + ' FOREIGN KEY(SEQPRODUTO) REFERENCES CADPRODUTOS(I_SEQ_PRO), ' + ' FOREIGN KEY(CODEMBALAGEM) REFERENCES EMBALAGEM(COD_EMBALAGEM), ' + ' FOREIGN KEY(CODAPLICACAO) REFERENCES APLICACAO(CODAPLICACAO), ' + ' PRIMARY KEY(CODFILIAL, SEQPROPOSTA, SEQITEM))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 27'); end; if VpaNumAtualizacao < 28 then begin VpfErro := '28'; ExecutaComandoSql(Aux,' ALTER TABLE PROPOSTAPRODUTOCLIENTE ADD DESOBSERVACAO VARCHAR2(100)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 28'); end; if VpaNumAtualizacao < 29 then begin VpfErro := '29'; ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTA ADD TIPHORASINSTALACAO NUMBER(10)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 29'); end; if VpaNumAtualizacao < 30 then begin VpfErro := '30'; ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_EST_AOC CHAR(1) NULL'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 30'); end; if VpaNumAtualizacao < 31 then begin VpfErro := '31'; ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EST_AOC = ''T'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 31'); end; if VpaNumAtualizacao < 32 then begin VpfErro := '32'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD I_EST_IMPC NUMBER(10)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 32'); end; if VpaNumAtualizacao < 33 then begin VpfErro := '33'; ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_POL_CTOT VARCHAR(1)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 33'); end; if VpaNumAtualizacao < 34 then begin VpfErro := '34'; ExecutaComandoSql(Aux,'ALTER TABLE RETORNOITEM MODIFY (DESDUPLICATA varchar2(20))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 34'); end; if VpaNumAtualizacao < 35 then begin VpfErro := '35'; ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRA ADD (CODSOLVEND NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 35'); end; if VpaNumAtualizacao < 36 then begin VpfErro := '36'; ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRA MODIFY (CODSOLVEND varchar2(20))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 36'); end; if VpaNumAtualizacao < 37 then begin VpfErro := '37'; ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD (C_MEN_BOL CHAR(1))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 37'); end; if VpaNumAtualizacao < 38 then begin VpfErro := '38'; ExecutaComandoSql(Aux,'UPDATE CADFILIAIS SET C_MEN_BOL= ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 38'); end; if VpaNumAtualizacao < 39 then begin VpfErro := '39'; ExecutaComandoSql(Aux,'CREATE TABLE PERFILCLIENTE (CODPERFIL INTEGER NOT NULL PRIMARY KEY, NOMPERFIL VARCHAR2(50))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 39'); end; if VpaNumAtualizacao < 40 then begin VpfErro := '40'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (C_GRU_ADM CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_GRU_ADM = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 40'); end; if VpaNumAtualizacao < 41 then begin VpfErro := '41'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (C_QTD_SOL CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_QTD_SOL = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 41'); end; if VpaNumAtualizacao < 42 then begin VpfErro := '42'; ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD (D_DAT_CER DATE)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 42'); end; if VpaNumAtualizacao < 43 then begin VpfErro := '43'; ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR ADD (I_COD_USU INTEGER)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 43'); end; if VpaNumAtualizacao < 44 then begin VpfErro := '44'; ExecutaComandoSql(Aux,'UPDATE CADNOTAFISCAISFOR SET I_COD_USU = 1'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 44'); end; if VpaNumAtualizacao < 45 then begin VpfErro := '45'; ExecutaComandoSql(Aux,'ALTER TABLE CADVENDEDORES ADD (C_IND_NFE CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CADVENDEDORES SET C_IND_NFE = ''N'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 45'); end; if VpaNumAtualizacao < 46 then begin VpfErro := '46'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (I_EST_COP NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 46'); end; if VpaNumAtualizacao < 47 then begin VpfErro := '47'; ExecutaComandoSql(Aux,'CREATE TABLE PRODUTOLOG( ' + ' SEQPRODUTO NUMBER(10) NOT NULL, ' + ' SEQLOG NUMBER(10) NOT NULL, ' + ' DATLOG DATE, ' + ' CODUSUARIO NUMBER(10),' + ' DESCAMINHOLOG VARCHAR2(200),' + ' PRIMARY KEY(SEQPRODUTO, SEQLOG))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 47'); end; if VpaNumAtualizacao < 48 then begin VpfErro := '48'; ExecutaComandoSql(Aux,'CREATE TABLE TABELAPERCOMISSAO( ' + ' CODACRESDESC NUMBER(10) NOT NULL, ' + ' PERCOMISSAO NUMBER(10),' + ' PERDESCONTO NUMBER(10),' + ' INDACRESDESC CHAR(1))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 48'); end; if VpaNumAtualizacao < 49 then begin VpfErro := '49'; ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD (I_PER_CLI NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 49'); end; if VpaNumAtualizacao < 50 then begin VpfErro := '50'; ExecutaComandoSql(Aux,'CREATE TABLE CONSUMOPRODUTOLOG( ' + ' SEQPRODUTO NUMBER(10) NOT NULL, ' + ' SEQLOG NUMBER(10) NOT NULL, ' + ' DATLOG DATE, ' + ' CODUSUARIO NUMBER(10),' + ' DESCAMINHOLOG VARCHAR2(200),' + ' PRIMARY KEY(SEQPRODUTO, SEQLOG))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 50'); end; if VpaNumAtualizacao < 51 then begin VpfErro := '51'; ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRA ADD (DESSOLVENDEDOR varchar2(20))'); ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRA DROP COLUMN CODSOLVEND'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 51'); end; if VpaNumAtualizacao < 52 then begin VpfErro := '52'; ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD (C_POL_CROM varchar2(1))'); ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD (C_POL_VROM VARCHAR2(1))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 52'); end; if VpaNumAtualizacao < 53 then begin VpfErro := '53'; ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_POL_CROM = ''F'''); ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_POL_VROM = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 53'); end; if VpaNumAtualizacao < 54 then begin VpfErro := '54'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD (C_IND_EMB varchar(1))'); ExecutaComandoSql(Aux,'UPDATE CFG_PRODUTO SET C_IND_EMB = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 54'); end; if VpaNumAtualizacao < 55 then begin VpfErro := '55'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (C_PCO_ARQ varchar(1))'); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_PCO_ARQ = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 55'); end; if VpaNumAtualizacao < 56 then begin VpfErro := '56'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (C_PCO_DIR varchar2(200))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 56'); end; if VpaNumAtualizacao < 57 then begin VpfErro := '57'; ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOCOMPRAITEM ADD (DESARQUIVOPROJETO varchar2(250))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 57'); end; if VpaNumAtualizacao < 58 then begin VpfErro := '58'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (I_TIP_EMB INTEGER)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 58'); end; if VpaNumAtualizacao < 59 then begin VpfErro := '59'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (I_PLA_EMB NUMBER(10), ' + ' I_PLS_EMB NUMBER(10), I_FER_EMB NUMBER(10), I_LAR_EMB NUMBER(10), I_ALT_EMB NUMBER(10), ' + ' I_FUN_EMB NUMBER(10), I_ABA_EMB NUMBER(10), I_DIA_EMB NUMBER(10), I_PEN_EMB NUMBER(10), ' + ' I_LAM_ZIP NUMBER(10), I_LAM_ABA NUMBER(10), I_FOT_NRO NUMBER(10), I_TAM_ZIP NUMBER(10), ' + ' I_COR_ZIP NUMBER(10), I_ALC_EMB NUMBER(10), I_IMP_EMB NUMBER(10), I_CBD_EMB NUMBER(10), ' + ' I_SIM_CAB NUMBER(10), I_BOT_EMB NUMBER(10), I_COR_BOT NUMBER(10), I_BOL_EMB NUMBER(10), ' + ' I_ZPE_EMB NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 59'); end; if VpaNumAtualizacao < 60 then begin VpfErro := '60'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (C_LOC_ALC VARCHAR(70), C_OBS_COR VARCHAR(70), C_INT_EMB VARCHAR(10), ' + ' C_INU_EMB VARCHAR(10), C_COR_IMP VARCHAR(40), C_OBS_BOT VARCHAR(70), C_ADI_EMB VARCHAR(70),' + ' C_PRE_FAC VARCHAR(15), C_PRC_EMB VARCHAR(15), C_COR_SIM CHAR(1), C_COR_NAO CHAR(1), ' + ' C_BOL_SIM CHAR(1), C_BOL_NAO CHAR(1), C_ITN_EMB CHAR(1), C_EXT_EMB CHAR(1))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 60'); end; if VpaNumAtualizacao < 61 then begin VpfErro := '61'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (I_COD_VIE INTEGER)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 61'); end; if VpaNumAtualizacao < 62 then begin VpfErro := '62'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (C_CAR_IEV CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CAR_IEV = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 62'); end; if VpaNumAtualizacao < 63 then begin VpfErro := '63'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (I_ETI_VOL INTEGER)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 63'); end; if VpaNumAtualizacao < 64 then begin VpfErro := '64'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS DROP (C_COR_SIM, C_COR_NAO, C_BOL_SIM, C_BOL_NAO, C_ITN_EMB, C_EXT_EMB)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 64'); end; if VpaNumAtualizacao < 65 then begin VpfErro := '65'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (C_IND_CRT CHAR(1), C_IND_BOL CHAR(1), C_IND_IEX CHAR(1))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 65'); end; if VpaNumAtualizacao < 66 then begin VpfErro := '66'; ExecutaComandoSql(Aux, 'CREATE TABLE ORCAMENTOROTEIROENTREGA( ' + ' SEQORCAMENTOROTEIRO NUMBER(10) NOT NULL, ' + ' CODENTREGADOR NUMBER(10) NOT NULL, ' + ' DATABERTURA DATE, '+ ' DATFECHAMENTO DATE,' + ' PRIMARY KEY(SEQORCAMENTOROTEIRO))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 66'); end; if VpaNumAtualizacao < 67 then begin VpfErro := '67'; ExecutaComandoSql(Aux, 'CREATE TABLE ORCAMENTOROTEIROENTREGAITEM( ' + ' SEQORCAMENTOROTEIRO NUMBER(10) NOT NULL, ' + ' SEQORCAMENTO NUMBER(10) NOT NULL, ' + ' CODFILIALORCAMENTO NUMBER(10) NOT NULL, ' + ' PRIMARY KEY(SEQORCAMENTO,CODFILIALORCAMENTO),' + ' FOREIGN KEY(SEQORCAMENTOROTEIRO) REFERENCES ORCAMENTOROTEIROENTREGA(SEQORCAMENTOROTEIRO))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 67'); end; if VpaNumAtualizacao < 68 then begin VpfErro := '68'; ExecutaComandoSql(Aux, 'DROP TABLE ORCAMENTOROTEIROENTREGAITEM'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 68'); end; if VpaNumAtualizacao < 69 then begin VpfErro := '69'; ExecutaComandoSql(Aux, 'CREATE TABLE ORCAMENTOROTEIROENTREGAITEM( ' + ' SEQORCAMENTOROTEIRO NUMBER(10) NOT NULL, ' + ' SEQORCAMENTO NUMBER(10) NOT NULL, ' + ' CODFILIALORCAMENTO NUMBER(10) NOT NULL, ' + ' PRIMARY KEY(SEQORCAMENTOROTEIRO,SEQORCAMENTO,CODFILIALORCAMENTO),' + ' FOREIGN KEY(SEQORCAMENTOROTEIRO) REFERENCES ORCAMENTOROTEIROENTREGA(SEQORCAMENTOROTEIRO),'+ ' FOREIGN KEY(SEQORCAMENTO, CODFILIALORCAMENTO) REFERENCES CADORCAMENTOS(I_LAN_ORC,I_EMP_FIL))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 69'); end; if VpaNumAtualizacao < 70 then begin VpfErro := '70'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS DROP (C_PRE_FAC,C_PRC_EMB)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 70'); end; if VpaNumAtualizacao < 71 then begin VpfErro := '71'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (I_PRE_FAC NUMBER(10), I_PRC_EMB NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 71'); end; if VpaNumAtualizacao < 72 then begin VpfErro := '72'; ExecutaComandoSql(Aux,'ALTER TABLE CHAMADOPRODUTO ADD (VALBACKUP NUMBER(15,3))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 72'); end; if VpaNumAtualizacao < 73 then begin VpfErro := '73'; ExecutaComandoSql(Aux,'ALTER TABLE CADVENDEDORES ADD (C_DES_MSN VARCHAR(50))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 73'); end; if VpaNumAtualizacao < 74 then begin VpfErro := '74'; ExecutaComandoSql(Aux,'ALTER TABLE CADVENDEDORES ADD (I_COD_PRF NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 74'); end; if VpaNumAtualizacao < 75 then begin VpfErro := '75'; ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTAPRODUTO ADD (SEQITEMCHAMADO NUMBER(10), SEQPRODUTOCHAMADO NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 75'); end; if VpaNumAtualizacao < 76 then begin VpfErro := '76'; ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTASERVICO ADD (SEQITEMCHAMADO NUMBER(10), SEQPRODUTOCHAMADO NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 76'); end; if VpaNumAtualizacao < 77 then begin VpfErro := '77'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (C_LOC_IMP VARCHAR(50))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 77'); end; if VpaNumAtualizacao < 78 then begin VpfErro := '78'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS DROP (I_FOT_NRO, I_LAM_ZIP, I_LAM_ABA)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 78'); end; if VpaNumAtualizacao < 79 then begin VpfErro := '79'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (C_FOT_NRO VARCHAR(15), C_LAM_ZIP VARCHAR(15), C_LAM_ABA VARCHAR(15))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 79'); end; if VpaNumAtualizacao < 80 then begin VpfErro := '80'; ExecutaComandoSql(Aux,'ALTER TABLE FACA ADD (ABAFACA NUMBER(9,3), FUNFACA NUMBER(9,3), TOTFACA NUMBER(9,3), PENFACA NUMBER(9,3))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 80'); end; if VpaNumAtualizacao < 81 then begin VpfErro := '81'; ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTAPRODUTOROTULADO ADD (OBSPRODUTO VARCHAR2(500))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 81'); end; if VpaNumAtualizacao < 82 then begin VpfErro := '82'; ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTAPRODUTOROTULADO ADD (DESPROROTULADO VARCHAR2(1000))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 82'); end; if VpaNumAtualizacao < 83 then begin VpfErro := '83'; ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD (C_TIP_FO1 VARCHAR2(10), C_TIP_FO2 VARCHAR2(10), C_TIP_FO3 VARCHAR2(10) )'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 83'); end; if VpaNumAtualizacao < 84 then begin VpfErro := '84'; ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD (C_END_COT VARCHAR2(60) )'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 84'); end; if VpaNumAtualizacao < 85 then begin VpfErro := '85'; ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD (N_QTD_TPR NUMBER(17,3) )'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 85'); end; if VpaNumAtualizacao < 86 then begin VpfErro := '86'; ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTA ADD (DESTEMPOGARANTIA VARCHAR2(10) )'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 86'); end; if VpaNumAtualizacao < 87 then begin VpfErro := '87'; ExecutaComandoSql(Aux,'CREATE TABLE OBSPROPOSTACOMERCIAL (CODOBSPROPOSTA NUMBER(10), OBSINSTALACAO VARCHAR2(1000))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 87'); end; if VpaNumAtualizacao < 88 then begin VpfErro := '88'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (C_DES_COM VARCHAR2(50))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 88'); end; if VpaNumAtualizacao < 89 then begin VpfErro := '89'; ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTA ADD (CODOBSINSTALACAO NUMBER(10) )'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 89'); end; if VpaNumAtualizacao < 90 then begin VpfErro := '90'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (C_INF_TEC VARCHAR2(1000))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 90'); end; if VpaNumAtualizacao < 91 then begin VpfErro := '91'; ExecutaComandoSql(Aux, 'DROP TABLE OBSPROPOSTACOMERCIAL'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 91'); end; if VpaNumAtualizacao < 92 then begin VpfErro := '92'; ExecutaComandoSql(Aux,'CREATE TABLE OBSERVACAOINSTALACAOPROPOSTA( ' + ' CODOBSINSTALACAOPROPOSTA NUMBER(10) NOT NULL, ' + ' NOMOBSINSTALACAOPROPOSTA VARCHAR(40), '+ ' DESOBSINSTALACAOPROPOSTA VARCHAR2(1000),' + ' PRIMARY KEY (CODOBSINSTALACAOPROPOSTA))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 92'); end; if VpaNumAtualizacao < 93 then begin VpfErro := '93'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS DROP(I_LAR_EMB,I_ALT_EMB, ' + ' I_FUN_EMB, I_ABA_EMB, I_DIA_EMB, I_PEN_EMB)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 93'); end; if VpaNumAtualizacao < 94 then begin VpfErro := '94'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD(C_LAR_EMB VARCHAR2(15),C_ALT_EMB VARCHAR2(15), ' + ' C_FUN_EMB VARCHAR2(15), C_ABA_EMB VARCHAR2(15), ' + ' C_DIA_EMB VARCHAR2(15), C_PEN_EMB VARCHAR2(15))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 94'); end; if VpaNumAtualizacao < 95 then begin VpfErro := '95'; ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (C_LOC_INT VARCHAR(50))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 95'); end; if VpaNumAtualizacao < 96 then begin VpfErro := '96'; ExecutaComandoSql(Aux,'ALTER TABLE CADEMPRESAS ADD (C_COT_MES CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CADEMPRESAS SET C_COT_MES = ''S'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 96'); end; if VpaNumAtualizacao < 97 then begin VpfErro := '97'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (C_DIR_PRO VARCHAR2(240))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 97'); end; if VpaNumAtualizacao < 98 then begin VpfErro := '98'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (I_EST_CAN NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 98'); end; if VpaNumAtualizacao < 99 then begin VpfErro := '99'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (C_CRM_INS CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CRM_INS = ''N'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 99'); end; if VpaNumAtualizacao < 100 then begin VpfErro := '100'; ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTA ADD (DESOBSERVACAOINSTALACAO VARCHAR2(3000)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 100'); end; if VpaNumAtualizacao < 101 then begin VpfErro := '101'; ExecutaComandoSql(Aux,' ALTER TABLE CHAMADOCORPO ADD (DESOBSERVACAOGERAL VARCHAR2(3000))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 101'); end; if VpaNumAtualizacao < 102 then begin VpfErro := '102'; ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTAPRODUTO ADD (DESOBSERVACAO VARCHAR2(200))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 102'); end; if VpaNumAtualizacao < 103 then begin VpfErro := '103'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (I_EST_CCA NUMBER (10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 103'); end; if VpaNumAtualizacao < 104 then begin VpfErro := '104'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (C_DIR_PRT VARCHAR2(240))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 104'); end; if VpaNumAtualizacao < 105 then begin VpfErro := '105'; ExecutaComandoSql(Aux,'CREATE TABLE PRODUTOCLIENTEPECA( ' + ' CODPRODUTOCLIENTEPECA NUMBER(10) NOT NULL, ' + ' SEQPRODUTOSELECIONADO NUMBER(10), ' + ' SEQPRODUTO NUMBER(10), '+ ' CODPRODUTO VARCHAR2(50),' + ' NOMPRODUTO VARCHAR2(100), ' + ' DESNUMSERIE VARCHAR2(30), ' + ' DATINSTALACAO DATE, ' + ' PRIMARY KEY (CODPRODUTOCLIENTEPECA, SEQPRODUTOSELECIONADO, SEQPRODUTO))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 105'); end; if VpaNumAtualizacao < 106 then begin VpfErro := '106'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_PRODUTO ADD(C_CLA_MPA VARCHAR2(15))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 106'); end; if VpaNumAtualizacao < 107 then begin VpfErro := '107'; ExecutaComandoSql(Aux,' ALTER TABLE SETOR ADD(INDIMPRESSAOOPCAO CHAR(1)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 107'); end; if VpaNumAtualizacao < 108 then begin VpfErro := '108'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_ORC_NPE CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_ORC_NPE = ''N'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 108'); end; if VpaNumAtualizacao < 109 then begin VpfErro := '109'; ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_LOG_PSC CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_LOG_PSC = ''N'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 109'); end; if VpaNumAtualizacao < 110 then begin VpfErro := '110'; ExecutaComandoSql(Aux,' CREATE TABLE PLANOCONTAORCADO( ' + ' CODEMPRESA NUMBER(10) NOT NULL, '+ ' CODPLANOCONTA VARCHAR2(20) NOT NULL,' + ' ANOORCADO NUMBER(10) NOT NULL, ' + ' VALJANEIRO NUMBER(15,3), ' + ' VALFEVEREIRO NUMBER(15,3), ' + ' VALMARCO NUMBER(15,3), ' + ' VALABRIL NUMBER(15,3), ' + ' VALMAIO NUMBER(15,3), ' + ' VALJUNHO NUMBER(15,3), ' + ' VALJULHO NUMBER(15,3), ' + ' VALAGOSTO NUMBER(15,3), ' + ' VALSETEMBRO NUMBER(15,3), ' + ' VALOUTUBRO NUMBER(15,3), ' + ' VALNOVEMBRO NUMBER(15,3), ' + ' VALDEZEMBRO NUMBER(15,3), ' + ' PRIMARY KEY (CODEMPRESA, CODPLANOCONTA, ANOORCADO))'); ExecutaComandoSql(Aux,'ALTER TABLE PLANOCONTAORCADO add CONSTRAINT PLANOCONTAORCADO_PLANO '+ ' FOREIGN KEY (CODEMPRESA,CODPLANOCONTA) '+ ' REFERENCES CAD_PLANO_CONTA (I_COD_EMP,C_CLA_PLA) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 110'); end; if VpaNumAtualizacao < 111 then begin VpfErro := '111'; ExecutaComandoSql(Aux,' ALTER TABLE CADEMPRESAS ADD (C_TMK_ORD CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CADEMPRESAS SET C_TMK_ORD = ''N'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 111'); end; if VpaNumAtualizacao < 112 then begin VpfErro := '112'; ExecutaComandoSql(Aux,' ALTER TABLE PEDIDOCOMPRAITEM ADD (VALIPI NUMBER(15,4))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 112'); end; if VpaNumAtualizacao < 113 then begin VpfErro := '113'; ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAISFOR ADD (N_VLR_MVA NUMBER(17,2), N_VLR_BST NUMBER(17,2), ' + ' N_VLR_TST NUMBER(17,2), N_PER_ACU NUMBER(8,3)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 113'); end; if VpaNumAtualizacao < 114 then begin VpfErro := '114'; ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD (C_ROM_ABE CHAR(1)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 114'); end; if VpaNumAtualizacao < 115 then begin VpfErro := '115'; ExecutaComandoSql(Aux,' ALTER TABLE PLANOCONTAORCADO ADD(VALTOTAL NUMBER (15,3)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 115'); end; if VpaNumAtualizacao < 116 then begin VpfErro := '116'; ExecutaComandoSql(Aux,' ALTER TABLE CADPRODUTOS MODIFY I_PRE_FAC NUMBER(15,3)'); ExecutaComandoSql(Aux,' ALTER TABLE CADPRODUTOS MODIFY I_PRC_EMB NUMBER(15,3)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 116'); end; if VpaNumAtualizacao < 117 then begin VpfErro := '117'; ExecutaComandoSql(Aux,' ALTER TABLE CHEQUE ADD (DATEMISSAO DATE) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 117'); end; if VpaNumAtualizacao < 118 then begin VpfErro := '118'; ExecutaComandoSql(Aux,' ALTER TABLE ORCAMENTOROTEIROENTREGAITEM ADD (DATFECHAMENTO DATE) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 118'); end; if VpaNumAtualizacao < 119 then begin VpfErro := '119'; ExecutaComandoSql(Aux,' ALTER TABLE CADPRODUTOS ADD (N_PER_ICM NUMBER(8,3))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 119'); end; if VpaNumAtualizacao < 120 then begin VpfErro := '120'; ExecutaComandoSql(Aux,'CREATE TABLE CHAMADOPRODUTOAPRODUZIR( ' + ' CODFILIAL NUMBER(10,0) NOT NULL, ' + ' NUMCHAMADO NUMBER(10,0) NOT NULL, ' + ' SEQITEM NUMBER(10,0) NOT NULL, '+ ' SEQITEMORCADO NUMBER(10,0) NOT NULL, ' + ' SEQPRODUTO NUMBER(10,0), ' + ' QTDPRODUTO NUMBER(15,4), '+ ' VALUNITARIO NUMBER(15,4), ' + ' VALTOTAL NUMBER(15,5), ' + ' DESUM VARCHAR2(2),' + ' PRIMARY KEY (CODFILIAL, NUMCHAMADO, SEQITEM, SEQITEMORCADO))'); ExecutaComandoSql(Aux,'ALTER TABLE CHAMADOPRODUTOAPRODUZIR add CONSTRAINT CHAMADOPRODUTOAPRODUZIR '+ ' FOREIGN KEY (CODFILIAL,NUMCHAMADO) '+ ' REFERENCES CHAMADOCORPO (CODFILIAL,NUMCHAMADO) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 120'); end; if VpaNumAtualizacao < 121 then begin VpfErro := '121'; ExecutaComandoSql(Aux,'ALTER TABLE ESTAGIOPRODUCAO ADD (INDEMAIL CHAR(1)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 121'); end; if VpaNumAtualizacao < 122 then begin VpfErro := '122'; ExecutaComandoSql(Aux,' ALTER TABLE CHAMADOPRODUTOAPRODUZIR ADD(DATENTREGA DATE) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 122'); end; if VpaNumAtualizacao < 123 then begin VpfErro := '123'; ExecutaComandoSql(Aux,' ALTER TABLE PROPOSTAPRODUTO ADD(PERIPI NUMBER(5,3), VALIPI NUMBER(15,4))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 123'); end; if VpaNumAtualizacao < 124 then begin VpfErro := '124'; ExecutaComandoSql(Aux,'CREATE TABLE MOVSERVICONOTAFOR( ' + ' I_EMP_FIL NUMBER(10,0) NOT NULL, ' + ' I_SEQ_NOT NUMBER(10,0) NOT NULL, ' + ' I_SEQ_MOV NUMBER(10,0) NOT NULL, ' + ' I_COD_SER NUMBER(10,0) NOT NULL, ' + ' N_VLR_SER NUMBER(17,3), ' + ' I_COD_EMP NUMBER(10,0), ' + ' N_QTD_SER NUMBER(17,3), ' + ' N_TOT_SER NUMBER(17,3), ' + ' D_ULT_ALT DATE, ' + ' C_DES_ADI VARCHAR2(70), ' + ' C_NOM_SER VARCHAR2(250), ' + ' PRIMARY KEY (I_EMP_FIL, I_SEQ_NOT, I_SEQ_MOV))'); ExecutaComandoSql(Aux,'ALTER TABLE MOVSERVICONOTAFOR add CONSTRAINT MOVSERVICONOTAFOR '+ ' FOREIGN KEY (I_EMP_FIL,I_SEQ_NOT) '+ ' REFERENCES CADNOTAFISCAISFOR (I_EMP_FIL,I_SEQ_NOT) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 124'); end; if VpaNumAtualizacao < 125 then begin VpfErro := '125'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_NOE_SPR CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_NOE_SPR = ''N'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 125'); end; if VpaNumAtualizacao < 126 then begin VpfErro := '126'; ExecutaComandoSql(Aux,' ALTER TABLE PROPOSTA ADD (VALTOTALPRODUTOS NUMBER(15,3), VALTOTALIPI NUMBER(15,3)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 126'); end; if VpaNumAtualizacao < 127 then begin VpfErro := '127'; ExecutaComandoSql(Aux,' ALTER TABLE CADNOTAFISCAISFOR ADD (N_TOT_SER NUMBER(17,2)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 127'); end; if VpaNumAtualizacao < 128 then begin VpfErro := '128'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD (C_CRM_DET CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CRM_DET = ''N'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 128'); end; if VpaNumAtualizacao < 129 then begin VpfErro := '129'; ExecutaComandoSql(Aux,'CREATE TABLE PROPOSTACONDICAOPAGAMENTO( ' + ' CODFILIAL NUMBER(10,0) NOT NULL, ' + ' SEQPROPOSTA NUMBER(10,0) NOT NULL, ' + ' CODCONDICAO NUMBER(10,0) NOT NULL, ' + ' NOMCONDICAO VARCHAR2(50), ' + ' INDAPROVADO CHAR(1), ' + ' PRIMARY KEY (CODFILIAL, SEQPROPOSTA, CODCONDICAO))'); ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTACONDICAOPAGAMENTO add CONSTRAINT PROPOSTACONDICAOPAGAMENTO '+ ' FOREIGN KEY (CODFILIAL,SEQPROPOSTA) '+ ' REFERENCES PROPOSTA (CODFILIAL,SEQPROPOSTA) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 129'); end; if VpaNumAtualizacao < 130 then begin VpfErro := '130'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD (C_CRM_OBP VARCHAR2(4000)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 130'); end; if VpaNumAtualizacao < 131 then begin VpfErro := '131'; ExecutaComandoSql(Aux,'CREATE TABLE PROPOSTAMATERIALACABAMENTO( ' + ' CODFILIAL NUMBER(10,0) NOT NULL, ' + ' SEQPROPOSTA NUMBER(10,0) NOT NULL, ' + ' SEQPRODUTO NUMBER(10,0) NOT NULL, ' + ' CODPRODUTO VARCHAR2(20), ' + ' NOMPRODUTO VARCHAR2(80),' + ' DESUM VARCHAR2(2),' + ' QTDPRODUTO NUMBER(15,4),' + ' VALUNITARIO NUMBER(15,4),' + ' VALTOTAL NUMBER(15,4),' + ' PRIMARY KEY (CODFILIAL, SEQPROPOSTA, SEQPRODUTO))'); ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTAMATERIALACABAMENTO add CONSTRAINT PROPOSTAMATERIALACABAMENTO '+ ' FOREIGN KEY (CODFILIAL,SEQPROPOSTA) '+ ' REFERENCES PROPOSTA (CODFILIAL,SEQPROPOSTA) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 131'); end; if VpaNumAtualizacao < 132 then begin VpfErro := '132'; ExecutaComandoSql(Aux,' ALTER TABLE CADGRUPOS ADD(C_CRM_EFC CHAR(1)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 132'); end; if VpaNumAtualizacao < 133 then begin VpfErro := '133'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD (C_EST_PRC NUMBER(10)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 133'); end; if VpaNumAtualizacao < 134 then begin VpfErro := '134'; ExecutaComandoSql(Aux,' ALTER TABLE CADGRUPOS ADD (C_CHA_EFC char(1)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 134'); end; if VpaNumAtualizacao < 135 then begin VpfErro := '135'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_FINANCEIRO ADD(C_CLI_BLO CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_FINANCEIRO SET C_CLI_BLO = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 135'); end; if VpaNumAtualizacao < 136 then begin VpfErro := '136'; ExecutaComandoSql(Aux,' ALTER TABLE CADGRUPOS ADD(C_CLI_INA CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_CLI_INA = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 136'); end; if VpaNumAtualizacao < 137 then begin VpfErro := '137'; ExecutaComandoSql(Aux,' ALTER TABLE CHAMADOPRODUTOORCADO ADD (DATPRODUCAO DATE) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 137'); end; if VpaNumAtualizacao < 138 then begin VpfErro := '138'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD (C_CHA_SDP CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CHA_SDP = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 138'); end; if VpaNumAtualizacao < 139 then begin VpfErro := '139'; ExecutaComandoSql(Aux,' ALTER TABLE CHAMADOCORPO ADD (DESTIPOCHAMADO VARCHAR2(50)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 139'); end; if VpaNumAtualizacao < 140 then begin VpfErro := '140'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_CRM_GAR VARCHAR2(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 140'); end; if VpaNumAtualizacao < 141 then begin VpfErro := '141'; ExecutaComandoSql(Aux,' ALTER TABLE PRODUTOACESSORIO ADD(SEQITEM NUMBER(10)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 141'); end; if VpaNumAtualizacao < 142 then begin VpfErro := '142'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_OBS_NOT CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_OBS_NOT = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 142'); end; if VpaNumAtualizacao < 143 then begin VpfErro := '143'; ExecutaComandoSql(Aux,' ALTER TABLE CHEQUE ADD(NUMCONTA NUMBER(10), NUMAGENCIA NUMBER(10)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 143'); end; if VpaNumAtualizacao < 144 then begin VpfErro := '144'; ExecutaComandoSql(Aux,' ALTER TABLE TAREFATELEMARKETING ADD(INDSITUACAOCLIENTE CHAR(1)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 144'); end; if VpaNumAtualizacao < 145 then begin VpfErro := '145'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_TAB_CLI CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_TAB_CLI = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 145'); end; if VpaNumAtualizacao < 146 then begin VpfErro := '146'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_PRE_TAB CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_PRE_TAB = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 146'); end; if VpaNumAtualizacao < 147 then begin VpfErro := '147'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_PEC_PDF CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_PEC_PDF = ''T'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 147'); end; if VpaNumAtualizacao < 148 then begin VpfErro := '148'; ExecutaComandoSql(Aux,'CREATE TABLE CONTRATOSERVICO( ' + ' CODFILIAL NUMBER(10,0) NOT NULL, ' + ' SEQCONTRATO NUMBER(10,0) NOT NULL, ' + ' SEQITEM NUMBER(10,0) NOT NULL, ' + ' CODSERVICO NUMBER(10,0) NOT NULL, ' + ' VALSERVICO NUMBER(17,3), ' + ' CODEMPRESA NUMBER(10,0), ' + ' QTDSERVICO NUMBER(17,3), ' + ' VALTOTSERVICO NUMBER(17,3), ' + ' DATULTIMAALTERACAO DATE, ' + ' DESADICIONAIS VARCHAR2(70), ' + ' NOMSERVICO VARCHAR2(250), ' + ' PRIMARY KEY (CODFILIAL, SEQCONTRATO, SEQITEM))'); ExecutaComandoSql(Aux,'ALTER TABLE CONTRATOSERVICO add CONSTRAINT CONTRATOSERVICO '+ ' FOREIGN KEY (CODFILIAL,SEQCONTRATO) '+ ' REFERENCES CONTRATOCORPO (CODFILIAL,SEQCONTRATO) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 148'); end; if VpaNumAtualizacao < 149 then begin VpfErro := '149'; ExecutaComandoSql(Aux,' UPDATE CFG_GERAL SET C_ORC_NPE = ''F'' WHERE C_ORC_NPE = ''N'''); ExecutaComandoSql(Aux,' UPDATE CFG_GERAL SET C_CRM_INS = ''F'' WHERE C_CRM_INS = ''N'''); ExecutaComandoSql(Aux,' UPDATE CFG_GERAL SET C_LOG_PSC = ''F'' WHERE C_LOG_PSC = ''N'''); ExecutaComandoSql(Aux,' UPDATE CFG_GERAL SET C_NOE_SPR = ''F'' WHERE C_NOE_SPR = ''N'''); ExecutaComandoSql(Aux,' UPDATE CFG_GERAL SET C_CRM_DET = ''F'' WHERE C_CRM_DET = ''N'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 149'); end; if VpaNumAtualizacao < 150 then begin VpfErro := '150'; ExecutaComandoSql(Aux,' ALTER TABLE AMOSTRA ADD(INDPRECOESTIMADO CHAR(1)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 150'); end; if VpaNumAtualizacao < 151 then begin VpfErro := '151'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_AMO_PEO CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_AMO_PEO = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 151'); end; if VpaNumAtualizacao < 152 then begin VpfErro := '152'; ExecutaComandoSql(Aux,' ALTER TABLE AMOSTRACOR ADD(VALPRECOESTIMADO NUMBER(15,4)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 152'); end; if VpaNumAtualizacao < 153 then begin VpfErro := '153'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_AMO_PRV CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_AMO_PRV = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 153'); end; if VpaNumAtualizacao < 154 then begin VpfErro := '154'; ExecutaComandoSql(Aux,' CREATE TABLE MOTIVOATRASO( ' + ' CODMOTIVOATRASO NUMBER(10,0) NOT NULL, ' + ' DESMOTIVOATRASO VARCHAR2(80), ' + ' PRIMARY KEY (CODMOTIVOATRASO))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 154'); end; if VpaNumAtualizacao < 155 then begin VpfErro := '155'; ExecutaComandoSql(Aux,' CREATE TABLE AMOSTRACORMOTIVOATRASO( ' + ' CODAMOSTRA NUMBER(10) NOT NULL, ' + ' CODCOR NUMBER(10) NOT NULL, ' + ' SEQITEM NUMBER(10) NOT NULL, ' + ' CODMOTIVOATRASO NUMBER(10), ' + ' DESOBSERVACAO VARCHAR2(80), ' + ' PRIMARY KEY (CODAMOSTRA, CODCOR, SEQITEM))'); ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRACORMOTIVOATRASO add CONSTRAINT AMOSTRACORMOTIVOATRASO '+ ' FOREIGN KEY (CODAMOSTRA,CODCOR) '+ ' REFERENCES AMOSTRACOR (CODAMOSTRA,CODCOR) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 155'); end; if VpaNumAtualizacao < 156 then begin VpfErro := '156'; ExecutaComandoSql(Aux,' ALTER TABLE AMOSTRACORMOTIVOATRASO ADD CODUSUARIO NUMBER(10)NULL'); ExecutaComandoSql(Aux,' CREATE INDEX AMOSTRACORMOTIVOATRASO_FK1 ON AMOSTRACORMOTIVOATRASO(CODMOTIVOATRASO)'); ExecutaComandoSql(Aux,' CREATE INDEX AMOSTRACORMOTIVOATRASO_FK2 ON AMOSTRACORMOTIVOATRASO(CODUSUARIO)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 156'); end; if VpaNumAtualizacao < 157 then begin VpfErro := '157'; ExecutaComandoSql(Aux,' ALTER TABLE MOVNOTASFISCAISFOR ADD(N_VLR_BIC NUMBER(8,3), N_VLR_ICM NUMBER(17,3)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 157'); end; if VpaNumAtualizacao < 158 then begin VpfErro := '158'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_COT_LMO CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_LMO = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 158'); end; if VpaNumAtualizacao < 159 then begin VpfErro := '159'; ExecutaComandoSql(Aux,' ALTER TABLE CADGRUPOS ADD(C_POL_NIC CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_POL_NIC = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 159'); end; if VpaNumAtualizacao < 160 then begin VpfErro := '160'; ExecutaComandoSql(Aux,' ALTER TABLE CADGRUPOS ADD(C_POL_ROT CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_POL_ROT = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 160'); end; if VpaNumAtualizacao < 161 then begin VpfErro := '161'; ExecutaComandoSql(Aux,' ALTER TABLE ORCAMENTOROTEIROENTREGAITEM ADD(DATSAIDAENTREGA DATE) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 161'); end; if VpaNumAtualizacao < 162 then begin VpfErro := '162'; ExecutaComandoSql(Aux,' ALTER TABLE PROPOSTA ADD(DESOBSDATAINSTALACAO VARCHAR2(70)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 162'); end; if VpaNumAtualizacao < 163 then begin VpfErro := '163'; ExecutaComandoSql(Aux,' ALTER TABLE ORCAMENTOROTEIROENTREGA ADD(DATBLOQUEIO DATE)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 163'); end; VpfErro := AtualizaBanco1(VpaNumAtualizacao); VpfSemErros := true; except on E : Exception do begin Aux.sql.SaveToFile('comando.sql'); Aux.Sql.text := E.message; Aux.Sql.SavetoFile('ErroInicio.txt'); if Confirmacao(VpfErro + ' PRG1 - Existe uma alteração para ser feita no banco de dados mas existem usuários'+ ' utilizando o sistema, ou algum outro sistema sendo utilizado no seu computador, é necessário'+ ' que todos os usuários saiam do sistema, para'+ ' poder continuar. Deseja continuar agora?') then Begin VpfSemErros := false; AdicionaSQLAbreTabela(Aux,'Select I_Ult_PR1 from CFG_GERAL '); VpaNumAtualizacao := Aux.FieldByName('I_ULT_PR1').AsInteger; end else exit; end; end; until VpfSemErros; end; {******************************************************************************} function TRBFunProgramador1.AtualizaBanco1(VpaNumAtualizacao: integer): string; begin Result:= ''; if VpaNumAtualizacao < 164 then begin Result := '164'; ExecutaComandoSql(Aux,' DROP TABLE PRODUTOCLIENTEPECA '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 164'); end; if VpaNumAtualizacao < 165 then begin Result := '165'; ExecutaComandoSql(Aux,'CREATE TABLE PRODUTOCLIENTEPECA( ' + ' SEQPRODUTOCLIENTE NUMBER(10) NOT NULL, ' + ' CODCLIENTE NUMBER(10) NOT NULL, '+ ' SEQITEMPRODUTOCLIENTE NUMBER(10) NOT NULL,' + ' SEQITEMPECA NUMBER(10) NOT NULL, ' + ' SEQPRODUTOPECA NUMBER(10) NOT NULL, ' + ' DESNUMSERIE VARCHAR2(30), ' + ' DATINSTALACAO DATE, ' + ' PRIMARY KEY (SEQPRODUTOCLIENTE, CODCLIENTE, SEQITEMPRODUTOCLIENTE, SEQITEMPECA ))'); ExecutaComandoSql(Aux,'ALTER TABLE PRODUTOCLIENTEPECA add CONSTRAINT PRODUTOCLIENTEPECA '+ ' FOREIGN KEY (SEQPRODUTOCLIENTE,CODCLIENTE,SEQITEMPRODUTOCLIENTE) '+ ' REFERENCES PRODUTOCLIENTE (SEQPRODUTO,CODCLIENTE,SEQITEM) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 165'); end; if VpaNumAtualizacao < 166 then begin Result := '16'; ExecutaComandoSql(Aux,' ALTER TABLE CADGRUPOS ADD(C_FAT_SPF CHAR(1))'); ExecutaComandoSql(Aux,' update CADGRUPOS CADGRUPOS SET C_FAT_SPF = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 166'); end; if VpaNumAtualizacao < 167 then begin Result := '167'; ExecutaComandoSql(Aux,' ALTER TABLE AMOSTRAPROCESSO ADD(DESOBSERVACAO VARCHAR2(150)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 167'); end; if VpaNumAtualizacao < 168 then begin Result := '168'; ExecutaComandoSql(Aux,' ALTER TABLE CADORCAMENTOS ADD(C_ORD_COR VARCHAR2(20)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 168'); end; if VpaNumAtualizacao < 169 then begin Result := '169'; ExecutaComandoSql(Aux,' ALTER TABLE ROMANEIOORCAMENTOITEM ADD(DESORDEMCORTE VARCHAR2(20)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 169'); end; if VpaNumAtualizacao < 170 then begin Result := '170'; ExecutaComandoSql(Aux,' ALTER TABLE MOVORCAMENTOS ADD(C_ORD_COR VARCHAR2(20)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 170'); end; if VpaNumAtualizacao < 171 then begin Result := '171'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_CRM_VUC CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CRM_VUC = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 171'); end; if VpaNumAtualizacao < 172 then begin Result := '172'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_CRM_PMP CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CRM_PMP = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 172'); end; if VpaNumAtualizacao < 173 then begin Result := '173'; ExecutaComandoSql(Aux,' ALTER TABLE CADGRUPOS ADD(C_CRM_VDR CHAR(1))'); ExecutaComandoSql(Aux,' update CADGRUPOS CADGRUPOS SET C_CRM_VDR = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 173'); end; if VpaNumAtualizacao < 174 then begin Result := '174'; ExecutaComandoSql(Aux,' ALTER TABLE RECIBOLOCACAOCORPO ADD(INDCANCELADO CHAR(1))'); ExecutaComandoSql(Aux,' update RECIBOLOCACAOCORPO SET INDCANCELADO = ''N'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 174'); end; if VpaNumAtualizacao < 175 then begin Result := '175'; ExecutaComandoSql(Aux,' ALTER TABLE RECIBOLOCACAOCORPO ADD(DESMOTIVOCANCELAMENTO VARCHAR2(40), DATCANCELAMENTO DATE, CODUSUARIOCANCELAMENTO NUMBER(10)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 175'); end; if VpaNumAtualizacao < 176 then begin Result := '176'; ExecutaComandoSql(Aux,' ALTER TABLE LEITURALOCACAOCORPO ADD(DESORDEMCOMPRA VARCHAR2(20))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 176'); end; if VpaNumAtualizacao < 177 then begin Result := '177'; ExecutaComandoSql(Aux,' ALTER TABLE RECIBOLOCACAOCORPO ADD(DESORDEMCOMPRA VARCHAR2(20))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 177'); end; if VpaNumAtualizacao < 178 then begin Result := '178'; ExecutaComandoSql(Aux,' ALTER TABLE RECIBOLOCACAOCORPO ADD(DESOBSERVACAOCOTACAO VARCHAR2(4000)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 178'); end; if VpaNumAtualizacao < 179 then begin Result := '179'; ExecutaComandoSql(Aux,'CREATE TABLE ALTERACLIENTEVENDEDOR (' + ' SEQITEM NUMBER(10) NOT NULL, '+ ' CODUSUARIO NUMBER(10)NULL, ' + ' DATALTERACAO DATE, ' + ' CODVENDEDORORIGEM NUMBER(10) NULL, ' + ' CODCLIENTEORIGEM NUMBER(10) NULL, '+ ' CODCIDADEORIGEM NUMBER(10) NULL, '+ ' CODVENDEDORDESTINO NUMBER(10) NULL, '+ ' QTDREGISTROSALTERADOS NUMBER(10) NULL, '+ ' PRIMARY KEY(SEQITEM))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 179'); end; if VpaNumAtualizacao < 180 then begin Result := '180'; ExecutaComandoSql(Aux,'CREATE TABLE ALTERACLIENTEVENDEDORITEM (' + ' SEQITEMALTERACLIENTEVENDEDOR NUMBER(10) NOT NULL, '+ ' SEQITEM NUMBER(10) NOT NULL, ' + ' CODCLIENTE NUMBER(10) NULL, '+ ' PRIMARY KEY(SEQITEMALTERACLIENTEVENDEDOR,SEQITEM))'); ExecutaComandoSql(Aux,'CREATE INDEX ALTERACLIENTEVENDEDORITEM_FK1 ON ALTERACLIENTEVENDEDORITEM(SEQITEMALTERACLIENTEVENDEDOR)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 180'); end; if VpaNumAtualizacao < 181 then begin Result := '181'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_PRODUTO ADD(C_FIL_FAT CHAR(1))'); ExecutaComandoSql(Aux,' update CFG_PRODUTO SET C_FIL_FAT = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 181'); end; if VpaNumAtualizacao < 182 then begin Result := '182'; ExecutaComandoSql(Aux,' ALTER TABLE CONHECIMENTOTRANSPORTE ADD(NUMCONHECIMENTO NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 182'); end; if VpaNumAtualizacao < 183 then begin Result := '183'; ExecutaComandoSql(Aux,'CREATE TABLE PRODUTOFILIALFATURAMENTO( ' + ' SEQPRODUTO NUMBER(10) NOT NULL REFERENCES CADPRODUTOS(I_SEQ_PRO), ' + ' CODFILIAL NUMBER(10) NOT NULL, ' + ' SEQITEM NUMBER(10) NOT NULL, ' + ' PRIMARY KEY(SEQPRODUTO,CODFILIAL, SEQITEM))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 183'); end; if VpaNumAtualizacao < 184 then begin Result := '184'; ExecutaComandoSql(Aux,'ALTER TABLE PRODUTOFILIALFATURAMENTO DROP PRIMARY KEY ' ); ExecutaComandoSql(Aux,'ALTER TABLE PRODUTOFILIALFATURAMENTO DROP(SEQITEM)' ); ExecutaComandoSql(Aux,'ALTER TABLE PRODUTOFILIALFATURAMENTO ADD PRIMARY KEY (SEQPRODUTO, CODFILIAL)' ); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 184'); end; if VpaNumAtualizacao < 185 then begin Result := '185'; ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECO ADD(N_VVE_ANT NUMBER(17,4))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 185'); end; if VpaNumAtualizacao < 186 then begin Result := '186'; ExecutaComandoSql(Aux,'CREATE TABLE PROPOSTAFORMAPAGAMENTO( ' + ' CODFILIAL NUMBER(10) NOT NULL, ' + ' SEQPROPOSTA NUMBER(10) NOT NULL, ' + ' SEQITEM NUMBER(10) NOT NULL, ' + ' VALPAGAMENTO NUMBER(15,3), ' + ' DESCONDICAO VARCHAR2(20), ' + ' DESFORMAPAGAMENTO VARCHAR2(30), ' + ' PRIMARY KEY(SEQPROPOSTA,CODFILIAL, SEQITEM))'); ExecutaComandoSql(Aux,'CREATE INDEX PROPOSTAFORMAPAGAMENTO_FK1 ON PROPOSTAFORMAPAGAMENTO(SEQPROPOSTA)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 186'); end; if VpaNumAtualizacao < 187 then begin Result := '187'; ExecutaComandoSql(Aux,'DROP INDEX PROPOSTAFORMAPAGAMENTO_FK1'); ExecutaComandoSql(Aux,'CREATE INDEX PROPOSTAFORMAPAGAMENTO_FK1 ON PROPOSTAFORMAPAGAMENTO(CODFILIAL,SEQPROPOSTA)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 187'); end; if VpaNumAtualizacao < 188 then begin result := '188'; ExecutaComandoSql(Aux,' CREATE TABLE CHAMADOANEXOIMAGEM( ' + ' CODFILIAL NUMBER(10) NOT NULL,' + ' NUMCHAMADO NUMBER(10) NOT NULL,' + ' SEQITEM NUMBER(10) NOT NULL, ' + ' DESCAMINHOIMAGEM VARCHAR2(100), ' + ' PRIMARY KEY(CODFILIAL, NUMCHAMADO, SEQITEM))'); // ExecutaComandoSql(Aux,'CREATE INDEX CHAMADOANEXOIMAGEM_FK1 ON CHAMADOCORPO(CODFILIAL, NUMCHAMADO)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 188'); end; if VpaNumAtualizacao < 189 then begin result := '189'; ExecutaComandoSql(Aux,' ALTER TABLE ORCAMENTOPARCIALCORPO ADD(PESLIQUIDO NUMBER(11,3), QTDVOLUME NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 189'); end; if VpaNumAtualizacao < 190 then begin result := '190'; ExecutaComandoSql(Aux,' DROP TABLE PROPOSTAFORMAPAGAMENTO'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 190'); end; if VpaNumAtualizacao < 191 then begin result := '191'; ExecutaComandoSql(Aux,'CREATE TABLE PROPOSTAPARCELAS( ' + ' CODFILIAL NUMBER(10) NOT NULL, ' + ' SEQPROPOSTA NUMBER(10) NOT NULL, ' + ' SEQITEM NUMBER(10) NOT NULL, ' + ' VALPAGAMENTO NUMBER(15,3), ' + ' DESCONDICAO VARCHAR2(20), ' + ' CODFORMAPAGAMENTO NUMBER(10) NOT NULL REFERENCES CADFORMASPAGAMENTO(I_COD_FRM), ' + ' PRIMARY KEY(SEQPROPOSTA,CODFILIAL, SEQITEM))'); ExecutaComandoSql(Aux,'CREATE INDEX PROPOSTAPARCELAS_FK1 ON PROPOSTAPARCELAS(CODFILIAL,SEQPROPOSTA)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 191'); end; if VpaNumAtualizacao < 192 then begin result := '192'; ExecutaComandoSql(Aux,' ALTER TABLE SETOR ADD(DESGARANTIA VARCHAR2(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 192'); end; if VpaNumAtualizacao < 193 then begin result := '193'; ExecutaComandoSql(Aux,' ALTER TABLE CHAMADOPRODUTOORCADO ADD(DESNUMSERIE VARCHAR2(20)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 193'); end; if VpaNumAtualizacao < 194 then begin result := '194'; ExecutaComandoSql(Aux,' ALTER TABLE CADCLIENTES ADD(C_EST_EMB VARCHAR2(2), C_LOC_EMB VARCHAR2(60))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 194'); end; if VpaNumAtualizacao < 195 then begin result := '195'; ExecutaComandoSql(Aux,' ALTER TABLE CADORCAMENTOS ADD(C_EST_EMB VARCHAR2(2), C_LOC_EMB VARCHAR2(60))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 195'); end; if VpaNumAtualizacao < 196 then begin result := '196'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_FINANCEIRO ADD(I_QTD_VEN NUMBER(10))'); ExecutaComandoSql(Aux,' UPDATE CFG_FINANCEIRO SET I_QTD_VEN = 2'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 196'); end; if VpaNumAtualizacao < 197 then begin result := '197'; ExecutaComandoSql(Aux,' ALTER TABLE CHEQUE ADD(CODFORNECEDORRESERVA NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 197'); end; if VpaNumAtualizacao < 198 then begin result := '198'; ExecutaComandoSql(Aux,' ALTER TABLE MOVNOTASFISCAISFOR ADD(N_MVA_AJU NUMBER(17,2))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 198'); end; if VpaNumAtualizacao < 199 then begin result := '199'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_EMA_PRO CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_EMA_PRO = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 199'); end; if VpaNumAtualizacao < 200 then begin result := '200'; ExecutaComandoSql(Aux,' ALTER TABLE ORCAMENTOROTEIROENTREGA ADD(CODREGIAOVENDAS NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 200'); end; if VpaNumAtualizacao < 201 then begin result := '201'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_PRODUTO ADD(C_COD_BAR CHAR(1))'); ExecutaComandoSql(Aux,' update CFG_PRODUTO SET C_COD_BAR = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 201'); end; if VpaNumAtualizacao < 202 then begin result := '202'; ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD (C_EXC_AMO varchar2(1))'); ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EXC_AMO = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 202'); end; if VpaNumAtualizacao < 203 then begin result := '203'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_PRODUTO ADD(C_PRA_OBR CHAR(1))'); ExecutaComandoSql(Aux,'UPDATE CFG_PRODUTO SET C_PRA_OBR = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 203'); end; if VpaNumAtualizacao < 204 then begin result := '204'; ExecutaComandoSql(Aux,' CREATE TABLE PRODUTONAOCOMPRADOCORPO(' + ' SEQPRODUTONAOCOMPRADO NUMBER(10) NOT NULL, ' + ' CODUSUARIO NUMBER(10) NOT NULL, ' + ' DATALTERACAO DATE,' + ' PRIMARY KEY(SEQPRODUTONAOCOMPRADO,CODUSUARIO))'); ExecutaComandoSql(Aux,'CREATE INDEX PRODCOMPRADOCORPO_FK1 ON PRODUTONAOCOMPRADOCORPO(SEQPRODUTONAOCOMPRADO)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 204'); end; if VpaNumAtualizacao < 205 then begin result := '205'; ExecutaComandoSql(Aux,' CREATE TABLE PRODUTONAOCOMPRADOITEM(' + ' SEQPRODUTONAOCOMPRADO NUMBER(10) NOT NULL, ' + ' CODFILIAL NUMBER(10) NOT NULL, ' + ' SEQORDEMPRODUCAO NUMBER(10) NOT NULL, '+ ' SEQFRACAO NUMBER(10) NOT NULL, ' + ' PRIMARY KEY(SEQPRODUTONAOCOMPRADO,CODFILIAL,SEQORDEMPRODUCAO,SEQFRACAO))'); ExecutaComandoSql(Aux,'CREATE INDEX PRODCOMPRADOITEM_FK1 ON PRODUTONAOCOMPRADOITEM(CODFILIAL,SEQORDEMPRODUCAO,SEQFRACAO)'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 205'); end; if VpaNumAtualizacao < 206 then begin result := '206'; ExecutaComandoSql(Aux,' ALTER TABLE CADGRUPOS ADD(C_IND_CVE CHAR(1)) '); ExecutaComandoSql(Aux,' UPDATE CADGRUPOS SET C_IND_CVE = C_IND_SCV '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 206'); end; if VpaNumAtualizacao < 207 then begin result := '207'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD(C_COT_ICO CHAR(1)) '); ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_ICO = ''F'''); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 207'); end; if VpaNumAtualizacao < 208 then begin result := '208'; ExecutaComandoSql(Aux,' ALTER TABLE CFG_GERAL ADD (I_SEQ_LOT NUMBER(10))'); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 208'); end; if VpaNumAtualizacao < 209 then begin result := '209'; ExecutaComandoSql(Aux,' ALTER TABLE MOVORCAMENTOS ADD(C_NUM_SER VARCHAR2(50)) '); ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_PR1 = 209'); end; end; end.
unit amqp.table; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses AMQP.Types, amqp.privt, amqp.mem; function amqp_decode_table(encoded : Tamqp_bytes; pool : Pamqp_pool; out output : Tamqp_table; offset : Psize_t):integer; function amqp_encode_table(encoded : Tamqp_bytes; input : Pamqp_table; offset : Psize_t):integer; function amqp_encode_field_value(encoded : Tamqp_bytes;const entry : Pamqp_field_value; offset : Psize_t):integer; function amqp_decode_field_value(encoded : Tamqp_bytes; pool : Pamqp_pool; out entry : Tamqp_field_value; offset : Psize_t):integer; //function amqp_table_get_entry_by_key(const table : Pamqp_table;const key : Tamqp_bytes):Pamqp_table_entry; function amqp_decode_array(encoded : Tamqp_bytes; pool : Pamqp_pool; out output : Tamqp_array; offset : Psize_t):integer; //function amqp_table_clone(const original: Tamqp_table;out clone : Tamqp_table; pool : Pamqp_pool):integer; //function amqp_table_entry_clone(const original: Pamqp_table_entry; clone : Pamqp_table_entry; pool : Pamqp_pool):integer; //function amqp_field_value_clone(const original: Pamqp_field_value; clone : Pamqp_field_value; pool : Pamqp_pool):integer; const INITIAL_ARRAY_SIZE =16; INITIAL_TABLE_SIZE =16; implementation function amqp_decode_array(encoded : Tamqp_bytes; pool : Pamqp_pool; out output : Tamqp_array; offset : Psize_t):integer; var arraysize : uint32; num_entries, allocated_entries : integer; entries : Pamqp_field_value; limit : size_t; res : integer; newentries : Pointer; label _out; begin {$POINTERMATH ON} num_entries := 0; allocated_entries := INITIAL_ARRAY_SIZE; if 0= amqp_decode_32(encoded, offset, &arraysize ) then begin Exit(Int(AMQP_STATUS_BAD_AMQP_DATA)); end; if arraysize + offset^ > encoded.len then begin Exit(Int(AMQP_STATUS_BAD_AMQP_DATA)); end; entries := allocMem(allocated_entries * sizeof(Tamqp_field_value)); if entries = nil then Exit(Int(AMQP_STATUS_NO_MEMORY)); limit := offset^ + arraysize; while offset^ < limit do begin if num_entries >= allocated_entries then begin allocated_entries := allocated_entries * 2; reallocMem(entries, allocated_entries * sizeof(Tamqp_field_value)); res := Int(AMQP_STATUS_NO_MEMORY); if entries = nil then goto _out; end; res := amqp_decode_field_value(encoded, pool, entries[num_entries], offset); if res < 0 then goto _out; Inc(num_entries); end; output.num_entries := num_entries; output.entries := pool.alloc( num_entries * sizeof(Tamqp_field_value)); { nil is legitimate if we requested a zero-length block. } if output.entries = nil then begin if num_entries = 0 then res := Int(AMQP_STATUS_OK) else res := Int(AMQP_STATUS_NO_MEMORY); end; memcpy(output.entries, entries, num_entries * sizeof(Tamqp_field_value)); res := Int(AMQP_STATUS_OK); _out: freeMem(entries); Result := res; {$POINTERMATH OFF} end; function amqp_decode_field_value(encoded : Tamqp_bytes;pool : Pamqp_pool; out entry : Tamqp_field_value; offset : Psize_t):integer; var res : integer; len : uint32; label _out; procedure SIMPLE_FIELD_DECODER(bits: Byte; dest: string); var Lval8: uint8_t; Lval16: uint16_t; Lval32: uint32_t; Lval64: uint64_t; label _out; begin case bits of 8: begin if (0=amqp_decode_8(encoded, offset, Lval8)) then goto _out; if dest = 'i8' then entry.value.i8 := Lval8 else if dest = 'boolean' then begin if Lval8 > 0 then entry.value.boolean := 1 else entry.value.boolean := 0; end; end; 16: begin if (0=amqp_decode_16(encoded, offset, Lval16)) then goto _out; if dest = 'i16' then entry.value.i16 := Lval16; end; 32: begin if (0=amqp_decode_32(encoded, offset, Lval32)) then goto _out; if dest = 'i32' then entry.value.i32 := Lval32; end; 64: begin if (0=amqp_decode_64(encoded, offset, Lval64)) then goto _out; if dest = 'i64' then entry.value.i64 := Lval64 end; end; _out: Result := res; end; procedure TRIVIAL_FIELD_DECODER(bits: byte); label _out; begin case bits of 8: if 0=amqp_decode_8(encoded, offset, entry.value.u8) then goto _out; 16: if 0=amqp_decode_16(encoded, offset, entry.value.u16) then goto _out; 32: if 0=amqp_decode_32(encoded, offset, entry.value.u32) then goto _out; end; _out: Result := res; end; begin res := Int(AMQP_STATUS_BAD_AMQP_DATA); if 0= amqp_decode_8(encoded, offset, entry.kind ) then goto _out; case entry.kind of Int(AMQP_FIELD_KIND_BOOLEAN): SIMPLE_FIELD_DECODER(8, 'boolean'); Int(AMQP_FIELD_KIND_I8): SIMPLE_FIELD_DECODER(8, 'i8'); Int(AMQP_FIELD_KIND_U8): TRIVIAL_FIELD_DECODER(8); Int(AMQP_FIELD_KIND_I16): SIMPLE_FIELD_DECODER(16, 'i16'); Int(AMQP_FIELD_KIND_U16): TRIVIAL_FIELD_DECODER(16); Int(AMQP_FIELD_KIND_I32): SIMPLE_FIELD_DECODER(32, 'i32'); Int(AMQP_FIELD_KIND_U32): TRIVIAL_FIELD_DECODER(32); Int(AMQP_FIELD_KIND_I64): SIMPLE_FIELD_DECODER(64, 'i64'); Int(AMQP_FIELD_KIND_U64): TRIVIAL_FIELD_DECODER(64); Int(AMQP_FIELD_KIND_F32): TRIVIAL_FIELD_DECODER(32); { and by punning, f32 magically gets the right value...! } Int(AMQP_FIELD_KIND_F64): TRIVIAL_FIELD_DECODER(64); { and by punning, f64 magically gets the right value...! } Int(AMQP_FIELD_KIND_DECIMAL): if (0= amqp_decode_8(encoded, offset, entry.value.decimal.decimals)) or (0= amqp_decode_32(encoded, offset, entry.value.decimal.value))then goto _out; Int(AMQP_FIELD_KIND_UTF8), { AMQP_FIELD_KIND_UTF8 and AMQP_FIELD_KIND_BYTES have the same implementation, but different interpretations. } { fall through } Int(AMQP_FIELD_KIND_BYTES): begin if (0= amqp_decode_32(encoded, offset, &len)) or (0= amqp_decode_bytes(encoded, offset, entry.value.bytes, len)) then goto _out; end; Int(AMQP_FIELD_KIND_ARRAY): res := amqp_decode_array(encoded, pool, entry.value.&array, offset); Int(AMQP_FIELD_KIND_TIMESTAMP): TRIVIAL_FIELD_DECODER(64); Int(AMQP_FIELD_KIND_TABLE): res := amqp_decode_table(encoded, pool, entry.value.table, offset); Int(AMQP_FIELD_KIND_VOID): else goto _out; end; res := Int(AMQP_STATUS_OK); _out: Result := res; end; function amqp_decode_table(encoded : Tamqp_bytes; pool : Pamqp_pool; out output : Tamqp_table; offset : Psize_t):integer; var tablesize : uint32; num_entries : integer; entries : Pamqp_table_entry; allocated_entries : integer; limit : size_t; res : integer; keylen : byte; newentries : Pointer; label _out; begin {$POINTERMATH ON} num_entries := 0; allocated_entries := INITIAL_TABLE_SIZE; if 0= amqp_decode_32(encoded, offset, &tablesize )then begin Exit(Int(AMQP_STATUS_BAD_AMQP_DATA)); end; if tablesize + offset^ > encoded.len then begin Exit(Int(AMQP_STATUS_BAD_AMQP_DATA)); end; entries := allocMem(allocated_entries * sizeof(Tamqp_table_entry)); if entries = nil then Exit(Int(AMQP_STATUS_NO_MEMORY)); limit := offset^ + tablesize; while offset^ < limit do begin res := Int(AMQP_STATUS_BAD_AMQP_DATA); if 0= amqp_decode_8(encoded, offset, &keylen )then goto _out; if num_entries >= allocated_entries then begin allocated_entries := allocated_entries * 2; reallocMem(entries, allocated_entries * sizeof(Tamqp_table_entry)); res := Int(AMQP_STATUS_NO_MEMORY); if entries = nil then goto _out; end; res := Int(AMQP_STATUS_BAD_AMQP_DATA); if 0= amqp_decode_bytes(encoded, offset, entries[num_entries].key, keylen) then goto _out; res := amqp_decode_field_value(encoded, pool, entries[num_entries].value,offset); if res < 0 then goto _out; Inc(num_entries); end; output.num_entries := num_entries; output.entries := pool.alloc( num_entries * sizeof(Tamqp_table_entry)); { nil is legitimate if we requested a zero-length block. } if output.entries = nil then begin if num_entries = 0 then res := Int(AMQP_STATUS_OK) else res := Int(AMQP_STATUS_NO_MEMORY); end; memcpy(output.entries, entries, num_entries * sizeof(Tamqp_table_entry)); res := Int(AMQP_STATUS_OK); _out: freemem(entries); Result := res; {$POINTERMATH OFF} end; function amqp_encode_array(encoded : Tamqp_bytes; input : Pamqp_array; offset : Psize_t):integer; var start : size_t; i, res : integer; label _out; begin {$POINTERMATH ON} start := offset^; offset^ := offset^ + 4; for i := 0 to input.num_entries-1 do begin res := amqp_encode_field_value(encoded, @input.entries[i], offset); if res < 0 then goto _out; end; if 0= amqp_encode_n(32, encoded, @start, uint32_t( offset^ - start - 4)) then begin res := Integer(AMQP_STATUS_TABLE_TOO_BIG); goto _out; end; res := Integer(AMQP_STATUS_OK); _out: Result := res; {$POINTERMATH OFF} end; function amqp_encode_field_value(encoded : Tamqp_bytes;const entry : Pamqp_field_value; offset : Psize_t):integer; var res, value : integer; label _out; procedure FIELD_ENCODER(bits, val: Byte); begin if 0= amqp_encode_n(bits, encoded, offset, val) then res := Integer(AMQP_STATUS_TABLE_TOO_BIG); end; begin res := Integer(AMQP_STATUS_BAD_AMQP_DATA); if 0= amqp_encode_n(8, encoded, offset, entry.kind) then goto _out; case entry.kind of uint8(AMQP_FIELD_KIND_BOOLEAN): begin if entry.value.boolean > 0 then value := 1 else value := 0; FIELD_ENCODER(8, value); end; uint8(AMQP_FIELD_KIND_I8): FIELD_ENCODER(8, entry.value.i8); uint8(AMQP_FIELD_KIND_U8): FIELD_ENCODER(8, entry.value.u8); uint8(AMQP_FIELD_KIND_I16): FIELD_ENCODER(16, entry.value.i16); uint8(AMQP_FIELD_KIND_U16): FIELD_ENCODER(16, entry.value.u16); uint8(AMQP_FIELD_KIND_I32): FIELD_ENCODER(32, entry.value.i32); uint8(AMQP_FIELD_KIND_U32): FIELD_ENCODER(32, entry.value.u32); uint8(AMQP_FIELD_KIND_I64): FIELD_ENCODER(64, entry.value.i64); uint8(AMQP_FIELD_KIND_U64): FIELD_ENCODER(64, entry.value.u64); uint8(AMQP_FIELD_KIND_F32): { by punning, u32 magically gets the right value...! } FIELD_ENCODER(32, entry.value.u32); uint8(AMQP_FIELD_KIND_F64): { by punning, u64 magically gets the right value...! } FIELD_ENCODER(64, entry.value.u64); uint8(AMQP_FIELD_KIND_DECIMAL): begin if (0= amqp_encode_n(8, encoded, offset, entry.value.decimal.decimals)) or (0= amqp_encode_n(32, encoded, offset, entry.value.decimal.value)) then begin res := Integer(AMQP_STATUS_TABLE_TOO_BIG); goto _out; end; end; uint8(AMQP_FIELD_KIND_UTF8), { AMQP_FIELD_KIND_UTF8 and AMQP_FIELD_KIND_BYTES have the same implementation, but different interpretations. } { fall through } uint8(AMQP_FIELD_KIND_BYTES): begin if (0= amqp_encode_n(32, encoded, offset, uint32_t (entry.value.bytes.len))) or (0= amqp_encode_bytes(encoded, offset, entry.value.bytes)) then begin res := Integer(AMQP_STATUS_TABLE_TOO_BIG); goto _out; end; end; uint8(AMQP_FIELD_KIND_ARRAY): begin res := amqp_encode_array(encoded, @entry.value.&array, offset); goto _out; end; uint8(AMQP_FIELD_KIND_TIMESTAMP): FIELD_ENCODER(64, entry.value.u64); uint8(AMQP_FIELD_KIND_TABLE): begin res := amqp_encode_table(encoded, @entry.value.table, offset); goto _out; end; uint8(AMQP_FIELD_KIND_VOID): begin // end; else res := Integer(AMQP_STATUS_INVALID_PARAMETER); end; res := Integer(AMQP_STATUS_OK); _out: Result := res; end; function amqp_encode_table(encoded : Tamqp_bytes; input : Pamqp_table; offset : Psize_t):integer; var start : size_t; i, res : integer; label _out; begin {$POINTERMATH ON} start := offset^; offset^ := offset^ + 4; for i := 0 to input.num_entries-1 do begin if 0= amqp_encode_n(8, encoded, offset, uint8_t(input.entries[i].key.len)) then begin res := Integer(AMQP_STATUS_TABLE_TOO_BIG); goto _out; end; if 0= amqp_encode_bytes(encoded, offset, input.entries[i].key ) then begin res := Integer(AMQP_STATUS_TABLE_TOO_BIG); goto _out; end; res := amqp_encode_field_value(encoded, @input.entries[i].value, offset); if res < 0 then goto _out; end; if 0= amqp_encode_n(32, encoded, @start, uint32_t( offset^ - start - 4)) then begin res := Integer(AMQP_STATUS_TABLE_TOO_BIG); goto _out; end; res := Integer(AMQP_STATUS_OK); _out: Result := res; {$POINTERMATH OFF} end; initialization end.
unit MainFormUnit; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.StdCtrls, Vcl.ExtDlgs, //GLS GLGui, GLScene, GLWin32Viewer, GLObjects, GLHUDObjects, GLWindows, GLBitmapFont, GLWindowsFont, GLTexture, FGuiSkinEditor, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) MainMenu1: TMainMenu; File1: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; Close1: TMenuItem; N1: TMenuItem; Import1: TMenuItem; N2: TMenuItem; Exit1: TMenuItem; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; GLGuiLayout1: TGLGuiLayout; ImportDialog: TOpenDialog; Edit1: TMenuItem; EditLayout1: TMenuItem; ListBox: TListBox; ListPopup: TPopupMenu; Add1: TMenuItem; Remove1: TMenuItem; Edit2: TMenuItem; N3: TMenuItem; GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCamera1: TGLCamera; GLPanel1: TGLPanel; WindowsBitmapFont1: TGLWindowsBitmapFont; Image1: TMenuItem; Load1: TMenuItem; OpenPictureDialog: TOpenPictureDialog; GLMaterialLibrary1: TGLMaterialLibrary; HUDSprite1: TGLHUDSprite; Edit3: TEdit; Label1: TLabel; Button1: TButton; Button2: TButton; procedure Open1Click(Sender: TObject); procedure Save1Click(Sender: TObject); procedure Close1Click(Sender: TObject); procedure Import1Click(Sender: TObject); procedure EditLayout1Click(Sender: TObject); procedure Add1Click(Sender: TObject); procedure Remove1Click(Sender: TObject); procedure Edit2Click(Sender: TObject); procedure ListBoxClick(Sender: TObject); procedure Load1Click(Sender: TObject); procedure Edit3Change(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Edit3KeyPress(Sender: TObject; var Key: Char); procedure Button2Click(Sender: TObject); private public Procedure UpdateLayoutList; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var MediaPath : String; I : Integer; begin MediaPath := ExtractFilePath(ParamStr(0)); I := Pos(UpperCase('Samples'), UpperCase(MediaPath)); if (I <> 0) then begin Delete(MediaPath, I+8, Length(MediaPath)-I); SetCurrentDir(MediaPath+'Media\'); end; GLMaterialLibrary1.Materials[0].Material.Texture.Image. LoadFromFile('DefaultSkin.bmp'); end; procedure TForm1.Open1Click(Sender: TObject); begin If OpenDialog.Execute then Begin GLScene1.BeginUpdate; try GLGuiLayout1.Clear; GLGuiLayout1.LoadFromFile(OpenDialog.FileName); UpdateLayoutList; finally GLScene1.EndUpdate; end; End; end; procedure TForm1.Save1Click(Sender: TObject); begin if SaveDialog.Execute then Begin GLGuiLayout1.SaveToFile(SaveDialog.FileName); End; end; procedure TForm1.Close1Click(Sender: TObject); begin GLScene1.BeginUpdate; try GLGuiLayout1.Clear; UpdateLayoutList; finally GLScene1.EndUpdate; end; End; procedure TForm1.Import1Click(Sender: TObject); Var XC : Integer; begin if ImportDialog.Execute then Begin GLScene1.BeginUpdate; try For XC := 0 to ImportDialog.Files.Count-1 do Begin try GLGuiLayout1.LoadFromFile(ImportDialog.Files[XC]); except end; End; UpdateLayoutList; finally GLScene1.EndUpdate; end; End; end; procedure TForm1.EditLayout1Click(Sender: TObject); begin Hide; GLScene1.BeginUpdate; try If ListBox.ItemIndex >= 0 then GUIComponentDialog((ListBox.Items.Objects[ListBox.ItemIndex] as TGLGuiComponent).Elements) finally GLScene1.EndUpdate; Show; end; end; Procedure TForm1.UpdateLayoutList; var i : Integer; begin ListBox.Clear; With GLGuiLayout1.GuiComponents do for i:=0 to Count-1 do ListBox.Items.AddObject(Items[i].Name, Items[i]); ListBox.Selected[GLGuiLayout1.GuiComponents.Count-1] := True; End; procedure TForm1.Add1Click(Sender: TObject); Var GuiComp : TGLGuiComponent; begin GuiComp := GLGuiLayout1.GuiComponents.Add as TGLGuiComponent; If ListBox.ItemIndex >= 0 then begin GuiComp.Name := 'Newly Added'; end else GuiComp.Name := Edit3.Text; UpdateLayoutList; end; procedure TForm1.Remove1Click(Sender: TObject); Var S : String; begin If ListBox.ItemIndex >= 0 then Begin GLScene1.BeginUpdate; try GLGuiLayout1.GUIComponents.Delete(ListBox.ItemIndex); ListBox.Items.Delete(ListBox.ItemIndex); S := GLPanel1.GuiLayoutName; GLPanel1.GuiLayoutName := ''; GLPanel1.GuiLayoutName := S; finally GLScene1.EndUpdate; end; End; end; procedure TForm1.Edit2Click(Sender: TObject); begin If ListBox.ItemIndex >= 0 then GUIComponentDialog((ListBox.Items.Objects[ListBox.ItemIndex] as TGLGuiComponent).Elements) end; procedure TForm1.ListBoxClick(Sender: TObject); begin GLScene1.BeginUpdate; try If ListBox.ItemIndex >= 0 then Begin GLPanel1.GuiLayoutName := GLGuiLayout1.GuiComponents.Items[ListBox.ItemIndex].Name; Edit3.text := GLPanel1.GuiLayoutName; End else Begin GLPanel1.GuiLayoutName := ''; Edit3.text := 'Newly Added'; End; GLPanel1.DoChanges; finally GLScene1.EndUpdate; end; end; procedure TForm1.Load1Click(Sender: TObject); Var Mat : TGLLibMaterial; MatName : String; begin If OpenPictureDialog.Execute then Begin GLScene1.BeginUpdate; try MatName := ExtractFileName(OpenPictureDialog.FileName); Mat := GLMaterialLibrary1.Materials.GetLibMaterialByName(MatName); If not Assigned(Mat) then Begin GLMaterialLibrary1.AddTextureMaterial(MatName,OpenPictureDialog.FileName).Material.Texture.TextureMode := tmReplace; End; GLGuiLayout1.Material.LibMaterialName := MatName; HUDSprite1.Material.LibMaterialName := MatName; finally GLScene1.EndUpdate; end; End; end; procedure TForm1.Edit3Change(Sender: TObject); begin If (ListBox.ItemIndex >= 0) then Begin ListBox.Items[ListBox.ItemIndex] := Edit3.Text; GLGuiLayout1.GuiComponents.Items[ListBox.ItemIndex].Name := Edit3.Text; End; end; procedure TForm1.Exit1Click(Sender: TObject); begin Application.Terminate; end; procedure TForm1.Button1Click(Sender: TObject); begin Add1Click(Sender); end; procedure TForm1.Edit3KeyPress(Sender: TObject; var Key: Char); begin If Key = #13 then Add1Click(Sender); end; procedure TForm1.Button2Click(Sender: TObject); begin Edit2Click(Sender); end; end.
{*************************************************************************** * * Orion-project.org Lazarus Helper Library * Copyright (C) 2016-2017 by Nikolay Chunosov * * This file is part of the Orion-project.org Lazarus Helper Library * https://github.com/Chunosov/orion-lazarus * * This Library is free software: you can redistribute it and/or modify it * under the terms of the MIT License. See enclosed LICENSE.txt for details. * ***************************************************************************} unit Test_Controls; {$mode objfpc}{$H+} interface uses FpcUnit, TestRegistry, Controls; type TTest_Controls = class(TTestCase) private procedure ShowControlSimple(AControl: TControl); published procedure OriTabSet; procedure OriFloatEdit; //procedure OriComboBox; end; implementation uses WinPropEditor, OriTabs, OriEditors; procedure TTest_Controls.OriTabSet; var TabSet: TOriTabSet; W: TWndPropEditor; begin W := ShowPropEditor; TabSet := TOriTabSet.Create(nil); TabSet.Parent := W; TabSet.Align := alClient; TabSet.Tabs.Add.Caption := 'Tab 1'; TabSet.Tabs.Add.Caption := 'Tab 2'; TabSet.Tabs.Add.Caption := 'Tab 3'; W.SetSelection(TabSet); end; procedure TTest_Controls.ShowControlSimple(AControl: TControl); var W: TWndPropEditor; begin W := ShowPropEditor; AControl.Parent := W; AControl.Left := 20; AControl.Top := 20; AControl.Width := 100; W.SetSelection(AControl); end; procedure TTest_Controls.OriFloatEdit; begin ShowControlSimple(TOriFloatEdit.Create(nil)); end; //procedure TTest_Controls.OriComboBox; //begin // ShowControlSimple(TOriComboBox.Create(nil)); //end; initialization RegisterTest(TTest_Controls); end.
unit ProductsSearchView; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ProductsBaseView1, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxCustomData, cxStyles, cxTL, cxMaskEdit, cxDBLookupComboBox, cxDropDownEdit, cxButtonEdit, cxTLdxBarBuiltInMenu, dxSkinsCore, dxSkinsDefaultPainters, cxCalendar, cxCurrencyEdit, Vcl.ExtCtrls, Vcl.Menus, System.Actions, Vcl.ActnList, dxBar, cxBarEditItem, cxClasses, Vcl.ComCtrls, cxInplaceContainer, cxDBTL, cxTLData, ProductsSearchViewModel, ProductsBaseView0; type TViewProductsSearch = class(TViewProductsBase1) actClear: TAction; actSearch: TAction; actPasteFromBuffer: TAction; clStoreHouseID2: TcxDBTreeListColumn; dxBarButton2: TdxBarButton; dxBarButton3: TdxBarButton; dxBarButton4: TdxBarButton; dxBarButton5: TdxBarButton; dxBarButton6: TdxBarButton; dxBarSubItem1: TdxBarSubItem; dxBarButton7: TdxBarButton; dxBarButton8: TdxBarButton; dxBarButton9: TdxBarButton; dxBarButton10: TdxBarButton; procedure actClearExecute(Sender: TObject); procedure actPasteFromBufferExecute(Sender: TObject); procedure actSearchExecute(Sender: TObject); procedure cxDBTreeListEdited(Sender: TcxCustomTreeList; AColumn: TcxTreeListColumn); private function GetSearchViewModel: TProductsSearchViewModel; procedure Search(ALike: Boolean); procedure SetSearchViewModel(const Value: TProductsSearchViewModel); { Private declarations } protected procedure ApplyGridSort; override; function CreateProductView: TViewProductsBase0; override; procedure InitializeColumns; override; function IsViewOK: Boolean; override; public procedure FocusValueColumn; procedure UpdateView; override; property SearchViewModel: TProductsSearchViewModel read GetSearchViewModel write SetSearchViewModel; { Public declarations } end; implementation uses SearchInterfaceUnit, Vcl.Clipbrd, ClipboardUnit, GridSort, dxCore, RepositoryDataModule; {$R *.dfm} procedure TViewProductsSearch.actClearExecute(Sender: TObject); begin inherited; if CheckAndSaveChanges = IDCANCEL then Exit; cxDBTreeList.BeginUpdate; try SearchViewModel.qProductsSearch.ClearSearchResult; UpdateView; finally cxDBTreeList.EndUpdate; end; FocusValueColumn; end; procedure TViewProductsSearch.actPasteFromBufferExecute(Sender: TObject); begin inherited; // Если в буфере обмена ничего нет if Clipboard.AsText.Trim.IsEmpty then Exit; cxDBTreeList.BeginUpdate; try SearchViewModel.qProductsSearch.W.AppendRows (SearchViewModel.qProductsSearch.W.Value.FieldName, TClb.Create.GetRowsAsArray); UpdateView; finally cxDBTreeList.EndUpdate; end; end; procedure TViewProductsSearch.actSearchExecute(Sender: TObject); begin inherited; Search(False); end; procedure TViewProductsSearch.ApplyGridSort; begin GridSort.Add(TSortVariant.Create(clValue, [clValue, clStoreHouseID2])); GridSort.Add(TSortVariant.Create(clIDProducer, [clIDProducer, clValue])); GridSort.Add(TSortVariant.Create(clLoadDate, [clLoadDate, clValue])); ApplySort(clValue, soAscending); end; function TViewProductsSearch.CreateProductView: TViewProductsBase0; begin Result := TViewProductsSearch.Create(nil); end; procedure TViewProductsSearch.cxDBTreeListEdited(Sender: TcxCustomTreeList; AColumn: TcxTreeListColumn); begin if SearchViewModel.qProductsSearch.ProductSearchW.Mode = SearchMode then begin if cxDBTreeList.LockUpdate > 0 then Exit; // Если закончили редактирование наименования if (AColumn as TcxDBTreeListColumn).DataBinding.FieldName = clValue. DataBinding.FieldName then begin if VarToStrDef(FocusedNodeValue(AColumn as TcxDBTreeListColumn), '') <> '' then Search(True); end; end else inherited; end; procedure TViewProductsSearch.FocusValueColumn; begin cxDBTreeList.SetFocus; // Переводим колонку в режим редактирования clValue.Editing := True; end; function TViewProductsSearch.GetSearchViewModel: TProductsSearchViewModel; begin Result := Model as TProductsSearchViewModel; end; procedure TViewProductsSearch.InitializeColumns; begin inherited; Assert(M <> nil); InitializeLookupColumn(clStorehouseId, SearchViewModel.qStoreHouseList.W.DataSource, lsEditFixedList, SearchViewModel.qStoreHouseList.W.Abbreviation.FieldName); InitializeLookupColumn(clStorehouseId2, SearchViewModel.qStoreHouseList.W.DataSource, lsEditFixedList, SearchViewModel.qStoreHouseList.W.Title.FieldName); end; function TViewProductsSearch.IsViewOK: Boolean; begin Result := (M <> nil) and (SearchViewModel.qProductsSearch <> nil) and (SearchViewModel.qProductsSearch.ProductSearchW.Mode = RecordsMode); end; procedure TViewProductsSearch.Search(ALike: Boolean); begin cxDBTreeList.BeginUpdate; try CheckAndSaveChanges; SearchViewModel.qProductsSearch.DoSearch(ALike); finally cxDBTreeList.EndUpdate; end; MyApplyBestFit; // cxDBTreeList.FullExpand; cxDBTreeList.SetFocus; // Переводим колонку в режим редактирования clValue.Editing := True; UpdateView; end; procedure TViewProductsSearch.SetSearchViewModel(const Value : TProductsSearchViewModel); begin if Model = Value then Exit; Model := Value; end; procedure TViewProductsSearch.UpdateView; var Ok: Boolean; begin inherited; Ok := (SearchViewModel <> nil) and (SearchViewModel.qProductsSearch.FDQuery.Active); actClear.Enabled := Ok and SearchViewModel.qProductsSearch.IsClearEnabled; actSearch.Enabled := Ok and SearchViewModel.qProductsSearch.IsSearchEnabled; actCommit.Enabled := Ok and SearchViewModel.qProductsSearch.HaveAnyChanges and (SearchViewModel.qProductsSearch.ProductSearchW.Mode = RecordsMode); actRollback.Enabled := actCommit.Enabled; actPasteFromBuffer.Enabled := Ok and (SearchViewModel.qProductsSearch.ProductSearchW.Mode = SearchMode); // cxGridDBBandedTableView.OptionsData.Appending := // qProductsSearch.qProductsSearch.Mode = SearchMode; // cxGridDBBandedTableView.OptionsData.Inserting := // qProductsSearch.qProductsSearch.Mode = SearchMode; actExportToExcelDocument.Caption := 'В документ Excel'; actExportToExcelDocument.Hint := 'Экспортировать в документ Excel'; actExportToExcelDocument.Enabled := Ok and (SearchViewModel.qProductsSearch.FDQuery.RecordCount > 0) and (SearchViewModel.qProductsSearch.ProductSearchW.Mode = RecordsMode); end; end.
unit CommandLineOperationsUnit; interface uses Classes; type TCommandLineOperations = class public //////////////////////////// // Constructor/Destructor // //////////////////////////// constructor Create(const sCommandLine: String); destructor Destroy; reintroduce; overload; // Validators { function ValidateCommandLineParses: Boolean; // top level check, is syntax correct? function ValidateImageListFile(const sFilename: String): Boolean; function ValidateSourceMethod: Boolean; // method is set, image list validates if necessary, source validates function ValidateCompressMethod: Boolean; // method is set, value set if override chosen function ValidateSource: Boolean; // directory exists/files exist function ValidateFileTypeMethod: Boolean; // method is set, image file type set if convert is choice function ValidateFileHandling: Boolean; // method is set function ValidatePreSuffix: Boolean; // values exist if flag is set function ValidateOutputPath: Boolean; // output path exists/can be created function ValidateScalingMethod: Boolean; // scaling method set, and accompanying width, height, and/or scale values // continue? procedure ParseCommandLineParams; // set up objects ??? } private { FImageProcessingMethods: TImageProcessingMethods; // Image processing methods FFileInformation: TFileStructureInformation; // File structure information FImageInformation: TImageResizingInformation; // Image resizing information } FGUI: Boolean; // do we need a GUI or not? FValidCommandLineOptions: Boolean; // are the options operable? // FBadFiles: TStringList; // List of bad files found during resizing published end; // TCommandLineOperations implementation { TCommandLineOperations } constructor TCommandLineOperations.Create(const sCommandLine: String); begin inherited Create; /////////////////////////// // Initialize everything // /////////////////////////// { FImageProcessingMethods := TImageProcessingMethods.Create; // Image processing methods FFileInformation := TFileStructureInformation.Create; // File information object FImageInformation := TImageResizingInformation.Create; // Image resizing information } FGUI := True; // assume we need the GUI // FBadFiles := TStringList.Create; end; destructor TCommandLineOperations.Destroy; begin ////////////// // Clean up // ////////////// { FreeAndNil(FImageProcessingMethods); FreeAndNil(FFileInformation); FreeAndNil(FImageInformation); FreeAndNil(FBadFiles); } inherited; end; end.
unit IdFingerServer; interface uses Classes, IdGlobal, IdTCPServer; type TIdFingerGetEvent = procedure(AThread: TIdPeerThread; const AUserName: string) of object; TIdFingerServer = class(TIdTCPServer) protected FOnCommandFinger: TIdFingerGetEvent; FOnCommandVerboseFinger: TIdFingerGetEvent; function DoExecute(AThread: TIdPeerThread): boolean; override; public constructor Create(AOwner: TComponent); override; published property OnCommandFinger: TIdFingerGetEvent read FOnCommandFinger write FOnCommandFinger; property OnCommandVerboseFinger: TIdFingerGetEvent read FOnCommandVerboseFinger write FOnCommandVerboseFinger; property DefaultPort default IdPORT_FINGER; end; implementation uses SysUtils; constructor TIdFingerServer.Create(AOwner: TComponent); begin inherited; DefaultPort := IdPORT_FINGER; end; function TIdFingerServer.DoExecute(AThread: TIdPeerThread): boolean; var s: string; begin result := true; s := TrimRight(AThread.Connection.Readln); if assigned(FOnCommandVerboseFinger) and (UpperCase(Copy(s, Length(s) - 1, 2)) = '/W') then begin s := Copy(s, 1, Length(s) - 2); OnCommandVerboseFinger(AThread, s); end else begin if assigned(OnCommandFinger) then begin OnCommandFinger(AThread, s); end; end; AThread.Connection.Disconnect; end; end.
// ---------------------------------------------------------- // This file is part of RTL. // // (c) Copyright 2021 Jens Kallup - paule32 // only for non-profit usage !!! // ---------------------------------------------------------- {$mode delphi} unit LazVision; interface type LazColorArray = Array[0..255, 0..255, 0..255] of Byte; type // TObject is the base of all classes of Qt5 LazObject = class public ClassName: LazString; constructor Create; destructor Destroy; end; type LazColor = class(LazObject) public function clBlack: LazColorArray; function clBlue: LazColorArray; function clFuchsia: LazColorArray; function clGray: LazColorArray; function clGreen: LazColorArray; function clLime: LazColorArray; function clBrown: LazColorArray; function clNavy: LazColorArray; function clOlive: LazColorArray; function clPurple: LazColorArray; function clRed: LazColorArray; function clSilver: LazColorArray; function clTeal: LazColorArray; function clCyan: LazColorArray; function clYellow: LazColorArray; function clWhite: LazColorArray; constructor Create; destructor Destroy; end; LazPalette = class(LazObject) private FForeground: LazColor; FBackground: LazColor; private procedure setForeground(v: LazColor); procedure setBackground(v: LazColor); public constructor Create; destructor Destroy; published property Background: LazColor read FBackground write setBackground; property Foreground: LazColor read FForeground write setForeground; end; type LazMenuBar = class(LazObject) public constructor Create; destructor Destroy; end; type LazStatusBar = class(LazObject) public constructor Create; destructor Destroy; end; type LazBackground = class(LazObject) private FPalette: LazPalette; FBgChar : Char; private procedure setBgChar(v: Char); function getBgChar: Char; public constructor Create; destructor Destroy; published property BgChar: Char read getBgChar write setBgChar; end; type LazApplication = class(LazObject) private FBackground: LazBackground; FMenuBar: LazMenuBar; FStatusBar: LazStatusBar; public procedure setBackground(v: LazBackground); procedure setMenuBar (v: LazMenuBar ); procedure setStatusBar (v: LazStatusBar ); // function getBackground: LazBackground; function getMenuBar: LazMenuBar; function getStatusBar: LazStatusBar; public constructor Create; destructor Destroy; published property Background: LazBackground read getBackground write setBackground; property MenuBar: LazMenuBar read getMenuBar write setMenuBar; property StatusBar: LazStatusBar read getStatusBar write setStatusBar; end; implementation // FPC ctor's ... constructor LazObject .Create; [alias: 'LazObject_Create' ]; cdecl; external 'laz_fpv.dll' name 'LazObject_Create'; constructor LazColor .Create; [alias: 'LazColor_Create' ]; cdecl; external 'laz_fpv.dll' name 'LazColor_Create'; constructor LazPalette .Create; [alias: 'LazPalette_Create' ]; cdecl; external 'laz_fpv.dll' name 'LazPalette_Create'; constructor LazMenuBar .Create; [alias: 'LazMenuBar_Create' ]; cdecl; external 'laz_fpv.dll' name 'LazMenuBar_Create'; constructor LazStatusBar .Create; [alias: 'LazStatusBar_Create' ]; cdecl; external 'laz_fpv.dll' name 'LazStatusBar_Create'; constructor LazBackground .Create; [alias: 'LazBackground_Create' ]; cdecl; external 'laz_fpv.dll' name 'LazBackground_Create'; constructor LazApplication.Create; [alias: 'LazApplication_Create' ]; cdecl; external 'laz_fpv.dll' name 'LazApplication_Create'; // FPC dtor's ... destructor LazObject .Destroy; [alias: 'LazObject_Destroy' ]; cdecl; external 'laz_fpv.dll' name 'LazObject_Destroy'; destructor LazColor .Destroy; [alias: 'LazColor_Destroy' ]; cdecl; external 'laz_fpv.dll' name 'LazColor_Destroy'; destructor LazPalette .Destroy; [alias: 'LazPalette_Destroy' ]; cdecl; external 'laz_fpv.dll' name 'LazPalette_Destroy'; destructor LazMenuBar .Destroy; [alias: 'LazMenuBar_Destroy' ]; cdecl; external 'laz_fpv.dll' name 'LazMenuBar_Destroy'; destructor LazStatusBar .Destroy; [alias: 'LazStatusBar_Destroy' ]; cdecl; external 'laz_fpv.dll' name 'LazStatusBar_Destroy'; destructor LazBackground .Destroy; [alias: 'LazBackground_Destroy' ]; cdecl; external 'laz_fpv.dll' name 'LazBackground_Destroy'; destructor LazApplication.Destroy; [alias: 'LazApplication_Destroy']; cdecl; external 'laz_fpv.dll' name 'LazApplication_Destroy'; // FPC members ... procedure LazApplication.setBackground(v: LazBackground); cdecl; external 'laz_fpv.dll' name 'LazApplication_setBackground'; procedure LazApplication.setMenuBar (v: LazMenuBar); cdecl; external 'laz_fpv.dll' name 'LazApplication_setMenuBar'; procedure LazApplication.setStatusBar (v: LazStatusBar); cdecl; external 'laz_fpv.dll' name 'LazApplication_setStatusBar'; // function LazApplication.getBackground: LazBackground; begin result := FBackground; end; function LazApplication.getMenuBar : LazMenuBar; begin result := FMenuBar; end; function LazApplication.getStatusBar : LazStatusBar; begin result := FStatusBar; end; // function LazColor.clBlack: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clBlack'; function LazColor.clBlue: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clBlue'; function LazColor.clFuchsia: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clFuchsia'; function LazColor.clGray: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clGray'; function LazColor.clGreen: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clGreeb'; function LazColor.clLime: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clLime'; function LazColor.clBrown: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clBrown'; function LazColor.clNavy: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clNavy'; function LazColor.clOlive: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clOlive'; function LazColor.clPurple: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clPurple'; function LazColor.clRed: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clRed'; function LazColor.clSilver: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clSilver'; function LazColor.clTeal: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clTeal'; function LazColor.clCyan: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clCyan'; function LazColor.clYellow: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clYellow'; function LazColor.clWhite: LazColorArray; cdecl; external 'laz_fpv.dll' name 'LazColor_clWhite'; // procedure LazBackground.setBgChar(v: Char); cdecl; external 'laz_fpv.dll' name 'LazBackground_setBgChar'; function LazBackground.getBgChar: Char; begin result := FBgChar; end; // procedure LazPalette.setBackground(v: LazTColor); cdecl; external 'laz_fpv.dll' name 'LazPalette_setBackground'; procedure LazPalette.setForeground(v: LazTColor); cdecl; external 'laz_fpv.dll' name 'LazPalette_setForeground'; // ------------------------------------------------------- // this procedure does nothing. // it's a dummy for fpc, to make .o file. // fpc does not create .o bject file, if you have only // interface "external"s. // ------------------------------------------------------- procedure dummy; begin end; end.
unit visibility_test_3; interface type TRec1 = record private FF: Int32; procedure SetF(Value: Int32); function GetF: Int32; public property F: Int32 read GetF write SetF; end; TRec2 = record private procedure SetF(Value: Int32); function GetF: Int32; public property F: Int32 read GetF write SetF; end; implementation var R1: TRec1; R2: TRec2; procedure TRec1.SetF(Value: Int32); begin FF := Value; end; function TRec1.GetF: Int32; begin Result := FF; end; procedure TRec2.SetF(Value: Int32); begin R1.F := Value; end; function TRec2.GetF: Int32; begin Result := R1.FF; end; procedure Test; begin R1.F := 12; end; initialization Test(); finalization Assert(R1.F = 12); Assert(R2.F = 12); end.
program RGR2(input, output); {Islamov Yahya PS-21 Организовать в основной памяти с помощью указателей очередь из стеков. Обеспечить операции ведения стека из начала очереди, дополнения и продвижения очереди, выдачи содержимого очереди (9).} type UkazS = ^Stack; Stack = record Name: string; NextS: UkazS; end; UkazQ = ^Que; Que = record TopS: UkazS; NextQ: UkazQ; end; var BegQ, KonQ, Last: UkazQ; Procedure PurgeStack(var BegQ: UkazQ); {процедура очищения стека} var KonS, Top: UkazS; begin Top := BegQ^.TopS; if Top = Nil then writeln('попытка удаление из пустого стека!') else while Top <> Nil do begin KonS := Top; Top := Top^.NextS; dispose(KonS) end end; Procedure DelFromStack(var BegQ: UkazQ);{удаление одного элемента из стека} var KonS, Top: UkazS; begin Top := BegQ^.TopS; if Top = Nil then writeln('попытка удаление из пустого стека!') else begin KonS := Top; Top := Top^.NextS; dispose(KonS); BegQ^.Tops := Top end end; Procedure AddEl(var KonQ: UkazQ); {добавление элементов в стек} var Top, Kon: UkazS; Rname: string; B: boolean; begin B := true; Top := nil; while B do begin writeln('введите очередной элемент'); readln(Rname); if (Rname = 'End') then begin KonQ^.TopS := Top; B := false end else begin New(Kon); Kon^.NextS := Top; Kon^.Name := Rname; Top := Kon; end end end; Procedure AddElToBg(var BegQ: UkazQ); {добавление элементов в стек от начала} var Top, Kon: UkazS; Rname: string; B: boolean; begin B := true; Top := nil; if BegQ <> nil then begin while B do begin writeln('введите очередной элемент'); readln(Rname); if (Rname = 'End') then begin BegQ^.TopS := Top; B := false end else begin New(Kon); Kon^.NextS := Top; Kon^.Name := Rname; Top := Kon; end end end else writeln('очередь не создана'); end; Procedure OrgEmptStack(var BegQ, KonQ: UkazQ); {организация очереди с пустым стеком} var Last: UkazQ; Ch: char; begin new(Last); If (BegQ = nil) then begin Last^.TopS := nil; BegQ := Last; BegQ^.NextQ := nil; KonQ := Last; end else begin KonQ^.NextQ := Last; Last^.TopS := nil; Last^.NextQ := nil; KonQ := Last end; end; Procedure OrgStackWithElements(var BegQ, KonQ: UkazQ); {организация ячейки очереди со стеком и ее заполнение} var KonS: UkazS; Last: UkazQ; begin new(Last); If (BegQ = nil) then begin BegQ := Last; KonQ := Last; writeln('вводите элементы стека(словом "End" вы завершите его заполнение)'); AddEl(KonQ); KonQ^.NextQ := nil; end else begin Last^.NextQ := nil; KonQ^.NextQ := Last; KonQ := Last; writeln('вводите элементы стека(словом "End" вы завершите его заполнение)'); AddEl(KonQ); end end; Procedure PromQ(var BegQ: UkazQ); {продвижение очереди} var Kon: UkazQ; begin if BegQ = nil then writeln('пустая очередь!') else begin PurgeStack(BegQ); Kon := BegQ; dispose(Kon); BegQ := BegQ^.NextQ end end; Procedure Out(var BegQ: UkazQ); {выдача очереди} var Top: UkazS; Kon: UkazQ; begin Kon := BegQ; Top := BegQ^.TopS; if Kon = nil then writeln('очередь пуста') else begin while Kon <> nil do begin if Top = nil then begin write('стек пуст'); Kon := Kon^.NextQ; if Kon <> nil then Top := Kon^.TopS; end else begin while Top <> nil do begin write(Top^.Name, ' '); Top := Top^.NextS end; Kon := Kon^.NextQ; if Kon <> nil then Top := Kon^.TopS; end; writeln end end end; Procedure StackFromBgQue(var BegQ: UkazQ); {стек от начала} var Con: UkazQ; Top: UkazS; begin Con := BegQ; end; Procedure FromStartQue(var BegQ: UkazQ; Var Variant2: char); begin writeln('Выберите нужный вариант'); writeln('1: Добавить эелемент в стек'); writeln('2: Удалить эелемент из стека'); writeln('3: очистить стек'); writeln('4: вернуться в меню'); readln(Variant2); case Variant2 of '1':begin AddElToBg(BegQ); writeln; FromStartQue(BegQ, Variant2) end; '2':begin DelFromStack(BegQ); writeln; FromStartQue(BegQ, Variant2) end; '3':begin PurgeStack(BegQ); writeln; FromStartQue(BegQ, Variant2) end; '4': Variant2 := 'M'; end; end; Procedure Menu(var BegQ, KonQ: UkazQ); {пункты меню для пользователя} var Variant, Variant2: char; B: Boolean; begin Variant := ' '; B := true; while ((Variant > '5') or (Variant < '1') and B) do begin writeln('Выберите нужное вам действие'); writeln('1: Добавить элемент в очередь'); writeln('2: продвижение очереди'); writeln('3: Вывод очереди'); writeln('4: Стек из начала очереди'); writeln('5: конец'); readln(Variant); case Variant of '1': begin writeln('выберите нужное вам действие:'); writeln('1: Оргиназиовать ячейку очереди с пустым стеком'); writeln('2: организовать ячейку очериди со стеком и заполнять ее'); writeln('3: вернуться в меню'); readln(Variant2); case Variant2 of '1': begin OrgEmptStack(BegQ, KonQ); Menu(BegQ, KonQ) end; '2':begin OrgStackWithElements(BegQ, KonQ); Menu(BegQ, KonQ) end; '3': begin Menu(BegQ, KonQ) end; end; end; '2': begin PromQ(BegQ); writeln; Menu(BegQ, KonQ) end; '3':begin Out(BegQ); writeln; Menu(BegQ, KonQ) end; '4':begin Variant2 := ' '; FromStartQue(BegQ, Variant2); if (Variant2 = 'M') then begin writeln; Menu(BegQ, KonQ) end end; '5': B := false; end end end; begin BegQ := nil; Menu(BegQ, KonQ) end.
{*******************************************************} { } { Delphi Visual Component Library } { Web server application components } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} // Parse an HTTP header. unit HTTPParse; interface uses System.SysUtils, System.Classes; const toEOF = AnsiChar(0); toSymbol = AnsiChar(1); toString = AnsiChar(2); toInteger = AnsiChar(3); toFloat = AnsiChar(4); toEOL = AnsiChar(5); toGET = AnsiChar(6); toHEAD = AnsiChar(7); toPUT = AnsiChar(8); toDELETE = AnsiChar(9); toPOST = AnsiChar(10); toPATCH = AnsiChar(11); toCOPY = AnsiChar(12); toUserAgent = AnsiChar(13); toAccept = AnsiChar(14); toContentType = AnsiChar(15); toContentLength = AnsiChar(16); toReferer = AnsiChar(17); toAuthorization = AnsiChar(18); toCacheControl = AnsiChar(19); toDate = AnsiChar(20); toFrom = AnsiChar(21); toHost = AnsiChar(22); toIfModified = AnsiChar(23); toContentEncoding = AnsiChar(24); toContentVersion= AnsiChar(25); toAllow = AnsiChar(26); toConnection = AnsiChar(27); toCookie = AnsiChar(28); toContentDisposition = AnsiChar(29); hcGET = $14F5; hcPUT = $4AF5; hcDELETE = $92B2; hcPOST = $361D; hcCacheControl = $4FF6; hcDate = $0EE6; hcFrom = $418F; hcHost = $3611; hcIfModified = $DDF0; hcAllow = $3D80; hcUserAgent = $E890; hcAccept = $1844; hcContentEncoding= $C586; hcContentVersion = $EDF4; hcContentType = $F0E0; hcContentLength = $B0C4; hcReferer = $CEA5; hcAuthorization = $ABCA; hcConnection = $0EDE; hcCookie = $27B3; hcContentDisposition = $CBEB; type { THTTPParser } THTTPParser = class(TObject) private FStream: TStream; FOrigin: Int64; FBuffer: PAnsiChar; FBufPtr: PAnsiChar; FBufEnd: PAnsiChar; FSourcePtr: PAnsiChar; FSourceEnd: PAnsiChar; FStringPtr: PAnsiChar; FSourceLine: Integer; FSaveChar: AnsiChar; FToken: AnsiChar; FHeaderField: Boolean; FTokenPtr: PAnsiChar; procedure ReadBuffer; procedure SkipBlanks; public constructor Create(Stream: TStream); destructor Destroy; override; procedure CheckToken(T: AnsiChar); procedure CheckTokenSymbol(const S: AnsiString); function CopyTo(Length: Integer): AnsiString; function CopyToEOL: AnsiString; function CopyToEOF: AnsiString; procedure Error(const Ident: string); procedure ErrorFmt(const Ident: string; const Args: array of const); procedure ErrorStr(const Message: string); procedure HexToBinary(Stream: TStream); function NextToken: AnsiChar; procedure SkipEOL; function SourcePos: Int64; function TokenFloat: Extended; function TokenInt: Longint; function TokenString: AnsiString; function TokenSymbolIs(const S: AnsiString): Boolean; function BufferRequest(Length: Integer): TStream; property SourceLine: Integer read FSourceLine; property Token: AnsiChar read FToken; property HeaderField: Boolean read FHeaderField write FHeaderField; property SourcePtr: PAnsiChar read FSourcePtr write FSourcePtr; property TokenPtr: PAnsiChar read FTokenPtr write FTokenPtr; property Stream: TStream read FStream; property SourceEnd: PAnsiChar read FSourceEnd; end; implementation uses System.RTLConsts, Winapi.Windows; const ParseBufSize = 4096; { THTTPParser } constructor THTTPParser.Create(Stream: TStream); begin FStream := Stream; GetMem(FBuffer, ParseBufSize); FBuffer[0] := #0; FBufPtr := FBuffer; FBufEnd := FBuffer + ParseBufSize; FSourcePtr := FBuffer; FSourceEnd := FBuffer; FTokenPtr := FBuffer; FSourceLine := 1; FHeaderField := True; NextToken; end; function THTTPParser.BufferRequest(Length: Integer): TStream; const BufSize = 1000; var Buffer: array[0..BufSize-1] of byte; Count: Integer; L, R, T, C: Integer; P1, P2: PAnsiChar; begin // Get processed contents of parser buffer Result := TMemoryStream.Create; Count := FSourcePtr - FBuffer; Result.Write(Pointer(FBuffer)^, Count); // Find end of parser buffer if Length > 0 then begin P1 := FSourcePtr; P2 := P1; while (P2^ <> #0) do Inc(P2); while Length > 0 do begin if Length > BufSize then L := BufSize else L := Length; if P1 < P2 then begin // Read from parser buffer if L > P2 - P1 then R := P2 - P1 else R := L; Move(P1^, Buffer, R); L := R; P1 := P1 + R; end else begin T := 0; R := L; repeat C := FStream.Read(Buffer[T], R-T); T := T + C; until (C = 0) or (T = R); end; Result.Write(Buffer, L); Length := Length - R; end; end; Result.Seek(Count, soFromBeginning); FStream := Result; end; destructor THTTPParser.Destroy; begin if FBuffer <> nil then begin FStream.Seek(IntPtr(FTokenPtr) - IntPtr(FSourceEnd), 1); FreeMem(FBuffer, ParseBufSize); end; end; procedure THTTPParser.CheckToken(T: AnsiChar); begin if Token <> T then case T of toSymbol: Error(SIdentifierExpected); System.Classes.toString: Error(SStringExpected); toInteger, toFloat: Error(SNumberExpected); else ErrorFmt(SCharExpected, [T]); end; end; procedure THTTPParser.CheckTokenSymbol(const S: AnsiString); begin if not TokenSymbolIs(S) then ErrorFmt(SSymbolExpected, [S]); end; function THTTPParser.CopyTo(Length: Integer): AnsiString; var P: PAnsiChar; Temp: AnsiString; begin Result := ''; repeat P := FTokenPtr; while (Length > 0) and (P^ <> #0) do begin Inc(P); Dec(Length); end; SetString(Temp, FTokenPtr, P - FTokenPtr); Result := Result + Temp; if Length > 0 then ReadBuffer; until (Length = 0) or (Token = toEOF); FSourcePtr := P; end; function THTTPParser.CopyToEOL: AnsiString; var P: PAnsiChar; begin P := FTokenPtr; while not (P^ in [#13, #10, #0]) do Inc(P); SetString(Result, FTokenPtr, P - FTokenPtr); if P^ = #13 then Inc(P); FSourcePtr := P; if P^ <> #0 then NextToken else FToken := #0; end; function THTTPParser.CopyToEOF: AnsiString; var P: PAnsiChar; Temp: AnsiString; begin repeat P := FTokenPtr; while P^ <> #0 do Inc(P); FSourcePtr := P; ReadBuffer; SetString(Temp, FTokenPtr, P - FTokenPtr); Result := Result + Temp; NextToken; until Token = toEOF; end; procedure THTTPParser.Error(const Ident: string); begin ErrorStr(Ident); end; procedure THTTPParser.ErrorFmt(const Ident: string; const Args: array of const); begin ErrorStr(Format(Ident, Args)); end; procedure THTTPParser.ErrorStr(const Message: string); begin raise EParserError.CreateResFmt(@SParseError, [Message, FSourceLine]); end; procedure THTTPParser.HexToBinary(Stream: TStream); var Count: Integer; Buffer: array[0..255] of AnsiChar; begin SkipBlanks; while FSourcePtr^ <> '}' do begin Count := HexToBin(FSourcePtr, Buffer, SizeOf(Buffer)); if Count = 0 then Error(SInvalidBinary); Stream.Write(Buffer, Count); Inc(FSourcePtr, Count * 2); SkipBlanks; end; NextToken; end; const CharValue: array[Byte] of Byte = ( $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$00,$00,$00,$00,$00,$00, $00,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4A,$4B,$4C,$4D,$4E,$4F, $50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5A,$00,$00,$00,$00,$5F, $00,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4A,$4B,$4C,$4D,$4E,$4F, $50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5A,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00); function GetHashCode(Ident: PAnsiChar; Length: Integer): Word; begin Result := 0; while Length > 0 do begin Result := (Result SHL 5) or (Result SHR (16 - 5)); PByte(@Result)[0] := PByte(@Result)[0] XOR CharValue[Byte(Ident^)]; Dec(Length); Inc(Ident); end; end; type TSymbolEntry = record HashCode: Word; Symbol: PAnsiChar; Token: AnsiChar; end; const SymbolTable: array[0..20] of TSymbolEntry = ( (HashCode: hcGet; Symbol: 'GET'; Token: toGET), (HashCode: hcPut; Symbol: 'PUT'; Token: toPUT), (HashCode: hcDelete; Symbol: 'DELETE'; Token: toDELETE), (HashCode: hcPost; Symbol: 'POST'; Token: toPOST), (HashCode: hcCacheControl; Symbol: 'Cache-Control'; Token: toCacheControl), (HashCode: hcDate; Symbol: 'Date'; Token: toDate), (HashCode: hcFrom; Symbol: 'From'; Token: toFrom), (HashCode: hcHost; Symbol: 'Host'; Token: toHost), (HashCode: hcIfModified; Symbol: 'If-Modified-Since'; Token: toIfModified), (HashCode: hcAllow; Symbol: 'Allow'; Token: toAllow), (HashCode: hcUserAgent; Symbol: 'User-Agent'; Token: toUserAgent), (HashCode: hcAccept; Symbol: 'Accept'; Token: toAccept), (HashCode: hcContentEncoding; Symbol: 'Content-Encoding'; Token: toContentEncoding), (HashCode: hcContentVersion; Symbol: 'Content-Version'; Token: toContentVersion), (HashCode: hcContentType; Symbol: 'Content-Type'; Token: toContentType), (HashCode: hcContentLength; Symbol: 'Content-Length'; Token: toContentLength), (HashCode: hcReferer; Symbol: 'Referer'; Token: toReferer), (HashCode: hcConnection; Symbol: 'Connection'; Token: toConnection), (HashCode: hcCookie; Symbol: 'Cookie'; Token: toCookie), (HashCode: hcAuthorization; Symbol: 'Authorization'; Token: toAuthorization), (HashCode: hcContentDisposition; Symbol: 'Content-Disposition'; Token: toContentDisposition)); function LookupToken(Sym: PAnsiChar): AnsiChar; var HCode: Word; I: Integer; begin Result := toSymbol; HCode := GetHashCode(Sym, StrLen(Sym)); for I := Low(SymbolTable) to High(SymbolTable) do with SymbolTable[I] do if HCode = HashCode then if StrIComp(Symbol, Sym) = 0 then begin Result := Token; Break; end; end; function THTTPParser.NextToken: AnsiChar; var I: Integer; P, S: PAnsiChar; SaveChar: AnsiChar; TokenChars: set of AnsiChar; begin SkipBlanks; P := FSourcePtr; FTokenPtr := P; if FHeaderField then TokenChars := ['A'..'Z', 'a'..'z', '0'..'9', '_', '-'] else TokenChars := ['A'..'Z', 'a'..'z', '0'..'9', '_']; case P^ of 'A'..'Z', 'a'..'z', '_': begin Inc(P); while P^ in TokenChars do Inc(P); SaveChar := P^; try P^ := #0; Result := LookupToken(FTokenPtr); finally P^ := SaveChar; end; end; #10: begin Inc(P); Inc(FSourceLine); Result := toEOL; end; '#', '''': begin S := P; while True do case P^ of '#': begin Inc(P); I := 0; while P^ in ['0'..'9'] do begin I := I * 10 + (Ord(P^) - Ord('0')); Inc(P); end; S^ := AnsiChar(I); Inc(S); end; '''': begin Inc(P); while True do begin case P^ of #0, #10, #13: Error(SInvalidString); '''': begin Inc(P); if P^ <> '''' then Break; end; end; S^ := P^; Inc(S); Inc(P); end; end; else Break; end; FStringPtr := S; Result := System.Classes.toString; end; '$': begin Inc(P); while P^ in ['0'..'9', 'A'..'F', 'a'..'f'] do Inc(P); Result := toInteger; end; '0'..'9': begin Inc(P); while P^ in ['0'..'9'] do Inc(P); Result := toInteger; while P^ in ['0'..'9', '.', 'e', 'E', '+'] do begin Inc(P); Result := toFloat; end; end; else Result := P^; if Result <> toEOF then Inc(P); end; FSourcePtr := P; FToken := Result; end; procedure THTTPParser.ReadBuffer; var Count: Int64; P: PAnsiChar; begin Inc(FOrigin, FSourcePtr - FBuffer); FSourceEnd[0] := FSaveChar; Count := FBufPtr - FSourcePtr; if Count <> 0 then Move(FSourcePtr[0], FBuffer[0], Count); FBufPtr := FBuffer + Count; Inc(FBufPtr, FStream.Read(FBufPtr[0], FBufEnd - FBufPtr)); FSourcePtr := FBuffer; FSourceEnd := FBufPtr; if FSourceEnd = FBufEnd then begin FSourceEnd := LineStart(FBuffer, FSourceEnd - 1); if FSourceEnd = FBuffer then Error(SLineTooLong); end; P := FBuffer; while P < FSourceEnd do begin Inc(P); end; FSaveChar := FSourceEnd[0]; FSourceEnd[0] := #0; end; procedure THTTPParser.SkipBlanks; begin while True do begin case FSourcePtr^ of #0: begin ReadBuffer; if FSourcePtr^ = #0 then Exit; Continue; end; #10: Exit; #33..#255: Exit; end; Inc(FSourcePtr); end; end; function THTTPParser.SourcePos: Int64; begin Result := FOrigin + (FTokenPtr - FBuffer); end; procedure THTTPParser.SkipEOL; begin if Token = toEOL then begin while FTokenPtr^ in [#13, #10] do Inc(FTokenPtr); FSourcePtr := FTokenPtr; if FSourcePtr^ <> #0 then NextToken else FToken := #0; end; end; function THTTPParser.TokenFloat: Extended; begin Result := StrToFloat(string(TokenString)); end; function THTTPParser.TokenInt: Longint; begin Result := StrToInt(string(TokenString)); end; function THTTPParser.TokenString: AnsiString; var L: Int64; begin if FToken = HTTPParse.toString then L := FStringPtr - FTokenPtr else L := FSourcePtr - FTokenPtr; SetString(Result, FTokenPtr, L); end; function THTTPParser.TokenSymbolIs(const S: AnsiString): Boolean; begin Result := (Token = toSymbol) and (AnsiStrComp(PAnsiChar(S), PAnsiChar(TokenString)) = 0); end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.ASE.Model; {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses System.SysUtils, System.Classes, System.TypInfo, FMX.Types3D, System.Types, FMX.ASE.Lexer, FMX.Import; type TAseMaterial = class; TAseMaterialDynArray = array of TAseMaterial; TAseMaterial = class(TGEMaterial) private FSubMaterials: TGEMaterials; public property SubMaterials: TGEMaterials read FSubMaterials; constructor Create; destructor Destroy; override; end; TAseMesh = record FVertexSource: TGEVertexSource; FTriangleMesh: TGETriangleMeshID; FFaceMaterials : TIntegerDynArray; FSubMeshes: array of TGEMesh; end; TAseMeshDynArray = array of TAseMesh; TAseModel = class(TCustomModel) private FMaterials: TGEMaterials; FMeshes: TAseMeshDynArray; procedure ParseVertexList( const ALexer : TAseLexer; const ANumVertex: Integer; const AVertexSource: TGEVertexSource); procedure ParseNormalList( const ALexer : TAseLexer; const ANumNormal: Integer; var AMesh: TAseMesh); procedure ParseTexCoordList( const ALexer : TAseLexer; const ANumTexCoord: Integer; const AVertexSource: TGEVertexSource); procedure ParseFaceList( const ALexer : TAseLexer; const ANumFaces: Integer; var AMesh: TAseMesh); procedure ParseTFaceList( const ALexer : TAseLexer; const ANumFaces: Integer; var AMesh: TAseMesh); procedure ParseMesh(const ALexer : TAseLexer; var AMesh : TAseMesh); procedure ParseMap(const ALexer : TAseLexer; var AFileName: String); procedure ParseMaterialList(const ALexer : TAseLexer); procedure ParseMaterial(const ALexer : TAseLexer; AMaterial: TAseMaterial); procedure ParseGeometry(const ALexer : TAseLexer); procedure ParseModel(const ALexer : TAseLexer); function AddSubMesh(const AVertexSource: TGEVertexSource): TGEMesh; public property Meshes: TAseMeshDynArray read FMeshes; property Materials: TGeMaterials read FMaterials; procedure LoadFromFile(const AFileName: String); override; constructor Create; destructor Destroy; override; end; EAseParserError = class(Exception); implementation uses FMX.Consts; type TAseLexerHack = class(TAseLexer); constructor TAseModel.Create; begin FMaterials := TGEMaterials.Create(True); end; destructor TAseModel.Destroy; var i , j: Integer; begin for i := 0 to High(FMeshes) do for j := 0 to High(FMeshes[i].FSubMeshes) do FMeshes[i].FSubMeshes[j].Free; FMaterials.Free; end; procedure TAseModel.ParseMap(const ALexer : TAseLexer; var AFileName: String); begin ALexer.NextTokenExpected(atOpenBracket); while not (ALexer.NextToken in [atEOF, atCloseBracket]) do begin ALexer.TokenExpected(atKeyWord); case ALexer.TokenKeyWord of kw_BITMAP: begin ALexer.NextTokenExpected(atString); AFileName := ALexer.TokenString; end; else ALexer.SkipKeyWordBlock; end; end; ALexer.TokenExpected(atCloseBracket); end; procedure TAseModel.ParseMaterial(const ALexer : TAseLexer; AMaterial: TAseMaterial); var LNumSubmaterials, LSubmaterial: Integer; begin // ALexer.NextTokenExpected(atInteger); // if (LIdx < 0) or (LIdx >= ANumTexCoord) then // ALexer.Error(''); ALexer.NextTokenExpected(atOpenBracket); while not (ALexer.NextToken in [atEOF, atCloseBracket]) do begin ALexer.TokenExpected(atKeyWord); case ALexer.TokenKeyWord of kw_MATERIAL_AMBIENT: begin ALexer.NextTokenExpected(atFloat); AMaterial.FAmbient.X := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); AMaterial.FAmbient.Y := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); AMaterial.FAmbient.Z := ALexer.TokenFloat; end; kw_MATERIAL_DIFFUSE: begin ALexer.NextTokenExpected(atFloat); AMaterial.FDiffuse.X := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); AMaterial.FDiffuse.Y := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); AMaterial.FDiffuse.Z := ALexer.TokenFloat; end; kw_MATERIAL_SPECULAR: begin ALexer.NextTokenExpected(atFloat); AMaterial.FSpecular.X := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); AMaterial.FSpecular.Y := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); AMaterial.FSpecular.Z := ALexer.TokenFloat; end; kw_MAP_DIFFUSE: begin ParseMap(ALexer, AMaterial.FDiffuseMap); end; kw_NUMSUBMTLS: begin ALexer.NextTokenExpected(atInteger); LNumSubmaterials := ALexer.TokenInteger; AMaterial.FSubMaterials.Count := LNumSubmaterials; end; kw_SUBMATERIAL: begin ALexer.NextTokenExpected(atInteger); LSubmaterial := ALexer.TokenInteger; AMaterial.FSubMaterials[LSubmaterial] := TaseMaterial.Create; AMaterial.FSubMaterials[LSubmaterial].FName := AMaterial.FName + 'sub'+ IntToStr(LSubmaterial); ParseMaterial(ALexer, TAseMaterial(AMaterial.FSubMaterials[LSubmaterial])); end; else ALexer.SkipKeyWordBlock; end; end; ALexer.TokenExpected(atCloseBracket); end; procedure TAseModel.ParseMaterialList(const ALexer : TAseLexer); var LNumMaterials: Integer; LIdx: Integer; begin LNumMaterials := 0; ALexer.NextTokenExpected(atOpenBracket); while not (ALexer.NextToken in [atEOF, atCloseBracket]) do begin ALexer.TokenExpected(atKeyWord); case ALexer.TokenKeyWord of kw_MATERIAL_COUNT: begin ALexer.NextTokenExpected(atInteger); LNumMaterials := ALexer.TokenInteger; FMaterials.Count := LNumMaterials; end; kw_MATERIAL: begin ALexer.NextTokenExpected(atInteger); LIdx := ALexer.TokenInteger; if (LIdx < 0) or (LIdx >= LNumMaterials) then raise EAseParserError.CreateRes(@SAseParserWrongMaterialsNumError); FMaterials[LIdx] := TaseMaterial.Create; FMaterials[LIdx].FName := IntToStr(LIdx); ParseMaterial(ALexer, TAseMaterial(FMaterials.Items[LIdx])); end; else ALexer.SkipKeyWordBlock; end; end; ALexer.TokenExpected(atCloseBracket); end; procedure TAseModel.ParseVertexList( const ALexer : TAseLexer; const ANumVertex: Integer; const AVertexSource: TGEVertexSource); var LNumVertex: Integer; LIdx: Integer; LPositions: TPoint3DDynArray; begin ALexer.NextTokenExpected(atOpenBracket); LNumVertex := 0; SetLength(LPositions, ANumVertex); while not (ALexer.NextToken in [atEOF, atCloseBracket]) do begin ALexer.TokenExpected(atKeyWord); case ALexer.TokenKeyWord of kw_MESH_VERTEX: begin Inc(LNumVertex); if (LNumVertex > ANumVertex) then raise EAseParserError.CreateRes(@SAseParserWrongVertexNumError); ALexer.NextTokenExpected(atInteger); LIdx := ALexer.TokenInteger; if (LIdx < 0) or (LIdx >= ANumVertex) then raise EAseParserError.CreateRes(@SAseParserWrongVertexIdxError); ALexer.NextTokenExpected(atFloat); LPositions[LIdx].X := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); LPositions[LIdx].Y := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); LPositions[LIdx].Z := ALexer.TokenFloat; end; else ALexer.SkipKeyWordBlock; end; end; ALexer.TokenExpected(atCloseBracket); if (ANumVertex <> LNumVertex) then raise EAseParserError.CreateRes(@SAseParserWrongVertexNumError); AVertexSource.PositionSource := LPositions; end; procedure TAseModel.ParseNormalList( const ALexer : TAseLexer; const ANumNormal: Integer; var AMesh: TAseMesh); var LNumNormal: Integer; LNormals: TPoint3DDynArray; begin ALexer.NextTokenExpected(atOpenBracket); LNumNormal := 0; SetLength(LNormals, ANumNormal); while not (ALexer.NextToken in [atEOF, atCloseBracket]) do begin ALexer.TokenExpected(atKeyWord); case ALexer.TokenKeyWord of kw_MESH_VERTEXNORMAL: begin if (LNumNormal + 1 > ANumNormal) then raise EAseParserError.CreateRes(@SAseParserWrongNormalNumError); ALexer.NextTokenExpected(atInteger); ALexer.NextTokenExpected(atFloat); LNormals[LNumNormal].X := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); LNormals[LNumNormal].Y := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); LNormals[LNumNormal].Z := ALexer.TokenFloat; AMesh.FTriangleMesh[LNumNormal div 3][LNumNormal mod 3].Normal := LNumNormal; Inc(LNumNormal); end; else ALexer.SkipKeyWordBlock; end; end; ALexer.TokenExpected(atCloseBracket); if (ANumNormal <> LNumNormal) then raise EAseParserError.CreateRes(@SAseParserWrongNormalNumError); AMesh.FVertexSource.NormalSource := LNormals; end; procedure TAseModel.ParseTexCoordList( const ALexer : TAseLexer; const ANumTexCoord: Integer; const AVertexSource: TGEVertexSource); var LNumTexCoord: Integer; LIdx: Integer; LTexCoord: TPointFDynArray; begin ALexer.NextTokenExpected(atOpenBracket); LNumTexCoord := 0; SetLength(LTexCoord, ANumTexCoord); while not (ALexer.NextToken in [atEOF, atCloseBracket]) do begin ALexer.TokenExpected(atKeyWord); case ALexer.TokenKeyWord of kw_MESH_TVERT: begin Inc(LNumTexCoord); if (LNumTexCoord > ANumTexCoord) then raise EAseParserError.CreateRes(@SAseParserWrongTexCoordNumError); ALexer.NextTokenExpected(atInteger); LIdx := ALexer.TokenInteger; if (LIdx < 0) or (LIdx >= ANumTexCoord) then raise EAseParserError.CreateRes(@SAseParserWrongTexCoordIdxError); ALexer.NextTokenExpected(atFloat); LTexCoord[LIdx].X := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); LTexCoord[LIdx].Y := ALexer.TokenFloat; ALexer.NextTokenExpected(atFloat); ALexer.TokenFloat; end; else ALexer.SkipKeyWordBlock; end; end; ALexer.TokenExpected(atCloseBracket); if (ANumTexCoord <> LNumTexCoord) then raise EAseParserError.CreateRes(@SAseParserWrongTexCoordNumError); AVertexSource.Texture0Source := LTexCoord; end; procedure TAseModel.ParseFaceList( const ALexer : TAseLexer; const ANumFaces: Integer; var AMesh: TAseMesh); var LTriangle: ^TGETriangleID; LNumFaces: Integer; LIdx, LSmoothGroup: Integer; LC: char; begin ALexer.NextTokenExpected(atOpenBracket); LNumFaces := 0; LIdx := -1; LTriangle := nil; while not (ALexer.NextToken in [atEOF, atCloseBracket]) do begin case ALexer.Token of atKeyWord: case ALexer.TokenKeyWord of kw_MESH_MTLID: begin ALexer.NextTokenExpected(atInteger); AMesh.FFaceMaterials[LIdx] := ALexer.TokenInteger; end; kw_MESH_SMOOTHING: begin ALexer.UseCommaToken := True; ALexer.NextTokenExpected(atInteger); LSmoothGroup := ALexer.TokenInteger; while ALexer.NextToken = atComma do ALexer.NextTokenExpected(atInteger); ALexer.Ahead := true; ALExer.UseCommaToken := False; if Assigned(LTriangle) then begin LTriangle[0].SmoothGroup := LSmoothGroup; LTriangle[1].SmoothGroup := LSmoothGroup; LTriangle[2].SmoothGroup := LSmoothGroup; end; end; kw_MESH_FACE: begin Inc(LNumFaces); if (LNumFaces > ANumFaces) then raise EAseParserError.CreateRes(@SAseParserWrongFacesNumError); ALexer.NextTokenExpected(atInteger); LIdx := ALexer.TokenInteger; if (LIdx < 0) or (LIdx >= ANumFaces) then raise EAseParserError.CreateRes(@SAseParserWrongFacesIdxError); LTriangle := @AMesh.FTriangleMesh[LIdx]; LTriangle[0] := NullVertexID; LTriangle[1] := NullVertexID; LTriangle[2] := NullVertexID; ALexer.NextTokenExpected(atColon); end; else ALexer.SkipKeyWordBlock; end; atIdent: begin if LIdx = -1 then raise EAseParserError.CreateRes(@SAseParserWrongFacesIdxError); case Length(ALexer.TokenIdent) of 1: begin LC := ALexer.TokenIdent[1]; ALexer.NextTokenExpected(atColon); ALexer.NextTokenExpected(atInteger); case LC of 'A': LTriangle[0].Position := ALexer.TokenInteger; 'B': LTriangle[1].Position := ALexer.TokenInteger; 'C': LTriangle[2].Position := ALexer.TokenInteger; end; end; // 2: else ALexer.NextTokenExpected(atColon); ALexer.NextTokenExpected(atInteger); Continue; end; end else raise EAseParserError.CreateRes(@SAseParserUnexpectedKyWordError); end; end; ALexer.TokenExpected(atCloseBracket); if (ANumFaces <> LNumFaces) then raise EAseParserError.CreateRes(@SAseParserWrongFacesNumError); end; procedure TAseModel.ParseTFaceList( const ALexer : TAseLexer; const ANumFaces: Integer; var AMesh: TAseMesh); var LNumFace: Integer; LIdx: Integer; begin ALexer.NextTokenExpected(atOpenBracket); LNumFace := 0; while not (ALexer.NextToken in [atEOF, atCloseBracket]) do begin ALexer.TokenExpected(atKeyWord); case ALexer.TokenKeyWord of kw_MESH_TFACE: begin Inc(LNumFace); if (LNumFace > Length(AMesh.FTriangleMesh)) then raise EAseParserError.CreateRes(@SAseParserWrongTriangleMeshNumError); ALexer.NextTokenExpected(atInteger); LIdx := ALexer.TokenInteger; if (LIdx < 0) or (LIdx > High(AMesh.FTriangleMesh)) then raise EAseParserError.CreateRes(@SAseParserWrongTriangleMeshIdxError); ALexer.NextTokenExpected(atInteger); AMesh.FTriangleMesh[LIdx][0].Texture0 := ALexer.TokenInteger; ALexer.NextTokenExpected(atInteger); AMesh.FTriangleMesh[LIdx][1].Texture0 := ALexer.TokenInteger; ALexer.NextTokenExpected(atInteger); AMesh.FTriangleMesh[LIdx][2].Texture0 := ALexer.TokenInteger; end; else ALexer.SkipKeyWordBlock; end; end; ALexer.TokenExpected(atCloseBracket); if (Length(AMesh.FTriangleMesh) <> LNumFace) then raise EAseParserError.CreateRes(@SAseParserWrongTriangleMeshNumError); end; function TAseModel.AddSubMesh(const AVertexSource: TGEVertexSource): TGEMesh; var LMesh: ^TAseMesh; begin result := TGEMesh.Create(AVertexSource); LMesh := @FMeshes[High(FMeshes)]; SetLength(LMesh.FSubMeshes, Length(LMesh.FSubMeshes) + 1); LMesh.FSubMeshes[High(LMesh.FSubMeshes)] := result; end; procedure TAseModel.ParseMesh(const ALexer : TAseLexer; var AMesh : TAseMesh); var LNumVertex, LNumFaces, LNumTVVertex: Integer; begin ALexer.NextTokenExpected(atOpenBracket); LNumFaces := 0; LNumVertex := 0; LNumTVVertex := 0; while not (ALexer.NextToken in [atEOF, atCloseBracket]) do begin ALexer.TokenExpected(atKeyWord); case ALexer.TokenKeyWord of kw_MESH_NUMVERTEX: begin ALexer.NextTokenExpected(atInteger); LNumVertex := ALexer.TokenInteger; end; kw_MESH_NUMFACES: begin ALexer.NextTokenExpected(atInteger); LNumFaces := ALexer.TokenInteger; SetLength(AMesh.FTriangleMesh, LNumFaces); SetLength(AMesh.FFaceMaterials, LNumFaces); end; kw_MESH_NUMTVERTEX: begin ALexer.NextTokenExpected(atInteger); LNumTVVertex := ALexer.TokenInteger; end; kw_MESH_VERTEX_LIST: ParseVertexList(ALexer, LNumVertex, AMesh.FVertexSource); kw_MESH_TVERTLIST: ParseTexCoordList(ALexer, LNumTVVertex, AMesh.FVertexSource); kw_MESH_NORMALS: ParseNormalList(ALexer, LNumFaces*3, AMesh); kw_MESH_FACE_LIST: ParseFaceList(ALexer, LNumFaces, AMesh); kw_MESH_TFACELIST: ParseTFaceList(ALexer, LNumFaces, AMesh); else ALexer.SkipKeyWordBlock; end; end; ALexer.TokenExpected(atCloseBracket); end; procedure TAseModel.ParseGeometry(const ALexer : TAseLexer); var LMaterialRef, LSubMaterial, i: Integer; LMeshData: TAseMesh; LMesh: TGEMesh; begin LMeshData.FVertexSource := TGEVertexSource.Create; ALexer.NextTokenExpected(atOpenBracket); LMaterialRef := -1; while not (ALexer.NextToken in [atEOF, atCloseBracket]) do begin ALexer.TokenExpected(atKeyWord); case ALexer.TokenKeyWord of kw_MESH: ParseMesh(ALexer, LMeshData); kw_MATERIAL_REF: begin ALexer.NextTokenExpected(atInteger); LMaterialRef := ALexer.TokenInteger; end; else ALexer.SkipKeyWordBlock; end; end; ALexer.TokenExpected(atCloseBracket); SetLength(FMeshes, Length(FMeshes) + 1); FMeshes[high(FMeshes)] := LMeshData; LSubMaterial := -1; LMesh := nil; if (LMaterialRef <> -1) and (TAseMaterial(FMaterials[LMaterialRef]).FSubMaterials.Count > 0) then begin for i := 0 to High(LMeshData.FFaceMaterials) do begin if (LSubMaterial <> LMeshData.FFaceMaterials[i]) then begin LSubMaterial := LMeshData.FFaceMaterials[i]; LMesh := AddSubMesh(LMeshData.FVertexSource); LMesh.MaterialName := inttostr(LMaterialRef)+ 'sub' + inttostr(LSubMaterial); end; LMesh.AddTriangle(LMeshData.FTriangleMesh[i]); end; end else begin LMesh := AddSubMesh(LMeshData.FVertexSource); LMesh.AddTriangleMesh(LMeshData.FTriangleMesh); LMesh.MaterialName := inttostr(LMaterialRef); end; LMeshData.FVertexSource.Free; end; procedure TAseModel.ParseModel(const ALexer : TAseLexer); begin while (ALexer.NextToken <> atEOF) do begin case ALexer.Token of atKeyWord: begin case ALexer.TokenKeyWord of kw_MATERIAL_LIST: ParseMaterialList(ALexer); kw_GEOMOBJECT: ParseGeometry(ALexer); else ALexer.SkipKeyWordBlock; end; end; else ALexer.TokenExpected(atKeyWord); end; end; end; procedure TAseModel.LoadFromFile(const AFileName: String); var LLexer : TAseLexer; begin LLexer := TAseLexer.Create(AFileName); ParseModel(LLexer); LLexer.Free; end; { TAseMaterial } constructor TAseMaterial.Create; begin FSubMaterials := TGEMaterials.Create(True); end; destructor TAseMaterial.Destroy; begin FSubMaterials.Free; inherited; end; end.
unit TransparentRectangleIconButton; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types, FMX.Objects, FMX.StdCtrls, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math, System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects, ColorClass; type TIconPosition = (Left, Right); TTransparentRectangleIconButton = class(TControl) private { Private declarations } protected { Protected declarations } FPointerOnMouseEnter: TNotifyEvent; FPointerOnMouseExit: TNotifyEvent; FPointerOnClick: TNotifyEvent; FAnimationOnClick: Boolean; FBackgroundSelect: TRectangle; FIcon: TPath; { Block focus on background } FButtonLockFocus: TButton; procedure Paint; override; procedure BackgroundOnEnter(Sender: TObject); virtual; procedure BackgroundOnExit(Sender: TObject); virtual; procedure BackgroundOnClick(Sender: TObject); virtual; function GetFButtonClass: TColorClass; virtual; procedure SetFButtonClass(const Value: TColorClass); virtual; function GetFBackgroudColor: TAlphaColor; virtual; procedure SetFBackgroudColor(const Value: TAlphaColor); virtual; function GetFTag: NativeInt; procedure SetFTag(const Value: NativeInt); function GetFIconAlign: TAlignLayout; procedure SetFIconAlign(const Value: TAlignLayout); function GetFBackgroudColorAlphaMax: TAlphaColor; function GetFCursor: TCursor; function GetFHitTest: Boolean; procedure SetFCursor(const Value: TCursor); procedure SetFHitTest(const Value: Boolean); function GetFIconData: TPathData; procedure SetFIconData(const Value: TPathData); function GetFIconSize: Single; procedure SetFIconSize(const Value: Single); function GetFOnClick: TNotifyEvent; function GetFOnDblClick: TNotifyEvent; function GetFOnMouseDown: TMouseEvent; function GetFOnMouseEnter: TNotifyEvent; function GetFOnMouseLeave: TNotifyEvent; function GetFOnMouseMove: TMouseMoveEvent; function GetFOnMouseUp: TMouseEvent; function GetFOnMouseWheel: TMouseWheelEvent; procedure SetFOnClick(const Value: TNotifyEvent); procedure SetFOnDblClick(const Value: TNotifyEvent); procedure SetFOnMouseDown(const Value: TMouseEvent); procedure SetFOnMouseEnter(const Value: TNotifyEvent); procedure SetFOnMouseLeave(const Value: TNotifyEvent); procedure SetFOnMouseMove(const Value: TMouseMoveEvent); procedure SetFOnMouseUp(const Value: TMouseEvent); procedure SetFOnMouseWheel(const Value: TMouseWheelEvent); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } property Align; property Anchors; property Enabled; property Height; property Opacity; property Visible; property Width; property Size; property Scale; property Margins; property Position; property RotationAngle; property RotationCenter; { Additional properties } property EnableAnimationOnClick: Boolean read FAnimationOnClick write FAnimationOnClick; property ButtonClass: TColorClass read GetFButtonClass write SetFButtonClass; property IconData: TPathData read GetFIconData write SetFIconData; property IconSize: Single read GetFIconSize write SetFIconSize; property IconAlign: TAlignLayout read GetFIconAlign write SetFIconAlign; property Cursor: TCursor read GetFCursor write SetFCursor; property HitTest: Boolean read GetFHitTest write SetFHitTest default True; property Color: TAlphaColor read GetFBackgroudColor write SetFBackgroudColor; property Tag: NativeInt read GetFTag write SetFTag; { Events } property OnPainting; property OnPaint; property OnResize; { Mouse events } property OnClick: TNotifyEvent read GetFOnClick write SetFOnClick; property OnDblClick: TNotifyEvent read GetFOnDblClick write SetFOnDblClick; property OnMouseDown: TMouseEvent read GetFOnMouseDown write SetFOnMouseDown; property OnMouseUp: TMouseEvent read GetFOnMouseUp write SetFOnMouseUp; property OnMouseWheel: TMouseWheelEvent read GetFOnMouseWheel write SetFOnMouseWheel; property OnMouseMove: TMouseMoveEvent read GetFOnMouseMove write SetFOnMouseMove; property OnMouseEnter: TNotifyEvent read GetFOnMouseEnter write SetFOnMouseEnter; property OnMouseLeave: TNotifyEvent read GetFOnMouseLeave write SetFOnMouseLeave; end; procedure Register; implementation procedure Register; begin RegisterComponents('Componentes Customizados', [TTransparentRectangleIconButton]); end; { TTransparentRectangleIconButton } procedure TTransparentRectangleIconButton.BackgroundOnClick(Sender: TObject); var CircleEffect: TCircle; Aux: Single; begin FButtonLockFocus.SetFocus; { Takes the focus off other components } if FAnimationOnClick then begin CircleEffect := TCircle.Create(Self); CircleEffect.HitTest := False; CircleEffect.Parent := FBackgroundSelect; CircleEffect.Align := TAlignLayout.Center; CircleEffect.Stroke.Kind := TBrushKind.None; CircleEffect.Fill.Color := GetFBackgroudColorAlphaMax; CircleEffect.SendToBack; FBackgroundSelect.ClipChildren := True; Aux := Max(FBackgroundSelect.Width, FBackgroundSelect.Height)*0.95; CircleEffect.Height := 0; CircleEffect.Width := 0; CircleEffect.Opacity := 0.6; CircleEffect.AnimateFloat('Height', Aux, 0.4, TAnimationType.Out, TInterpolationType.Circular); CircleEffect.AnimateFloat('Width', Aux, 0.4, TAnimationType.Out, TInterpolationType.Circular); CircleEffect.AnimateFloat('Opacity', 0, 0.4); end; if Assigned(FPointerOnClick) then FPointerOnClick(Sender); end; procedure TTransparentRectangleIconButton.BackgroundOnEnter(Sender: TObject); begin FBackgroundSelect.AnimateFloat('Opacity', 1, 0.2, TAnimationType.InOut); if Assigned(FPointerOnMouseEnter) then FPointerOnMouseEnter(Sender); end; procedure TTransparentRectangleIconButton.BackgroundOnExit(Sender: TObject); begin FBackgroundSelect.AnimateFloat('Opacity', 0, 0.2, TAnimationType.InOut); if Assigned(FPointerOnMouseExit) then FPointerOnMouseExit(Sender); end; constructor TTransparentRectangleIconButton.Create(AOwner: TComponent); begin inherited; Self.Height := 40; Self.Width := 40; FAnimationOnClick := True; FButtonLockFocus := TButton.Create(Self); Self.AddObject(FButtonLockFocus); FButtonLockFocus.SetSubComponent(True); FButtonLockFocus.Stored := False; FButtonLockFocus.Opacity := 0; FButtonLockFocus.TabStop := False; FButtonLockFocus.Width := 1; FButtonLockFocus.Height := 1; FButtonLockFocus.HitTest := False; FButtonLockFocus.SendToBack; FBackgroundSelect := TRectangle.Create(Self); Self.AddObject(FBackgroundSelect); FBackgroundSelect.Align := TAlignLayout.Contents; FBackgroundSelect.HitTest := True; FBackgroundSelect.SetSubComponent(True); FBackgroundSelect.Stored := False; FBackgroundSelect.Stroke.Kind := TBrushKind.None; FBackgroundSelect.Visible := True; FBackgroundSelect.Opacity := 0; FBackgroundSelect.OnMouseEnter := BackgroundOnEnter; FBackgroundSelect.OnMouseLeave := BackgroundOnExit; FBackgroundSelect.OnClick := BackgroundOnClick; FBackgroundSelect.Cursor := crHandPoint; SetFBackgroudColor(TRANSPARENT_PRIMARY_COLOR); FBackgroundSelect.SendToBack; FIcon := TPath.Create(Self); Self.AddObject(FIcon); FIcon.SetSubComponent(True); FIcon.Stored := False; FIcon.Align := TAlignLayout.Contents; FIcon.WrapMode := TPathWrapMode.Fit; FIcon.Fill.Color := GetFBackgroudColorAlphaMax; FIcon.Stroke.Kind := TBrushKind.None; FIcon.Margins.Top := 10; FIcon.Margins.Bottom := 10; FIcon.Margins.Left := 10; FIcon.Margins.Right := 10; FIcon.HitTest := False; FIcon.Data.Data := 'M12,19.2C9.5,19.2 7.29,17.92 6,16C6.03,14 10,12.9 12,12.9C14,12.9 17.97,14 18,16C16.71,17.92 14.5,19.2 12,19.2M12,5A3,3 0 0,1 15,8A3,3 0 0,1 12,11A3,3 0 0,1 9,8A3,3 0 0,1 12,5M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12C22,6.47 17.5,2 12,2Z'; FIcon.BringToFront; end; destructor TTransparentRectangleIconButton.Destroy; begin if Assigned(FIcon) then FIcon.Free; if Assigned(FBackgroundSelect) then FBackgroundSelect.Free; if Assigned(FButtonLockFocus) then FButtonLockFocus.Free; inherited; end; function TTransparentRectangleIconButton.GetFBackgroudColor: TAlphaColor; begin Result := FBackgroundSelect.Fill.Color; end; function TTransparentRectangleIconButton.GetFBackgroudColorAlphaMax: TAlphaColor; var Color: TAlphaColorRec; begin Color.Color := GetFBackgroudColor; Color.A := $FF; Result := Color.Color; end; function TTransparentRectangleIconButton.GetFButtonClass: TColorClass; begin if FBackgroundSelect.Fill.Color = TRANSPARENT_PRIMARY_COLOR then Result := TColorClass.Primary else if FBackgroundSelect.Fill.Color = TRANSPARENT_SECONDARY_COLOR then Result := TColorClass.Secondary else if FBackgroundSelect.Fill.Color = TRANSPARENT_ERROR_COLOR then Result := TColorClass.Error else if FBackgroundSelect.Fill.Color = TRANSPARENT_WARNING_COLOR then Result := TColorClass.Warning else if FBackgroundSelect.Fill.Color = TRANSPARENT_SUCCESS_COLOR then Result := TColorClass.Success else if FBackgroundSelect.Fill.Color = TRANSPARENT_NORMAL_COLOR then Result := TColorClass.Normal else Result := TColorClass.Custom; end; function TTransparentRectangleIconButton.GetFCursor: TCursor; begin Result := FBackgroundSelect.Cursor; end; function TTransparentRectangleIconButton.GetFHitTest: Boolean; begin Result := FBackgroundSelect.HitTest; end; function TTransparentRectangleIconButton.GetFIconAlign: TAlignLayout; begin Result := FIcon.Align; end; function TTransparentRectangleIconButton.GetFIconData: TPathData; begin Result := FIcon.Data; end; function TTransparentRectangleIconButton.GetFIconSize: Single; begin Result := FIcon.Width; end; function TTransparentRectangleIconButton.GetFOnClick: TNotifyEvent; begin Result := FPointerOnClick; end; function TTransparentRectangleIconButton.GetFOnDblClick: TNotifyEvent; begin Result := FBackgroundSelect.OnDblClick; end; function TTransparentRectangleIconButton.GetFOnMouseDown: TMouseEvent; begin Result := FBackgroundSelect.OnMouseDown; end; function TTransparentRectangleIconButton.GetFOnMouseEnter: TNotifyEvent; begin Result := FPointerOnMouseEnter; end; function TTransparentRectangleIconButton.GetFOnMouseLeave: TNotifyEvent; begin Result := FPointerOnMouseExit; end; function TTransparentRectangleIconButton.GetFOnMouseMove: TMouseMoveEvent; begin Result := FBackgroundSelect.OnMouseMove; end; function TTransparentRectangleIconButton.GetFOnMouseUp: TMouseEvent; begin Result := FBackgroundSelect.OnMouseUp; end; function TTransparentRectangleIconButton.GetFOnMouseWheel: TMouseWheelEvent; begin Result := FBackgroundSelect.OnMouseWheel; end; function TTransparentRectangleIconButton.GetFTag: NativeInt; begin Result := TControl(Self).Tag; end; procedure TTransparentRectangleIconButton.Paint; begin inherited; if FIcon.Data.Data.Equals('') then FIcon.Visible := False else FIcon.Visible := True; FIcon.Fill.Color := GetFBackgroudColorAlphaMax; end; procedure TTransparentRectangleIconButton.SetFBackgroudColor(const Value: TAlphaColor); begin FBackgroundSelect.Fill.Color := Value; end; procedure TTransparentRectangleIconButton.SetFButtonClass(const Value: TColorClass); begin if Value = TColorClass.Primary then begin SetFBackgroudColor(TRANSPARENT_PRIMARY_COLOR); end else if Value = TColorClass.Secondary then begin SetFBackgroudColor(TRANSPARENT_SECONDARY_COLOR); end else if Value = TColorClass.Error then begin SetFBackgroudColor(TRANSPARENT_ERROR_COLOR); end else if Value = TColorClass.Warning then begin SetFBackgroudColor(TRANSPARENT_WARNING_COLOR); end else if Value = TColorClass.Normal then begin SetFBackgroudColor(TRANSPARENT_NORMAL_COLOR); end else if Value = TColorClass.Success then begin SetFBackgroudColor(TRANSPARENT_SUCCESS_COLOR); end else begin SetFBackgroudColor(TAlphaColor($1E303030)); end; end; procedure TTransparentRectangleIconButton.SetFCursor(const Value: TCursor); begin FBackgroundSelect.Cursor := Value; end; procedure TTransparentRectangleIconButton.SetFHitTest(const Value: Boolean); begin FBackgroundSelect.HitTest := Value; end; procedure TTransparentRectangleIconButton.SetFIconAlign(const Value: TAlignLayout); begin FIcon.Align := Value; end; procedure TTransparentRectangleIconButton.SetFIconData(const Value: TPathData); begin FIcon.Data := Value; end; procedure TTransparentRectangleIconButton.SetFIconSize(const Value: Single); begin FIcon.Width := Value; FIcon.Height := Value; end; procedure TTransparentRectangleIconButton.SetFOnClick(const Value: TNotifyEvent); begin FPointerOnClick := Value; end; procedure TTransparentRectangleIconButton.SetFOnDblClick(const Value: TNotifyEvent); begin FBackgroundSelect.OnDblClick := Value; end; procedure TTransparentRectangleIconButton.SetFOnMouseDown(const Value: TMouseEvent); begin FBackgroundSelect.OnMouseDown := Value; end; procedure TTransparentRectangleIconButton.SetFOnMouseEnter(const Value: TNotifyEvent); begin FPointerOnMouseEnter := Value; end; procedure TTransparentRectangleIconButton.SetFOnMouseLeave(const Value: TNotifyEvent); begin FPointerOnMouseExit := Value; end; procedure TTransparentRectangleIconButton.SetFOnMouseMove(const Value: TMouseMoveEvent); begin FBackgroundSelect.OnMouseMove := Value; end; procedure TTransparentRectangleIconButton.SetFOnMouseUp(const Value: TMouseEvent); begin FBackgroundSelect.OnMouseUp := Value; end; procedure TTransparentRectangleIconButton.SetFOnMouseWheel(const Value: TMouseWheelEvent); begin FBackgroundSelect.OnMouseWheel := Value; end; procedure TTransparentRectangleIconButton.SetFTag(const Value: NativeInt); begin FBackgroundSelect.Tag := Value; TControl(Self).Tag := Value; end; end.
unit UnComandaController; interface uses StdCtrls, ExtCtrls, Classes, { Fluente } Util, UnComandaModelo, SearchUtil, UnAplicacao, Pagamentos; type TComandaController = class(TAplicacao, IResposta) private FComandaModelo: TComandaModelo; FDivisao: string; FOnChangeModel: TNotifyEvent; protected public constructor Create(const ComandaModelo: TComandaModelo); reintroduce; property Divisao: string read FDivisao write FDivisao; property OnChangeModel: TNotifyEvent read FOnChangeModel write FOnChangeModel; function Dividir(Sender: TObject; const AfterChange: TNotifyEvent): TComandaController; function ExibirPagamentos(Sender: TObject): TComandaController; procedure LancarDinheiro(Sender: TObject; const AfterChange: TNotifyEvent); procedure LancarCredito(Sender: TObject; const AfterChange: TNotifyEvent); procedure LancarDebito(Sender: TObject; const AfterChange: TNotifyEvent); function Modelo(const Modelo: TModelo): end; implementation uses Controls, SysUtils, DB, { Fluente } UnDividirView, UnLancarCreditoView, UnLancarDebitoView, UnLancarDinheiroView, UnPagamentosView; { TComandaController } constructor TComandaController.Create(const ComandaModelo: TComandaModelo); begin Self.FComandaModelo := ComandaModelo; end; function TComandaController.Dividir(Sender: TObject; const AfterChange: TNotifyEvent): TComandaController; var _dividirView: TDividirView; begin if Self.FComandaModelo.DataSet.FieldByName('coma_saldo').AsFloat > 0 then begin _dividirView := TDividirView.Create(nil) .ComandaModelo(Self.FComandaModelo) .Preparar; try if (_dividirView.ShowModal = mrOk) and Assigned(AfterChange) then AfterChange(Self); finally _dividirView.Descarregar; FreeAndNil(_dividirView); end; end else TFlMessages.MensagemErro('Não há saldo para dividir!'); Result := Self; end; procedure TComandaController.LancarDinheiro(Sender: TObject; const AfterChange: TNotifyEvent); var _lancarDinheiroView: ITela; begin Self.FComandaModelo.Parametros.GravarParametro('total', Self.FComandaModelo.DataSet.FieldByName('COMA_SALDO').AsString); _lancarDinheiroView := TLancarDinheiroView.Create(nil) .Modelo(Self.FComandaModelo) .Preparar; try if (_lancarDinheiroView.ExibirTela = mrOk) and Assigned(AfterChange) then AfterChange(Self); finally _lancarDinheiroView.Descarregar; FreeAndNil(_lancarDinheiroView); end; end; procedure TComandaController.LancarCredito(Sender: TObject; const AfterChange: TNotifyEvent); var _lancarCreditoView: TLancarCreditoView; begin _lancarCreditoView := TLancarCreditoView.Create(nil) .Modelo(Self.FComandaModelo) .Preparar; try if (_lancarCreditoView.ShowModal = mrOk) and Assigned(AfterChange) then AfterChange(Self); finally _lancarCreditoView.Descarregar; FreeAndNil(_lancarCreditoView); end; end; procedure TComandaController.LancarDebito(Sender: TObject; const AfterChange: TNotifyEvent); var _lancarDebito: TLancarDebitoView; begin _lancarDebito := TLancarDebitoView.Create(nil) .Modelo(Self.FComandaModelo) .Preparar; try if (_lancarDebito.ShowModal = mrOk) and Assigned(AfterChange) then AfterChange(Self); finally _lancarDebito.Descarregar; FreeAndNil(_lancarDebito); end; end; function TComandaController.ExibirPagamentos( Sender: TObject): TComandaController; var _dataSet: TDataSet; _pagamentos: ITela; begin _dataSet := Self.FComandaModelo.DataSet('comap'); Self.FComandaModelo.Parametros .GravarParametro('total', FloatToStr(_dataSet.FieldByName('VALOR_TOTAL').AsFloat)) .GravarParametro('datasource', 'mcx'); _pagamentos := TPagamentosView.Create(nil) .Modelo(Self.FComandaModelo) .Preparar; try _pagamentos.ExibirTela finally _pagamentos.Descarregar; FreeAndNil(_pagamentos); end; Result := Self; end; end.
unit VerifyRepairCmd; interface procedure VerifyRepair(op : String; tablename : String; startAt : String; databaseName : String; userId, password : String; hostName : String; hostPort : Integer); implementation uses SysUtils, Classes, edbcomps, SessionManager, ConsoleHelper, QueryCmd; procedure VerifyRepair(op : String; tablename : String; startAt : String; databaseName : String; userId, password : String; hostName : String; hostPort : Integer); var sessionMgr : TSessionManager; db : TEDBDatabase; ds : TEDBQuery; tables : TStringList; iTable: Integer; begin if (lowercase(op) <> 'verify') and (lowercase(op) <> 'repair') then raise Exception.Create('bad op'); sessionMgr := TSessionManager.Create(userId, password, hostName, hostPort); tables := TStringList.Create; try if tableName = '*' then // verify all of the tables begin db := TEDBDatabase.Create(nil); ds := TEDBQuery.Create(nil); try db.SessionName := sessionMgr.session.Name; db.Database := databaseName; db.LoginPrompt := true; db.DatabaseName := databaseName + DateTimeToStr(now); ds.SessionName := sessionMgr.session.SessionName; ds.DatabaseName := db.Database; ds.SQL.Add('Select Name from information.tables Order By Name'); ds.ExecSQL; while not ds.EOF do begin if (startAt = '') or (UpperCase(ds.FieldByName('Name').AsString) >= UpperCase(startAt)) then tables.Add(ds.FieldByName('Name').AsString); ds.Next; end; finally FreeAndNil(db); FreeAndNil(ds); end; end else begin tables.Add(tableName); end; for iTable := 0 to tables.Count - 1 do begin WritelnStatus('Performing ' + op + ' on ' + tables[iTable]); Query(op + ' TABLE "' + tables[iTable] + '"', 0, databaseName, userId, password, hostName, hostPort, false, 'table', true, ''); end; finally FreeAndNil(tables); end; end; end.
//Algorithme : croix //But : Demander à l'utilisateur un caractère et une taille et effectuer une croix avec ces données. //VAR //car : caractère //taille, height, width : entier //DEBUT //ECRIRE "Veuillez entrer le caractère que vous voulez utiliser pour réaliser la croix" //LIRE car //ECRIRE "Veuillez entrer la taille de la croix" //LIRE taille //POUR height <-- 0 TO taille-1 FAIRE //DEBUT //POUR width <-- 0 TO taille-1 FAIRE //DEBUT //SI (height=width) OU (width=((taille-1)-height)) ALORS //DEBUT //ECRIRE "car" //FIN //SINON //DEBUT //ECRIRE " " //FIN //FIN //ECRIRE ""; //FIN //FIN. PROGRAM croix; uses crt; VAR car : char; taille, height, width : integer; BEGIN writeln('Veuillez entrer le caractère que vous voulez utiliser pour réaliser la croix'); readln(car); writeln('Veuillez entrer la taille de la croix'); readln(taille); FOR height:=0 TO taille-1 DO BEGIN FOR width:=0 TO taille-1 DO BEGIN IF (height=width) OR (width=((taille-1)-height)) THEN BEGIN write(car); END ELSE BEGIN write(' '); END; END; writeln(); END; readln; END.
{ ******************************************************************************************************************* CGIUtils: Contains TCGIRequest class for CGI protocol Author: Motaz Abdel Azeem email: motaz@code.sd Home page: http://code.sd License: LGPL Last modifie: 12.July.2012 ******************************************************************************************************************* } unit CGIUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, SpiderUtils; type { TCGIRequest } TCGIRequest = class(TSpiderRequest) private procedure ReadCookies; override; procedure DecodeMultiPart; override; function ReadContent: string; override; procedure ReadVariables; override; procedure DisplayErrorMessage(Msg: string); override; public end; implementation procedure TCGIRequest.ReadCookies; var TempStr: string; Line: string; i: Integer; begin Line:=''; TempStr:= GetEnvironmentVariable('HTTP_COOKIE'); for i:= 1 to Length(TempStr) do if Tempstr[i] = ';' then begin fCookieList.Add(Trim(Line)); Line:= ''; end else Line:= Line + TempStr[i]; if Line <> '' then fCookieList.Add(Trim(Line)); end; procedure TCGIRequest.DecodeMultiPart; var Line: string; FieldName: string; Lines: string; IsFile: Boolean; FileContentType: string; FileName: string; Ch: Char; ReadPos: Integer; ContentLen: Integer; begin IsFile:= False; ReadPos:= 0; FieldName:=''; Lines:=''; ContentLen:= StrToInt(GetEnvironmentVariable('CONTENT_LENGTH')); while ReadPos < ContentLen do begin Line:= ''; repeat Read(Ch); Inc(ReadPos); Line:= Line + Ch; until (ReadPos >= ContentLen) or (Ch = #10); if (Pos(fBoundary, Line) > 0) then begin if FieldName <> '' then begin if IsFile then begin fFiles[High(fFiles)].FileContent:= Copy(Lines, 1, Length(Lines) - 2); fFiles[High(fFiles)].FieldName:= Fieldname; fFiles[High(fFiles)].FileSize:= Length(fFiles[High(fFiles)].FileContent); IsFile:= False; end else fContentFields.Add(FieldName + '=' + Lines); Lines:= ''; end; Line:= ''; repeat Read(Ch); Inc(ReadPos); if CH <> #10 then Line:= Line + Ch; until (ReadPos >= ContentLen) or (Ch = #10); if Pos('filename=', Line) > 0 then begin IsFile:= True; Inc(fFilesCount); SetLength(fFiles, Length(fFiles) + 1); FileName:= Copy(Line, Pos('filename=', Line) + 10, Length(Line)); FileName:= Copy(FileName, 1, Pos('"', FileName) - 1); Line:= Copy(Line, 1, Pos('filename=', Line) - 1); FileContentType:= ''; repeat Read(Ch); Inc(ReadPos); if CH <> #10 then FileContentType:= FileContentType + Ch; until (ReadPos >= ContentLen) or (Ch = #10); fFiles[High(fFiles)].ContentType:= FileContentType; fFiles[High(fFiles)].FileName:= FileName; repeat Read(Ch); Inc(ReadPos); until (ReadPos >= ContentLen) or (Ch = #10); end else IsFile:= False; FieldName:= Copy(Line, Pos('name="', Line) + 6, Length(Line)); FieldName:= Copy(FieldName, 1, Pos('"', FieldName) - 1); Lines:= ''; end else Lines:= Lines + Line; end; if (Lines <> '') then begin if IsFile then begin fFiles[High(fFiles)].FileContent:= Copy(Lines, 1, Length(Lines) - 2); fFiles[High(fFiles)].FieldName:= Fieldname; fFiles[High(fFiles)].FileSize:= Length(fFiles[High(fFiles)].FileContent); end else if (FieldName <> '') then fContentFields.Add(FieldName + '=' + Lines); end; end; function TCGIRequest.ReadContent : string; var ContentLen : integer; ReadPos : integer; ch : char; begin ContentLen:= StrToInt(GetEnvironmentVariable('CONTENT_LENGTH')); ReadPos := 0; Result := ''; while ReadPos < ContentLen do begin Read(Ch); inc (ReadPos); if (Result <> #10) then Result := Result + Ch; end; end; procedure TCGIRequest.ReadVariables; begin fRequestMethod:= GetEnvironmentVariable('REQUEST_METHOD'); fUserAgent:= GetEnvironmentVariable('HTTP_USER_AGENT'); fRemoteAddress:= GetEnvironmentVariable('REMOTE_ADDR'); fContentType:= GetEnvironmentVariable('CONTENT_TYPE'); fQueryString:= GetEnvironmentVariable('QUERY_STRING'); fURI:= LowerCase(GetEnvironmentVariable('REQUEST_URI')); fHost:= LowerCase(GetEnvironmentVariable('HTTP_HOST')); fWebServerSoftware:= LowerCase(GetEnvironmentVariable('SERVER_SOFTWARE')); fPathInfo:= Trim(GetEnvironmentVariable('PATH_INFO')); if (fPathInfo <> '') and (fPathInfo[Length(fPathInfo)] = '/') then fPathInfo:= Copy(fPathInfo, 1, Length(fPathInfo) - 1); fReferer:= Trim(LowerCase(GetEnvironmentVariable('HTTP_REFERER'))); fIsApache:= False; fIsCGI:= True; end; procedure TCGIRequest.DisplayErrorMessage(Msg: string); begin Writeln('CONTENT-TYPE: TEXT/HTML'); Writeln; Writeln('<font color=red>' + Msg + '<font>'); end; end.
{ ************************************************************ } { } { Borland Web Application Debugger } { } { Copyright (c) 2001-2002 Borland Software Corporation } { } { ************************************************************ } unit WebAppDbgHelp; interface {$IFDEF MSWINDOWS} function GetHelpPath: String; {$ENDIF} implementation uses Windows, SysUtils; {$IFDEF MSWINDOWS} const Software = 'Software'; Borland = 'Borland'; WinHelpPath = 'WinHelpPath'; CurProductName = 'Delphi'; Help = 'Help'; VerNo = '7.0'; function RegOpenKey(Key: HKey; const SubKey: string): HKey; begin if Windows.RegOpenKey(Key, PChar(SubKey), Result) <> 0 then Result := 0; end; function GetRegistryPath: String; var SoftwareKey, BorlandKey, DelphiKey, VerNoKey, HelpKey: HKey; BufferSize: LongInt; Buffer: array[0..255] of Char; begin Result := ''; { this is intended to retrieve help path information from the Delphi install registry keys. } BufferSize := Sizeof(Buffer); SoftwareKey := RegOpenKey(HKEY_CURRENT_USER, Software); if SoftwareKey <> 0 then begin BorlandKey := RegOpenKey(SoftwareKey, Borland); if BorlandKey <> 0 then begin DelphiKey := RegOpenKey(BorlandKey, CurProductName); if DelphiKey <> 0 then begin VerNoKey := RegOpenKey(DelphiKey, VerNo); if VerNoKey <> 0 then begin HelpKey := RegOpenKey(VerNoKey, Help); if HelpKey <> 0 then begin if (RegQueryValueEx(HelpKey, PChar(WinHelpPath), nil, nil, @Buffer, @BufferSize) = 0) then begin Result := Buffer; end; RegCloseKey(HelpKey); end; RegCloseKey(VerNoKey); end; RegCloseKey(DelphiKey); end; RegCloseKey(BorlandKey); end; RegCloseKey(SoftwareKey); end; end; function GetHelpPath: String; begin Result := ''; Result := SysUtils.GetEnvironmentVariable('BORHELP'); if Result = '' then Result := GetRegistryPath; if Result = '' then Result := GetCurrentDir; Result := Result + '\'; end; {$ENDIF} end.
unit mobile_desktop_form; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, vr_utils, chrome_jsonrpc; type { TCustomMobileDesktopForm } TCustomMobileDesktopForm = class(TForm) btnBack: TButton; btnHome: TButton; btnRefresh: TButton; pnlBrowser: TPanel; pnlBottom: TPanel; procedure btnRefreshClick(Sender: TObject); private FWB: TJsonRpcChromeBrowser; protected property WB: TJsonRpcChromeBrowser read FWB; procedure Loaded; override; procedure DoClose(var CloseAction: TCloseAction); override; public end; var CustomMobileDesktopForm: TCustomMobileDesktopForm; implementation {$R *.lfm} { TCustomMobileDesktopForm } procedure TCustomMobileDesktopForm.btnRefreshClick(Sender: TObject); begin FWB.Refresh(True); end; procedure TCustomMobileDesktopForm.Loaded; begin inherited Loaded; FWB := TJsonRpcChromeBrowser.CreateWithParent(Self, pnlBrowser); FWB.Align := alClient; end; procedure TCustomMobileDesktopForm.DoClose(var CloseAction: TCloseAction); begin Include(AppStates, apsClosing); inherited DoClose(CloseAction); end; end.
Unit Skyrim; Uses 'Dcc\Util'; { TES5Edit Reference: http://www.creationkit.com/index.php?title=TES5Edit_Scripting_Functions } Interface Function FormCopy: IInterface; Function FormCopyFromTemplateID(): IInterface; Function FormFind: IInterface; Function FormGet: IInterface; Const Debug = FALSE; LineBreak = #13#10; ArmorTypeCloth = 0; ArmorTypeLight = 1; ArmorTypeHeavy = 2; ArmaModelMaleThird = 2; ArmaModelFemaleThird = 3; ArmaModelMaleFirst = 4; ArmaModelFemaleFirst = 5; Implementation //////// //////// Function FormFind(Plugin: IInterface; FormType: String; EditorID: String): IInterface; Begin // according to the ck wiki, MainRecordByEditorID does not work very // well unless you narrow it down by group. Result := MainRecordByEditorID( GroupBySignature(Plugin,UpperCase(FormType)), EditorID ); End; Function FormCopy(Form: IInterface): IInterface; Begin If(Debug) Then AddMessage('[:::] Copying ' + EditorID(Form)); Result := wbCopyElementToFile( Form, GetFile(Form), TRUE, TRUE ); End; Function FormCopyFromTemplateID(Plugin: IInterface; TemplateID: Integer): IInterface; Var FormID: Integer; Begin FormID := (GetLoadOrder(Plugin) shl 24) + TemplateID; Result := FormCopy(FormGet(FormID)); End; Function FormGet(FormID: Integer): IInterface; Begin Result := RecordByFormID( FileByLoadOrder(FormID shr 24), LoadOrderFormIDtoFileFormID( FileByLoadOrder(FormID shr 24), FormID ), True ); End; //////// //////// // these are functions which can be used on multiple different form types // because they share field names. granted not all forms will have all the // fields but if they were generic enough they went here. you will have // to be smart and not try to do something like set a Weight on a Texture // Set or whatever dumbness. Function FormHasKeywordString(Form: IInterface; KeywordID: String): Integer; Var Keyring: IInterface; Count: Integer; Output: Integer; Begin Output := -1; Keyring := ElementBySignature(Form,'KWDA'); Count := ElementCount(Keyring); While Count > 0 Do Begin If(CompareText(EditorID(LinksTo(ElementByIndex(Keyring,(Count-1)))),KeywordID) = 0) Then Begin Output := Count; Count := -1; End; Dec(Count); End; Result := Output; End; Function FormGetName(Form: IInterface): String; Begin Result := GetEditValue(ElementbySignature(Form,'FULL')); End; Procedure FormSetName(Form: IInterface; NewName: String); Begin SetEditValue( ElementBySignature(Form,'FULL'), NewName ); End; Procedure FormSetEditorID(Form: IInterface; EditorID: String); Begin SetElementEditValues(Form,'EDID - Editor ID',EditorID); End; Function FormGetValue(Form: IInterface): Integer; Begin Result := Floor(GetElementNativeValues( Form, 'DATA - Data\Value' )); End; Procedure FormSetValue(Form: IInterface; Value: Integer); Begin SetElementNativeValues( Form, 'DATA - Data\Value', Value ); End; Function FormGetWeight(Form: IInterface): Integer; Begin Result := Floor(GetElementNativeValues( Form, 'DATA - Data\Weight' )); End; Procedure FormSetWeight(Form: IInterface; Value: Integer); Begin SetElementNativeValues( Form, 'DATA - Data\Weight', Value ); End; //////// //////// // TextureSet specific functions. Procedure TxstSetTextureDiffuse(Form: IInterface; Filename: String); Begin SetElementEditValues(Form,'Textures (RGB/A)\TX00 - Difuse',Filename); End; Procedure TxstSetTextureNormal(Form: IInterface; FileName: String); Begin SetElementEditValues(Form,'Textures (RGB/A)\TX01 - Normal/Gloss',Filename); End; Procedure TxstSetTextureEnv(Form: IInterface; FileName: String); Begin SetElementEditValues(Form,'Textures (RGB/A)\TX05 - Environment',Filename); End; //////// //////// // Armor specific functions. Function GetArmorTypeWord(ArmorType: Integer): String; Begin Case ArmorType Of 1: Result := 'Light'; 2: Result := 'Heavy'; Else Result := 'Cloth'; End; End; Function ArmoGetArmorType(Form: IInterface): Integer; Var ArmorType: String; Output: Integer; Begin Output := 0; ArmorType := GetElementEditValues( Form, 'BOD2 - Biped Body Template\Armor Type' ); If(CompareText('Light Armor',ArmorType) = 0) Then Begin Output := ArmorTypeLight; End Else If(CompareText('Heavy Armor',ArmorType) = 0) Then Begin Output := ArmorTypeHeavy; End; Result := Output; End; Procedure ArmoSetArmorType(Form: IInterface; ArmorType: Integer); Var ArmorWord: String; Begin // ArmorType: 0 = Clothing, 1 = Light, 2 = Heavy Case ArmorType Of 1: ArmorWord := 'Light Armor'; 2: ArmorWord := 'Heavy Armor'; Else ArmorWord := 'Clothing'; End; SetElementEditValues( Form, 'BOD2 - Biped Body Template\Armor Type', ArmorWord ); End; Procedure ArmoSetArmorRating(Form: IInterface; ArmorValue: Integer); Begin // passing a value of 42 for a weight resulted in it being set as // 0.42 in the form. SetElementNativeValues( Form, 'DNAM - Armor Rating', (ArmorValue * 100) ); End; Procedure ArmoSetArmorRatingAuto(Form: IInterface; BaseValue: Integer); Var Rating: Int; Begin Rating := (BaseValue * 0.2); If(ArmoGetArmorType(Form) = 0) Then Begin Rating := 0; End Else If(FormHasKeywordString(Form,'ArmorCuirass') <> -1) Then Begin Rating := BaseValue; End Else If(FormHasKeywordString(Form,'ArmorGauntlets') <> -1) Then Begin Rating := (BaseValue * 0.3); End Else If(FormHasKeywordString(Form,'ArmorBoots') <> -1) Then Begin Rating := (BaseValue * 0.4); End Else If(FormHasKeywordString(Form,'ArmorHelmet') <> -1) Then Begin Rating := (BaseValue * 0.3); End; ArmoSetArmorRating(Form,Rating); End; Procedure ArmoReplaceArmorTypeName(Form: IInterface; ArmorType: Integer); Var Reg: TPerlRegex; Begin Reg := TPerlRegex.Create(); Reg.RegEx := '\b(light|heavy|cloth)\b'; Reg.Options := [ preCaseLess ]; Reg.Subject := FormGetName(Form); Case ArmorType Of 1: Reg.Replacement := 'Light'; 2: Reg.Replacement := 'Heavy'; Else Reg.Replacement := 'Cloth'; End; If(Reg.Match()) Then Begin Reg.ReplaceAll(); FormSetName(Form,Reg.Subject); End Else Begin FormSetName(Form,Reg.Subject + ' (' + Reg.Replacement + ')'); End; End; Procedure ArmoReplaceArmorTypeKeywords(Form: IInterface; TargetType: Integer); Var Iter: Integer; Kter: Integer; Kndex: Integer; KeywordCount: Integer; KeywordBox: IInterface; KeywordItem: IInterface; KeywordNew: IInterface; ArmorTypeSet: Array[0..5] of TStringList; Begin // given the target armor type, look for keywords from the old type // and replace them with their matching. E.g. swap out keywords like // Armor* for Clothing*, ArmorType*, VendorType* // this should probably be moved to a global location and be // initialised at startup. Iter := 0; While Iter < Length(ArmorTypeSet) Do Begin ArmorTypeSet[Iter] := TStringList.Create; Inc(Iter); End; ArmorTypeSet[0].Add('ClothingBody'); ArmorTypeSet[0].Add('ArmorCuirass'); ArmorTypeSet[0].Add('ArmorCuirass'); ArmorTypeSet[1].Add('ClothingFeet'); ArmorTypeSet[1].Add('ArmorBoots'); ArmorTypeSet[1].Add('ArmorBoots'); ArmorTypeSet[2].Add('ClothingHands'); ArmorTypeSet[2].Add('ArmorGauntlets'); ArmorTypeSet[2].Add('ArmorGauntlets'); ArmorTypeSet[3].Add('ClothingHead'); ArmorTypeSet[3].Add('ArmorHelmet'); ArmorTypeSet[3].Add('ArmorHelmet'); ArmorTypeSet[4].Add('VendorItemClothing'); ArmorTypeSet[4].Add('VendorItemArmor'); ArmorTypeSet[4].Add('VendorItemArmor'); ArmorTypeSet[5].Add('ArmorClothing'); ArmorTypeSet[5].Add('ArmorLight'); ArmorTypeSet[5].Add('ArmorHeavy'); //////// //////// KeywordBox := ElementBySignature(Form,'KWDA'); KeywordCount := ElementCount(KeywordBox); Iter := 0; While Iter < KeywordCount Do Begin KeywordItem := LinksTo(ElementByIndex(KeywordBox,Iter)); Kter := 0; While Kter < Length(ArmorTypeSet) Do Begin Kndex := ArmorTypeSet[Kter].IndexOf(EditorID(KeywordItem)); If(Kndex <> -1) Then Begin KeywordNew := FormFind( GetFile(KeywordItem), 'KYWD', ArmorTypeSet[Kter].Strings[TargetType] ); SetEditValue( ElementByIndex(KeywordBox,Iter), IntToHex(FormID(KeywordNew),8) ); Kter := Length(ArmorTypeSet) + 1; End; Inc(Kter); End; Inc(Iter); End; Iter := 0; While Iter < Length(ArmorTypeSet) Do Begin ArmorTypeSet[Iter].Free(); Inc(Iter); End; End; Function ArmoGetModelElement(Form: IInterface): IInterface; Begin Result := ElementByPath(Form,'Armature'); End; Function ArmoGetModelCount(Form: IInterface): Integer; Begin Result := ElementCount(ArmoGetModelElement(Form)); End; Procedure ArmoSetModelByIndex(Form: IInterface; ModelNum: Integer; Model: IInterface); Begin SetEditValue( ElementByIndex(ArmoGetModelElement(Form),ModelNum), IntToHex(FormID(Model),8) ); End; //////// //////// Function GetArmaPathRoot(ModelKey: Integer): String; Begin Case ModelKey Of 2: Result := 'Male world model'; 3: Result := 'Female world model'; 4: Result := 'Male 1st Person'; 5: Result := 'Female 1st Person'; Else Result := 'Male world model'; End; End; Function ArmaGetModelFilename(Form: IInterface; ModelKey: Integer): String; Var ModelPath: String; Begin ModelPath := GetArmaPathRoot(ModelKey) + '\MOD' + IntToStr(ModelKey) + ' - Model Filename'; Result := GetEditValue(ElementByPath(Form,ModelPath)); End; Function ArmaGetModelTextureElementByIndex(Form: IInterface; ModelKey: Integer): IInterface; Var ModelPath: String; TextureCount: Integer; Iter: Integer; Begin ModelPath := GetArmaPathRoot(ModelKey) + '\MO' + IntToStr(ModelKey) + 'S - Alternate Textures'; Result := ElementByPath(Form,ModelPath); End; Function ArmaGetModelTextureCount(Form: IInterface; ModelKey: Integer): Integer; Begin Result := ElementCount(ArmaGetModelTextureElementByIndex(Form,ModelKey)); End; Function ArmaGetModelTextureSetByIndex(Form: IInterface; ModelKey: Integer; TextureKey: Integer): IInterface; Var TextureElement: IInterface; Begin TextureElement := ElementByIndex(ArmaGetModelTextureElementByIndex(Form,ModelKey),TextureKey); Result := LinksTo(ElementByPath(TextureElement,'New Texture')); End; Procedure ArmaSetModelTextureSetByIndex(Form: IInterface; ModelKey: Integer; TextureKey: Integer; TextureSet: IInterface); Var TextureElement: IInterface; Begin TextureElement := ElementByIndex(ArmaGetModelTextureElementByIndex(Form,ModelKey),TextureKey); SetEditValue( ElementByPath(TextureElement,'New Texture'), IntToHex(FormID(TextureSet),8) //IntToHex(LoadOrderFormIDtoFileFormID( FileByLoadOrder(TextureSet shr 24), TextureSet )), ); End; //////////////////////////////// //////////////////////////////// FUNCTION ArmaGetModelTextureSetByShape( Form: IInterface; ModelKey: Integer; ShapeName: String ): IInterface; VAR TextureList: IInterface; TextureCount: Integer; TextureIter: Integer; TextureItem: IInterface; TextureName: String; BEGIN TextureList := ArmaGetModelTextureElementByIndex(Form,ModelKey); TextureCount := ElementCount(TextureList); FOR TextureIter := 0 TO (TextureCount - 1) DO BEGIN TextureItem := ElementByIndex(TextureList,TextureIter); TextureName := GetEditValue(ElementByPath(TextureItem,'3D Name')); IF(CompareText(TextureName,ShapeName) = 0) THEN BEGIN Result := LinksTo(ElementByPath(TextureItem,'New Texture')); EXIT; END; END; Result := NIL; END; //////////////////////////////// //////////////////////////////// PROCEDURE ArmaSetModelTextureSetByShape( Form: IInterface; ModelKey: Integer; ShapeName: String; TextureSet: IInterface ); VAR TextureList: IInterface; TextureCount: Integer; TextureIter: Integer; TextureItem: IInterface; TextureName: String; BEGIN TextureList := ArmaGetModelTextureElementByIndex(Form,ModelKey); TextureCount := ElementCount(TextureList); FOR TextureIter := 0 TO (TextureCount - 1) DO BEGIN TextureItem := ElementByIndex(TextureList,TextureIter); TextureName := GetEditValue(ElementByPath(TextureItem,'3D Name')); IF(CompareText(TextureName,ShapeName) = 0) THEN BEGIN SetEditValue( ElementByPath(TextureItem,'New Texture'), IntToHex(FormID(TextureSet),8) ); EXIT; END; END; END; //////////////////////////////// //////////////////////////////// Function CobjGetWorkebenchKeyword(Form: IInterface): IInterface; Begin Result := GetEditValue(ElementbySignature(Form,'BNAM')); End; Procedure CobjSetWorkebenchKeyword(Form: IInterface; FormID: Integer); Begin SetEditValue( ElementBySignature(Form,'BNAM'), FormID ); End; //////////////////////////////// //////////////////////////////// FUNCTION CobjGetCreatedObject(Form: IInterface): IInterface; BEGIN Result := GetEditValue(ElementBySignature(Form,'CNAM')); END; //////////////////////////////// //////////////////////////////// PROCEDURE CobjSetCreatedObject(Form: IInterface; CreateObject: IInterface); BEGIN SetEditValue( ElementBySignature(Form,'CNAM'), IntToHex(FormID(CreateObject),8) ); END; End.
unit ActnPopup; interface uses Classes, Controls, Menus, ActnMenus, XPActnCtrls, ActnMan, ActnList; type { TCustomActionPopupMenuEx } TPopupActionBar = class; TCustomActionPopupMenuEx = class(TXPStylePopupMenu) private FPopupActionBar: TPopupActionBar; protected procedure DoPopup(Item: TCustomActionControl); override; function GetPopupClass: TCustomPopupClass; override; procedure ExecAction(Action: TContainedAction); override; public procedure LoadMenu(Clients: TActionClients; AMenu: TMenuItem); end; { TPopupActionBar } TPopupActionBar = class(TPopupMenu) private FPopupMenu: TCustomActionPopupMenuEx; FActionManager: TCustomActionManager; function GetMenuActive: Boolean; public constructor Create(AOwner: TComponent); override; procedure Popup(X: Integer; Y: Integer); override; property MenuActive: Boolean read GetMenuActive; published property PopupMenu: TCustomActionPopupMenuEx read FPopupMenu write FPopupMenu; end; function NewPopupMenu(Owner: TComponent; const AName: string; Alignment: TPopupAlignment; AutoPopup: Boolean; const Items: array of TMenuItem): TPopupMenu; implementation uses SysUtils, Windows, Messages, Forms; type TMenuAction = class(TCustomAction) private FMenuItem: TMenuItem; public function Execute: Boolean; override; constructor Create(AOwner: TComponent; AMenuItem: TMenuItem); reintroduce; end; procedure InitMenuItems(AMenu: TMenu; const Items: array of TMenuItem); var I: Integer; procedure SetOwner(Item: TMenuItem); var I: Integer; begin if Item.Owner = nil then AMenu.Owner.InsertComponent(Item); for I := 0 to Item.Count - 1 do SetOwner(Item[I]); end; begin for I := Low(Items) to High(Items) do begin SetOwner(Items[I]); AMenu.Items.Add(Items[I]); end; end; function NewPopupMenu(Owner: TComponent; const AName: string; Alignment: TPopupAlignment; AutoPopup: Boolean; const Items: array of TMenuItem): TPopupMenu; begin Result := TPopupActionBar.Create(Owner); Result.Name := AName; Result.AutoPopup := AutoPopup; Result.Alignment := Alignment; InitMenuItems(Result, Items); end; { TPopupActionBar } type TCustomActionPopupMenuClass = class(TCustomActionPopupMenu); constructor TPopupActionBar.Create(AOwner: TComponent); begin inherited Create(AOwner); FActionManager := TActionManager.Create(Self); end; function TPopupActionBar.GetMenuActive: Boolean; begin Result := Assigned(FPopupMenu); end; resourcestring sActionManagerNotAssigned = '%s ActionManager property has not been assigned'; procedure TPopupActionBar.Popup(X, Y: Integer); begin if Assigned(FPopupMenu) then exit; DoPopup(Self); FPopupMenu := TCustomActionPopupMenuEx.Create(nil); try FActionManager.ActionBars.Clear; FPopupMenu.Designable := False; FPopupMenu.AnimationStyle := asNone; FPopupMenu.FPopupActionBar := Self; // FPopupMenu.Name := 'InternalPopup'; FActionManager.Images := Images; with FActionManager.ActionBars.Add do begin ActionBar := FPopupMenu; ActionBar.Orientation := boTopToBottom; AutoSize := False; end; FPopupMenu.AutoSize := True; if not Assigned(FPopupMenu.ActionClient) then raise Exception.CreateFmt(sActionManagerNotAssigned, [Name]); FPopupMenu.ActionClient.Items.Clear; FPopupMenu.LoadMenu(FPopupMenu.ActionClient.Items, Self.Items); FPopupMenu.RecreateControls; FPopupMenu.Popup(X, Y); finally FreeAndNil(FPopupMenu); end; end; { TCustomActionPopupMenuEx } procedure TCustomActionPopupMenuEx.DoPopup(Item: TCustomActionControl); begin inherited; // Check to see if we've already built this submenu this time around if Item.ActionClient.Items[0].Tag <> 0 then exit; // If we haven't then call the actual TMenuItem's OnClick event (if assigned) // which causing any dynamically created menus to populate if Assigned(TMenuItem(Item.ActionClient.Tag).OnClick) then TMenuItem(Item.ActionClient.Tag).OnClick(TMenuItem(Item.ActionClient.Tag)); // Since submenus are always recreated clear any old items... Item.ActionClient.Items.Clear; // ...and reload the actual TMenuItem LoadMenu(Item.ActionClient.Items, TMenuItem(Item.ActionClient.Tag)); end; type TActionListCracker = class(TCustomActionManager); TActionBarCracker = class(TCustomActionBar); procedure TCustomActionPopupMenuEx.ExecAction(Action: TContainedAction); begin PostMessage(PopupList.Window, WM_COMMAND, TMenuItem(FSelectedItem.Tag).Command, 0); end; function TCustomActionPopupMenuEx.GetPopupClass: TCustomPopupClass; begin Result := TXPStylePopupMenu; end; procedure TCustomActionPopupMenuEx.LoadMenu(Clients: TActionClients; AMenu: TMenuItem); var I: Integer; AC: TActionClientItem; begin Clients.AutoHotKeys := False; for I := 0 to AMenu.Count - 1 do begin AC := Clients.Add; AC.Caption := AMenu.Items[I].Caption; AC.Tag := Integer(AMenu.Items[I]); AC.Action := TContainedAction(AMenu.Items[I].Action); if (AMenu.Items[I].Count > 0) and (AMenu.Items[I].Visible) then AC.Items.Add else if ((AMenu.Items[I].Caption <> '') and (AMenu.Items[I].Action = nil) and (AMenu.Items[I].Caption <> '-')) then begin AC.Action := TMenuAction.Create(Self, AMenu.Items[I]); AC.Action.ActionList := FPopupActionBar.FActionManager; AC.Action.Tag := AMenu.Items[I].Tag; TCustomAction(AC.Action).ImageIndex := AMenu.Items[I].ImageIndex; TCustomAction(AC.Action).Visible := AMenu.Items[I].Visible; TCustomAction(AC.Action).Checked := AMenu.Items[I].Checked; TCustomAction(AC.Action).Caption := AMenu.Items[I].Caption; TCustomAction(AC.Action).ShortCut := AMenu.Items[I].ShortCut; TCustomAction(AC.Action).Enabled := AMenu.Items[I].Enabled; AC.ImageIndex := AMenu.Items[I].ImageIndex; AC.ShortCut := AMenu.Items[I].ShortCut; end; AC.Caption := AMenu.Items[I].Caption; AC.ShortCut := AMenu.Items[I].ShortCut; AC.HelpContext := AMenu.Items[I].HelpContext; AC.ImageIndex := AMenu.Items[I].ImageIndex; AC.Visible := AMenu.Items[I].Visible; end; end; { TMenuAction } constructor TMenuAction.Create(AOwner: TComponent; AMenuItem: TMenuItem); begin inherited Create(AOwner); FMenuItem := AMenuItem; end; function TMenuAction.Execute: Boolean; begin Result := True; if (FMenuItem <> nil) and Assigned(FMenuItem.OnClick) then FMenuItem.OnClick(FMenuItem); end; end.
unit Person; interface type TAction = class; TPerson = class public procedure Accept(Visitor: TAction); virtual; abstract; end; TMan = class(TPerson) private FName: string; public constructor Create; procedure Accept(Visitor: TAction); override; property Name: string read FName; end; TWoman = class(TPerson) private FName: string; public constructor Create; procedure Accept(Visitor: TAction); override; property Name: string read FName; end; TAction = class public procedure GetManConclusion(ConcreteElementA: TMan); virtual; abstract; procedure GetWomanConclusion(ConcreteElementB: TWoman); virtual; abstract; end; TSuccess = class(TAction) private FName: string; public constructor Create; procedure GetManConclusion(ConcreteElementA: TMan); override; procedure GetWomanConclusion(ConcreteElementB: TWoman); override; property Name: string read FName; end; TFailing = class(TAction) private FName: string; public constructor Create; procedure GetManConclusion(ConcreteElementA: TMan); override; procedure GetWomanConclusion(ConcreteElementB: TWoman); override; property Name: string read FName; end; implementation uses Dialogs, SysUtils; { TWoman } procedure TWoman.Accept(Visitor: TAction); begin Visitor.GetWomanConclusion(Self); end; constructor TWoman.Create; begin FName := '女人'; end; { TMan } procedure TMan.Accept(Visitor: TAction); begin Visitor.GetManConclusion(Self); end; constructor TMan.Create; begin FName := '男人'; end; { TSuccess } constructor TSuccess.Create; begin FName := '成功'; end; procedure TSuccess.GetManConclusion(ConcreteElementA: TMan); var S: string; begin S := Format('%s%s时,背后多半有一个伟大的女人。', [ConcreteElementA.Name, Self.Name]); ShowMessage(S); end; procedure TSuccess.GetWomanConclusion(ConcreteElementB: TWoman); var S: string; begin S := Format('%s%s时,背后大多有一个不成功的男人。', [ConcreteElementB.Name, Self.Name]); ShowMessage(S); end; { TFailing } constructor TFailing.Create; begin FName := '失败'; end; procedure TFailing.GetManConclusion(ConcreteElementA: TMan); var S: string; begin S := Format('%s%s时,闷头喝酒,谁也不用劝。', [ConcreteElementA.Name, Self.Name]); ShowMessage(S); end; procedure TFailing.GetWomanConclusion(ConcreteElementB: TWoman); var S: string; begin S := Format('%s%s时,眼泪汪汪,谁也劝不了。', [ConcreteElementB.Name, Self.Name]); ShowMessage(S); end; end.
{**********************************************} { TBigCandleSeries (TCandleSeries) } { Copyright (c) 1996-2004 by David Berneda } {**********************************************} unit BigCandl; {$I TeeDefs.inc} interface uses {$IFDEF CLR} Classes, {$ELSE} {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, {$ELSE} Graphics, Controls, Forms, Dialogs, {$ENDIF} {$ENDIF} TeEngine, Series, OHLChart, CandleCh; type TBigCandleSeries = class(TCandleSeries) private { Private declarations } FHorizGap : Integer; FVertGap : Integer; protected { Protected declarations } Procedure DrawMark( ValueIndex:Integer; Const St:String; APosition:TSeriesMarkPosition); override; Procedure SetHorizGap(Value:Integer); Procedure SetVertGap(Value:Integer); public { Public declarations } Constructor Create(AOwner: TComponent); override; published { Published declarations } property HorizGap:Integer read FHorizGap write SetHorizGap; property VertGap:Integer read FVertGap write SetVertGap; end; implementation Uses {$IFDEF CLR} SysUtils, {$ENDIF} Chart, TeCanvas, TeeProCo; { TBigCandleSeries } Constructor TBigCandleSeries.Create(AOwner: TComponent); begin inherited; FHorizGap:=20; FVertGap:=6; Marks.Visible:=True; Marks.Callout.Length:=0; end; Procedure TBigCandleSeries.SetHorizGap(Value:Integer); begin SetIntegerProperty(FHorizGap,Value); end; Procedure TBigCandleSeries.SetVertGap(Value:Integer); begin SetIntegerProperty(FVertGap,Value); end; Procedure TBigCandleSeries.DrawMark( ValueIndex:Integer; Const St:String; APosition:TSeriesMarkPosition); Procedure InternalDrawMark(Const AValue:Double); begin inherited DrawMark(ValueIndex,FormatFloat(ValueFormat,AValue),APosition); end; Var tmpX : Integer; tmpHorizOffset : Integer; tmpVertOffset : Integer; begin With APosition do begin tmpHorizOffset:=(Width div 2)+ FHorizGap ; { <-- custom horiz "gap" } tmpVertOffset :=Height + FVertGap; { <-- custom vert "gap" } tmpX:=LeftTop.X; { Open Price Mark } With LeftTop do begin Y:=CalcYPosValue(OpenValues.Value[ValueIndex])-(Height div 2); X:=tmpX-tmpHorizOffset; end; InternalDrawMark(OpenValues.Value[ValueIndex]); { Close Price Mark } With LeftTop do begin Y:=CalcYPosValue(CloseValues.Value[ValueIndex])-(Height div 2); X:=tmpX+tmpHorizOffset; end; InternalDrawMark(CloseValues.Value[ValueIndex]); { High Price Mark } LeftTop.Y:=CalcYPosValue(HighValues.Value[ValueIndex])-tmpVertOffset; InternalDrawMark(HighValues.Value[ValueIndex]); { Low Price Mark } LeftTop.Y:=CalcYPosValue(LowValues.Value[ValueIndex])+tmpVertOffset-Height; InternalDrawMark(LowValues.Value[ValueIndex]); end; end; initialization RegisterTeeSeries( TBigCandleSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryBigCandle, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GallerySamples, 1 ); finalization UnRegisterTeeSeries([TBigCandleSeries]); end.
Program Catch222; {From Turbo Pascal Reference (Feb84) pg. 138} Var X: Integer; function Up(Var I: Integer): Integer; forward; function Down(Var I: Integer): Integer; begin I := I div 2; Writeln(I); if I <> 1 then I := Up(I); end; function Up(Var I: Integer): Integer; begin while I mod 2 <> 0 do begin I := I*3+1; Writeln(I); end; I := Down(I); end; begin Write('Enter any integer: '); Readln(X); X := Up(X); Writeln('Ok. Program stopped again.'); end.
unit TransparentAlert; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types, FMX.Objects, FMX.StdCtrls, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math, System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects, ColorClass; type TIconPosition = (Left, Right); TTransparentAlert = class(TControl) private { Private declarations } protected FPointerOnClick: TNotifyEvent; { Protected declarations } FText: TLabel; FIcon: TPath; { Block focus on background } FButtonLockFocus: TButton; procedure Paint; override; procedure OnTransparentAlertClick(Sender: TObject); function GetFIconPosition: TIconPosition; procedure SetFIconPosition(const Value: TIconPosition); function GetFCursor: TCursor; procedure SetFCursor(const Value: TCursor); function GetFTag: NativeInt; procedure SetFTag(const Value: NativeInt); function GetFIconMargins: TBounds; procedure SetFIconMargins(const Value: TBounds); function GetFButtonClass: TColorClass; function GetFIconColor: TAlphaColor; function GetFIconData: TPathData; function GetFIconSize: Single; function GetFText: String; function GetFTextSettings: TTextSettings; procedure SetFButtonClass(const Value: TColorClass); procedure SetFIconColor(const Value: TAlphaColor); procedure SetFIconData(const Value: TPathData); procedure SetFIconSize(const Value: Single); procedure SetFText(const Value: String); procedure SetFTextSettings(const Value: TTextSettings); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Open(TextAlert: String = ''; Duration: Single = 0.2); virtual; procedure Close(Duration: Single = 0.2); virtual; published { Published declarations } property Align; property Anchors; property Enabled; property Height; property Opacity; property Visible; property Width; property Size; property Scale; property Margins; property Position; property RotationAngle; property RotationCenter; { Additional properties } property HitTest; property Cursor; property ButtonClass: TColorClass read GetFButtonClass write SetFButtonClass; property Text: String read GetFText write SetFText; property TextSettings: TTextSettings read GetFTextSettings write SetFTextSettings; property IconData: TPathData read GetFIconData write SetFIconData; property IconColor: TAlphaColor read GetFIconColor write SetFIconColor; property IconSize: Single read GetFIconSize write SetFIconSize; property IconMargins: TBounds read GetFIconMargins write SetFIconMargins; property IconPosition: TIconPosition read GetFIconPosition write SetFIconPosition; property Tag; { Events } property OnPainting; property OnPaint; property OnResize; { Mouse events } property OnClick: TNotifyEvent read FPointerOnClick write FPointerOnClick; property OnDblClick; property OnMouseDown; property OnMouseUp; property OnMouseWheel; property OnMouseMove; property OnMouseEnter; property OnMouseLeave; end; procedure Register; implementation procedure Register; begin RegisterComponents('Componentes Customizados', [TTransparentAlert]); end; { TTransparentAlert } constructor TTransparentAlert.Create(AOwner: TComponent); begin inherited; Self.Width := 230; Self.Height := 20; Self.Cursor := crDefault; TControl(Self).OnClick := OnTransparentAlertClick; FButtonLockFocus := TButton.Create(Self); Self.AddObject(FButtonLockFocus); FButtonLockFocus.SetSubComponent(True); FButtonLockFocus.Stored := False; FButtonLockFocus.Opacity := 0; FButtonLockFocus.TabStop := False; FButtonLockFocus.Width := 1; FButtonLockFocus.Height := 1; FButtonLockFocus.HitTest := False; FButtonLockFocus.SendToBack; FText := TLabel.Create(Self); Self.AddObject(FText); FText.Align := TAlignLayout.Client; FText.HitTest := False; FText.StyledSettings := []; FText.TextSettings.Font.Size := 14; FText.TextSettings.Font.Family := 'SF Pro Display'; FText.TextSettings.FontColor := SOLID_PRIMARY_COLOR; FText.SetSubComponent(True); FText.Stored := False; FIcon := TPath.Create(Self); Self.AddObject(FIcon); FIcon.SetSubComponent(True); FIcon.Stored := False; FIcon.Align := TAlignLayout.Left; FIcon.WrapMode := TPathWrapMode.Fit; FIcon.Fill.Color := SOLID_PRIMARY_COLOR; FIcon.Stroke.Kind := TBrushKind.None; FIcon.Width := 33; FIcon.HitTest := False; FIcon.Visible := False; end; destructor TTransparentAlert.Destroy; begin if Assigned(FIcon) then FIcon.Free; if Assigned(FText) then FText.Free; if Assigned(FButtonLockFocus) then FButtonLockFocus.Free; inherited; end; function TTransparentAlert.GetFButtonClass: TColorClass; begin if (FText.TextSettings.FontColor = SOLID_PRIMARY_COLOR) and (GetFIconColor() = SOLID_PRIMARY_COLOR) then Result := TColorClass.Primary else if (FText.TextSettings.FontColor = SOLID_SECONDARY_COLOR) and (GetFIconColor() = SOLID_SECONDARY_COLOR) then Result := TColorClass.Secondary else if (FText.TextSettings.FontColor = SOLID_ERROR_COLOR) and (GetFIconColor() = SOLID_ERROR_COLOR) then Result := TColorClass.Error else if (FText.TextSettings.FontColor = SOLID_WARNING_COLOR) and (GetFIconColor() = SOLID_WARNING_COLOR) then Result := TColorClass.Warning else if (FText.TextSettings.FontColor = SOLID_SUCCESS_COLOR) and (GetFIconColor() = SOLID_SUCCESS_COLOR) then Result := TColorClass.Success else if (FText.TextSettings.FontColor = SOLID_NORMAL_COLOR) and (GetFIconColor() = SOLID_NORMAL_COLOR) then Result := TColorClass.Normal else Result := TColorClass.Custom; end; function TTransparentAlert.GetFCursor: TCursor; begin Result := TControl(Self).Cursor; end; function TTransparentAlert.GetFIconColor: TAlphaColor; begin Result := FIcon.Fill.Color; end; function TTransparentAlert.GetFIconData: TPathData; begin Result := FIcon.Data; end; function TTransparentAlert.GetFIconMargins: TBounds; begin Result := FIcon.Margins; end; function TTransparentAlert.GetFIconPosition: TIconPosition; begin Result := TIconPosition.Right; if FIcon.Align = TAlignLayout.Right then Result := TIconPosition.Right else if FIcon.Align = TAlignLayout.Left then Result := TIconPosition.Left; end; function TTransparentAlert.GetFIconSize: Single; begin Result := FIcon.Width; end; function TTransparentAlert.GetFTag: NativeInt; begin Result := TControl(Self).Tag; end; function TTransparentAlert.GetFText: String; begin Result := FText.Text; end; function TTransparentAlert.GetFTextSettings: TTextSettings; begin Result := FText.TextSettings; end; procedure TTransparentAlert.OnTransparentAlertClick(Sender: TObject); begin FButtonLockFocus.SetFocus; if Assigned(FPointerOnClick) then FPointerOnClick(Sender); end; procedure TTransparentAlert.Open(TextAlert: String = ''; Duration: Single = 0.2); begin if not TextAlert.Equals('') then FText.Text := TextAlert; Self.BringToFront; Self.Visible := True; Self.Opacity := 0; Self.AnimateFloat('Opacity', 1, Duration, TAnimationType.InOut, TInterpolationType.Circular); end; procedure TTransparentAlert.Close(Duration: Single = 0.2); begin Self.AnimateFloatWait('Opacity', 0, Duration, TAnimationType.InOut, TInterpolationType.Circular); Self.Visible := False; Self.Opacity := 1; end; procedure TTransparentAlert.Paint; begin inherited; if FIcon.Data.Data.Equals('') then FIcon.Visible := False else FIcon.Visible := True; end; procedure TTransparentAlert.SetFButtonClass(const Value: TColorClass); begin if Value = TColorClass.Primary then begin FText.TextSettings.FontColor := SOLID_PRIMARY_COLOR; SetFIconColor(SOLID_PRIMARY_COLOR); end else if Value = TColorClass.Secondary then begin FText.TextSettings.FontColor := SOLID_SECONDARY_COLOR; SetFIconColor(SOLID_SECONDARY_COLOR); end else if Value = TColorClass.Error then begin FText.TextSettings.FontColor := SOLID_ERROR_COLOR; SetFIconColor(SOLID_ERROR_COLOR); end else if Value = TColorClass.Warning then begin FText.TextSettings.FontColor := SOLID_WARNING_COLOR; SetFIconColor(SOLID_WARNING_COLOR); end else if Value = TColorClass.Normal then begin FText.TextSettings.FontColor := SOLID_NORMAL_COLOR; SetFIconColor(SOLID_NORMAL_COLOR); end else if Value = TColorClass.Success then begin FText.TextSettings.FontColor := SOLID_SUCCESS_COLOR; SetFIconColor(SOLID_SUCCESS_COLOR); end else begin FText.TextSettings.FontColor := SOLID_BLACK; SetFIconColor(SOLID_BLACK); end; end; procedure TTransparentAlert.SetFCursor(const Value: TCursor); begin Cursor := Value; end; procedure TTransparentAlert.SetFIconColor(const Value: TAlphaColor); begin FIcon.Fill.Color := Value; end; procedure TTransparentAlert.SetFIconData(const Value: TPathData); begin FIcon.Data := Value; end; procedure TTransparentAlert.SetFIconMargins(const Value: TBounds); begin FIcon.Margins := Value; end; procedure TTransparentAlert.SetFIconPosition(const Value: TIconPosition); begin if Value = TIconPosition.Right then FIcon.Align := TAlignLayout.Right else FIcon.Align := TAlignLayout.Left end; procedure TTransparentAlert.SetFIconSize(const Value: Single); begin FIcon.Width := Value; FIcon.Height := Value; end; procedure TTransparentAlert.SetFTag(const Value: NativeInt); begin TControl(Self).Tag := Value; end; procedure TTransparentAlert.SetFText(const Value: String); begin FText.Text := Value; end; procedure TTransparentAlert.SetFTextSettings(const Value: TTextSettings); begin FText.TextSettings := Value; end; end.
unit HKPaginationModel; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpjson, LResources, Forms, Controls, Graphics, Dialogs, HKModel; type { THKPaginationModel } THKPaginationModel = class(THKModel) private FCurrentPage: Integer; FOnPageChanged: TNotifyEvent; FOnPerPageChanged: TNotifyEvent; FOnTotalRecordsChanged: TNotifyEvent; FPaginationQuery: String; FRowPerPage: Integer; FSearchQry: String; FTotalPage: Integer; FTotalRecords: Integer; FDoc:String; procedure SetCurrentPage(AValue: Integer); procedure SetOnPageChanged(AValue: TNotifyEvent); procedure SetOnPerPageChanged(AValue: TNotifyEvent); procedure SetOnTotalRecordsChanged(AValue: TNotifyEvent); procedure SetPaginationQuery(AValue: String); procedure SetRowPerPage(AValue: Integer); procedure SetSearchQry(AValue: String); procedure SetTotalPage(AValue: Integer); procedure SetTotalRecords(AValue: Integer); protected function GetDocument: String; override; procedure SetDocument(AValue: String); override; function DoResponseData(aResp: TJSONData): TJSONData; override; procedure DoPageChanged; procedure DoPerPageChanged; procedure DoTotalRowsChanged; public constructor Create(AOwner: TComponent); override; procedure NextPage; procedure GoToPage(aPage:Integer); procedure PrevPage; procedure FirstPage; procedure LastPage; procedure Search(aFilter:String); published property SearchQry:String read FSearchQry write SetSearchQry; property PaginationQuery:String read FPaginationQuery write SetPaginationQuery; property RowPerPage:Integer read FRowPerPage write SetRowPerPage; property CurrentPage:Integer read FCurrentPage write SetCurrentPage; property TotalPage:Integer read FTotalPage write SetTotalPage; property TotalRecords:Integer read FTotalRecords write SetTotalRecords; property OnPageChanged:TNotifyEvent read FOnPageChanged write SetOnPageChanged; property OnPerPageChanged:TNotifyEvent read FOnPerPageChanged write SetOnPerPageChanged; property OnTotalRecordsChanged:TNotifyEvent read FOnTotalRecordsChanged write SetOnTotalRecordsChanged; end; procedure Register; implementation uses HKCompPacksTypes, Math; procedure Register; begin {$I hkpaginationmodel_icon.lrs} RegisterComponents('HKCompPacks',[THKPaginationModel]); end; { THKPaginationModel } procedure THKPaginationModel.SetCurrentPage(AValue: Integer); begin if FCurrentPage=AValue then Exit; FCurrentPage:=AValue; DoPageChanged; end; procedure THKPaginationModel.SetOnPageChanged(AValue: TNotifyEvent); begin if FOnPageChanged=AValue then Exit; FOnPageChanged:=AValue; end; procedure THKPaginationModel.SetOnPerPageChanged(AValue: TNotifyEvent); begin if FOnPerPageChanged=AValue then Exit; FOnPerPageChanged:=AValue; end; procedure THKPaginationModel.SetOnTotalRecordsChanged(AValue: TNotifyEvent); begin if FOnTotalRecordsChanged=AValue then Exit; FOnTotalRecordsChanged:=AValue; end; procedure THKPaginationModel.SetPaginationQuery(AValue: String); begin if FPaginationQuery=AValue then Exit; FPaginationQuery:=AValue; end; procedure THKPaginationModel.SetRowPerPage(AValue: Integer); begin if FRowPerPage=AValue then Exit; FRowPerPage:=AValue; DoPerPageChanged; end; procedure THKPaginationModel.SetSearchQry(AValue: String); begin if FSearchQry=AValue then Exit; FSearchQry:=AValue; end; procedure THKPaginationModel.SetTotalPage(AValue: Integer); begin if FTotalPage=AValue then Exit; FTotalPage:=AValue; end; procedure THKPaginationModel.SetTotalRecords(AValue: Integer); begin FTotalRecords:=AValue; if (FTotalRecords=0) or (RowPerPage=0) then Exit; TotalPage:=Ceil(FTotalRecords/RowPerPage);// FTotalRecords div FRowPerPage; DoTotalRowsChanged; end; function THKPaginationModel.GetDocument: String; begin Result:=FDoc+Format(PaginationQuery, [RowPerPage, CurrentPage, SearchQry]); end; procedure THKPaginationModel.SetDocument(AValue: String); var a: Integer; begin //inherited SetDocument(AValue);String; a:=Pos('?',AValue); if a>0 then FDoc:=LeftStr(AValue, a-1) else FDoc:=AValue; end; function THKPaginationModel.DoResponseData(aResp: TJSONData): TJSONData; var aJson: TJSONObject; arr: TJSONArray; begin aJson:=aResp as TJSONObject; try arr:=GetJsonArrayValue(aJson, 'data'); Result:=arr.Clone; TotalRecords:=GetJsonNumberValue(aJson, 'total'); finally aJson.Free; end; end; procedure THKPaginationModel.DoPageChanged; begin if Assigned(OnPageChanged)then OnPageChanged(Self); end; procedure THKPaginationModel.DoPerPageChanged; begin if Assigned(OnPerPageChanged)then OnPerPageChanged(Self); end; procedure THKPaginationModel.DoTotalRowsChanged; begin if Assigned(OnTotalRecordsChanged)then OnTotalRecordsChanged(Self); end; constructor THKPaginationModel.Create(AOwner: TComponent); begin TotalPage:=0; CurrentPage:=0; TotalRecords:=0; RowPerPage:=25; PaginationQuery:='?perPage=%d&page=%d&search=%s'; inherited Create(AOwner); end; procedure THKPaginationModel.NextPage; begin if CurrentPage>TotalPage then exit; GoToPage(CurrentPage+1); end; procedure THKPaginationModel.GoToPage(aPage: Integer); begin CurrentPage:=aPage; Refresh; end; procedure THKPaginationModel.PrevPage; begin if CurrentPage<=1 then exit; GoToPage(CurrentPage-1); end; procedure THKPaginationModel.FirstPage; begin GoToPage(1); end; procedure THKPaginationModel.LastPage; begin GoToPage(TotalPage); end; procedure THKPaginationModel.Search(aFilter: String); begin SearchQry:=aFilter; FirstPage; end; end.
{ *************************************************************************** } { } { Delphi and Kylix Cross-Platform Visual Component Library } { Internet Application Runtime } { } { Copyright (C) 1997, 2001 Borland Software Corporation } { } { Licensees holding a valid Borland No-Nonsense License for this Software may } { use this file in accordance with such license, which appears in the file } { license.txt that came with this Software. } { } { *************************************************************************** } {$DENYPACKAGEUNIT} unit WebBroker; interface uses SysUtils, Classes, HTTPApp, Contnrs, WebReq; type TServerExceptionEvent = procedure (E: Exception; wr: TWebResponse) of object; TWebApplication = class(TWebRequestHandler) private FTitle: string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; // The following is uses the current behaviour of the IDE module manager procedure CreateForm(InstanceClass: TComponentClass; var Reference); virtual; procedure Initialize; virtual; procedure Run; virtual; property Title: string read FTitle write FTitle; end; var Application: TWebApplication = nil; implementation {$IFDEF MSWINDOWS} uses Windows, BrkrConst; {$ENDIF} {$IFDEF Linux} uses Libc, BrkrConst; {$ENDIF} { TWebApplication } procedure DoneVCLApplication; export; begin with Application do begin Destroying; DestroyComponents; end; end; procedure DLLExitProc(Reason: Integer); register; export; begin {$IFDEF MSWINDOWS} if Reason = DLL_PROCESS_DETACH then DoneVCLApplication; {$ENDIF} end; function WebRequestHandler: TWebRequestHandler; export; begin Result := Application; end; constructor TWebApplication.Create(AOwner: TComponent); begin WebReq.WebRequestHandlerProc := WebRequestHandler; inherited Create(AOwner); Classes.ApplicationHandleException := HandleException; if IsLibrary then begin IsMultiThread := True; DLLProc := @DLLExitProc; end; end; destructor TWebApplication.Destroy; begin Classes.ApplicationHandleException := nil; inherited Destroy; end; procedure TWebApplication.CreateForm(InstanceClass: TComponentClass; var Reference); begin // Support CreateForm for backward compatability with D3, D4, and // D5 web modules. D6 generated web modules register a factory. if WebModuleClass = nil then WebModuleClass := InstanceClass else if WebModuleClass <> InstanceClass then raise Exception.CreateRes(@sOnlyOneDataModuleAllowed); end; procedure TWebApplication.Initialize; begin // This is a place holder if InitProc <> nil then TProcedure(InitProc); end; procedure TWebApplication.Run; begin if not IsLibrary then AddExitProc(DoneVCLApplication); end; end.
unit commands; interface uses SysUtils, Windows, ShellApi, MMSystem, Classes, global; // This unit contains general commands that are useful for scripting in any language. type TDelayFunc = function(Duration : Cardinal) : Boolean of object; TCmd = class(TObject) private Delay : TDelayFunc; function StdDelay(Duration : Cardinal) : Boolean; public constructor Create(DFunc : TDelayFunc); procedure Wait(Duration, Rnd : Cardinal); function OnHotkey(KeyStr : AnsiString; Ctrl,Alt,Shift : Boolean) : Boolean; procedure Shutdown(Force : Boolean = False); function Execute(App,Par : AnsiString; Show : Boolean; TimeOut : Cardinal = 0) : Boolean; procedure Sound(SndFile : AnsiString = ''); function GetPix(Wnd : Cardinal; X,Y : Cardinal) : Cardinal; function GetCliTitle(Wnd : Cardinal) : AnsiString; procedure SetCliTitle(Wnd : Cardinal; Title : AnsiString); end; implementation //////////////////////////////////////////////////////////////////////////////// function TCmd.StdDelay(Duration : Cardinal) : Boolean; begin Sleep(Duration); Result:=True; end; //////////////////////////////////////////////////////////////////////////////// constructor TCmd.Create(DFunc : TDelayFunc); begin inherited Create; // assign standard delay function if none is provided if DFunc=nil then Delay:=@StdDelay else Delay:=DFunc; end; //////////////////////////////////////////////////////////////////////////////// procedure TCmd.Wait(Duration, Rnd : Cardinal); // waits a specified amount of time begin Delay(Duration+Random(Rnd)); end; //////////////////////////////////////////////////////////////////////////////// function TCmd.OnHotkey(KeyStr : AnsiString; Ctrl,Alt,Shift : Boolean) : Boolean; // returns true if the specified key combination is pressed var VK : Cardinal; begin Result:=False; VK:=GetVK(KeyStr); if VK=0 then Exit; // check individual keys if (Hi(GetAsyncKeyState(VK))<128) then Exit; if Ctrl xor (Hi(GetAsyncKeyState(VK_CONTROL))>127) then Exit; if Alt xor (Hi(GetAsyncKeyState(VK_MENU))>127) then Exit; if Shift xor (Hi(GetAsyncKeyState(VK_SHIFT))>127) then Exit; Result:=True; end; //////////////////////////////////////////////////////////////////////////////// function TCmd.Execute(App,Par : AnsiString; Show : Boolean; TimeOut : Cardinal = 0) : Boolean; // executes a file and waits for completion or until a timeout is reached var Info : ShellExecuteInfoA; begin Info.cbSize:=SizeOf(ShellExecuteInfoA); Info.fMask:=SEE_MASK_DOENVSUBST or SEE_MASK_NOCLOSEPROCESS; Info.Wnd:=0; Info.lpVerb:='open'; Info.lpFile:=PAnsiChar(App); Info.lpParameters:=PAnsiChar(Par); Info.lpDirectory:=''; Info.nShow:=SW_SHOW*Byte(Show)+SW_HIDE*Byte(not Show); ShellExecuteExA(@Info); // exit on failure Result:=Info.hInstApp>32; if not Result then Exit; // wait for completion or timeout if TimeOut>0 then Result:=WaitForSingleObject(Info.hProcess,TimeOut)<>WAIT_FAILED; CloseHandle(Info.hProcess); end; //////////////////////////////////////////////////////////////////////////////// procedure TCmd.Shutdown(Force : Boolean = False); // shuts the computer down, even in the presence of unsaved files if forced var hTokenHandle : Cardinal; PrivLUID : Int64; TokenPriv : TOKEN_PRIVILEGES; tkpDummy : TOKEN_PRIVILEGES; lDummy : Cardinal; begin // adjust privileges OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hTokenHandle); LookupPrivilegeValue('', 'SeShutdownPrivilege', PrivLUID); TokenPriv.PrivilegeCount:=1; TokenPriv.Privileges[0].Luid:=PrivLUID; TokenPriv.Privileges[0].Attributes:=SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hTokenHandle, False, TokenPriv, SizeOf(tkpDummy), tkpDummy, lDummy); CloseHandle(hTokenHandle); // initiate shutdown ExitWindowsEx(EWX_FORCE*Byte(Force)+EWX_POWEROFF+EWX_SHUTDOWN, 0); end; //////////////////////////////////////////////////////////////////////////////// procedure TCmd.Sound(SndFile : AnsiString = ''); // play a specific file or a simple beep begin if SndFile='' then MessageBeep($FFFFFFFF) else SndPlaySound(@SndFile[1], SND_ASYNC or SND_NOSTOP or SND_NODEFAULT); end; //////////////////////////////////////////////////////////////////////////////// function TCmd.GetPix(Wnd : Cardinal; X,Y : Cardinal) : Cardinal; // returns the value of a pixel on screen var DC : HDC; begin DC:=GetDC(Wnd); Result:=GetPixel(DC,X,Y); ReleaseDC(Wnd,DC); end; //////////////////////////////////////////////////////////////////////////////// function TCmd.GetCliTitle(Wnd : Cardinal) : AnsiString; // returns the specified window's title begin SetLength(Result,1024); GetWindowText(Wnd,@Result[1],1024); Result:=PAnsiChar(@Result[1]); end; //////////////////////////////////////////////////////////////////////////////// procedure TCmd.SetCliTitle(Wnd : Cardinal; Title : AnsiString); // sets the specified window's title begin SetWindowText(Wnd,@Title[1]); end; //////////////////////////////////////////////////////////////////////////////// initialization Randomize; end.
Unit myEdgeList; Interface Type pointList = ^edgeList; edgeList = record nodeOneID: string; nodeTwoID: string; countNearEdges: integer; isMetk: boolean; next: pointList; end; Var pListHead: pointList; Function getNewPointList():pointList;//создание нового указателя-начала списка Procedure addPointInTail(var pList: pointList; metk: pointList);//добавление указателя в конец списка Procedure fillList(var pList:pointList; FILE_NAME: string);//заполнение списка данными из файла Procedure setMetk(var pList: pointList);//отмечаем ребро как пройденное Procedure setCountNearEdges(var pList: pointList);//нахождение количества соседних рёбер у данного ребра Function isExistNotMetk(pList: pointList):boolean;//проверка на существование непройденных рёбер Function isExistMetkPoint(pList: pointList):boolean;//проверка на непройденость ребра Function getNearNotMetkEdge(pList: pointList; edge:pointList):pointList;//получение указателя на соседнее непройденное ребро Procedure sortEdgesByCountFromMinToMax(var pList: pointList);//сортировка рёбер по возрастанию количества соседних рёбер Procedure sortEdgesByCountFromMaxToMin(var pList: pointList);//сортировка рёбер по убыванию количества соседних рёбер Procedure printList(pList: pointList; FILE_NAME:string);//вывод списка рёбер в файл Implementation Procedure initList(var pList: pointList);//инициализация указателя begin new(pList); pList^.next:=pList; end; Function getNewPointList():pointList;//создание нового указателя-начала списка begin initList(pListHead); getNewPointList:=pListHead; end; Procedure addTail(var pList: pointList; nodeOneID: string; nodeTwoID: string);//добавление элемента в конец списка var y: pointList; begin new(y); y^.next:=pList^.next; pList^.nodeOneID:=nodeOneID; pList^.nodeTwoID:=nodeTwoID; pList^.countNearEdges:=0; pList^.isMetk:=false; pList^.next:=y; pList:=y; end; Function getLastPoint(pList: pointList):pointList;//получение последнего (не считая "болванчика") указателя списка var metk:pointList; begin metk:=pList^.next; While metk^.next<>pList do metk:=metk^.next; getLastPoint:=metk; end; Procedure copyPointDates(var pList: pointList; metk: pointList);//копирование данных одного указателя другим begin pList^.nodeOneID:=metk^.nodeOneID; pList^.nodeTwoID:=metk^.nodeTwoID; pList^.countNearEdges:=metk^.countNearEdges; pList^.isMetk:=metk^.isMetk; end; Procedure addPointInTail(var pList: pointList; metk: pointList);//добавление указателя в конец списка var lastPoint:pointList; begin addTail(pList, metk^.nodeOneID, metk^.nodeTwoID); lastPoint:=getLastPoint(pList); copyPointDates(lastPoint, metk); end; Procedure getParseStr(str: string; var stringOne: string; var stringTwo: string);//парсинг строки в соответствии с задачей const SPACE = ' '; var i:integer; begin stringOne:=''; stringTwo:=''; i:=1; While (i<=length(str)) and (str[i]<>SPACE) do i+=1; stringOne:=copy(str, 1, i-1); stringTwo:=copy(str, i+1, length(str)-i); end; Procedure fillList(var pList:pointList; FILE_NAME: string);//заполнение списка данными из файла var f:text; str: string; nodeOneID: string; nodeTwoID: string; begin Assign(f, FILE_NAME); Reset(f); While not Eof(f) do begin ReadLn(f, str); getParseStr(str, nodeOneID, nodeTwoID); addTail(pList, nodeOneID, nodeTwoID); end; Close(f); end; Procedure setMetk(var pList: pointList);//отмечаем ребро как пройденное begin pList^.isMetk:=true; end; Function isNearEdges(edgeOne: pointList; edgeTwo: pointList):boolean;//проверка - являются ли два ребра соседними begin isNearEdges:=(edgeOne<>edgeTwo) and ((edgeOne^.nodeOneID=edgeTwo^.nodeOneID)or(edgeOne^.nodeOneID=edgeTwo^.nodeTwoID) or(edgeOne^.nodeTwoID=edgeTwo^.nodeOneID)or(edgeOne^.nodeTwoID=edgeTwo^.nodeTwoID)); end; Procedure setCountNearEdges(var pList: pointList);//нахождение количества соседних рёбер у данного ребра var metkOne:pointList; metkTwo:pointList; begin metkOne:=pList^.next; While metkOne<>pList do begin metkTwo:=metkOne^.next; While metkTwo<>pList do begin If isNearEdges(metkOne, metkTwo) then begin metkOne^.countNearEdges+=1; metkTwo^.countNearEdges+=1; end; metkTwo:=metkTwo^.next; end; metkOne:=metkOne^.next; end; end; Function isLess(edgeOne: pointList; edgeTwo: pointList):boolean;//проверка - является ли один элемент списка меньше другого (сравнение по количеству соседних рёбер) begin isLess:=edgeOne^.countNearEdges<edgeTwo^.countNearEdges; end; Function isExistNotMetk(pList: pointList):boolean;//проверка на существование непройденных рёбер var metk:pointList; f:boolean; begin metk:=pList^.next; f:=not metk^.isMetk; While (metk<>pList) and not f do begin metk:=metk^.next; f:=not metk^.isMetk; end; isExistNotMetk:=f; end; Function isExistMetkPoint(pList: pointList):boolean;//проверка на непройденость ребра begin isExistMetkPoint:=pList^.isMetk; end; Function getNearNotMetkEdge(pList: pointList; edge:pointList):pointList;//получение указателя на соседнее непройденное ребро var metk:pointList; f:boolean; begin metk:=pList^.next; f:=not isExistMetkPoint(metk) and (edge<>metk) and ((edge^.nodeOneID=metk^.nodeOneID)or(edge^.nodeOneID=metk^.nodeTwoID) or(edge^.nodeTwoID=metk^.nodeOneID)or(edge^.nodeTwoID=metk^.nodeTwoID)); while (metk<>pList) and not f do begin metk:=metk^.next; f:=not isExistMetkPoint(metk) and (edge<>metk) and ((edge^.nodeOneID=metk^.nodeOneID)or(edge^.nodeOneID=metk^.nodeTwoID) or(edge^.nodeTwoID=metk^.nodeOneID)or(edge^.nodeTwoID=metk^.nodeTwoID)); end; getNearNotMetkEdge:=metk; end; Procedure exchangePointDates(var pListOne: pointList; var pListTwo: pointList);//обмен данных между двумя элементами списка var metk:pointList; begin new(metk); metk^.nodeOneID:=pListOne^.nodeOneID; metk^.nodeTwoID:=pListOne^.nodeTwoID; metk^.countNearEdges:=pListOne^.countNearEdges; metk^.isMetk:=pListOne^.isMetk; pListOne^.nodeOneID:=pListTwo^.nodeOneID; pListOne^.nodeTwoID:=pListTwo^.nodeTwoID; pListOne^.countNearEdges:=pListTwo^.countNearEdges; pListOne^.isMetk:=pListTwo^.isMetk; pListTwo^.nodeOneID:=metk^.nodeOneID; pListTwo^.nodeTwoID:=metk^.nodeTwoID; pListTwo^.countNearEdges:=metk^.countNearEdges; pListTwo^.isMetk:=metk^.isMetk; dispose(metk); end; Procedure sortEdgesByCountFromMinToMax(var pList: pointList);//сортировка рёбер по возрастанию количества соседних рёбер var metk:pointList; lastMetk:pointList; f:boolean; begin lastMetk:=pList^.next; metk:=lastMetk^.next; while metk<>pList do begin f:=isLess(metk, lastMetk); If f then begin exchangePointDates(metk, lastMetk); metk:=lastMetk; While lastMetk^.next<>metk do lastMetk:=lastMetk^.next; end; If not f or (lastMetk=pList) then begin lastMetk:=metk; metk:=metk^.next; end; end; end; Procedure sortEdgesByCountFromMaxToMin(var pList: pointList);//сортировка рёбер по убыванию количества соседних рёбер var metk:pointList; lastMetk:pointList; f:boolean; begin lastMetk:=pList^.next; metk:=lastMetk^.next; while metk<>pList do begin f:=isLess(lastMetk, metk); If f then begin exchangePointDates(metk, lastMetk); metk:=lastMetk; While lastMetk^.next<>metk do lastMetk:=lastMetk^.next; end; If not f or (lastMetk=pList) then begin lastMetk:=metk; metk:=metk^.next; end; end; end; Procedure printList(pList: pointList; FILE_NAME:string);//вывод списка рёбер в файл var f:text; metk:pointList; begin metk:=pList^.next; Assign(f,FILE_NAME); Rewrite(f); While metk<>pList do begin WriteLn(f,metk^.nodeOneID,' ',metk^.nodeTwoID); metk:=metk^.next; end; Close(f); end; Initialization End.
unit Memory; interface function Alloc(size: integer) : pointer; type MemoryState = pointer; procedure SaveState (var MS : MemoryState); procedure RestoreState (const MS : MemoryState); function GetPtr : pointer; procedure FreePtr (p : pointer); // открываю для сейвлода type PPoolItem = ^PoolItem; PoolItem = record case boolean of true : ( Free : boolean; Ptr : PPoolItem; ); false : ( bytes : array [0..31] of byte ); end; var Data : array [0..$1ffffff] of char; Beg : pointer = @Data[0]; MaxMem : pointer = @Data[0]; const MaxPools = $80000; var PoolCount : integer; Pool : array [0..MaxPools-1] of PoolItem; Free : PPoolItem; implementation function Alloc(size: integer) : pointer; begin if size>0 then begin Assert(PChar(Beg)+size-1 <= @Data[High(Data)], 'Memory overflow!'); result := Beg; Inc(PChar(Beg), size); if (PChar(Beg)>PChar(MaxMem)) then MaxMem := Beg; end else result := nil; end; procedure SaveState (var MS : MemoryState); begin MS := Beg; end; procedure RestoreState (const MS : MemoryState); begin Beg := MS; Assert (cardinal(Beg)>=cardinal(@Data)); end; function GetPtr : pointer; begin Assert(PoolCount+1<MaxPools, 'Memory overflow!'); Assert(Free<>nil); Assert(Free.Free); Result := @Free.Ptr; Free.Free := False; Free := Free.Ptr; Inc(PoolCount); end; procedure FreePtr (p : pointer); var PI : PPoolItem; begin PI := PPoolItem( PChar(p)-(PChar(@Pool[0].Ptr)-PChar(@Pool[0])) ); Assert(not PI.Free); PI.Free := True; PI.Ptr := Free; Free := Pi; Dec(PoolCount); end; procedure InitPools; var i : integer; begin PoolCount := 0; Free := @Pool[Low(Pool)]; for i := Low(Pool) to High(Pool)-1 do begin Pool[i].Ptr := @Pool[i+1]; Pool[i].Free := True; end; Pool[High(Pool)].Ptr := nil; end; initialization InitPools; end.
unit debunpak; {$mode delphi}{$H+} interface uses SysUtils, Classes; // Extract 'control' from control.tar.* function Deb_ExtractCtrlInfoFile(const DebFile: String; var DescFile: String): Boolean; implementation uses dpkg_deb, libtar, AbXz, ZStream; var DebPkg: TDebianPackage; const HEAD_CRC = $02; { bit 1 set: header CRC present } EXTRA_FIELD = $04; { bit 2 set: extra field present } ORIG_NAME = $08; { bit 3 set: original file name present } COMMENT = $10; { bit 4 set: file comment present } type TGzHeader = packed record ID1 : Byte; ID2 : Byte; Method : Byte; Flags : Byte; ModTime : UInt32; XtraFlags : Byte; OS : Byte; end; function ExtractGzip(InStream, OutStream: TStream): Boolean; var ALength: Integer; AHeader: TGzHeader; ABuffer: array[Word] of Byte; begin Result:= False; InStream.ReadBuffer(AHeader, SizeOf(TGzHeader)); if (AHeader.ID1 = $1F) and (AHeader.ID2 = $8B) and (AHeader.Method = 8) then begin // Skip the extra field if (AHeader.Flags and EXTRA_FIELD <> 0) then begin ALength:= InStream.ReadWord; while ALength > 0 do begin InStream.ReadByte; Dec(ALength); end; end; // Skip the original file name if (AHeader.Flags and ORIG_NAME <> 0) then begin while (InStream.ReadByte > 0) do; end; // Skip the .gz file comment if (AHeader.Flags and COMMENT <> 0) then begin while (InStream.ReadByte > 0) do; end; // Skip the header crc if (AHeader.Flags and HEAD_CRC <> 0) then begin InStream.ReadWord; end; with TDecompressionStream.Create(InStream, True) do try while True do begin ALength:= Read(ABuffer[0], SizeOf(ABuffer)); if (ALength = 0) then Break; OutStream.Write(ABuffer[0], ALength); end; Result:= True; finally Free; end; end; end; function ExtractXz(InStream, OutStream: TStream): Boolean; begin with TLzmaDecompression.Create(InStream, OutStream) do try Result:= Code(); finally Free; end; end; function UnpackDebFile(const DebFile: String; MemberIdx: Integer; OutStream: TStream): Boolean; var Index: Integer; FileExt: String; TempStream: TMemoryStream; begin Result:= False; if (MemberIdx in [MEMBER_CONTROL, MEMBER_DATA]) then try // a debian package must have control.tar.* and data.tar.* if DebPkg.ReadFromFile(DebFile) < 2 then Exit; // Check file type FileExt:= TrimRight(DebPkg.FMemberList[MemberIdx].ar_name); Index:= Pos(ExtensionSeparator, FileExt); if Index = 0 then Exit; FileExt:= Copy(FileExt, Index, MaxInt); if (FileExt = '.tar.xz') then begin TempStream:= TMemoryStream.Create; try if DebPkg.ExtractMemberToStream(MemberIdx, TempStream) then begin TempStream.Position:= 0; Result:= ExtractXz(TempStream, OutStream); end; finally TempStream.Free; end; end; if (FileExt = '.tar.gz') then begin TempStream:= TMemoryStream.Create; try if DebPkg.ExtractMemberToStream(MemberIdx, TempStream) then begin TempStream.Position:= 0; Result:= ExtractGzip(TempStream, OutStream); end; finally TempStream.Free; end; end; except Result:= False; end; end; function Deb_ExtractCtrlInfoFile(const DebFile: String; var DescFile: String): Boolean; var TA: TTarArchive; DirRec: TTarDirRec; OutStream: TMemoryStream; begin Result:= False; OutStream:= TMemoryStream.Create; try Result:= UnpackDebFile(DebFile, MEMBER_CONTROL, OutStream); if Result then try TA := TTarArchive.Create(OutStream); try while TA.FindNext(DirRec) do begin if (DirRec.Name = './control') or (DirRec.Name = '.\control') or (DirRec.Name = 'control') then begin DescFile:= TA.ReadFile; Result:= True; Break; end; end; finally TA.Free; end; except // Ignore end; finally OutStream.Free; end; end; initialization DebPkg := TDebianPackage.Create; finalization DebPkg.Free; end.
unit GameUnit; interface uses ClassUnit, StatusUnit, Contnrs, Classes; type TMonsterParameter = class Name : string; Life : integer; Attack : integer; Defence : integer; Count : integer; end; TMonsterParameterList = class (TObjectList) protected function GetItems ( Index : integer ) : TMonsterParameter; procedure SetItems ( Index : integer; const Value : TMonsterParameter ); public procedure LoadFromFile; procedure SaveToFile; function Add(aClass: TMonsterParameter): Integer; function Remove(aClass: TMonsterParameter): Integer; function IndexOf(aClass: TMonsterParameter): Integer; procedure Insert(Index: Integer; aClass: TMonsterParameter); property Items[Index: Integer]: TMonsterParameter read GetItems write SetItems; default; end; TMonsterList = class ( TObjectList ) protected function GetItems ( Index : integer ) : TMonster; procedure SetItems ( Index : integer; const Value : TMonster ); public function Add(aClass: TMonster): Integer; function Remove(aClass: TMonster): Integer; function IndexOf(aClass: TMonster): Integer; procedure Insert(Index: Integer; aClass: TMonster); property Items[Index: Integer]: TMonster read GetItems write SetItems; default; end; TLifeBonusList = class ( TObjectList ) protected function GetItems ( Index : integer ) : TLifeBonus; procedure SetItems ( Index : integer; const Value : TLifeBonus ); public function Add(aClass: TLifeBonus): Integer; function Remove(aClass: TLifeBonus): Integer; function IndexOf(aClass: TLifeBonus): Integer; procedure Insert(Index: Integer; aClass: TLifeBonus); property Items[Index: Integer]: TLifeBonus read GetItems write SetItems; default; end; TAttackBonusList = class ( TObjectList ) protected function GetItems ( Index : integer ) : TAttackBonus; procedure SetItems ( Index : integer; const Value : TAttackBonus ); public function Add(aClass: TAttackBonus): Integer; function Remove(aClass: TAttackBonus): Integer; function IndexOf(aClass: TAttackBonus): Integer; procedure Insert(Index: Integer; aClass: TAttackBonus); property Items[Index: Integer]: TAttackBonus read GetItems write SetItems; default; end; TDefenceBonusList = class ( TObjectList ) protected function GetItems ( Index : integer ) : TDefenceBonus; procedure SetItems ( Index : integer; const Value : TDefenceBonus ); public function Add(aClass: TDefenceBonus): Integer; function Remove(aClass: TDefenceBonus): Integer; function IndexOf(aClass: TDefenceBonus): Integer; procedure Insert(Index: Integer; aClass: TDefenceBonus); property Items[Index: Integer]: TDefenceBonus read GetItems write SetItems; default; end; TObstacleList = class ( TObjectList ) protected function GetItems ( Index : integer ) : TObstacle; procedure SetItems ( Index : integer; const Value : TObstacle ); public function Add(aClass: TObstacle): Integer; function Remove(aClass: TObstacle): Integer; function IndexOf(aClass: TObstacle): Integer; procedure Insert(Index: Integer; aClass: TObstacle); property Items[Index: Integer]: TObstacle read GetItems write SetItems; default; end; TGame = class private FField : TField; FHero : THero; FMonsterList : TMonsterList; FLifeBonusList : TLifeBonusList; FAttackBonusList : TAttackBonusList; FDefenceBonusList : TDefenceBonusList; FObstacleList : TObstacleList; FExit : TExit; FBattleTurn : TBattleTurn; public CurrentMonster : TMonster; BattleMonster : TMonster; EofMonster : boolean; Battle : boolean; property Field : TField read FField; property Hero : THero read FHero; property MonsterList : TMonsterList read FMonsterList; property LifeBonusList : TLifeBonusList read FLifeBonusList; property AttackBonusList : TAttackBonusList read FAttackBonusList; property DefenceBonusList : TDefenceBonusList read FDefenceBonusList; property BattleTurn : TBattleTurn read FBattleTurn; procedure NextMonster; constructor Create; procedure SetFieldParameters ( const FieldWidth, FieldHeight : ShortInt; const ObstaclePercent : byte ); procedure SetHeroParameters ( const MaxLife, MaxAttack, MaxDefence : integer; const GA : TGlobalAimes ); procedure SetMonsterParameters ( const MonsterParameters : TMonsterParameterList ); procedure SetLifeParameters ( const One, Five, Ten : integer ); procedure SetAttackParameters ( const One, Five, Ten : integer ); procedure SetDefenceParameters ( const One, Five, Ten : integer ); function HasBonuses : boolean; function HasLifeBonuses : boolean; function HasAttackBonuses : boolean; function HasDefenceBonuses : boolean; function HasMonsters : boolean; procedure BeginBattle ( const C1, C2 : TCreature ); procedure NextBattleTurn; procedure EndBattle; function DeathByFirstAttack (const C1, C2 : TCreature ) : boolean; procedure DeathOfMonster; procedure ReAimMonsters; procedure ReAimHero; procedure AssignForm ( StatusForm : TStatusForm ); procedure UpdateField; procedure DeleteBonus ( C : TFieldPoint ); end; implementation { TMonsterList } uses SysUtils; function TMonsterList.Add(aClass: TMonster): Integer; begin Result := inherited Add(aClass); end; function TMonsterList.GetItems(Index: integer): TMonster; begin Result := TMonster(inherited GetItem (Index)); end; function TMonsterList.IndexOf(aClass: TMonster): Integer; begin Result := inherited IndexOf(aClass); end; procedure TMonsterList.Insert(Index: Integer; aClass: TMonster); begin inherited Insert(Index, aClass); end; function TMonsterList.Remove(aClass: TMonster): Integer; begin Result := inherited Remove(aClass); end; procedure TMonsterList.SetItems(Index: integer; const Value: TMonster); begin inherited Items[Index] := Value; end; { TLifeBonusList } function TLifeBonusList.Add(aClass: TLifeBonus): Integer; begin Result := inherited Add(aClass); end; function TLifeBonusList.GetItems(Index: integer): TLifeBonus; begin Result := TLifeBonus(inherited GetItem(Index)); end; function TLifeBonusList.IndexOf(aClass: TLifeBonus): Integer; begin Result := inherited IndexOf(aClass); end; procedure TLifeBonusList.Insert(Index: Integer; aClass: TLifeBonus); begin inherited Insert(Index, aClass); end; function TLifeBonusList.Remove(aClass: TLifeBonus): Integer; begin Result := inherited Remove(aClass); end; procedure TLifeBonusList.SetItems(Index: integer; const Value: TLifeBonus); begin inherited SetItem(Index, Value); end; { TAttackBonusList } function TAttackBonusList.Add(aClass: TAttackBonus): Integer; begin Result := inherited Add(aClass); end; function TAttackBonusList.GetItems(Index: integer): TAttackBonus; begin Result := TAttackBonus(inherited GetItem(Index)); end; function TAttackBonusList.IndexOf(aClass: TAttackBonus): Integer; begin Result := inherited IndexOf(aClass); end; procedure TAttackBonusList.Insert(Index: Integer; aClass: TAttackBonus); begin inherited Insert(Index, aClass); end; function TAttackBonusList.Remove(aClass: TAttackBonus): Integer; begin Result := inherited Remove(aClass); end; procedure TAttackBonusList.SetItems(Index: integer; const Value: TAttackBonus); begin inherited SetItem(Index, Value); end; { TDefenceBonusList } function TDefenceBonusList.Add(aClass: TDefenceBonus): Integer; begin Result := inherited Add(aClass); end; function TDefenceBonusList.GetItems(Index: integer): TDefenceBonus; begin Result := TDefenceBonus(inherited GetItem(Index)); end; function TDefenceBonusList.IndexOf(aClass: TDefenceBonus): Integer; begin Result := inherited IndexOf(aClass); end; procedure TDefenceBonusList.Insert(Index: Integer; aClass: TDefenceBonus); begin inherited Insert(Index, aClass); end; function TDefenceBonusList.Remove(aClass: TDefenceBonus): Integer; begin Result := inherited Remove(aClass); end; procedure TDefenceBonusList.SetItems(Index: integer; const Value: TDefenceBonus); begin inherited SetItem(Index, Value); end; { TObstacleList } function TObstacleList.Add(aClass: TObstacle): Integer; begin Result := inherited Add(aClass); end; function TObstacleList.GetItems(Index: integer): TObstacle; begin Result := TObstacle(inherited GetItem(Index)); end; function TObstacleList.IndexOf(aClass: TObstacle): Integer; begin Result := inherited IndexOf(aClass); end; procedure TObstacleList.Insert(Index: Integer; aClass: TObstacle); begin inherited Insert(Index, aClass); end; function TObstacleList.Remove(aClass: TObstacle): Integer; begin Result := inherited Remove(aClass); end; procedure TObstacleList.SetItems(Index: integer; const Value: TObstacle); begin inherited SetItem(Index, Value); end; { TGame } procedure TGame.AssignForm(StatusForm: TStatusForm); var i : integer; begin FHero.StatusForm := StatusForm; for i := 0 to FMonsterList.Count - 1 do FMonsterList[i].StatusForm := StatusForm; for i := 0 to FLifeBonusList.Count - 1 do FLifeBonusList[i].StatusForm := StatusForm; for i := 0 to FAttackBonusList.Count - 1 do FAttackBonusList[i].StatusForm := StatusForm; for i := 0 to FDefenceBonusList.Count - 1 do FDefenceBonusList[i].StatusForm := StatusForm; end; procedure TGame.BeginBattle(const C1, C2: TCreature); begin Battle := true; FBattleTurn := TBattleTurn.Create; FBattleTurn.StatusForm := FHero.StatusForm; FBattleTurn.StatusForm.HeroMemo.Lines.Add('Begin battle!'); FBattleTurn.Attacker := C1; FBattleTurn.Defender := C2; if FBattleTurn.Attacker is THero then FBattleTurn.StatusForm.HeroMemo.Lines.Add('Attacker = Hero, Defender = Monster') else FBattleTurn.StatusForm.HeroMemo.Lines.Add('Attacker = Monster, Defender = Hero'); FBattleTurn.CountAll; end; constructor TGame.Create; var m : TMonsterParameterList; begin FField := TField.Create; FAttackBonusList := TAttackBonusList.Create; FDefenceBonusList := TDefenceBonusList.Create; FHero := THero.Create(FField); FMonsterList := TMonsterList.Create; FLifeBonusList := TLifeBonusList.Create; FObstacleList := TObstacleList.Create; FExit := TExit.Create(FField); SetFieldParameters(20, 15, 5); SetHeroParameters(10, 10, 10, [gaExit, gaBonus]); m := TMonsterParameterList.Create; m.LoadFromFile; SetMonsterParameters(m); SetLifeParameters(3, 3, 3); SetAttackParameters(3, 3, 3); SetDefenceParameters(3, 3, 3); CurrentMonster := FMonsterList[0]; end; function TGame.DeathByFirstAttack(const C1, C2: TCreature): boolean; begin FBattleTurn := TBattleTurn.Create; FBattleTurn.Attacker := C1; FBattleTurn.Defender := C2; Result := FBattleTurn.DeadByFirstAttack; FBattleTurn.Free; FBattleTurn := nil; end; procedure TGame.DeathOfMonster; var Index : integer; begin if FMonsterList.IndexOf(CurrentMonster) = FMonsterList.Count - 1 then begin EofMonster := true; FMonsterList.Remove(CurrentMonster); CurrentMonster := nil; end else begin EofMonster := false; Index := FMonsterList.IndexOf(CurrentMonster); FMonsterList.Remove(CurrentMonster); if FMonsterList.Count = 0 then begin EofMonster := true; CurrentMonster := nil; end else CurrentMonster := FMonsterList[Index]; end; end; procedure TGame.DeleteBonus(C: TFieldPoint); begin if Field[C.x, C.y] is TBonus then begin if Field[C.x, C.y] is TAttackBonus then begin FAttackBonusList.Remove(Field[C.x, C.y] as TAttackBonus); UpdateField; end else begin if Field[C.x, C.y] is TLifeBonus then begin FLifeBonusList.Remove(Field[C.x, C.y] as TLifeBonus); UpdateField; end else begin if Field[C.x, C.y] is TDefenceBonus then begin FDefenceBonusList.Remove(Field[C.x, C.y] as TDefenceBonus); UpdateField; end; end; end; end; end; procedure TGame.EndBattle; begin FBattleTurn.StatusForm.HeroMemo.Lines.Add('End battle!'); if FBattleTurn.Attacker.Life > 0 then FField.FieldMatrix[FBattleTurn.Attacker.Coords.x, FBattleTurn.Attacker.Coords.y] := FBattleTurn.Attacker else FField.FieldMatrix[FBattleTurn.Defender.Coords.x, FBattleTurn.Defender.Coords.y] := FBattleTurn.Defender; FBattleTurn.Attacker := nil; FBattleTurn.Defender := nil; FBattleTurn.Free; FBattleTurn := nil; Battle := false; end; function TGame.HasAttackBonuses: boolean; begin Result := (FAttackBonusList.Count <> 0); end; function TGame.HasBonuses: boolean; begin Result := HasLifeBonuses or HasAttackBonuses or HasDefenceBonuses; end; function TGame.HasDefenceBonuses: boolean; begin Result := (FDefenceBonusList.Count <> 0); end; function TGame.HasLifeBonuses: boolean; begin Result := (FLifeBonusList.Count <> 0); end; function TGame.HasMonsters: boolean; begin Result := (FMonsterList.Count <> 0); end; procedure TGame.NextBattleTurn; var tmp : TCreature; begin tmp := FBattleTurn.Attacker; FBattleTurn.Attacker := FBattleTurn.Defender; FBattleTurn.Defender := tmp; FBattleTurn.StatusForm.HeroMemo.Lines.Add('Next battle turn!'); if FBattleTurn.Attacker is THero then FBattleTurn.StatusForm.HeroMemo.Lines.Add('Attacker = Hero, Defender = Monster') else FBattleTurn.StatusForm.HeroMemo.Lines.Add('Attacker = Monster, Defender = Hero'); FBattleTurn.CountAll; end; procedure TGame.NextMonster; begin if EofMonster then begin if FMonsterList.Count <> 0 then begin CurrentMonster := FMonsterList[0]; EofMonster := false; end; end else begin if FMonsterList.IndexOf(CurrentMonster) = FMonsterList.Count - 1 then begin EofMonster := true; CurrentMonster := nil; end else begin CurrentMonster := FMonsterList[FMonsterList.IndexOf(CurrentMonster)+1]; EofMonster := false; end; end; end; procedure TGame.ReAimHero; var i, j : integer; fl : boolean; begin if FHero.Aim = atMonster then begin fl := false; if not(FField.FieldMatrix[FHero.AimCoords.x, FHero.AimCoords.y] is TMonster) then begin for i := -1 to 1 do for j := -1 to 1 do if FField[FHero.AimCoords.x+i, FHero.AimCoords.y+j] is TMonster then begin FHero.AimCoords := (FField[FHero.AimCoords.x+i, FHero.AimCoords.y+j] as TMonster).Coords; fl := true; end; end else fl := true; if not(fl) then FHero.FindAim(atMonster); end; end; procedure TGame.ReAimMonsters; var i : integer; begin for i := 0 to FMonsterList.Count - 1 do FMonsterList[i].FindAim(atHero); end; procedure TGame.SetAttackParameters(const One, Five, Ten: integer); var i : integer; begin FAttackBonusList.Clear; for i := 1 to One do FAttackBonusList.Add(TAttackBonus.Create(FField, 1)); for i := 1 to Five do FAttackBonusList.Add(TAttackBonus.Create(FField, 5)); for i := 1 to Ten do FAttackBonusList.Add(TAttackBonus.Create(FField, 10)); for i := 0 to FAttackBonusList.Count - 1 do FAttackBonusList[i].GenerateAttackBonus; end; procedure TGame.SetDefenceParameters(const One, Five, Ten: integer); var i : integer; begin FDefenceBonusList.Clear; for i := 1 to One do FDefenceBonusList.Add(TDefenceBonus.Create(FField, 1)); for i := 1 to Five do FDefenceBonusList.Add(TDefenceBonus.Create(FField, 5)); for i := 1 to Ten do FDefenceBonusList.Add(TDefenceBonus.Create(FField, 10)); for i := 0 to FDefenceBonusList.Count - 1 do FDefenceBonusList[i].GenerateDefenceBonus; end; procedure TGame.SetFieldParameters(const FieldWidth, FieldHeight: ShortInt; const ObstaclePercent: byte); var i : integer; begin if (FieldWidth >= 10) and (FieldWidth <= 100) then FField.FieldWidth := FieldWidth; if (FieldHeight >= 10) and (FieldHeight <= 100) then FField.FieldHeight := FieldHeight; FField.ClearField; FObstacleList.Clear; for i := 0 to trunc(FieldWidth*FieldHeight*ObstaclePercent/100) - 1 do FObstacleList.Add(TObstacle.Create(FField)); for i := 0 to FObstacleList.Count - 1 do FObstacleList[i].GenerateObstacle; FExit.GenerateExit; // TObject or TObstacle? забивать их в ObstacleList? FField.FieldMatrix[-1,-1] := TObject.Create; FField.FieldMatrix[-1,FieldHeight] := TObject.Create; FField.FieldMatrix[FieldWidth,-1] := TObject.Create; FField.FieldMatrix[FieldWidth,FieldHeight] := TObject.Create; for i := 0 to FieldWidth - 1 do begin FField.FieldMatrix[i,-1] := TObject.Create; FField.FieldMatrix[i,FieldHeight] := TObject.Create; end; for i := 0 to FieldHeight - 1 do begin FField.FieldMatrix[-1,i] := TObject.Create; FField.FieldMatrix[FieldWidth,i] := TObject.Create; end; end; procedure TGame.SetHeroParameters(const MaxLife, MaxAttack, MaxDefence: integer; const GA : TGlobalAimes ); begin FHero.SetMaxLife(MaxLife); FHero.SetMaxDefence(MaxDefence); FHero.SetMaxAttack(MaxAttack); FHero.GlobalAimes := GA; FHero.GenerateCreature; end; procedure TGame.SetLifeParameters(const One, Five, Ten: integer); var i : integer; begin FLifeBonusList.Clear; for i := 1 to One do FLifeBonusList.Add(TLifeBonus.Create(FField, 1)); for i := 1 to Five do FLifeBonusList.Add(TLifeBonus.Create(FField, 5)); for i := 1 to Ten do FLifeBonusList.Add(TLifeBonus.Create(FField, 10)); for i := 0 to FLifeBonusList.Count - 1 do FLifeBonusList[i].GenerateLifeBonus; end; procedure TGame.SetMonsterParameters( const MonsterParameters: TMonsterParameterList); var i : integer; j : integer; Monster : TMonster; begin if MonsterParameters <> nil then begin FMonsterList.Clear; for i := 0 to MonsterParameters.Count - 1 do for j := 0 to MonsterParameters[i].Count - 1 do begin Monster := TMonster.Create(FField); Monster.SetMaxLife(MonsterParameters[i].Life); Monster.SetMaxAttack(MonsterParameters[i].Attack); Monster.SetMaxDefence(MonsterParameters[i].Defence); Monster.MissTurnCount := 0; // Monster.FindAim(atHero); FMonsterList.Add(Monster); end; for i := 0 to FMonsterList.Count - 1 do begin FMonsterList[i].GenerateCreature; FMonsterList[i].FindAim(atHero); end; end; end; procedure TGame.UpdateField; var i, j : integer; begin for i := 0 to 99 do for j := 0 to 99 do FField[i, j] := nil; for i := 0 to FObstacleList.Count - 1 do FField[FObstacleList[i].Coords.x, FObstacleList[i].Coords.y] := FObstacleList[i]; FField[FExit.Coords.x, FExit.Coords.y] := FExit; for i := 0 to FLifeBonusList.Count - 1 do if FField[FLifeBonusList[i].Coords.x, FLifeBonusList[i].Coords.y] = nil then FField[FLifeBonusList[i].Coords.x, FLifeBonusList[i].Coords.y] := FLifeBonusList[i]; for i := 0 to FAttackBonusList.Count - 1 do if FField[FAttackBonusList[i].Coords.x, FAttackBonusList[i].Coords.y] = nil then FField[FAttackBonusList[i].Coords.x, FAttackBonusList[i].Coords.y] := FAttackBonusList[i]; for i := 0 to FDefenceBonusList.Count - 1 do if FField[FDefenceBonusList[i].Coords.x, FDefenceBonusList[i].Coords.y] = nil then FField[FDefenceBonusList[i].Coords.x, FDefenceBonusList[i].Coords.y] := FDefenceBonusList[i]; for i := 0 to FMonsterList.Count - 1 do if FField[FMonsterList[i].Coords.x, FMonsterList[i].Coords.y] = nil then FField[FMonsterList[i].Coords.x, FMonsterList[i].Coords.y] := FMonsterList[i]; if FField[FHero.Coords.x, FHero.Coords.y] = nil then FField[FHero.Coords.x, FHero.Coords.y] := FHero; end; { TMonsterParameterList } function TMonsterParameterList.Add(aClass: TMonsterParameter): Integer; begin Result := inherited Add(aClass); end; function TMonsterParameterList.GetItems(Index: integer): TMonsterParameter; begin Result := TMonsterParameter(inherited GetItem(Index)); end; function TMonsterParameterList.IndexOf(aClass: TMonsterParameter): Integer; begin Result := inherited IndexOf(aClass); end; procedure TMonsterParameterList.Insert(Index: Integer; aClass: TMonsterParameter); begin inherited Insert(Index, aClass); end; procedure TMonsterParameterList.LoadFromFile; var f : TextFile; MonsterParameter : TMonsterParameter; begin AssignFile(f, 'Monsters.txt'); try reset(f); while not(eof(f)) do begin MonsterParameter := TMonsterParameter.Create; readln(f, MonsterParameter.Name); readln(f, MonsterParameter.Life); readln(f, MonsterParameter.Attack); readln(f, MonsterParameter.Defence); MonsterParameter.Count := 1; Add(MonsterParameter); end; CloseFile(f); except raise EAbort.Create(''); end; end; function TMonsterParameterList.Remove(aClass: TMonsterParameter): Integer; begin Result := inherited Remove(aClass); end; procedure TMonsterParameterList.SaveToFile; var f : TextFile; i : integer; begin AssignFile (f, 'Monsters.txt'); try rewrite(f); for i := 0 to Count - 1 do begin writeln(Items[i].Name); writeln(Items[i].Life); writeln(Items[i].Attack); writeln(Items[i].Defence); end; CloseFile(f); except raise EAbort.Create(''); end; end; procedure TMonsterParameterList.SetItems(Index: integer; const Value: TMonsterParameter); begin inherited SetItem (Index, Value); end; end.
unit Comp_UIntf; interface uses Comp_UTypes, Graphics, Types; type { IViewOwner } IViewOwner = interface ['{1FBB192B-8F43-468D-B949-4AD97FB2BD4C}'] function GetCanvas: TCanvas; function GetHandle: THandle; procedure InvalidateRect(const Source: TRect); property Canvas: TCanvas read GetCanvas; property Handle: THandle read GetHandle; end; { ITogglable } ITogglable = interface ['{1D562094-09E1-4C9C-8BF1-C4EEA03EF02F}'] function GetToggleButtonStyle: TScToggleButtonStyle; property ToggleButtonStyle: TScToggleButtonStyle read GetToggleButtonStyle; end; implementation end.
unit RegSynEditAlt; interface uses Windows,Classes,pFIBSyntaxMemo,RegFIBPlusEditors; type TFIBSQLSyntaxEditor=class(TMPSyntaxMemo,IFIBSQLTextEditor) private function GetReadOnly:boolean; procedure SetReadOnly(Value:boolean); function GetLines:TStrings; procedure SetLines(Value: TStrings); function GetSelStart: Integer; procedure SetSelStart(Value: Integer); function GetSelLength: Integer; procedure SetSelLength(Value: Integer); procedure SelectAll; function GetModified: Boolean; procedure SetModified(Value: Boolean); function GetCaretX:integer; function GetCaretY:integer; procedure iSetCaretPos(X,Y:integer); procedure ISetProposalItems(ts1,ts2:TStrings); function GetBeforePropCall:TiBeforeProposalCall; procedure SetBeforePropCall(Event:TiBeforeProposalCall); end; implementation uses IBSQLSyn; { TFIBSQLSyntaxEditor } function TFIBSQLSyntaxEditor.GetCaretX: integer; begin Result:=Range.PosX end; function TFIBSQLSyntaxEditor.GetCaretY: integer; begin Result:=Range.PosY end; function TFIBSQLSyntaxEditor.GetLines: TStrings; begin Result:=Lines end; function TFIBSQLSyntaxEditor.GetModified: Boolean; begin Result:=Lines.Modified end; function TFIBSQLSyntaxEditor.GetReadOnly: boolean; begin Result:=smoReadOnly in Options end; function TFIBSQLSyntaxEditor.GetSelLength: Integer; begin Result:=Range.SelLength end; function TFIBSQLSyntaxEditor.GetSelStart: Integer; begin Result:=Range.Position end; procedure TFIBSQLSyntaxEditor.SelectAll; begin Range.SelectAll end; procedure TFIBSQLSyntaxEditor.iSetCaretPos(X,Y:integer); begin Range.Pos:=Point(X,Y) end; procedure TFIBSQLSyntaxEditor.SetLines(Value: TStrings); begin Lines.Text:=Value.Text end; procedure TFIBSQLSyntaxEditor.SetModified(Value: Boolean); begin Lines.Modified:=Value end; procedure TFIBSQLSyntaxEditor.SetReadOnly(Value: boolean); begin if Value then Options:=Options+[smoReadOnly] else Options:=Options-[smoReadOnly] end; procedure TFIBSQLSyntaxEditor.SetSelLength(Value: Integer); begin Range.SelLength:=Value end; procedure TFIBSQLSyntaxEditor.SetSelStart(Value: Integer); begin Range.Position:=Value end; procedure TFIBSQLSyntaxEditor.ISetProposalItems(ts1, ts2: TStrings); var PI:TMPProposalItems; begin PI[0]:=ts1; PI[1]:=ts2; SetProposalItems(PI) end; function TFIBSQLSyntaxEditor.GetBeforePropCall: TiBeforeProposalCall; begin Result:= BeforeProposalCall end; procedure TFIBSQLSyntaxEditor.SetBeforePropCall( Event: TiBeforeProposalCall); begin BeforeProposalCall:=Event end; initialization RegisterFIBSQLTextEditor(TFIBSQLSyntaxEditor); RegisterSyntax end.
{ } { Complex numbers v3.05 } { } { This unit is copyright © 1999-2003 by David Butler (david@e.co.za) } { } { This unit is part of Delphi Fundamentals. } { Its original file name is cComplex.pas } { The latest version is available from the Fundamentals home page } { http://fundementals.sourceforge.net/ } { } { I invite you to use this unit, free of charge. } { I invite you to distibute this unit, but it must be for free. } { I also invite you to contribute to its development, } { but do not distribute a modified copy of this file. } { } { A forum is available on SourceForge for general discussion } { http://sourceforge.net/forum/forum.php?forum_id=2117 } { } { } { Revision history: } { 1999/10/02 0.01 Added TComplex. } { 1999/11/21 0.02 Added TComplex.Power } { 2001/05/21 0.03 Moved TTRational and TTComplex from cExDataStructs. } { 2002/06/01 0.04 Created cComplex unit from cMaths. } { 2003/02/16 3.05 Revised for Fundamentals 3. } { } {$INCLUDE ..\cDefines.inc} unit cComplex; interface uses { Delphi } SysUtils; { } { Complex numbers } { Class that represents a complex number (Real + i * Imag) } { } type EComplex = class(Exception); TComplex = class private FReal, FImag : Extended; function GetAsString: String; procedure SetAsString(const S: String); public constructor Create(const TheRealPart: Extended = 0.0; const TheImaginaryPart: Extended = 0.0); property RealPart: Extended read FReal write FReal; property ImaginaryPart: Extended read FImag write FImag; property AsString: String read GetAsString write SetAsString; procedure Assign(const C: TComplex); overload; procedure Assign(const V: Extended); overload; procedure AssignZero; procedure AssignI; procedure AssignMinI; function Duplicate: TComplex; function IsEqual(const C: TComplex): Boolean; overload; function IsEqual(const R, I: Extended): Boolean; overload; function IsReal: Boolean; function IsZero: Boolean; function IsI: Boolean; procedure Add(const C: TComplex); overload; procedure Add(const V: Extended); overload; procedure Subtract(const C: TComplex); overload; procedure Subtract(const V: Extended); overload; procedure Multiply(const C: TComplex); overload; procedure Multiply (Const V: Extended); overload; procedure MultiplyI; procedure MultiplyMinI; procedure Divide(const C: TComplex); overload; procedure Divide(const V: Extended); overload; procedure Negate; function Modulo: Extended; function Denom: Extended; procedure Conjugate; procedure Inverse; procedure Sqrt; procedure Exp; procedure Ln; procedure Sin; procedure Cos; procedure Tan; procedure Power(const C: TComplex); end; implementation uses { Delphi } Math, { Fundamentals } cUtils, cStrings, cMaths; { } { TComplex } { } constructor TComplex.Create(const TheRealPart, TheImaginaryPart: Extended); begin inherited Create; FReal := TheRealPart; FImag := TheImaginaryPart; end; function TComplex.IsI: Boolean; begin Result := FloatZero(FReal) and FloatOne(FImag); end; function TComplex.IsReal: Boolean; begin Result := FloatZero(FImag); end; function TComplex.IsZero: Boolean; begin Result := FloatZero(FReal) and FloatZero(FImag); end; function TComplex.IsEqual(const C: TComplex): Boolean; begin Result := ApproxEqual(FReal, C.FReal) and ApproxEqual(FImag, C.FImag); end; function TComplex.IsEqual(const R, I: Extended): Boolean; begin Result := ApproxEqual(FReal, R) and ApproxEqual(FImag, I); end; procedure TComplex.AssignZero; begin FReal := 0.0; FImag := 0.0; end; procedure TComplex.AssignI; begin FReal := 0.0; FImag := 1.0; end; procedure TComplex.AssignMinI; begin FReal := 0.0; FImag := -1.0; end; procedure TComplex.Assign(const C: TComplex); begin FReal := C.FReal; FImag := C.FImag; end; procedure TComplex.Assign(const V: Extended); begin FReal := V; FImag := 0.0; end; function TComplex.Duplicate: TComplex; begin Result := TComplex.Create(FReal, FImag); end; function TComplex.GetAsString: String; var RZ, IZ : Boolean; begin RZ := FloatZero(FReal); IZ := FloatZero(FImag); if IZ then Result := FloatToStr(FReal) else begin Result := Result + FloatToStr(FImag) + 'i'; if not RZ then Result := Result + iif(Sgn(FReal) >= 0, '+', '-') + FloatToStr(Abs(FReal)); end; end; procedure TComplex.SetAsString(const S: String); var F, G, H : Integer; begin F := Pos('(', S); G := Pos(',', S); H := Pos(')', S); if (F <> 1) or (H <> Length(S)) or (G < F) or (G > H) then raise EConvertError.Create('Can not convert string to complex number'); FReal := StrToFloat(CopyRange(S, F + 1, G - 1)); FImag := StrToFloat(CopyRange(S, G + 1, H - 1)); end; procedure TComplex.Add(const C: TComplex); begin FReal := FReal + C.FReal; FImag := FImag + C.FImag; end; procedure TComplex.Add(const V: Extended); begin FReal := FReal + V; end; procedure TComplex.Subtract(const C: TComplex); begin FReal := FReal - C.FReal; FImag := FImag - C.FImag; end; procedure TComplex.Subtract(const V: Extended); begin FReal := FReal - V; end; procedure TComplex.Multiply(const C: TComplex); var R, I : Extended; begin R := FReal * C.FReal - FImag * C.FImag; I := FReal * C.FImag + FImag * C.FReal; FReal := R; FImag := I; end; procedure TComplex.Multiply(const V: Extended); begin FReal := FReal * V; FImag := FImag * V; end; procedure TComplex.MultiplyI; var R : Extended; begin R := FReal; FReal := -FImag; FImag := R; end; procedure TComplex.MultiplyMinI; var R : Extended; begin R := FReal; FReal := FImag; FImag := -R; end; function TComplex.Denom: Extended; begin Result := Sqr(FReal) + Sqr(FImag); end; procedure TComplex.Divide(const C: TComplex); var R, D : Extended; begin D := Denom; if FloatZero(D) then raise EDivByZero.Create('Complex division by zero') else begin R := FReal; FReal := (R * C.FReal + FImag * C.FImag) / D; FImag := (FImag * C.FReal - FReal * C.FImag) / D; end; end; procedure TComplex.Divide(const V: Extended); var D : Extended; begin D := Denom; if FloatZero(D) then raise EDivByZero.Create('Complex division by zero') else begin FReal := (FReal * V) / D; FImag := (FImag * V) / D; end; end; procedure TComplex.Negate; begin FReal := -FReal; FImag := -FImag; end; procedure TComplex.Conjugate; begin FImag := -FImag; end; procedure TComplex.Inverse; var D : Extended; begin D := Denom; if FloatZero(D) then raise EDivByZero.Create('Complex division by zero'); FReal := FReal / D; FImag := - FImag / D; end; procedure TComplex.Exp; var ExpZ : Extended; S, C : Extended; begin ExpZ := System.Exp(FReal); SinCos(FImag, S, C); FReal := ExpZ * C; FImag := ExpZ * S; end; procedure TComplex.Ln; var ModZ : Extended; begin ModZ := Denom; if FloatZero(ModZ) then raise EDivByZero.Create('Complex log zero'); FReal := System.Ln(ModZ); FImag := ArcTan2(FReal, FImag); end; procedure TComplex.Power(const C: TComplex); begin if not IsZero then begin Ln; Multiply(C); Exp; end else if C.IsZero then Assign(1.0) else { lim a^a = 1 as a-> 0 } AssignZero; { 0^a = 0 for a <> 0 } end; function TComplex.Modulo: Extended; begin Result := System.Sqrt(Denom); end; procedure TComplex.Sqrt; var Root, Q : Extended; begin if not FloatZero(FReal) or not FloatZero(FImag) then begin Root := System.Sqrt(0.5 * (Abs(FReal) + Modulo)); Q := FImag / (2.0 * Root); if FReal >= 0.0 then begin FReal := Root; FImag := Q; end else if FImag < 0.0 then begin FReal := - Q; FImag := - Root; end else begin FReal := Q; FImag := Root; end; end else AssignZero; end; procedure TComplex.Cos; begin FReal := System.Cos(FReal) * Cosh(FImag); FImag := -System.Sin(FReal) * Sinh(FImag); end; procedure TComplex.Sin; begin FReal := System.Sin(FReal) * Cosh(FImag); FImag := -System.Cos(FReal) * Sinh(FImag); end; procedure TComplex.Tan; var CCos : TComplex; begin CCos := TComplex.Create(FReal, FImag); try CCos.Cos; if CCos.IsZero then raise EDivByZero.Create('Complex division by zero'); self.Sin; self.Divide(CCos); finally CCos.Free; end; end; end.
unit while_loop_2; interface var G: Int32; implementation procedure Test; var x: Int32; begin x := 0; while x < 100 do x := x + 1; G := x; end; initialization Test(); finalization Assert(G = 100); end.
unit UProtocol; { 游戏内封包协议管理 不可缺少 } interface uses windows; type //封包数据结构,用户可以根据游戏的数据结构进行调整 PPacketObject = ^TPacketObject; TPacketObject = packed record pBuffer:Pointer; BufferSize:Cardinal; end; {************************游戏内封包结构*******************************} {************************游戏内封包协议*******************************} //获取协议ID Function GetProtocolId(pBuffer:Pointer):Integer; implementation Function GetProtocolId(pBuffer:Pointer):Integer; begin Result:=pInteger(pBuffer)^; end; end.
{=============================================================================== Copyright(c) 2014, 北京北研兴电力仪表有限责任公司 All rights reserved. 学员信息导入导出单元 + TStudentTableOption 学员信息导入导出类 ===============================================================================} unit xStudentTabelOutOrIn; interface uses System.Classes, System.SysUtils, {$IFDEF MSWINDOWS} System.Win.ComObj, {$ENDIF} xVCL_FMX; type /// <summary> /// 学员信息导入导出类 /// </summary> TStudentTableOption = class private {$IFDEF MSWINDOWS} FDlgSaveExecl : TMySaveDialog; FDlgOpenExecl : TMyOpenDialog; /// <summary> /// 导出学员时,对Excel设置合适的列宽,并初始化表头 /// </summary> procedure SetExcelWideIn(AExcel: Variant); {$ENDIF} public /// <summary> /// 将将Excel表格中的学员信息导入 /// </summary> /// <returns>0表示成功,1表示失败,2表示操作者在 OpenDialog 控件中点击了取消,没有导入Excel</returns> function ImportStu(slStus : TStringList) : Integer; /// <summary> /// 将学生信息导出到Excel表格中 /// </summary> /// <returns>0表示成功,1表示失败,2表示操作者在 SaveDialog 控件中点击了取,没有导出记录</returns> function ExportStu(slStus:TStringList ):Integer; end; implementation uses xStudentInfo; { TStudentTableOption } function TStudentTableOption.ExportStu(slStus: TStringList): Integer; {$IFDEF MSWINDOWS} var sExeclFile : string; AObjExecl : Variant; i : integer; ASheet: Variant; {$ENDIF} begin result := 1; {$IFDEF MSWINDOWS} if Assigned(slStus) then begin FDlgSaveExecl := TMySaveDialog.Create(nil); //设置文件格式 FDlgSaveExecl.Filter := 'Excel files (*.xls)|.xls|所有文件(*.*)|*.*'; //设置后缀并名 FDlgSaveExecl.DefaultExt:='.xls'; if FDlgSaveExecl.Execute then begin sExeclFile := FDlgSaveExecl.FileName; try // 新建Excel 初始化 AObjExecl := CreateOleObject('Excel.application'); AObjExecl.Visible := False; //初始化单元格 AObjExecl.WorkBooks.Add(-4167); AObjExecl.WorkBooks[1].Sheets[1].name :='学员信息'; ASheet := AObjExecl.WorkBooks[1].Sheets['学员信息']; SetExcelWideIn(AObjExecl); //对象信息导入Excel for i := slStus.Count - 1 downto 0 do begin with TStudentInfo(slStus.Objects[i]) do begin AObjExecl.Cells[i+2,1].Value := stuName; AObjExecl.Cells[i+2,2].Value := stuSex; AObjExecl.Cells[i+2,3].Value := stuIDcard; AObjExecl.Cells[i+2,4].Value := stuLogin; AObjExecl.Cells[i+2,5].Value := stuPwd; AObjExecl.Cells[i+2,6].Value := stuArea; AObjExecl.Cells[i+2,7].Value := stuTel; AObjExecl.Cells[i+2,8].Value := stuNote1; end; end; //存储新建Excel ASheet.SaveAs( sExeclFile ); AObjExecl.WorkBooks.Close; AObjExecl.Quit; FDlgSaveExecl.Free; VarClear(AObjExecl); Result := 0; except AObjExecl.WorkBooks.Close; AObjExecl.Quit; AObjExecl.Free; VarClear(AObjExecl); end; end else begin FDlgSaveExecl.Free; Result := 2; end; end; {$ENDIF} end; function TStudentTableOption.ImportStu(slStus: TStringList): Integer; {$IFDEF MSWINDOWS} var sExeclFile : string; AObjExecl : Variant; i : Integer; AStuInfo : TStudentInfo; {$ENDIF} begin Result := 1; {$IFDEF MSWINDOWS} if Assigned(slStus) then begin FDlgOpenExecl := TMyOpenDialog.Create(nil); FDlgOpenExecl.Filter :='Excel files (*.xls)|*.xls'; if FDlgOpenExecl.Execute then begin sExeclFile := FDlgOpenExecl.FileName; AObjExecl := CreateOleObject('Excel.application'); AObjExecl.WorkBooks.Open( sExeclFile ); AObjExecl.Visible := False; try if AObjExecl.WorkSheets[1].UsedRange.Columns.Count <> 8 then begin AObjExecl.WorkBooks.Close; AObjExecl.Quit; varclear(AObjExecl); result := 1; Exit; end; //读取Excel中的记录到学员对象 for i := 2 to AObjExecl.WorkSheets[1].UsedRange.Rows.Count do begin AStuInfo := TStudentInfo.Create; with AStuInfo do begin stuName := AObjExecl.Cells[i,1].Value; stuSex := AObjExecl.Cells[i,2].Value; stuIDcard := AObjExecl.Cells[i,3].Value; stuLogin := AObjExecl.Cells[i,4].Value; stuPwd := AObjExecl.Cells[i,5].Value; stuArea := AObjExecl.Cells[i,6].Value; stuTel := AObjExecl.Cells[i,7].Value; stuNote1 := AObjExecl.Cells[i,8].Value; stuNote2 := AObjExecl.Cells[i,9].Value; slStus.AddObject('' ,AStuInfo); end; end; AObjExecl.WorkBooks.Close; AObjExecl.Quit; VarClear(AObjExecl); FDlgOpenExecl.free; Result := 0; except AObjExecl.WorkBooks.Close; AObjExecl.Quit; VarClear(AObjExecl); end; end else begin FDlgOpenExecl.Free; Result := 2; end; end; {$ENDIF} end; {$IFDEF MSWINDOWS} procedure TStudentTableOption.SetExcelWideIn(AExcel: Variant); begin // 初始化表头 AExcel.Cells[1,1].Value := '姓名'; AExcel.Cells[1,2].Value := '性别'; AExcel.Cells[1,3].Value := '身份证号'; AExcel.Cells[1,4].Value := '登陆名'; AExcel.Cells[1,5].Value := '密码'; AExcel.Cells[1,6].Value := '所在地'; AExcel.Cells[1,7].Value := '联系电话'; AExcel.Cells[1,8].Value := '备注'; //初始化列宽 AExcel.ActiveSheet.Columns[1].ColumnWidth := 10; AExcel.ActiveSheet.Columns[2].ColumnWidth := 8; AExcel.ActiveSheet.Columns[3].ColumnWidth := 20; AExcel.ActiveSheet.Columns[4].ColumnWidth := 20; AExcel.ActiveSheet.Columns[5].ColumnWidth := 15; AExcel.ActiveSheet.Columns[6].ColumnWidth := 8; AExcel.ActiveSheet.Columns[7].ColumnWidth := 12; AExcel.ActiveSheet.Columns[8].ColumnWidth := 15; //将指定列设置成文本格式 AExcel.ActiveSheet.Columns[3].NumberFormatLocal := '@'; AExcel.ActiveSheet.Columns[4].NumberFormatLocal := '@'; AExcel.ActiveSheet.Columns[5].NumberFormatLocal := '@'; AExcel.ActiveSheet.Columns[7].NumberFormatLocal := '@'; AExcel.ActiveSheet.Columns[8].NumberFormatLocal := '@'; end; {$ENDIF} end.
unit uDB2Writer; interface type TDFDB2Writer = class(TSqlDbWriter_c) private FDB2Database: TDb2Database; FWriteLock: TDb2Database; FOptions: TReducedDfOptions; FSQLFormat: TSQLFormat_DB2; FTableSpaceName: string; FLobTableSpaceName: string; FIndexTableSpaceName: string; FPrefetchRows: integer; FIndexMinPctUsed: integer; FIndexPctFree: integer; FTablePctFree: integer; procedure OwnStandardTAParams(out AParams: TTaConstructorParameters_db2; const ATableName: string; const AAccessMode: TTAAccessMode; const AOpenExclusively: boolean; const AIsProviderTableLoad: boolean); procedure OwnTaForLoad(const ATableName: string; const AIsRoot: boolean; out ATAccess: TabstractTableAccess); procedure OwnTaForTableLikeUsage(const ATableName: string; const AOpenExclusively: boolean; out ATAccess: TAbstractTableAccess); procedure CorrectFieldDefs(ATableAccess: TAbstractTableAccess; AFieldInfo: PTDFFieldInfo); procedure LockTable(ADataBase: TSDDatabase; const ATable: string); procedure ConnectToDatabase(ADatabase: TSDDatabase; AOptions: IDfOptions); protected procedure OpenDatabase(AOptions: IDfOptions); override; procedure FreeDatabase; override; procedure GetDbTableNames(ATableNames: TStringList); override; function GetDatabaseType: TDatabaseType; override; function GetSQLFormat: TSQLFormat_a; override; class function GetElemPropRange( AElementType: TDRElementType): TDRElementPropertyRange; override; function GetSupportsReading: boolean; override; function GetForeignKeyParent: boolean; override; function InternalOwnTableAccess(const ATableName: string; var ATableAccess: TAbstractTableAccess; AOpenExclusively: boolean; ARetrieveIndexes: boolean; AAddToRepository: boolean; AWriteOnly: Boolean; const AFilter: string; ARetrieveAutoIncInfo: boolean): boolean; override; procedure InternalOwnDbDDataSet(ATableName: string; ANode: PMdNode; AOpenMode: TDFOpenModes; out AFields: TDbDFSetDataFields); override; public function GetInTransaction: boolean; override; procedure doStartTransaction; override; procedure doRollback; override; procedure SetOptions(AOptions: IDFOptions); override; function GetDbTableName(AName: string): string; override; function GetTableExists(const ATableName: string): boolean; override; end; implementation const CInvalidTableName = '''%s'' is not a valid tablename'; const CMaxTypeMappings = 8; CDb2DbDfTypeMapping: array[0..CMaxTypeMappings] of TDbDfTypeMapping = ( (Db: 'integer'; Df: dtInteger), (Db: 'decimal'; Df: dtInt64), (Db: 'double'; Df: dtDouble), (Db: 'date'; Df: dtDate), (Db: 'time'; Df: dtTime), (Db: 'timestamp'; Df: dtDateTime), (Db: 'varchar'; Df: dtString), (Db: 'clob'; Df: dtString), (Db: 'blob'; Df: dtBlob)); //---------------------------------------------------------------------------- procedure TDFDB2Writer.InternalDoCommit; begin // no inherited; (abstract) try FDB2Database.Commit; except on E: EDB2Error do raise EWriterUsrInfo.Fire(Self, E.Message); end; end; //---------------------------------------------------------------------------- procedure TDFDB2Writer.doRollback; begin // no inherited; (abstract) try FDB2Database.Rollback; except on E: EDB2Error do raise EWriterUsrInfo.Fire(Self, E.Message); end; end; //---------------------------------------------------------------------------- procedure TDFDB2Writer.doStartTransaction; begin // no inherited; (abstract) try FDB2Database.StartTransaction; except on E: EDB2Error do raise EWriterUsrInfo.Fire(Self, E.Message); end; end; //---------------------------------------------------------------------------- function TDFDB2Writer.getDatabaseType: TDatabaseType; begin //no inherited (abstract) Result := tdbtDB2; end; //---------------------------------------------------------------------------- // T42: function TDFDB2Writer.getDataSetCount: integer; begin // no inherited (abstract) Result := FDB2Database.DataSetCount; end; //---------------------------------------------------------------------------- // N,PS T42: function TDFDB2Writer.getDbAttribStr(AAttrib: string): string; begin //no inherited (abstract) Result := TDB2TableAccess.getDbAttribStr(AAttrib); end; //---------------------------------------------------------------------------- // N,PS T42: function TDFDB2Writer.getDbTableName(AName: string): string; begin //no inherited (abstract) Result := TDB2TableAccess.getQryAttribStr(AName); end; //---------------------------------------------------------------------------- class function TDFDB2Writer.getElemPropRange( AElementType: TDRElementType): TDRElementPropertyRange; begin // no inherited (abstract) Result := TDB2TableAccess.getElemPropRange(AElementType); end; //---------------------------------------------------------------------------- // N,PS T42: function TDFDB2Writer.getQryAttribStr(AAttrib: string): string; begin // no inherited (abstract) Result := TDB2TableAccess.getQryAttribStr(AAttrib); end; //---------------------------------------------------------------------------- // N,PS T42: function TDFDB2Writer.getSQLFormat: TSQLFormat_a; begin // no inherited (abstract) Result := FSqlFormat; end; //---------------------------------------------------------------------------- // N,PS T42: procedure TDFDB2Writer.OwnStandardTAParams( out AParams: TTaConstructorParameters_db2; const ATableName: string; const AAccessMode: TTAAccessMode; const AOpenExclusively: boolean; const AIsProviderTableLoad: boolean); begin AParams := TTaConstructorParameters_db2.Create( ATableName, FDB2Database, AAccessMode, FIndexMinPctUsed, FIndexPctFree, FTablePctFree, FIndexTableSpaceName, FLobTableSpaceName, FTableSpaceName, CFreeTableOnDestroy, AOpenExclusively, AIsProviderTableLoad ); end; //---------------------------------------------------------------------------- // N,PS T42: procedure TDFDB2Writer.OwnClone(out AClone: TAbstractWriter); begin //no inherited (abstract) if OpenExclusively then raise EWriterIntern.Fire(self, 'Can not clone if opended exclusively'); AClone := TDFDB2Writer.Create; AClone.SetOptions(Self.GetOptions); end; //---------------------------------------------------------------------------- // N,PS T42: function TDFDB2Writer.getSupportsReading: boolean; begin // no inherited (abstract) Result := true; end; //---------------------------------------------------------------------------- //2004-01-04 18:39 N,PS T42: procedure TDFDB2Writer.DetermineDataType(const AFieldInfoQuery: TDataSet; out ADataType: TDataType; out ALength: integer; out AFieldName: string); var lDbTypeString: string; i: integer; begin // no inherited (abstract) checkAssigned(AFieldInfoQuery); checkEquals(AFieldInfoQuery.Fields.count, 3, 'invalid query result received for determining field information'); checkEquals(AFieldInfoQuery.bof, false, 'bof reached in query result for determining field information'); AFieldName := AFieldInfoQuery.Fields[0].AsString; ALength := AFieldInfoQuery.Fields[2].AsInteger; lDbTypeString := AnsiLowerCase(AFieldInfoQuery.Fields[1].AsString); ADataType := dtUnknown; for i := 0 to CMaxTypeMappings do with CDb2DbDfTypeMapping[i] do if lDbTypeString = Db then begin ADataType := Df; break; end; if ADataType = dtUnknown then raise EWriterUsrInfo.FireFmt( Self, LangHdl.Translate(STdftUnknown), [AFieldName, lDbTypeString]); if ADataType in [dtInteger, dtInt64, dtDate, dtTime, dtDateTime, dtDouble] then ALength := 0; end; //---------------------------------------------------------------------------- // N,PS T42: function TDFDB2Writer.getFieldInfoQuery(const ATableName: string): string; begin // no inherited (abstract) Result := 'SELECT COLNAME , TYPENAME , LENGTH ' + 'FROM SYSCAT.COLUMNS ' + 'WHERE TABNAME = ''%s'' ' + 'ORDER BY COLNO ASC'; Result := Format(Result, [ATableName]) end; //---------------------------------------------------------------------------- // N,PS T42: function TDFDB2Writer.CreateTableAccessForDataStructureCheck(AFieldInfo: PTDFFieldInfo): TAbstractTableAccess; var lNode: PMdNode; begin checkAssigned(AFieldInfo); lNode := CreateMetaNodesForDataStructureCheck(AFieldInfo); Result := TDb2CheckDataStructureTableAccess.Create(self, lNode); //owns lnode end; //---------------------------------------------------------------------------- // N,PS T42: procedure TDFDB2Writer.TransferFieldProperties(ASource, ADest: TDataSet); var i: integer; lSrcName, lDestName: string; begin checkAssigned(ASource); checkAssigned(ADest); checkEquals(ASource.FieldDefs.Count, ADest.FieldDefs.Count, 'number of FieldDefs different'); ADest.FieldDefs.BeginUpdate; try for i := 0 to ASource.FieldDefs.Count - 1 do begin lSrcName := ASource.FieldDefs[i].Name; lDestName := ADest.FieldDefs[i].Name; checkEquals(lSrcName, lDestName, Fmt('Field names differ on position %d (%s <> %s)', [i, lSrcName, lDestName])); ADest.FieldDefs[i].DataType := ASource.FieldDefs[i].DataType; ADest.FieldDefs[i].Size := ASource.FieldDefs[i].Size; end; finally ADest.FieldDefs.EndUpdate; end; end; //---------------------------------------------------------------------------- // N,PS T42: function TDFDB2Writer.getConstraintsQuery(const ATableName: string): string; begin // no inherited (abstract) Result := uDfDb2WriterUtil.getConstraintsQuery(tctForeignKey, ATableName); end; //---------------------------------------------------------------------------- // N,PS T42: procedure TDFDB2Writer.OwnTaForTableLikeUsage(const ATableName: string; const AOpenExclusively: boolean; out ATAccess: TAbstractTableAccess); var lInitParams: TTaConstructorParameters_db2; begin OwnStandardTAParams(lInitParams, ATableName, tamReadWrite, AOpenExclusively, not CIsProviderTableLoad); try ATAccess := TDB2TableAccess.Create(Self, lInitParams); finally FreeAndNil(lInitParams); end; end; //---------------------------------------------------------------------------- // N,PS: function TDFDB2Writer.GetLockQuery(const ATableName: string): string; begin Result := 'LOCK TABLE ' + ATableName + ' IN EXCLUSIVE MODE'; end; end.
unit Threads; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, System.Threading; type TfThreads = class(TForm) Progressbar: TProgressBar; btnProcessar: TButton; grpbThread2: TGroupBox; Label2: TLabel; Label4: TLabel; lblContador2: TLabel; edtTimeThread2: TEdit; grpbThread1: TGroupBox; Label5: TLabel; Label3: TLabel; lblContador1: TLabel; edtTimeThread1: TEdit; lblProgresso: TLabel; procedure btnProcessarClick(Sender: TObject); private procedure CountThread1; procedure CountThread2; public end; var fThreads: TfThreads; implementation {$R *.dfm} procedure TfThreads.btnProcessarClick(Sender: TObject); var Tasks: array [0 .. 1] of ITask; begin Progressbar.Position := 0; Progressbar.Max := 200; Tasks[0] := TTask.Create(CountThread1); Tasks[0].Start; Tasks[1] := TTask.Create(CountThread2); Tasks[1].Start; end; procedure TfThreads.CountThread1; var i: Integer; begin for i := 0 to 100 do begin Sleep(StrToInt(edtTimeThread1.Text)); lblContador1.Caption := i.ToString; Progressbar.Position := Progressbar.Position + 1; Application.ProcessMessages; end; end; procedure TfThreads.CountThread2; var i: Integer; begin for i := 0 to 100 do begin Sleep(StrToInt(edtTimeThread2.Text)); lblContador2.Caption := i.ToString; Progressbar.Position := Progressbar.Position + 1; lblProgresso.Caption := 'Progresso: ' + Progressbar.Position.ToString; Application.ProcessMessages; end; end; end.
unit StackAp; interface uses error; type TElement = integer; { replacable element type } const MAXS = 100; //maximal size type arr= array[1..MAXS] of TElement; pTStack = ^TStack; TStack = record last,MAXS: integer; E: ^arr; end; procedure InitStack (var S: pTStack; MAXS1:integer); procedure CleanUpStack (var S: pTStack); procedure push (var S: pTStack; E: TElement); function pop (var S: pTStack): TElement; function top (var S: pTStack): TElement; function IsStackEmpty (var S: pTStack): boolean; implementation procedure InitStack (var S: pTStack; MAXS1:integer); begin GetMem(S,sizeof(TStack)); {'GetMemory' is system dependent} S^.last := 0; S^.MAXS := MAXS1; GetMem(S^.E,sizeof(TElement)*MAXS1); end; procedure CleanUpStack (var S:pTStack); begin FreeMem(S^.E, sizeof(TElement)*S^.MAXS); FreeMem(S),sizeof(TStack); end; procedure push (var S: pTStack; E: TElement); begin S^.last := S^.last + 1; if S^.last > MAXS then FatalError('stack overflow!'); S^.E^[S^.last] := E; end; function pop (var S: pTStack): TElement; begin if IsStackEmpty(S) then FatalError('stack underflow!'); pop := S^.E^[S^.last]; S^.last := S^.last-1; end; function top (var S: pTStack): TElement; begin if IsStackEmpty(S) then LiteError('Stack is empty, cannot return top.') else top := S^.E^[S^.last]; end; function IsStackEmpty (var S: pTStack): boolean; begin IsStackEmpty := (S^.last=0); end; end.
unit CargoDataUn; interface uses SysUtils, Classes, FMTBcd, DB, Provider, osSQLDataSetProvider, SqlExpr, osUtils, osCustomDataSetProvider, osSQLDataSet; type TCargoData = class(TDataModule) MasterDataSet: TosSQLDataset; MasterProvider: TosSQLDataSetProvider; MasterDataSetIDCARGO: TIntegerField; MasterDataSetNOME: TStringField; MasterDataSetAREAATUACAO: TStringField; private public procedure Validate(PDataSet: TDataSet); end; var CargoData: TCargoData; implementation uses osErrorHandler, SQLMainData; {$R *.dfm} procedure TCargoData.Validate(PDataSet: TDataSet); begin with PDataSet, HError do begin Clear; CheckEmpty(FieldByName('Nome')); CheckEmpty(FieldByName('AreaAtuacao')); Check; end; end; initialization OSRegisterClass(TCargoData); end.
unit uTest; interface uses DUnitX.TestFramework, SSHCommand; type [TestFixture] TMyTestObject = class(TObject) public [Setup] procedure Setup; [TearDown] procedure TearDown; [TEST] procedure TestParameterLineCommandStandardPort; [TEST] procedure TestParameterLineCommandOtherPort; [TEST] procedure TestParameterLineSCPToRemoteStandardPort; [TEST] procedure TestParameterLineSCPFromRemoteStandardPort; end; implementation procedure TMyTestObject.Setup; begin end; procedure TMyTestObject.TearDown; begin end; procedure TMyTestObject.TestParameterLineSCPFromRemoteStandardPort; var LSSHCommander : TSSHCommand; LGoodLine : string; begin LSSHCommander.HostName := 'example.com'; LSSHCommander.UserName := 'myuser'; LSSHCommander.KeyFile := '~/.ssh/mykey'; LSSHCommander.Source := '/home/myuser/list1.txt'; LSSHCommander.Destination := 'c:\Users\bill\'; // scp -P 22 -i keyfile user@remotehost:/home/myuser/file1.csv c:\tools\ LGoodLine := '-P 22 -i ~/.ssh/mykey myuser@example.com:/home/myuser/list1.txt c:\Users\bill\'; Assert.AreEqual(LGoodLine, LSSHCommander.GetSCPFromRemoteParameterLine, 'Parameterlist scp from remote standardport incorrect'); end; procedure TMyTestObject.TestParameterLineSCPToRemoteStandardPort; var LSSHCommander : TSSHCommand; LGoodLine : string; begin LSSHCommander.HostName := 'example.com'; LSSHCommander.UserName := 'myuser'; LSSHCommander.KeyFile := '~/.ssh/mykey'; LSSHCommander.Source := 'c:\Users\bill\list1.txt'; LSSHCommander.Destination := '/home/myuser/list2.txt'; // scp -P 22 -i keyfile c:\Users\bill\list1.txt user@remotehost:/home/myuser/file1.csv LGoodLine := '-P 22 -i ~/.ssh/mykey c:\Users\bill\list1.txt myuser@example.com:/home/myuser/list2.txt'; Assert.AreEqual(LGoodLine, LSSHCommander.GetSCPToRemoteParameterLine, 'Parameterlist scp to remote standardport incorrect'); end; procedure TMyTestObject.TestParameterLineCommandOtherPort; var LSSHCommander : TSSHCommand; LGoodLine : string; begin LSSHCommander.HostName := 'example.com'; LSSHCommander.UserName := 'myuser'; LSSHCommander.PortNum := 12322; LSSHCommander.KeyFile := '~/.ssh/mykey'; LSSHCommander.Command := 'MyCommand'; LSSHCommander.CommandParameter := 'DoNothing'; // ssh remotehost -p 12322 -i keyfile -l user -t "command commandparameter" LGoodline := 'example.com -p 12322 -i ~/.ssh/mykey -l myuser -t "MyCommand DoNothing"'; Assert.AreEqual(LGoodLine, LSSHCommander.GetCommandParameterLine, 'Parameterlist Command other port incorrect'); end; procedure TMyTestObject.TestParameterLineCommandStandardPort; var LSSHCommander : TSSHCommand; LGoodLine : string; begin LSSHCommander.HostName := 'example.com'; LSSHCommander.UserName := 'myuser'; LSSHCommander.KeyFile := '~/.ssh/mykey'; LSSHCommander.Command := 'MyCommand'; LSSHCommander.CommandParameter := 'DoNothing'; // ssh remotehost -p 22 -i keyfile -l user -t "command commandparameter" LGoodline := 'example.com -p 22 -i ~/.ssh/mykey -l myuser -t "MyCommand DoNothing"'; Assert.AreEqual(LGoodLine, LSSHCommander.GetCommandParameterLine, 'Parameterlist Command standardport incorrect'); end; initialization TDUnitX.RegisterTestFixture(TMyTestObject); end.
unit uMainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DB, IBDatabase, IBExtract; type TMainForm = class(TForm) ibDatabase: TIBDatabase; ibTransaction: TIBTransaction; ibExtract: TIBExtract; gbSettings: TGroupBox; gbConnection: TGroupBox; bConnect: TButton; lServer: TLabel; editServer: TEdit; lDB: TLabel; editDB: TEdit; lUserName: TLabel; editUserName: TEdit; lPassword: TLabel; editPassword: TEdit; editObjectName: TEdit; lObjectName: TLabel; chkbAllDatabase: TCheckBox; bFind: TButton; gbOutput: TGroupBox; mOutput: TMemo; procedure bConnectClick(Sender: TObject); procedure bFindClick(Sender: TObject); procedure chkbAllDatabaseClick(Sender: TObject); private { Private declarations } LastObjectName : String; procedure GetDDLForObject( const ObjectName : String ); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.bConnectClick(Sender: TObject); const UserNameDB : String = 'user_name='; PasswordDB : String = 'password='; begin ibDatabase.Connected := false; if ( Trim( editServer.Text ) <> '' ) then ibDatabase.DatabaseName := Trim( editServer.Text ) + ':' + Trim( editDB.Text ) else ibDatabase.DatabaseName := Trim( editDB.Text ); ibDatabase.Params.Add( UserNameDB + Trim( editUserName.Text ) ); ibDatabase.Params.Add( PasswordDB + Trim( editPassword.Text ) ); try ibDatabase.Connected := true; LastObjectName := ''; mOutput.Lines.Text := ''; bFind.Enabled := ibDatabase.Connected; MessageDlg( 'Подключено!', mtInformation, [mbOk], 0 ); except on E : Exception do MessageDlg( Format( 'Не удалось подключиться к базе данных!%s"%s"', [sLineBreak, E.Message] ), mtError, [mbOk], 0 ); end; end; procedure TMainForm.bFindClick(Sender: TObject); begin if ( not chkbAllDatabase.Checked and ( Trim( editObjectName.Text ) = '' ) ) then MessageDlg( 'Не введено имя объекта!', mtError, [mbOk], 0 ) else if ( ( mOutput.Lines.Text <> '' ) and ( ( chkbAllDatabase.Checked and ( LastObjectName = '' ) ) or ( LastObjectName = Trim( editObjectName.Text ) ) ) ) then MessageDlg( 'Объект уже получен!', mtInformation, [mbOk], 0 ) else begin LastObjectName := Trim( editObjectName.Text ); GetDDLForObject( LastObjectName ); end; end; procedure TMainForm.chkbAllDatabaseClick(Sender: TObject); begin if ( chkbAllDatabase.Checked ) then editObjectName.Text := ''; editObjectName.Enabled := not chkbAllDatabase.Checked; end; procedure TMainForm.GetDDLForObject( const ObjectName : String ); var ObjectType : TExtractObjectTypes; begin mOutput.Clear(); if ( ObjectName = '' ) then begin ibExtract.Items.Clear(); ibExtract.ExtractObject( eoDatabase, '', [] ); mOutput.Lines.Add( ibExtract.Items.Text ); end else for ObjectType := Low(TExtractObjectTypes) to High(TExtractObjectTypes) do if not ( ObjectType in [eoDatabase, eoRole, eoData] ) then begin ibExtract.Items.Clear(); ibExtract.ExtractObject( ObjectType, ObjectName, [] ); if ( Trim( ibExtract.Items.Text ) <> '' ) then mOutput.Lines.Add( ibExtract.Items.Text ); end; end; end.
unit UVariaveis; interface uses IniFiles,Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, TemplateCadastroArquivoIni, StdCtrls, Buttons, ExtCtrls,DBClient, Db; function getLastId(cds:TClientDataSet;CampoPrimario:String): integer; procedure LoadVariables(); const XMLAreaProcesso: String = 'AreaProcesso.xml'; XMLFormaRepresentacao: String = 'FormaRepresentacao.xml'; XMLMetaGenerica: String = 'MetaGenerica.xml'; XMLModeloReferencia:String='ModeloReferencia.xml'; XMLNivelCapacidade:String='NivelCapacidade.xml'; XMLNivelCapacidadeXMetasGenericas:String= 'NivelCapacidadeXMetasGenericas.xml'; XMLMetasEspecificas:String='MetasEspecificas.xml'; XMLPraticasEspecificas:String='PraticasEspecificas.xml'; XMLCategoria:String='Categoria.xml'; XMLNivelMaturidade:String='NivelMaturidade.xml'; XMLNivelMaturidadeXAreaProcesso:String='NivelMaturidadeXAreaProcesso.xml'; var PathBaseDadosXML:String; implementation procedure LoadVariables(); var config: TIniFile; begin Try {Cria o ini em tempo de execucao} config := TIniFile.Create(ExtractFilePath(Application.ExeName)+'\config.ini'); PathBaseDadosXML := config.readstring('configuracoes', 'edtPathBaseDadosXML', ''); Finally config.Free; End; end; function getLastId(cds:TClientDataSet;CampoPrimario:String): integer; var cdsTemp:TClientDataSet; begin if cds.IsEmpty then Result :=1 else begin Try cdsTemp := TClientDataSet.Create(nil); cdsTemp.CloneCursor(cds,false,false); cdsTemp.Last(); Result := cdsTemp.FieldByName(CampoPrimario).AsInteger Finally cdsTemp.Free(); End; end; end; end.
unit DPM.IDE.PackageDetailsFrame; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Imaging.pngimage, Vcl.Themes, DPM.Core.Types, DPM.Core.Configuration.Interfaces, DPM.Core.Package.Interfaces, DPM.Core.Logging, DPM.IDE.Logger, DPM.Core.Options.Search, DPM.IDE.PackageDetailsPanel, DPM.IDE.IconCache, DPM.IDE.Types, Spring.Container, Spring.Collections, VSoft.Awaitable, SVGInterfaces, ToolsAPI; {$I ..\DPMIDE.inc} type //implemented by the EditorViewFrame IPackageSearcher = interface ['{4FBB9E7E-886A-4B7D-89FF-FA5DBC9D93FD}'] function GetSearchOptions : TSearchOptions; function SearchForPackagesAsync(const options : TSearchOptions) : IAwaitable<IList<IPackageSearchResultItem>>;overload; function SearchForPackages(const options : TSearchOptions) : IList<IPackageSearchResultItem>;overload; function GetCurrentPlatform : string; procedure SaveBeforeChange; procedure PackageInstalled(const package : IPackageSearchResultItem); procedure PackageUninstalled(const package : IPackageSearchResultItem); end; TPackageDetailsFrame = class(TFrame) sbPackageDetails : TScrollBox; pnlPackageId : TPanel; pnlInstalled : TPanel; lblPackageId : TLabel; imgPackageLogo : TImage; pnlVersion : TPanel; Label1 : TLabel; txtInstalledVersion : TEdit; btnUninstall : TButton; lblVersionTitle : TLabel; cboVersions : TComboBox; btnInstallOrUpdate : TButton; procedure cboVersionsMeasureItem(Control : TWinControl; Index : Integer; var Height : Integer); procedure cboVersionsDrawItem(Control : TWinControl; Index : Integer; Rect : TRect; State : TOwnerDrawState); procedure cboVersionsChange(Sender : TObject); procedure btnInstallOrUpdateClick(Sender : TObject); procedure btnUninstallClick(Sender : TObject); private FContainer : TContainer; FIconCache : TDPMIconCache; FPackageSearcher : IPackageSearcher; FPackageMetaData : IPackageSearchResultItem; FDetailsPanel : TPackageDetailsPanel; FCurrentTab : TCurrentTab; FCancellationTokenSource : ICancellationTokenSource; FRequestInFlight : boolean; FVersionsDelayTimer : TTimer; FConfiguration : IConfiguration; FLogger : IDPMIDELogger; FClosing : boolean; FIncludePreRelease : boolean; FPackageInstalledVersion : string; FPackageId : string; FProjectFile : string; FCurrentPlatform : TDPMPlatform; FIDEStyleServices : TCustomStyleServices; protected procedure SetIncludePreRelease(const Value : boolean); procedure VersionsDelayTimerEvent(Sender : TObject); procedure OnDetailsUriClick(Sender : TObject; const uri : string; const element : TDetailElement); procedure Loaded; override; public constructor Create(AOwner : TComponent); override; procedure Init(const container : TContainer; const iconCache : TDPMIconCache; const config : IConfiguration; const packageSearcher : IPackageSearcher; const projectFile : string); procedure Configure(const value : TCurrentTab; const preRelease : boolean); procedure SetPackage(const package : IPackageSearchResultItem); procedure SetPlatform(const platform : TDPMPlatform); procedure ViewClosing; procedure ThemeChanged; property IncludePreRelease : boolean read FIncludePreRelease write SetIncludePreRelease; end; implementation {$R *.dfm} uses System.StrUtils, WinApi.ShellApi, SVGGraphic, DPM.Core.Utils.Strings, DPM.Core.Dependency.Version, DPM.Core.Repository.Interfaces, DPM.Core.Options.Install, DPM.Core.Options.UnInstall; const cLatestStable = 'Latest stable '; cLatestPrerelease = 'Latest prerelease '; { TPackageDetailsFrame } procedure TPackageDetailsFrame.btnInstallOrUpdateClick(Sender : TObject); var packageInstaller : IPackageInstaller; options : TInstallOptions; installResult : boolean; newVersion : TPackageVersion; sVersion : string; begin btnInstallOrUpdate.Enabled := false; installResult := false; try if FRequestInFlight then FCancellationTokenSource.Cancel; while FRequestInFlight do Application.ProcessMessages; FCancellationTokenSource.Reset; FLogger.Clear; FLogger.StartInstall(FCancellationTokenSource); FPackageSearcher.SaveBeforeChange; if btnInstallOrUpdate.Caption = 'Update' then begin //get the version from the current item. sVersion := cboVersions.Items[cboVersions.ItemIndex]; if TStringUtils.StartsWith(sVersion, cLatestPrerelease, true) then Delete(sVersion, 1, Length(cLatestPrerelease)) else if TStringUtils.StartsWith(sVersion, cLatestStable, true) then Delete(sVersion, 1, Length(cLatestStable)); newVersion := TPackageVersion.Parse(sVersion); end else newVersion := TPackageVersion.Parse(FPackageMetaData.Version); FLogger.Information('Installing package ' + FPackageMetaData.Id + ' - ' + newVersion.ToString + ' [' + FPackageSearcher.GetCurrentPlatform + ']'); options := TInstallOptions.Create; options.ConfigFile := FConfiguration.FileName; options.PackageId := FPackageMetaData.Id; options.Version := newVersion; options.ProjectPath := FProjectFile; options.Platforms := [ProjectPlatformToDPMPlatform(FPackageSearcher.GetCurrentPlatform)]; options.Prerelease := FIncludePreRelease; options.CompilerVersion := IDECompilerVersion; //make sure we have the correct metadata for the new version FPackageMetaData := FPackageSearcher.SearchForPackages(options).FirstOrDefault; //install will fail if a package is already installed, unless you specify force. if btnInstallOrUpdate.Caption = 'Update' then options.Force := true; packageInstaller := FContainer.Resolve<IPackageInstaller>; installResult := packageInstaller.Install(FCancellationTokenSource.Token, options); if installResult then begin FPackageMetaData.InstalledVersion := FPackageMetaData.Version; FPackageMetaData.Installed := true; FPackageInstalledVersion := FPackageMetaData.InstalledVersion; FLogger.Information('Package ' + FPackageMetaData.Id + ' - ' + newVersion.ToString + ' [' + FPackageSearcher.GetCurrentPlatform + '] installed.'); FPackageSearcher.PackageInstalled(FPackageMetaData); SetPackage(FPackageMetaData); end else FLogger.Error('Package ' + FPackageMetaData.Id + ' - ' + newVersion.ToString + ' [' + FPackageSearcher.GetCurrentPlatform + '] did not install.'); finally btnInstallOrUpdate.Enabled := true; FLogger.EndInstall(installResult); end; end; procedure TPackageDetailsFrame.btnUninstallClick(Sender : TObject); var packageInstaller : IPackageInstaller; options : TUnInstallOptions; uninstallResult : boolean; begin btnUninstall.Enabled := false; uninstallResult := false; try if FRequestInFlight then FCancellationTokenSource.Cancel; while FRequestInFlight do Application.ProcessMessages; FCancellationTokenSource.Reset; FLogger.Clear; FLogger.StartUnInstall(FCancellationTokenSource); FPackageSearcher.SaveBeforeChange; FLogger.Information('UnInstalling package ' + FPackageMetaData.Id + ' - ' + FPackageMetaData.Version + ' [' + FPackageSearcher.GetCurrentPlatform + ']'); options := TUnInstallOptions.Create; options.ConfigFile := FConfiguration.FileName; options.PackageId := FPackageMetaData.Id; options.Version := TPackageVersion.Parse(FPackageMetaData.Version); options.ProjectPath := FProjectFile; options.Platforms := [ProjectPlatformToDPMPlatform(FPackageSearcher.GetCurrentPlatform)]; packageInstaller := FContainer.Resolve<IPackageInstaller>; uninstallResult := packageInstaller.UnInstall(FCancellationTokenSource.Token, options); if uninstallResult then begin FPackageMetaData.InstalledVersion := FPackageMetaData.Version; FPackageMetaData.Installed := true; FPackageInstalledVersion := FPackageMetaData.InstalledVersion; FLogger.Information('Package ' + FPackageMetaData.Id + ' - ' + FPackageMetaData.Version + ' [' + FPackageSearcher.GetCurrentPlatform + '] uninstalled.'); FPackageSearcher.PackageUninstalled(FPackageMetaData); SetPackage(nil); end else FLogger.Error('Package ' + FPackageMetaData.Id + ' - ' + FPackageMetaData.Version + ' [' + FPackageSearcher.GetCurrentPlatform + '] did not uninstall.'); finally btnUninstall.Enabled := true; FLogger.EndUnInstall(uninstallResult); end; end; procedure TPackageDetailsFrame.cboVersionsChange(Sender : TObject); var searchOptions : TSearchOptions; package : IPackageSearchResultItem; sVersion : string; begin searchOptions := FPackageSearcher.GetSearchOptions; searchOptions.SearchTerms := FPackageMetaData.Id; sVersion := cboVersions.Items[cboVersions.ItemIndex]; if TStringUtils.StartsWith(sVersion, cLatestPrerelease, true) then Delete(sVersion, 1, Length(cLatestPrerelease)) else if TStringUtils.StartsWith(sVersion, cLatestStable, true) then Delete(sVersion, 1, Length(cLatestStable)); searchOptions.Version := TPackageVersion.Parse(sVersion); searchOptions.Prerelease := true; searchOptions.Commercial := true; searchOptions.Trial := true; FPackageSearcher.SearchForPackagesAsync(searchOptions) .OnException( procedure(const e : Exception) begin FRequestInFlight := false; if FClosing then exit; FLogger.Error(e.Message); end) .OnCancellation( procedure begin FRequestInFlight := false; //if the view is closing do not do anything else. if FClosing then exit; FLogger.Debug('Cancelled searching for packages.'); end) .Await( procedure(const theResult : IList<IPackageSearchResultItem>) begin FRequestInFlight := false; //if the view is closing do not do anything else. if FClosing then exit; // FLogger.Debug('Got search results.'); package := theResult.FirstOrDefault; SetPackage(package); end); end; procedure TPackageDetailsFrame.cboVersionsDrawItem(Control : TWinControl; Index : Integer; Rect : TRect; State : TOwnerDrawState); begin cboVersions.Canvas.FillRect(Rect); if (cboVersions.Items.Count = 0) or (index < 0) then exit; if odComboBoxEdit in State then cboVersions.Canvas.TextOut(Rect.Left + 1, Rect.Top + 1, cboVersions.Items[Index]) //Visual state of the text in the edit control else cboVersions.Canvas.TextOut(Rect.Left + 2, Rect.Top, cboVersions.Items[Index]); //Visual state of the text(items) in the deployed list if odComboBoxEdit in State then exit; if Integer(cboVersions.Items.Objects[index]) <> 0 then begin cboVersions.Canvas.Pen.Color := clGray; cboVersions.Canvas.MoveTo(Rect.Left, Rect.Bottom - 1); cboVersions.Canvas.LineTo(Rect.Right, Rect.Bottom - 1); end; end; procedure TPackageDetailsFrame.cboVersionsMeasureItem(Control : TWinControl; Index : Integer; var Height : Integer); begin if (cboVersions.Items.Count = 0) or (index < 0) then exit; if cboVersions.Items.Objects[index] <> nil then Inc(Height, 4); end; procedure TPackageDetailsFrame.Configure(const value : TCurrentTab; const preRelease : boolean); begin if (FCurrentTab <> value) or (FIncludePreRelease <> preRelease) then begin FPackageMetaData := nil; FPackageId := ''; FDetailsPanel.SetDetails(nil); FCurrentTab := value; FIncludePreRelease := preRelease; case FCurrentTab of TCurrentTab.Installed : begin btnInstallOrUpdate.Caption := 'Update'; end; TCurrentTab.Updates : begin btnInstallOrUpdate.Caption := 'Update'; end; TCurrentTab.Search : begin btnInstallOrUpdate.Caption := 'Install'; end; TCurrentTab.Conflicts : ; end; SetPackage(nil); end; end; constructor TPackageDetailsFrame.Create(AOwner : TComponent); begin inherited; //not published in older versions, so get removed when we edit in older versions. {$IFDEF STYLEELEMENTS} StyleElements := [seFont]; {$ENDIF} FDetailsPanel := TPackageDetailsPanel.Create(AOwner); FDetailsPanel.ParentColor := false; FDetailsPanel.ParentBackground := false; FDetailsPanel.DoubleBuffered := true; FDetailsPanel.Align := alTop; FDetailsPanel.Height := 200; FDetailsPanel.Top := pnlVErsion.Top + pnlVErsion.Top + 20; FDetailsPanel.OnUriClick := Self.OnDetailsUriClick; FDetailsPanel.Parent := sbPackageDetails; FCurrentPlatform := TDPMPlatform.UnknownPlatform; FVersionsDelayTimer := TTimer.Create(AOwner); FVersionsDelayTimer.Interval := 200; FVersionsDelayTimer.Enabled := false; FVersionsDelayTimer.OnTimer := VersionsDelayTimerEvent; FCancellationTokenSource := TCancellationTokenSourceFactory.Create; ThemeChanged; end; procedure TPackageDetailsFrame.Init(const container : TContainer; const iconCache : TDPMIconCache; const config : IConfiguration; const packageSearcher : IPackageSearcher; const projectFile : string); begin FContainer := container; FIconCache := iconCache; FConfiguration := config; FLogger := FContainer.Resolve<IDPMIDELogger>; FPackageSearcher := packageSearcher; FProjectFile := projectFile; SetPackage(nil); end; procedure TPackageDetailsFrame.Loaded; begin inherited; // sbPackageDetails.Color := Self.Color; // sbPackageDetails.ParentBackground := false; // // FDetailsPanel.ParentColor := true; // FDetailsPanel.ParentBackground := false; // FDetailsPanel.Color := Self.Color; // FDetailsPanel.Font.Assign(Self.Font); end; procedure TPackageDetailsFrame.OnDetailsUriClick(Sender : TObject; const uri : string; const element : TDetailElement); begin case element of deNone : ; deLicense, deProjectUrl, deReportUrl : ShellExecute(Application.Handle, 'open', PChar(uri), nil, nil, SW_SHOWNORMAL); deTags : ; end; end; procedure TPackageDetailsFrame.SetIncludePreRelease(const Value : boolean); begin if FIncludePreRelease <> Value then begin FIncludePreRelease := Value; SetPackage(FPackageMetaData); end; end; procedure TPackageDetailsFrame.SetPackage(const package : IPackageSearchResultItem); var logo : IPackageIconImage; bFetchVersions : boolean; graphic : TGraphic; begin FVersionsDelayTimer.Enabled := false; if FRequestInFlight then FCancellationTokenSource.Cancel; FPackageMetaData := package; if package <> nil then begin if (package.Id <> FPackageId) then begin bFetchVersions := true; FPackageId := package.Id; if package.Installed then FPackageInstalledVersion := package.InstalledVersion else FPackageInstalledVersion := ''; end else begin //same id, so we might just be displaying a new version. //since we're just getting the item from the feed rather than the project //it won't have installed or installed version set. package.InstalledVersion := FPackageInstalledVersion; if package.Installed then FPackageInstalledVersion := package.Version else begin if package.Version = FPackageInstalledVersion then package.Installed := true; end; bFetchVersions := false; //we already have them. end; lblPackageId.Caption := package.Id; logo := FIconCache.Request(package.Id); if logo = nil then logo := FIconCache.Request('missing_icon'); if logo <> nil then begin graphic := logo.ToGraphic; try imgPackageLogo.Picture.Assign(graphic); imgPackageLogo.Visible := true; finally graphic.Free; end; end else imgPackageLogo.Visible := false; case FCurrentTab of TCurrentTab.Search : begin pnlInstalled.Visible := FPackageInstalledVersion <> ''; if pnlInstalled.Visible then begin btnInstallOrUpdate.Caption := 'Update' end else begin btnInstallOrUpdate.Caption := 'Install'; end; end; TCurrentTab.Installed : begin pnlInstalled.Visible := true; btnInstallOrUpdate.Caption := 'Update'; end; TCurrentTab.Updates : begin pnlInstalled.Visible := true; btnInstallOrUpdate.Caption := 'Update'; end; TCurrentTab.Conflicts : ; end; txtInstalledVersion.Text := FPackageInstalledVersion; btnInstallOrUpdate.Enabled := (not package.Installed) or (package.InstalledVersion <> package.Version); sbPackageDetails.Visible := true; FVersionsDelayTimer.Enabled := bFetchVersions; end else begin sbPackageDetails.Visible := false; // pnlPackageId.Visible := false; // pnlInstalled.Visible := false; // pnlVErsion.Visible := false; end; FDetailsPanel.SetDetails(package); end; procedure TPackageDetailsFrame.SetPlatform(const platform : TDPMPlatform); begin if platform <> FCurrentPlatform then begin end; end; procedure TPackageDetailsFrame.ThemeChanged; {$IFDEF THEMESERVICES} var ideThemeSvc : IOTAIDEThemingServices; {$ENDIF} begin {$IFDEF THEMESERVICES} ideThemeSvc := (BorlandIDEServices as IOTAIDEThemingServices); ideThemeSvc.ApplyTheme(Self); FIDEStyleServices := ideThemeSvc.StyleServices; {$ELSE} FIDEStyleServices := Vcl.Themes.StyleServices; {$ENDIF} sbPackageDetails.Color := FIDEStyleServices.GetSystemColor(clWindow); {$IF CompilerVersion >= 32.0} sbPackageDetails.ParentColor := false; sbPackageDetails.ParentBackground := false; sbPackageDetails.StyleElements := [seFont]; sbPackageDetails.Color := FIDEStyleServices.GetSystemColor(clWindow); pnlPackageId.StyleElements := [seFont]; pnlPackageId.Color := sbPackageDetails.Color; pnlInstalled.StyleElements := [seFont]; pnlInstalled.Color := sbPackageDetails.Color; pnlVersion.StyleElements := [seFont]; pnlVersion.Color := sbPackageDetails.Color; FDetailsPanel.StyleElements := [seFont]; FDetailsPanel.Color := sbPackageDetails.Color; FDetailsPanel.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText); {$ELSE} sbPackageDetails.Color := FIDEStyleServices.GetSystemColor(clWindow); FDetailsPanel.Color := FIDEStyleServices.GetSystemColor(clWindow); FDetailsPanel.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText); {$IFEND} end; procedure TPackageDetailsFrame.VersionsDelayTimerEvent(Sender : TObject); var versions : IList<TPackageVersion>; repoManager : IPackageRepositoryManager; options : TSearchOptions; config : IConfiguration; lStable : string; lPre : string; sVersion : string; sInstalledVersion : string; begin FVersionsDelayTimer.Enabled := false; if FRequestInFlight then FCancellationTokenSource.Cancel; while FRequestInFlight do Application.ProcessMessages; FCancellationTokenSource.Reset; cboVersions.Clear; repoManager := FContainer.Resolve<IPackageRepositoryManager>; options := TSearchOptions.Create; options.CompilerVersion := IDECompilerVersion; options.AllVersions := true; options.SearchTerms := FPackageMetaData.Id; if FCurrentTab = TCurrentTab.Installed then options.Prerelease := true //should this be checking the package meta data version for pre-release? else options.Prerelease := FIncludePreRelease; options.Platforms := [FCurrentPlatform]; config := FConfiguration; sInstalledVersion := FPackageInstalledVersion; TAsync.Configure < IList<TPackageVersion> > ( function(const cancelToken : ICancellationToken) : IList<TPackageVersion> begin result := repoManager.GetPackageVersions(cancelToken, options, config); end, FCancellationTokenSource.Token) .OnException( procedure(const e : Exception) begin FRequestInFlight := false; if FClosing then exit; FLogger.Error(e.Message); end) .OnCancellation( procedure begin FRequestInFlight := false; //if the view is closing do not do anything else. if FClosing then exit; FLogger.Debug('Cancelled getting package versions.'); end) .Await( procedure(const theResult : IList<TPackageVersion>) var version : TPackageVersion; begin FRequestInFlight := false; //if the view is closing do not do anything else. if FClosing then exit; versions := theResult; FLogger.Debug('Got package versions .'); cboVersions.Items.BeginUpdate; try cboVersions.Clear; if versions.Any then begin if options.Prerelease then begin version := versions.FirstOrDefault( function(const value : TPackageVersion) : boolean begin result := value.IsStable = false; end); if not version.IsEmpty then lPre := cLatestPrerelease + version.ToStringNoMeta; end; version := versions.FirstOrDefault( function(const value : TPackageVersion) : boolean begin result := value.IsStable; end); if not version.IsEmpty then lStable := cLatestStable + version.ToStringNoMeta; if (lStable <> '') and (lPre <> '') then begin cboVersions.Items.Add(lPre); cboVersions.Items.AddObject(lStable, TObject(1)); end else if lStable <> '' then cboVersions.Items.AddObject(lStable, TObject(1)) else if lPre <> '' then cboVersions.Items.AddObject(lPre, TObject(1)); for version in versions do cboVersions.Items.Add(version.ToStringNoMeta); if FCurrentTab = TCurrentTab.Installed then cboVersions.ItemIndex := cboVersions.Items.IndexOf(sInstalledVersion) else cboVersions.ItemIndex := 0; sVersion := cboVersions.Items[cboVersions.ItemIndex]; if TStringUtils.StartsWith(sVersion, cLatestPrerelease, true) then Delete(sVersion, 1, Length(cLatestPrerelease)) else if TStringUtils.StartsWith(sVersion, cLatestStable, true) then Delete(sVersion, 1, Length(cLatestStable)); btnInstallOrUpdate.Enabled := sVersion <> sInstalledVersion; end; finally cboVersions.Items.EndUpdate; end; end); end; procedure TPackageDetailsFrame.ViewClosing; begin FClosing := true; FPackageSearcher := nil; FCancellationTokenSource.Cancel; end; end.
unit uADChangeNotifier; interface uses {$IF CompilerVersion > 22} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, {$ELSE} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, {$IFEND} CNClrLib.Control.Base, CNClrLib.Component.ADChangeNotifier, CNClrLib.Control.EnumTypes; type TForm12 = class(TForm) CnADChangeNotifier1: TCnADChangeNotifier; Memo1: TMemo; Button1: TButton; Button2: TButton; procedure CnADChangeNotifier1ObjectChanged(Sender: TObject; E: _ObjectChangedEventArgs); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form12: TForm12; implementation {$R *.dfm} uses CNClrLib.Core, CNClrLib.Host; procedure TForm12.Button1Click(Sender: TObject); begin // Note: The SearchRequests have been speified on the design screen. // If you don't want to create the SearchRequests on design time, // you can call the RegisterNotifications overload method to register // the distinguish name for notification. CnADChangeNotifier1.RegisterNotifications; Button1.Enabled := False; Button2.Enabled := True; end; procedure TForm12.Button2Click(Sender: TObject); begin // Cancel all notifications CnADChangeNotifier1.AbortNotifications; Button1.Enabled := True; Button2.Enabled := False; end; procedure TForm12.CnADChangeNotifier1ObjectChanged(Sender: TObject; E: _ObjectChangedEventArgs); var attributeEnum: _IEnumerator; attrName: String; values: _ObjectArray; I: Integer; begin attributeEnum := E.Result.Attributes.AttributeNames.AsIEnumerable.GetEnumerator; Memo1.Lines.Add(E.Result.DistinguishedName); while attributeEnum.MoveNext do begin //For more information about Active Directory Attributes, see http://www.kouti.com/tables/userattributes.htm attrName := attributeEnum.Current; Memo1.Lines.Add(attrName + 'AD Attribute:'); if attrName = 'whenCreated' then //Object created begin Memo1.Lines.Add(chr(9) + 'Object Created'); end else if attrName = 'whenChanged' then //Object Modified begin Memo1.Lines.Add(chr(9) + 'Object Modified'); end else if attrName = 'isDeleted' then begin Memo1.Lines.Add(chr(9) + 'Object is Deleted'); end; values := E.Result.Attributes[attrName].GetValues(TClrAssembly.GetType('System.String')); for I := 0 to values.Length - 1 do begin Memo1.Lines.Add(chr(9) + chr(9) + values[I]); end; end; Memo1.Lines.Add('-------------------------------------------------------'); Memo1.Lines.Add(''); end; procedure TForm12.FormShow(Sender: TObject); begin CnADChangeNotifier1.Server := 'example.com';//Specify the LDAP server //Add SearchReguest which will be registered and monitored for changes with CnADChangeNotifier1.SearchRequests.Add do begin DistinguishedName := 'cn=madhuka+sn=udantha,ou=users,dc=example,dc=com'; Filter := '(objectClass=*)'; Scope := TSearchScope.ssBase; end; end; end.
unit CrashMgr; interface uses Windows, SysUtils, Classes, Forms, Dialogs; type TLanguage = (laFrench, laEnglish); TCrashMgr = class(TComponent) private { Déclarations privées } FChecked: Boolean; FOnCrashResume: TNotifyEvent; FOnCrashCancel: TNotifyEvent; FOnCrashHelp: TNotifyEvent; FHeader: String; FDetails: String; FLanguage: TLanguage; FShowLoading: Boolean; function GetCrashFlag: Boolean; procedure SetCrashFlag(Value: Boolean); procedure RunCrashReport; protected { Déclarations protégées } public { Déclarations publiques } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Déclarations publiées } property OnCrashResume: TNotifyEvent read FOnCrashResume write FOnCrashResume; property OnCrashCancel: TNotifyEvent read FOnCrashCancel write FOnCrashCancel; property OnCrashHelp: TNotifyEvent read FOnCrashHelp write FOnCrashHelp; property Header: String read FHeader write FHeader; property Details: String read FDetails write FDetails; property Language: TLanguage read FLanguage write FLanguage; property ShowLoading: Boolean read FShowLoading write FShowLoading; procedure Execute; end; const DEFAULT_HEADER: array [TLanguage] of String = ('Votre application s''est fermée inopinément à sa dernière exécution.', 'This program closed unexpectedly at its last execution.'); DEFAULT_DETAILS: array [TLanguage] of String = ( 'Plusieurs causes peuvent être à l''origine de cette erreur :' + chr(13) + chr(13) + ' - l''application a rencontré un problème l''empêchant de continuer' + chr(13) + ' - le système a rencontré une erreur et s''est arrêté' + chr(13) + ' - votre matériel a connu une défaillance conduisant à l''arrêt de l''ordinateur' + chr(13) + chr(13) + 'Que voulez-vous faire ?', 'Various events may have caused this issue :' + chr(13) + chr(13) + ' - the program encountered an error preventing further execution' + chr(13) + ' - the system encountered an error and stopped' + chr(13) + ' - your hardware met an issue that led to computer failure' + chr(13) + chr(13) + 'What should the program do ?'); procedure Register; implementation uses CrashForm; procedure Register; begin RegisterComponents('Système', [TCrashMgr]); end; constructor TCrashMgr.Create(AOwner: TComponent); begin inherited Create(AOwner); FHeader := '[Default]'; FDetails := '[Default]'; FLanguage := laFrench; FShowLoading := True; end; destructor TCrashMgr.Destroy; begin SetCrashFlag(False); inherited Destroy; end; function TCrashMgr.GetCrashFlag: Boolean; begin Result := FileExists(Format('%s%s', [ParamStr(0), '.dat'])); end; procedure TCrashMgr.SetCrashFlag(Value: Boolean); begin case Value of False: DeleteFile(Format('%s%s', [ParamStr(0), '.dat'])); True: CloseHandle(FileCreate(Format('%s%s', [ParamStr(0), '.dat']))); end; end; procedure TCrashMgr.RunCrashReport; Var Frm: TCrashReportForm; begin if not (csDesigning in ComponentState) then begin Frm := TCrashReportForm.Create(nil); try Frm.ResumeEvent := FOnCrashResume; Frm.CancelEvent := FOnCrashCancel; Frm.HelpEvent := FOnCrashHelp; Frm.Header := FHeader; Frm.Details := FDetails; Frm.Language := FLanguage; Frm.ShowLoading := ShowLoading; Frm.ShowModal; finally Frm.Release; end; end; end; procedure TCrashMgr.Execute; begin if not FChecked then begin FChecked := True; if GetCrashFlag then RunCrashReport else SetCrashFlag(True); end; end; end.
unit URegraCRUDLoteVacina; interface uses URegraCRUD , URepositorioDB , URepositorioLoteVacina , UEntidade , ULoteVacina ; type TRegraCRUDLoteVacina = class(TRegraCRUD) protected procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override; public constructor Create; override; end; implementation { TRegraCRUDCidade } uses SysUtils , UUtilitarios , UMensagens , UConstantes ; constructor TRegraCRUDLoteVacina.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioLoteVacina.Create); end; procedure TRegraCRUDLoteVacina.ValidaInsercao(const coENTIDADE: TENTIDADE); begin inherited; if Trim(TLOTEVACINA(coENTIDADE).VACINA_NOME) = EmptyStr Then raise EValidacaoNegocio.Create(STR_VACINA_NAO_INFORMADA); if (TLOTEVACINA(coENTIDADE).LOTE) = EmptyStr then raise EValidacaoNegocio.Create (STR_LOTE_VACINA_NAO_INFORMADO); if Trim(TLOTEVACINA(coENTIDADE).LABORATORIO) = EmptyStr Then raise EValidacaoNegocio.Create(STR_LABORATORIO_NAO_INFORMADO); //if Trim(TLOTEVACINA(coENTIDADE).VENCIMENTO_LOTE) = EmptyStr Then //raise EValidacaoNegocio.Create(STR_LOTE_VENCIMENTO_NAO_INFORMADO); end; end.
{Ejercicio 12 Escriba una función en Pascal para determinar el área de una figura de cuatro lados, dadas las coordenadas de los vértices de la figura. Utilice la función de área de triángulos siguiente.} program ejercicio12; type coordenadas = record x,y : integer end; var v1,v2,v3,v4 : coordenadas; ladoa,ladob,ladoc,ladod,hip:real; procedure LeerCoordenadas(var vertice: coordenadas); begin read(vertice.x); read(vertice.y); end; function CalcArea( a, b, c: Real ) : Real; (*Calcula el area de un triangulo de lados a, b, c*) var s : Real; (* Mitad del perimetro del triangulo*) perimetro : Real; (* Perimetro del triangulo*) begin perimetro := a + b + c; s := perimetro / 2; (* Calculo del area mediante la formula de Heron *) CalcArea := sqrt (s * (s-a) * (s-b) * (s-c)) end; function CalcLado(v1,v2:coordenadas):real; begin CalcLado := sqrt(sqr((v2.x-v1.x))+sqr((v2.y-v1.y))); end; begin writeln('Ingrese 4 vertices: '); LeerCoordenadas(v1); LeerCoordenadas(v2); LeerCoordenadas(v3); LeerCoordenadas(v4); ladoa := CalcLado(v1,v2); ladob := CalcLado(v2,v3); ladoc := CalcLado(v4,v3); ladod := CalcLado(v4,v1); hip := CalcLado(v3,v1); writeln('Area total. ',CalcArea(ladoa,ladob,hip) + CalcArea(ladoc,ladod,hip):4:2); end.
unit caTimer; {$INCLUDE ca.inc} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, MMSystem, caTypes; type TcaTimer = class; //---------------------------------------------------------------------------- // TcaTimerThread   //---------------------------------------------------------------------------- TcaTimerThread = class(TThread) private FTimer: TcaTimer; protected procedure DoExecute; public constructor CreateTimerThread(Timer: TcaTimer); procedure Execute; override; end; //---------------------------------------------------------------------------- // IcaTimer   //---------------------------------------------------------------------------- IcaTimer = interface ['{0BB08B16-3CDF-4211-BC6E-D08B563F9F09}'] function GetEnabled: Boolean; function GetInterval: LongWord; function GetOnTimer: TNotifyEvent; function GetPriority: TThreadPriority; procedure SetEnabled(const Value: Boolean); procedure SetInterval(const Value: LongWord); procedure SetOnTimer(const Value: TNotifyEvent); procedure SetPriority(const Value: TThreadPriority); procedure Start; procedure Stop; property Enabled: Boolean read GetEnabled write SetEnabled; property Interval: LongWord read GetInterval write SetInterval; property OnTimer: TNotifyEvent read GetOnTimer write SetOnTimer; property Priority: TThreadPriority read GetPriority write SetPriority; end; //---------------------------------------------------------------------------- // TcaTimer   //---------------------------------------------------------------------------- TcaTimer = class(TComponent, IcaTimer) private FInterval: LongWord; FPriority: TThreadPriority; FOnTimer: TNotifyEvent; FContinue: Boolean; FRunning: Boolean; FEnabled: Boolean; function GetEnabled: Boolean; function GetInterval: LongWord; function GetOnTimer: TNotifyEvent; function GetPriority: TThreadPriority; procedure SetEnabled(const Value: Boolean); procedure SetInterval(const Value: LongWord); procedure SetOnTimer(const Value: TNotifyEvent); procedure SetPriority(const Value: TThreadPriority); protected property Continue: Boolean read FContinue write FContinue; public constructor Create(Owner: TComponent); override; destructor Destroy; override; procedure Start; procedure Stop; published property Enabled: Boolean read GetEnabled write SetEnabled; property Interval: LongWord read GetInterval write SetInterval; property OnTimer: TNotifyEvent read GetOnTimer write SetOnTimer; property Priority: TThreadPriority read GetPriority write SetPriority; end; implementation //---------------------------------------------------------------------------- // TcaTimerThread   //---------------------------------------------------------------------------- constructor TcaTimerThread.CreateTimerThread(Timer: TcaTimer); begin inherited Create(True); FTimer := Timer; FreeOnTerminate := True; end; procedure TcaTimerThread.Execute; var SleepTime, Last: LongWord; begin while FTimer.Continue do begin Last := timeGetTime; Synchronize(DoExecute); SleepTime := FTimer.Interval - (timeGetTime - Last); if SleepTime < 10 then SleepTime := 10; Sleep(SleepTime); end; end; procedure TcaTimerThread.DoExecute; begin if Assigned(FTimer.OnTimer) then FTimer.OnTimer(FTimer); end; //---------------------------------------------------------------------------- // TcaTimer   //---------------------------------------------------------------------------- constructor TcaTimer.Create(Owner: TComponent); begin inherited; FPriority := tpNormal; end; destructor TcaTimer.Destroy; begin Stop; inherited; end; function TcaTimer.GetEnabled: Boolean; begin Result := FEnabled; end; function TcaTimer.GetInterval: LongWord; begin Result := FInterval; end; function TcaTimer.GetOnTimer: TNotifyEvent; begin Result := FOnTimer; end; function TcaTimer.GetPriority: TThreadPriority; begin Result := FPriority; end; procedure TcaTimer.SetEnabled(const Value: Boolean); begin if Value <> FEnabled then begin FEnabled := Value; if FEnabled then Start else Stop; end; end; procedure TcaTimer.SetInterval(const Value: LongWord); begin FInterval := Value; end; procedure TcaTimer.SetOnTimer(const Value: TNotifyEvent); begin FOnTimer := Value; end; procedure TcaTimer.SetPriority(const Value: TThreadPriority); begin FPriority := Value; end; procedure TcaTimer.Start; var TimerThread: TcaTimerThread; begin if not FRunning then begin FContinue := True; if not (csDesigning in ComponentState) then begin TimerThread := TcaTimerThread.CreateTimerThread(Self); TimerThread.Priority := FPriority; TimerThread.Resume; end; FRunning := True; end; end; procedure TcaTimer.Stop; begin FContinue := False; FRunning := False; end; end.
unit FormPanelWizardBase; (* FormPanelWizardBase.pas/dfm --------------------------- Begin: 2006/07/18 Last revision: $Date: 2008-12-10 21:03:31 $ $Author: areeves $ Version number: $Revision: 1.5 $ Project: APHI General Purpose Delphi Libary Website: http://www.naadsm.org/opensource/delphi/ Author: Aaron Reeves <aaron.reeves@naadsm.org> -------------------------------------------------- Copyright (C) 2006 - 2008 Animal Population Health Institute, Colorado State University This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. *) interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, //cDictionaries, QStringMaps, FrameWizardBase ; type TNextPanel = ( NPNone, NPBack, NPNext ); type TFormPanelWizardBase = class( TForm ) pnlWizardButtons: TPanel; btnCancel: TBitBtn; btnBack: TBitBtn; btnNext: TBitBtn; btnFinish: TBitBtn; procedure FormCreate( Sender: TObject ); procedure wizardButtonClick( sender: TObject ); procedure FormClose( Sender: TObject; var Action: TCloseAction ); protected // NextForm is used by Used by TFormMain.showParamForm to determine whether the // next or previous form in paramFormList should be shown. NextForm is set // by wizardButtonClick. _nextPanel: TNextPanel; // Has value of NPNone, NPBack, or NPNext. _fraMain: TFrame; //_frameList: TObjectDictionary; _frameList: TQStringObjectMap; _visibleFrame: TFrameWizardBase; _currentFrameIndex: integer; _okToClose: boolean; procedure translateUI(); procedure fillFrameList(); virtual; abstract; procedure showPanel( panelName: string ); overload; procedure showPanel( idx: integer ); overload; // Remember to override these. function initializeAndShow(): boolean; virtual; abstract; procedure updateParams(); virtual; abstract; function dataIsValid(): boolean; virtual; abstract; public constructor create( AOwner: TComponent ); override; destructor destroy(); override; property nextPanel: TNextPanel read _nextPanel; end ; implementation {$R *.dfm} uses MyDialogs, MyStrUtils, ControlUtilities ; constructor TFormPanelWizardBase.create( AOwner: TComponent ); begin dbcout( 'TFormPanelWizardBase.create' ); inherited create( AOwner ); translateUI(); // Deal with form scaling //----------------------- Assert(not Scaled, 'You should set Scaled property of Form to False!'); // Set this value to the PPI AT WHICH THE FORM WAS ORIGINALLY DESIGNED!! self.PixelsPerInch := 96; // FormCreate() will handle the rest. self.Visible := false; self.Enabled := true; _okToClose := false; //_frameList := TObjectDictionary.Create(); _frameList := TQStringObjectMap.create(); end ; procedure TFormPanelWizardBase.translateUI(); begin // This function was generated automatically by Caption Collector 0.6.0. // Generation date: Mon Feb 25 15:48:33 2008 // File name: C:/Documents and Settings/apreeves/My Documents/NAADSM/Interface-Fremont/general_purpose_gui/FormPanelWizardBase.dfm // File date: Tue Oct 10 08:22:48 2006 // Set Caption, Hint, Text, and Filter properties with self do begin Caption := tr( 'FormWizardBase' ); btnCancel.Caption := tr( '&Cancel' ); btnCancel.Hint := tr( 'Abort current operations, not saving information on the screen and return to the main menu' ); btnBack.Caption := tr( '< &Back' ); btnBack.Hint := tr( 'Return to the previous screen, saving this information' ); btnNext.Caption := tr( '&Next >' ); btnNext.Hint := tr( 'Proceed to the next screen, saving this information' ); btnFinish.Caption := tr( '&Finish' ); btnFinish.Hint := tr( 'Complete working on the screen by saving the information' ); end ; end ; procedure TFormPanelWizardBase.FormCreate(Sender: TObject); begin if Screen.PixelsPerInch <> PixelsPerInch then ScaleBy( Screen.PixelsPerInch, PixelsPerInch ) ; end ; destructor TFormPanelWizardBase.destroy(); begin _frameList.Free(); inherited destroy(); end ; procedure TFormPanelWizardBase.wizardButtonClick( sender: TObject ); var clickedButton: TBitBtn; begin screen.Cursor := crHourGlass; clickedButton := TBitBtn( sender ); dbcout( '*** Button ' + clickedButton.Name + ' clicked' ); _okToClose := true; if( btnCancel = clickedButton ) then begin _nextPanel := NPNone; exit; end ; if( dataIsValid() ) then begin updateParams(); if( btnBack = clickedButton ) then begin _nextPanel := NPBack; showPanel( _currentFrameIndex - 1 ); end else if( btnNext = clickedButton ) then begin _nextPanel := NPNext; showPanel( _currentFrameIndex + 1 ); end else if( btnFinish = clickedButton ) then begin _nextPanel := NPNone; end else begin raise exception.create( self.name + ': illegal button' ); _nextPanel := NPNone; end ; end ; screen.Cursor := crDefault; end ; procedure TFormPanelWizardBase.showPanel( panelName: string ); var i: integer; begin dbcout( 'Show panel: ' + panelName ); // Then show the selected panel for i := 0 to _frameList.Count - 1 do begin dbcout( _frameList.GetKeyByIndex(i) ); if( panelName = _frameList.GetKeyByIndex(i) ) then begin showPanel( i ); break; end ; end ; end ; procedure TFormPanelWizardBase.showPanel( idx: integer ); var i: integer; frame: TFrameWizardBase; pnl1: TPanel; begin dbcout( 'Showing panel ' + intToStr( idx ) ); // First, hide all panels for i := 0 to _frameList.count - 1 do begin frame := _frameList.GetItemByIndex(i) as TFrameWizardBase; frame.visible := false; //_frameList[i].Visible := false; frame.Align := alNone; end ; // Then show the selected panel _currentFrameIndex := idx; _visibleFrame := _fraMain.Controls[idx] as TFrameWizardBase; _visibleFrame.Width := self.clientWidth; _visibleFrame.Height := self.ClientHeight - pnlWizardButtons.Height - 15; _visibleFrame.Align := alClient; pnl1 := _visibleFrame.Controls[0] as TPanel; horizVertCenterInside( pnl1, _visibleFrame ); pnl1.BevelInner := bvNone; pnl1.BevelOuter := bvNone; // Finally, deal with the buttons btnBack.Enabled := not( 0 = idx ); btnNext.Enabled := not( _fraMain.ControlCount - 1 = idx ); dbcout( 'Visible fram is nil: ' + boolToText( _visibleFrame = nil ) ); if( initializeAndShow() ) then _visibleFrame.Visible := true else begin if( NPBack = _nextPanel ) then showPanel( _currentFrameIndex - 1 ) else if( NPNext = _nextPanel ) then showPanel( _currentFrameIndex + 1 ) ; end ; end ; procedure TFormPanelWizardBase.FormClose( Sender: TObject; var Action: TCloseAction ); begin if( NPNone <> _nextPanel ) then action := caNone ; end ; end.
{ Copyright (C) 1998-2011, written by Mike Shkolnik, Scalabium Software E-Mail: mshkolnik@scalabium WEB: http://www.scalabium.com Const strings for localization freeware SMComponent library } unit SMCnst; interface {English strings} const strMessage = 'Tisk...'; strSaveChanges = 'Chcete zapsat změny do Databázového Serveru?'; strErrSaveChanges = 'Nelze provést zápis. Zkontrolujte platnost dat nebo konektivitu se Serverem.'; strDeleteWarning = 'Chcete doopravdy vymazat tabulku %s?'; strEmptyWarning = 'Chcete doopravdy vypráznit tabulku %s?'; const PopUpCaption: array [0..24] of string[33] = ('Nový záznam', 'Vložit záznam', 'Oprava záznamu', 'Vymazat záznam', '-', 'Tisk ...', 'Export ...', 'Filtr ...', 'Hledej ...', '-', 'Uložit změny', 'Vrátit změny', 'Obnovit', '-', 'Označit/Odznačit záznamy', 'Označit záznam', 'Označit všechny záznamy', '-', 'Odznačit záznam', 'Odznačit všechny záznamy', '-', 'Uložit strukturu sloupců', 'Načíst strukturu sloupců', '-', 'Nastavení...'); const //for TSMSetDBGridDialog SgbTitle = ' Titulek '; SgbData = ' Data '; STitleCaption = 'Nadpis:'; STitleAlignment = 'Zarovnání:'; STitleColor = 'Pozadí:'; STitleFont = 'Písmo:'; SWidth = 'šířka:'; SWidthFix = 'znaky'; SAlignLeft = 'vlevo'; SAlignRight = 'vpravo'; SAlignCenter = 'na střed'; const //for TSMDBFilterDialog strEqual = 'rovná se'; strNonEqual = 'nerovná se'; strNonMore = 'je menší nebo se rovná'; strNonLess = 'je větší nebo se rovná'; strLessThan = 'je menší'; strLargeThan = 'je větší'; strExist = 'prázdný'; strNonExist = 'neprázdný'; strIn = 'nachází se v'; strBetween = 'je v rozsahu'; strLike = 'obsahuje'; strOR = 'nebo'; strAND = 'a zároveň'; strField = 'Položka'; strCondition = 'Podmínka'; strValue = 'Hodnota'; strAddCondition = ' Definice dodatečné podmínky: '; strSelection = ' Seznam záznamů pro následné podmínky:'; strAddToList = 'Přidat do seznamu'; strEditInList = 'Upravit do seznamu'; strDeleteFromList = 'Odstranit ze seznamu'; strTemplate = 'Filtr vzorového dialogu'; strFLoadFrom = 'Číst z...'; // New constatns strFSaveAs = 'Uložit jako..'; strFDescription = 'Popis'; strFFileName = 'Název'; strFCreate = 'Vytvořené : %s'; strFModify = 'Upravené : %s'; strFProtect = 'Zamezit přepsání'; strFProtectErr = 'Soubor nelze přepsat !'; const //for SMDBNavigator SFirstRecord = 'První záznam'; SPriorRecord = 'Předchozí záznam'; SNextRecord = 'Další záznam'; SLastRecord = 'Poslední záznam'; SInsertRecord = 'Přidat záznam'; SCopyRecord = 'Kopírovat záznam'; SDeleteRecord = 'Vymazat záznam'; SEditRecord = 'Upravit záznam'; SFilterRecord = 'Filtrovací podmínka'; SFindRecord = 'Hledání v záznamech'; SPrintRecord = 'Tisk záznamů'; SExportRecord = 'Export záznamů'; SImportRecord = 'Import záznamů'; SPostEdit = 'Uložení změn'; SCancelEdit = 'Zrušení změn'; SRefreshRecord = 'Obnovit data'; SChoice = 'Vyberte si záznam'; SClear = 'Ostranit vybrané záznamy'; SDeleteRecordQuestion = 'Smazat záznam?'; SDeleteMultipleRecordsQuestion = 'Skutečně chcete smazat vybrané záznamy?'; SRecordNotFound = 'Záznam nenalezen'; SFirstName = 'První'; SPriorName = 'Předchozí'; SNextName = 'Další'; SLastName = 'Poslední'; SInsertName = 'Přidat'; SCopyName = 'Kopírovat'; SDeleteName = 'Vymazat'; SEditName = 'Upravit'; SFilterName = 'Filtr'; SFindName = 'Hledání'; SPrintName = 'Tisk'; SExportName = 'Export'; SImportName = 'Import'; SPostName = 'Uložit'; SCancelName = 'Storno'; SRefreshName = 'Obnovit'; SChoiceName = 'Volba'; SClearName = 'Odstranit'; SBtnOk = '&OK'; SBtnCancel = '&Storno'; SBtnLoad = 'Číst'; SBtnSave = 'Uložit'; SBtnCopy = 'Kopírovat'; SBtnPaste = 'Přidat'; SBtnClear = 'Odstranit'; SRecNo = 'záz.'; SRecOf = ' z '; const //for EditTyped etValidNumber = 'platné číslo'; etValidInteger = 'platná num.hodnota'; etValidDateTime = 'platný datum/čas'; etValidDate = 'platný datum'; etValidTime = 'platný čas'; etValid = 'platný'; etIsNot = 'Není'; etOutOfRange = 'Hodnota %s je mimo rozsahu %s..%s'; SApplyAll = 'Použít na všechny'; SNoDataToDisplay = '<žádná data k zobrazení>'; SPrevYear = 'minulý rok'; SPrevMonth = 'minulý měsíc'; SNextMonth = 'příští měsíc'; SNextYear = 'příští rok'; implementation end.
unit _frMonitor; interface uses FrameBase, JsonData, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.jpeg, Vcl.ExtCtrls, Vcl.Imaging.pngimage, Vcl.StdCtrls; type TfrMonitor = class(TFrame) Image: TImage; Label1: TLabel; Label2: TLabel; Label3: TLabel; rbRegion: TRadioButton; rbFull: TRadioButton; rbWindow: TRadioButton; Label4: TLabel; procedure SelectCaptureSource(Sender: TObject); private public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published procedure rp_ShowOptionControl(AParams:TJsonData); procedure rp_SetFullScreen(AParams:TJsonData); end; implementation uses Core, Options; {$R *.dfm} { TfrMonitor } constructor TfrMonitor.Create(AOwner: TComponent); begin inherited; TCore.Obj.View.Add(Self); end; destructor TfrMonitor.Destroy; begin TCore.Obj.View.Remove(Self); inherited; end; procedure TfrMonitor.SelectCaptureSource(Sender: TObject); begin TCore.Obj.View.sp_SetSelectRegionVisible(rbRegion.Checked); TCore.Obj.View.sp_SetSelectWindowVisible(rbWindow.Checked); if rbFull.Checked then TOptions.Obj.ScreenOption.SetFullScreen; end; procedure TfrMonitor.rp_SetFullScreen(AParams: TJsonData); begin rbFull.Checked := true; TOptions.Obj.ScreenOption.SetFullScreen; end; procedure TfrMonitor.rp_ShowOptionControl(AParams: TJsonData); begin Visible := AParams.Values['Target'] = HelpKeyword; end; end.
unit MergeDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Forms, Dialogs, Controls, StdCtrls, Buttons, IntelHEX; type TMergeDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; HelpBtn: TButton; SrcList: TListBox; DstList: TListBox; DstLabel: TLabel; IncludeBtn: TSpeedButton; ExcludeBtn: TSpeedButton; SourceBox: TComboBox; procedure IncludeBtnClick(Sender: TObject); procedure ExcludeBtnClick(Sender: TObject); procedure SourceBoxChange(Sender: TObject); private { déclarations privées } public { déclarations publiques } procedure SetItem(List: TListBox; Index: Integer); function GetFirstSelection(List: TCustomListBox): Integer; procedure SetButtons; procedure SetSrcList(Source : TIntelHexFile); function Execute(Sources : TList; Dest : TIntelHexFile) : integer; end; var MergeDlg: TMergeDlg; implementation {$R *.dfm} procedure TMergeDlg.IncludeBtnClick(Sender: TObject); var Index: Integer; begin Index := GetFirstSelection(SrcList); DstList.Items.AddObject(Format('[%s]%s', [SourceBox.Text , SrcList.Items[Index]]), SrcList.Items.Objects[Index]); SrcList.Items.Delete(Index); SetItem(SrcList, Index); end; procedure TMergeDlg.ExcludeBtnClick(Sender: TObject); var Index: Integer; begin Index := GetFirstSelection(DstList); DstList.Items.Delete(Index); SetSrcList(TIntelHexFile(SourceBox.Items.Objects[SourceBox.ItemIndex])); SetItem(DstList, Index); end; procedure TMergeDlg.SetButtons; var SrcEmpty, DstEmpty: Boolean; begin SrcEmpty := SrcList.Items.Count = 0; DstEmpty := DstList.Items.Count = 0; IncludeBtn.Enabled := not SrcEmpty; ExcludeBtn.Enabled := not DstEmpty; end; function TMergeDlg.GetFirstSelection(List: TCustomListBox): Integer; begin for Result := 0 to List.Items.Count - 1 do if List.Selected[Result] then Exit; Result := LB_ERR; end; procedure TMergeDlg.SetItem(List: TListBox; Index: Integer); var MaxIndex: Integer; begin with List do begin SetFocus; MaxIndex := List.Items.Count - 1; if Index = LB_ERR then Index := 0 else if Index > MaxIndex then Index := MaxIndex; Selected[Index] := True; end; SetButtons; end; procedure TMergeDlg.SetSrcList(Source : TIntelHexFile); var i : integer; begin SrcList.Clear; i := 0; while i < Source.HexSections.Count do begin if Source.HexSections.Item[i].Count>0 then if DstList.Items.IndexOf(Format('[%s]%s', [ExtractFileName(Source.FileName),Source.HexSections.Item[i].SectionName])) = -1 then SrcList.AddItem(Source.HexSections.Item[i].SectionName, Source.HexSections.Item[i]); inc(i); end; SetButtons; end; function TMergeDlg.Execute(Sources : TList; Dest : TIntelHexFile) : integer; var i,j : integer; Offset : integer; begin SourceBox.Items.Clear; i := 0; while i < Sources.Count do begin SourceBox.Items.AddObject(ExtractFileName(TIntelHexFile(Sources[i]).FileName), Sources[i]); inc(i); end; if Sources.Count>0 then begin SetSrcList(TIntelHexFile(Sources[0])); SourceBox.ItemIndex := 0; end; result := ShowModal; if result <> mrOK then exit; i := 0; while i < DstList.Items.Count do begin j := 0; while j< TIntelHexSection(DstList.Items.Objects[i]).Count do begin with TIntelHexSection(DstList.Items.Objects[i]).Item[j] do Dest.AddData(Address, DataPtr^, ByteCount); inc(j); end; inc(i); end; end; procedure TMergeDlg.SourceBoxChange(Sender: TObject); begin SetSrcList(TIntelHexFile(SourceBox.Items.Objects[SourceBox.ItemIndex])); end; end.
(* Name: kpinstallfont Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 14 Sep 2006 Modified Date: 3 Feb 2015 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 14 Sep 2006 - mcdurdin - Fix bug where registry was still in read-only state 30 May 2007 - mcdurdin - I850 - Fix font installation under Vista 19 Jun 2007 - mcdurdin - I815 - Install font for current user 18 Mar 2011 - mcdurdin - I2751 - When font is in use, strange errors can appear during install/uninstall 03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors 03 Feb 2015 - mcdurdin - I4574 - V9.0 - If any files are read-only, they need the read-only flag removed on install *) unit kpinstallfont; interface uses kpbase; type TKPInstallFont = class(TKPBase) function Execute(const src_filename: string): Boolean; end; implementation uses windows, sysutils, shellapi, shlobj, ttinfo, utildir, utilsystem, ErrorControlledRegistry, registrykeys, getosversion, keymanerrorcodes, Variants; function TKPInstallFont.Execute(const src_filename: string): Boolean; var filename, fontnm: string; begin Result := False; with TTTInfo.Create(src_filename, [tfNames]) do try fontnm := FullName; finally Free; end; filename := GetFolderPath(CSIDL_FONTS) + ExtractFileName(src_filename); with TRegistryErrorControlled.Create do // I2890 try RootKey := HKEY_LOCAL_MACHINE; if not OpenKeyReadOnly(SRegKey_NTFontList) then begin WarnFmt(KMN_W_InstallFont_CannotInstallFont, VarArrayOf([ExtractFileName(filename), SysErrorMessage(GetLastError), Integer(GetLastError)])); Exit; end; if ValueExists(fontnm + ' (TrueType)') then begin // we'll assume we don't need to update for now? Result := False; // not installed, so don't uninstall Exit; end; finally Free; end; if CopyFileCleanAttr(PChar(src_filename), PChar(filename), True) then // I2751 // I4574 begin with TRegistryErrorControlled.Create do // I2890 try RootKey := HKEY_LOCAL_MACHINE; if not OpenKey(SRegKey_NTFontList, False) then begin WarnFmt(KMN_W_InstallFont_CannotInstallFontAdmin, VarArrayOf([ExtractFileName(filename)])); Exit; end; if AddFontResource(PChar(filename)) = 0 then begin WarnFmt(KMN_W_InstallFont_CannotInstallFont, VarArrayOf([ExtractFileName(filename), SysErrorMessage(GetLastError), Integer(GetLastError)])); Exit; end; WriteString(fontnm + ' (TrueType)', ExtractFileName(filename)); Result := True; // font should be uninstalled. finally Free; end; end else begin // Not IsAdmin if AddFontResource(PChar(src_filename)) = 0 then // I2751 begin WarnFmt(KMN_W_InstallFont_CannotInstallFont, VarArrayOf([ExtractFileName(filename), SysErrorMessage(GetLastError), Integer(GetLastError)])); Exit; end; Result := True; // font should be uninstalled - it will be loaded by Keyman (I815) end; end; end.
unit bool_or_5; interface implementation function GetBool(Value: Boolean): Boolean; begin Result := Value; end; var B: Boolean = False; procedure Test; begin B := GetBool(False) or GetBool(True); end; initialization Test(); finalization Assert(B); end.
unit View.Register.Base; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, View.Base, System.ImageList, Vcl.ImgList, System.Actions, Vcl.ActnList, Vcl.StdCtrls, Vcl.ExtCtrls; type TSaveRegister = procedure of object; TCancelRegister = procedure of object; type TfrmRegister = class(TfrmBase) pnlOptions: TPanel; btnEditItem: TButton; btnNewItem: TButton; actSave: TAction; actCancel: TAction; procedure actSaveExecute(Sender: TObject); procedure actCancelExecute(Sender: TObject); private FOnCancelRegister: TCancelRegister; FOnSaveRegister: TSaveRegister; procedure SetOnCancelRegister(const Value: TCancelRegister); procedure SetOnSaveRegister(const Value: TSaveRegister); { Private declarations } public property OnSaveRegister: TSaveRegister read FOnSaveRegister write SetOnSaveRegister; property OnCancelRegister: TCancelRegister read FOnCancelRegister write SetOnCancelRegister; end; implementation {$R *.dfm} procedure TfrmRegister.actCancelExecute(Sender: TObject); begin inherited; try OnCancelRegister; Close; except on E: Exception do MessageDlg(E.Message, TMsgDlgType.mtWarning, [mbOK], 0); end; end; procedure TfrmRegister.actSaveExecute(Sender: TObject); begin inherited; try OnSaveRegister; Close; except on E: Exception do MessageDlg(E.Message, TMsgDlgType.mtWarning, [mbOK], 0); end; end; procedure TfrmRegister.SetOnCancelRegister(const Value: TCancelRegister); begin FOnCancelRegister := Value; end; procedure TfrmRegister.SetOnSaveRegister(const Value: TSaveRegister); begin FOnSaveRegister := Value; end; end.
program TestEnums; type Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat); var day : Days; begin WriteLn('Ord(Mon): ', Ord(Mon)); day := Tue; WriteLn('Ord(day): ', Ord(day)); end.
{$V-} {$R-} {Range checking off} {$S+} {Stack checking on} { } { Module Name: BTRIEVE.PAS } { } { Description: This is the Btrieve interface for Turbo Pascal (MS-DOS). } { This routine sets up the parameter block expected by } { Btrieve, and issues interrupt 7B. It should be compiled } { with the $V- switch so that runtime checks will not be } { performed on the variable parameters. } { } { Synopsis: STAT := BTRV (OpCode, POS.START, DataBuf.START, BufLen, } { KeyBuf.START, Key); } { where } { OpCode is an integer, } { POS is a 128 byte array, } { DataBuf is an untyped parameter for the data buffer, } { BufLen is the integer length of the data buffer, } { KeyBuf is the untyped parameter for the key buffer, } { and Key is an integer. } { } { Returns: Btrieve status code (see Appendix B of the Btrieve Manual). } { } { Note: The Btrieve manual states that the 2nd, 3rd, and 5th } { parameters be declared as variant records, with an integer } { type as one of the variants (used only for Btrieve calls), } { as is shown in the example below. This is supported, but } { the restriction is no longer necessary. In other words, any } { variable can be sent in those spots as long as the variable } { uses the correct amount of memory so Btrieve does not } { overwrite other variables. } { } { var DataBuf = record case boolean of } { FALSE: ( START: integer ); } { TRUE: ( EMPLOYEE_ID: 0..99999; } { EMPLOYEE_NAME: packed array[1..50] of char; } { SALARY: real; } { DATA_OF_HIRE: DATE_TYPE ); } { end; } { } { There should NEVER be any string variables declared in the } { data or key records, because strings store an extra byte for } { the length, which affects the total size of the record. } { } { } UNIT BTRIEVE; interface Uses Dos; CONST KeyLength = 255; { file open modes } Normal = 0; Accelerated = -1; ReadOnly = -2; Verify = -3; Exclusive = -4; { Btrieve Operation Codes } AbortTrans = 21; BeginTrans = 19; ClearOwner = 30; BTRClose = 1; Create = 14; CreateIndex = 31; BTRDelete = 4; DropIndex = 32; EndTrans = 20; Extend = 16; GetDirect = 23; GetDirectory = 18; GetEqual = 5; GetFirst = 12; GetGreater = 8; GetGreaterOrEqual = 9; GetLast = 13; GetLessThan = 10; GetLessThanOrEqual = 11; GetNext = 6; GetPos = 22; GetPrevious = 7; BTRInsert = 2; BTROpen = 0; BTRReset = 28; SetDirectory = 17; SetOwner = 29; Stat = 15; StepFirst = 33; StepLast = 34; StepNext = 24; StepPrevious = 36; Stop = 25; UnLock = 27; UpDate = 3; Version = 26; { Additive operation modifiers } { Add to a get } GetKey = 50; { Add locks to Get, Step, Open, or Begin } LockSingleWait = 100; LockSingleNoWait = 200; LockMultiWait = 300; LockMultiNoWait = 400; { BTRIEVE Status Return Codes } Sucess = 0; InvalidOperation = 1; IoError = 2; FileNotOpen = 3; KeyNotFound = 4; DuplicateKey = 5; InvalidKey = 6; DifferentKey = 7; InvalidPos = 8; EndOfFile = 9; NonModifiableKey = 10; InvalidFileName = 11; FileNotFound = 12; ExtendedFileError = 13; PreImageOpenError = 14; PreImageIoError = 15; ExpansionError = 16; CloseError = 17; DiskFull = 18; UnrecoverableErr = 19; BTRNotLoaded = 20; Conflict = 80; TYPE PosBlock = ARRAY[1..128] OF BYTE; KeyBufType = ARRAY[1..KeyLength] OF CHAR; (* ---------------------------------------------- *) PROCEDURE BTRString(var Dest;len : BYTE; Source : string); { Converts Turbo strings to ARRAY OF CHAR without length byte } { Dest will be filled up to LEN, excess is lost, surplus padded } { with #0. } (* ---------------------------------------------- *) PROCEDURE TurboString(VAR Dest : String; len : BYTE; VAR Source); { Converts ARRAY OF CHAR without length byte to Turbo String } { Dest will be filled up to LEN, excess is lost, surplus padded } { with #0. } (* ---------------------------------------------- *) PROCEDURE AssignKey(var Dest : KeyBufType; Source : string); { Converts Turbo strings to valid BTRIEVE key buffer } (* ---------------------------------------------- *) function BTRV (OpCode : integer; var POS, DataBuf; var BufLen: integer; var KeyBuf : KeyBufType; Key: integer): integer; {======================================================================} implementation (* ---------------------------------------------- *) PROCEDURE TurboString(VAR Dest : String; len : BYTE; VAR Source); BEGIN { copy string bytes from first data byte } IF len > 255 THEN len := 255; Move(Source,Dest[1],len); Dest[0] := chr(len); END (* TurboString *); (* ---------------------------------------------- *) PROCEDURE BTRString(var Dest;len : BYTE; Source : string); { Converts Turbo strings to ARRAY OF CHAR without length byte } { Dest will be filled up to LEN, excess is lost, surplus padded } { with #0. } CONST PadChar = #0; VAR n, stop : INTEGER; BEGIN { pad with null char } FillChar(Dest,len,PadChar); { copy string bytes from first data byte } IF ORD(Source[0]) > len THEN n := len ELSE n := ORD(Source[0]); Move(Source[1],Dest,n); (* n := 1; stop := ord(Source[0])+1; { length of Source + 1 } WHILE n < stop DO BEGIN Dest[n] := Source[n]; inc(n); END; *) END (* BTRString *); (* ---------------------------------------------- *) PROCEDURE AssignKey(var Dest : KeyBufType; Source : string); { Converts Turbo strings to valid BTRIEVE key buffer } BEGIN BTRString(Dest,SIZEOF(KeyBufType),Source); END (* AssignKey *); (* ---------------------------------------------- *) function BTRV (OpCode : integer; var POS, DataBuf; var BufLen: integer; var KeyBuf : KeyBufType; Key: integer): integer; const VAR_ID = $6176; {id for variable length records - 'va'} BTR_INT = $7B; BTR2_INT = $2F; BTR_OFFSET = $0033; MULTI_FUNCTION = $AB; { ProcId is used for communicating with the Multi Tasking Version of } { Btrieve. It contains the process id returned from BMulti and should } { not be changed once it has been set. } { } ProcId: integer = 0; { initialize to no process id } MULTI: boolean = false; { set to true if BMulti is loaded } VSet: boolean = false; { set to true if we have checked for BMulti } type ADDR32 = record {32 bit address} OFFSET: integer; SEGMENT: integer; end; BTR_PARMS = record USER_BUF_ADDR: ADDR32; {data buffer address} USER_BUF_LEN: integer; {data buffer length} USER_CUR_ADDR: ADDR32; {currency block address} USER_FCB_ADDR: ADDR32; {file control block address} USER_FUNCTION: integer; {Btrieve operation} USER_KEY_ADDR: ADDR32; {key buffer address} USER_KEY_LENGTH: BYTE; {key buffer length} USER_KEY_NUMBER: BYTE; {key number} USER_STAT_ADDR: ADDR32; {return status address} XFACE_ID: integer; {language interface id} end; var STAT: integer; {Btrieve status code} XDATA: BTR_PARMS; {Btrieve parameter block} REGS: Dos.Registers; {register structure used on interrrupt call} DONE: boolean; begin REGS.AX := $3500 + BTR_INT; INTR ($21, REGS); if (REGS.BX <> BTR_OFFSET) then {make sure Btrieve is installed} STAT := 20 else begin if (not VSet) then {if we haven't checked for Multi-User version} begin REGS.AX := $3000; INTR ($21, REGS); if ((REGS.AX AND $00FF) >= 3) then begin VSet := true; REGS.AX := MULTI_FUNCTION * 256; INTR (BTR2_INT, REGS); MULTI := ((REGS.AX AND $00FF) = $004D); end else MULTI := false; end; {make normal btrieve call} with XDATA do begin USER_BUF_ADDR.SEGMENT := SEG (DataBuf); USER_BUF_ADDR.OFFSET := OFS (DataBuf); {set data buffer address} USER_BUF_LEN := BufLen; USER_FCB_ADDR.SEGMENT := SEG (POS); USER_FCB_ADDR.OFFSET := OFS (POS); {set FCB address} USER_CUR_ADDR.SEGMENT := USER_FCB_ADDR.SEGMENT; {set cur seg} USER_CUR_ADDR.OFFSET := USER_FCB_ADDR.OFFSET+38;{set cur ofs} USER_FUNCTION := OpCode; {set Btrieve operation code} USER_KEY_ADDR.SEGMENT := SEG (KeyBuf); USER_KEY_ADDR.OFFSET := OFS (KeyBuf); {set key buffer address} USER_KEY_LENGTH := KeyLength; {assume its large enough} USER_KEY_NUMBER := Key; {set key number} USER_STAT_ADDR.SEGMENT := SEG (STAT); USER_STAT_ADDR.OFFSET := OFS (STAT); {set status address} XFACE_ID := VAR_ID; {set lamguage id} end; REGS.DX := OFS (XDATA); REGS.DS := SEG (XDATA); if (NOT MULTI) then {MultiUser version not installed} INTR (BTR_INT, REGS) else begin DONE := FALSE; repeat REGS.BX := ProcId; REGS.AX := 1; if (REGS.BX <> 0) then REGS.AX := 2; REGS.AX := REGS.AX + (MULTI_FUNCTION * 256); INTR (BTR2_INT, REGS); if ((REGS.AX AND $00FF) = 0) then DONE := TRUE else begin REGS.AX := $0200; INTR ($7F, REGS); DONE := FALSE; end; until (DONE); if (ProcId = 0) then ProcId := REGS.BX; end; BufLen := XDATA.USER_BUF_LEN; end; BTRV := STAT; end {BTRV}; { --------------------------------------------------------------------} END {BRTIEVE}. 
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} {/* * (c) Copyright 1993, Silicon Graphics, Inc. * 1993-1995 Microsoft Corporation * ALL RIGHTS RESERVED */} unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormResize(Sender: TObject); private DC : HDC; hrc: HGLRC; end; var frmGL: TfrmGL; implementation uses DGlut; {$R *.DFM} // Initialize z-buffer, projection matrix, light source, // and lighting model. Do not specify a material property here. procedure MyInit; const position : array[0..3] of GLfloat = ( 0.0, 3.0, 2.0, 0.0 ); lmodel_ambient : array[0..3] of GLfloat = ( 0.4, 0.4, 0.4, 1.0 ); begin glEnable(GL_DEPTH_TEST); glLightfv(GL_LIGHT0, GL_POSITION, @position); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, @lmodel_ambient); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glClearColor(0.0, 0.1, 0.1, 0.0); end; {======================================================================= Рисование картинки} procedure TfrmGL.FormPaint(Sender: TObject); const no_mat : array[0..3] of GLfloat = ( 0.0, 0.0, 0.0, 1.0 ); mat_ambient : array[0..3] of GLfloat = ( 0.7, 0.7, 0.7, 1.0 ); mat_ambient_color : array[0..3] of GLfloat = ( 0.8, 0.8, 0.2, 1.0 ); mat_diffuse : array[0..3] of GLfloat = ( 0.1, 0.5, 0.8, 1.0 ); mat_specular : array[0..3] of GLfloat = ( 1.0, 1.0, 1.0, 1.0 ); no_shininess : array[0..0] of GLfloat = ( 0.0 ); low_shininess : array[0..0] of GLfloat = ( 5.0 ); high_shininess : array[0..0] of GLfloat = ( 100.0 ); mat_emission : array[0..3] of GLfloat = ( 0.3, 0.2, 0.2, 0.0 ); begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); // draw sphere in first row, first column // diffuse reflection only; no ambient or specular glPushMatrix; glTranslatef (-3.75, 3.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @no_mat); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @no_mat); glMaterialfv(GL_FRONT, GL_SHININESS, @no_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @no_mat); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in first row, second column // diffuse and specular reflection; low shininess; no ambient glPushMatrix; glTranslatef (-1.25, 3.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @no_mat); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, @low_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @no_mat); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in first row, third column // diffuse and specular reflection; high shininess; no ambient glPushMatrix; glTranslatef (1.25, 3.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @no_mat); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, @high_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @no_mat); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in first row, fourth column // diffuse reflection; emission; no ambient or specular reflection glPushMatrix; glTranslatef (3.75, 3.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @no_mat); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @no_mat); glMaterialfv(GL_FRONT, GL_SHININESS, @no_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @mat_emission); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in second row, first column // ambient and diffuse reflection; no specular glPushMatrix; glTranslatef (-3.75, 0.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @no_mat); glMaterialfv(GL_FRONT, GL_SHININESS, @no_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @no_mat); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in second row, second column // ambient, diffuse and specular reflection; low shininess glPushMatrix; glTranslatef (-1.25, 0.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, @low_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @no_mat); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in second row, third column // ambient, diffuse and specular reflection; high shininess glPushMatrix; glTranslatef (1.25, 0.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, @high_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @no_mat); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in second row, fourth column // ambient and diffuse reflection; emission; no specular glPushMatrix; glTranslatef (3.75, 0.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @no_mat); glMaterialfv(GL_FRONT, GL_SHININESS, @no_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @mat_emission); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in third row, first column // colored ambient and diffuse reflection; no specular glPushMatrix; glTranslatef (-3.75, -3.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient_color); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @no_mat); glMaterialfv(GL_FRONT, GL_SHININESS, @no_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @no_mat); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in third row, second column // colored ambient, diffuse and specular reflection; low shininess glPushMatrix; glTranslatef (-1.25, -3.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient_color); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, @low_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @no_mat); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in third row, third column // colored ambient, diffuse and specular reflection; high shininess glPushMatrix; glTranslatef (1.25, -3.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient_color); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, @high_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @no_mat); glutSolidSphere(1.0, 16, 16); glPopMatrix; // draw sphere in third row, fourth column // colored ambient and diffuse reflection; emission; no specular glPushMatrix; glTranslatef (3.75, -3.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient_color); glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @no_mat); glMaterialfv(GL_FRONT, GL_SHININESS, @no_shininess); glMaterialfv(GL_FRONT, GL_EMISSION, @mat_emission); glutSolidSphere(1.0, 16, 16); glPopMatrix; SwapBuffers(DC); end; {======================================================================= Формат пикселя} procedure SetDCPixelFormat (hdc : HDC); var pfd : TPixelFormatDescriptor; nPixelFormat : Integer; begin FillChar (pfd, SizeOf (pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat (hdc, @pfd); SetPixelFormat (hdc, nPixelFormat, @pfd); end; {======================================================================= Создание формы} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC (Handle); SetDCPixelFormat(DC); hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); MyInit; end; {======================================================================= Конец работы приложения} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC (Handle, DC); DeleteDC (DC); end; procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; end; procedure TfrmGL.FormResize(Sender: TObject); begin glViewport(0, 0, ClientWidth, ClientHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity; if ClientWidth <= (ClientHeight * 2) then glOrtho (-6.0, 6.0, -3.0*(ClientHeight*2)/ClientWidth, 3.0*(ClientHeight*2)/ClientWidth, -10.0, 10.0) else glOrtho (-6.0*ClientWidth/(ClientHeight*2), 6.0*ClientWidth/(ClientHeight*2), -3.0, 3.0, -10.0, 10.0); glMatrixMode(GL_MODELVIEW); InvalidateRect(Handle, nil, False); end; end.
unit ansi_to_unicode_0; interface implementation const SA: AnsiString = 'ansi'; var SU: string; procedure Test; begin SU := SA; end; initialization Test(); finalization Assert(SU = 'ansi'); end.
unit SLLMan; interface uses Windows; type LLData = ^TLLData; TLLData = record Info: TProcessInformation; blocca: boolean; end; PSLLItem = ^TSLLItem; TSLLItem = record Next: pointer; Data: LLData; end; function llsGetItem(id: cardinal; var start: PSLLItem): PSLLItem; function llsTakeOutItem(id: cardinal; var start: PSLLItem): PSLLItem; procedure llsInsertItem(item: PSLLItem; var start: PSLLItem); function llsGetItemCount(start: PSLLItem): cardinal; function llsNewSLLHeader: PSLLItem; procedure llsKillSLLHeader(hdr: PSLLItem); // These ids are numbered from 0 implementation function malloc(size: cardinal): pointer; begin GetMem(result,size); end; function llsGetItemCount(start: pointer): cardinal; var cur: PSLLItem; tmp: cardinal; begin if start = nil then begin llsGetItemCount := 0; Exit; end; tmp := 1; cur := start; while (cur^.Next <> nil) do begin Inc(tmp); cur := cur^.Next; end; llsGetItemCount := tmp; end; procedure llsKillSLLHeader(hdr: pointer); begin if hdr = nil then Exit; FreeMem(hdr); end; function llsNewSLLHeader: PSLLItem; var tmp: PSLLItem; begin tmp := malloc(sizeof(TSLLItem)); tmp^.Next := nil; tmp^.Data := nil; llsNewSLLHeader := tmp; end; function llsGetItem(id: cardinal; var start: pointer): pointer; var cur: PSLLItem; begin if start = nil then begin llsGetItem := nil; Exit; end; cur := start; while (id<>0) do begin if cur^.Next <> nil then begin Dec(id); cur := cur^.Next; end else begin llsGetItem := nil; Exit; end; end; llsGetItem := cur; end; function llsTakeOutItem(id: cardinal; var start: pointer): pointer; var tmp: PSLLItem; last: PSLLItem; begin if start = nil then begin llsTakeOutItem := nil; Exit; end; if (id = 0) then begin tmp := start; if tmp^.Next = nil then start := nil else start := tmp^.Next; llsTakeOutItem := tmp; Exit; end; tmp := start; repeat dec(id); last := tmp; tmp := tmp^.Next; until (id = 0); last^.Next := tmp^.Next; llsTakeOutitem := tmp; end; procedure llsInsertItem(item: PSLLItem; var start: PSLLItem); var cur: PSLLItem; begin if start = nil then begin start := item; exit; end; cur := start; while (cur^.Next<>nil) do cur := cur^.Next; cur^.Next := item; end; end.
unit PAgricultureSubFormUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, DBCtrls, Grids, Wwdbigrd, Wwdbgrid, Buttons, ExtCtrls, ComCtrls, Db, Wwdatsrc, DBTables, Wwtable, wwdblook; type TAgricultureSubform = class(TForm) AgriculturePageControl: TPageControl; SoilsTabSheet: TTabSheet; DetailsTabSheet: TTabSheet; Panel5: TPanel; Panel6: TPanel; gdAgricultureSoils: TwwDBGrid; tbAgriculture: TwwTable; dsAgricultureSoils: TwwDataSource; tbAgricultureSoils: TwwTable; btnNewSoil: TBitBtn; btnDeleteSoil: TBitBtn; Panel2: TPanel; tbAgricultureSoilsSoilGroupCode: TStringField; tbAgricultureSoilsAgAcreage: TFloatField; tbAgricultureSoilsAssessmentPerAcre: TIntegerField; tbAgricultureSoilsAssessment: TIntegerField; tbSoilRatings: TwwTable; dsSoilRatings: TwwDataSource; lcbxSoilRating: TwwDBLookupCombo; Label3: TLabel; edLandValue: TEdit; edImprovementValue: TEdit; Label1: TLabel; edEligibleAcres: TEdit; Label2: TLabel; edCertifiedAssessment: TEdit; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; edTotalValue: TEdit; edTotalHomesteadValue: TEdit; edTotalFarmStructureValue: TEdit; edTotalOtherStructureValue: TEdit; edIneligibleWoodlandsAcreage: TEdit; edIneligibleWoodlandsLandValue: TEdit; edTotalIneligibleLandValue2: TEdit; edTotalIneligibleAcreage: TEdit; edTotalIneligibleLandValue: TEdit; edTotalIneligibleImprovements: TEdit; edTotalIneligibleValue: TEdit; edTotalAcres: TEdit; edAssessedValueEligible: TEdit; Label16: TLabel; Label17: TLabel; Label18: TLabel; edTotalAgricultureAssessment: TEdit; Label19: TLabel; edTotalAgricultureExemption: TEdit; edTotalIneligibleWoodlands: TEdit; edResidentialAcreage: TDBEdit; dsAgriculture: TDataSource; edResidentialLand: TDBEdit; edResidentialBuilding: TDBEdit; edFarmStructureValue: TDBEdit; edOtherStructureValue: TDBEdit; edIneligibleAcreage: TDBEdit; edIneligibleLand: TDBEdit; edAssessedSupportStructure: TDBEdit; tbParcel: TTable; tbAssess: TTable; tbSwis: TTable; tbExemption: TwwTable; Label20: TLabel; edExemption: TEdit; btnUpdateExemption: TBitBtn; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnDeleteSoilClick(Sender: TObject); procedure btnNewSoilClick(Sender: TObject); procedure tbAgricultureSoilsCalcFields(DataSet: TDataSet); procedure AgValueEditExit(Sender: TObject); private { Private declarations } public { Public declarations } InitializingForm : Boolean; Agriculture_ID, AssessmentYear, SwisSBLKey, Category, UnitName, EditMode : String; Procedure InitializeForm(sSwisSBLKey : String; iAgricultureID : Integer; sEditMode : String); Procedure LoadAgricultureInformation; Function GetEligibleAcreage : Double; Function GetCertifiedAssessment : LongInt; Procedure DisplaySoilTotals; end; var AgricultureSubform: TAgricultureSubform; implementation {$R *.DFM} uses PASUtils, WinUtils, Utilitys, DataAccessUnit, PASTypes, GlblVars, GlblCnst; {==================================================================} Procedure TAgricultureSubform.LoadAgricultureInformation; begin _SetRange(tbAgricultureSoils, [Agriculture_ID, ''], [Agriculture_ID, '999'], '', []); _Locate(tbAgriculture, [Agriculture_ID], '', []); end; {LoadAgricultureInformation} {================================================================} Procedure TAgricultureSubform.DisplaySoilTotals; var iIneligibleValue, iEligibleValue, iCertifiedAssessment, iTotalAgricultureAssessment, iTotalAgricultureExemption, iIneligibleImprovements : LongInt; dEqualizationRate : Double; begin iCertifiedAssessment := GetCertifiedAssessment; dEqualizationRate := tbSwis.FieldByName('EqualizationRate').AsFloat; edEligibleAcres.Text := FormatFloat(DecimalDisplay, GetEligibleAcreage); edCertifiedAssessment.Text := FormatFloat(IntegerDisplay, iCertifiedAssessment); edLandValue.Text := FormatFloat(IntegerDisplay, tbAssess.FieldByName('LandAssessedVal').AsInteger); edImprovementValue.Text := FormatFloat(IntegerDisplay, (tbAssess.FieldByName('TotalAssessedVal').AsInteger - tbAssess.FieldByName('LandAssessedVal').AsInteger)); edIneligibleWoodlandsAcreage.Text := FormatFloat(DecimalDisplay, 0); edIneligibleWoodlandsLandValue.Text := FormatFloat(IntegerDisplay, tbAgriculture.FieldByName('Woodland50').AsInteger); with tbAgriculture do begin iIneligibleImprovements := FieldByName('ResidentialBuilding').AsInteger + FieldByName('FarmStructureValue').AsInteger + FieldByName('OtherStructureValue').AsInteger; iIneligibleValue := FieldByName('IneligibleLand').AsInteger + iIneligibleImprovements; end; edTotalIneligibleAcreage.Text := FormatFloat(DecimalDisplay, tbAgriculture.FieldByName('IneligibleAcreage').AsFloat); edTotalIneligibleLandValue.Text := FormatFloat(IntegerDisplay, tbAgriculture.FieldByName('IneligibleLand').AsInteger); edTotalIneligibleImprovements.Text := FormatFloat(IntegerDisplay, iIneligibleImprovements); edTotalAcres.Text := FormatFloat(DecimalDisplay, tbParcel.FieldByName('Acreage').AsFloat); edTotalValue.Text := FormatFloat(IntegerDisplay, tbAssess.FieldByName('TotalAssessedVal').AsInteger); edTotalHomesteadValue.Text := FormatFloat(IntegerDisplay, tbAgriculture.FieldByName('ResidentialBuilding').AsInteger); edTotalFarmStructureValue.Text := FormatFloat(IntegerDisplay, tbAgriculture.FieldByName('FarmStructureValue').AsInteger); edTotalOtherStructureValue.Text := FormatFloat(IntegerDisplay, tbAgriculture.FieldByName('OtherStructureValue').AsInteger); edTotalIneligibleLandValue2.Text := FormatFloat(IntegerDisplay, tbAgriculture.FieldByName('IneligibleLand').AsInteger); edTotalIneligibleWoodlands.Text := FormatFloat(IntegerDisplay, tbAgriculture.FieldByName('Woodland50').AsInteger); iEligibleValue := tbAssess.FieldByName('TotalAssessedVal').AsInteger - iIneligibleValue; iTotalAgricultureAssessment := Trunc(iCertifiedAssessment * (dEqualizationRate / 100)); iTotalAgricultureExemption := iEligibleValue - iTotalAgricultureAssessment; edTotalIneligibleValue.Text := FormatFloat(IntegerDisplay, iIneligibleValue); edAssessedValueEligible.Text := FormatFloat(IntegerDisplay, iEligibleValue); edTotalAgricultureAssessment.Text := FormatFloat(IntegerDisplay, iTotalAgricultureAssessment); edTotalAgricultureExemption.Text := FormatFloat(IntegerDisplay, iTotalAgricultureExemption); end; {DisplaySoilTotals} {==================================================================} Procedure TAgricultureSubform.InitializeForm(sSwisSBLKey : String; iAgricultureID : Integer; sEditMode : String); var sAssessmentYear : String; begin WindowState := Application.MainForm.WindowState; InitializingForm := True; sAssessmentYear := GetTaxRlYr; UnitName := 'PAgricultureSubformUnit'; Caption := 'Agriculture Worksheet (' + ConvertSwisSBLToDashDot(sSwisSBLKey) + ' - ' + sAssessmentYear + ')'; If (sEditMode = 'V') then begin tbAgriculture.ReadOnly := True; tbAgricultureSoils.ReadOnly := True; btnNewSoil.Enabled := False; btnDeleteSoil.Enabled := False; end; {If (EditMode = 'V')} OpenTablesForForm(Self, GlblProcessingType); _Locate(tbParcel, [sAssessmentYear, sSwisSBLKey], '', [loParseSwisSBLKey]); _Locate(tbAssess, [sAssessmentYear, sSwisSBLKey], '', []); _Locate(tbSwis, [Copy(sSwisSBLKey, 1, 6)], '', []); edExemption.Text := tbAgriculture.FieldByName('ExemptionCode').AsString; InitializingForm := False; tbAgricultureSoils.Refresh; DisplaySoilTotals; end; {InitializeForm} {================================================================} Procedure TAgricultureSubform.FormKeyPress( Sender: TObject; var Key: Char); begin If (Key = #13) then begin Perform(WM_NextDlgCtl, 0, 0); Key := #0; end; {If (Key = #13)} end; {FormKeyPress} {============================================================================} Function TAgricultureSubform.GetEligibleAcreage : Double; begin Result := 0; with tbAgricultureSoils do begin DisableControls; First; while not EOF do begin Result := Result + FieldByName('AgAcreage').AsFloat; Next; end; end; {with tbAgricultureSoils do} end; {GetEligibleAcreage} {============================================================================} Function TAgricultureSubform.GetCertifiedAssessment : LongInt; begin Result := 0; with tbAgricultureSoils do begin DisableControls; First; while not EOF do begin Result := Result + FieldByName('Assessment').AsInteger; Next; end; end; {with tbAgricultureSoils do} end; {GetCertifiedAssessment} {============================================================================} Procedure TAgricultureSubform.tbAgricultureSoilsCalcFields(DataSet: TDataSet); begin If not InitializingForm then with Dataset as TwwTable do begin _Locate(tbSoilRatings, [FieldByName('SoilGroupCode').AsString], '', []); FieldByName('AssessmentPerAcre').AsInteger := tbSoilRatings.FieldByName('ValuePerAcre').AsInteger; FieldByName('Assessment').AsInteger := Trunc(FieldByName('AgAcreage').AsFloat * FieldByName('AssessmentPerAcre').AsInteger); end; {with Sender as TwwTable do} end; {tbAgricultureSoilsCalcFields} {============================================================================} Procedure TAgricultureSubform.btnNewSoilClick(Sender: TObject); begin tbAgricultureSoils.Append; end; {btnNewSoilClick} {============================================================================} Procedure TAgricultureSubform.btnDeleteSoilClick(Sender: TObject); begin with tbAgricultureSoils do If (MessageDlg('Are you sure you want to delete soil ' + FieldByName('SoilGroupCode').AsString + '?', mtConfirmation, [mbYes, mbNo], 0) = idYes) then try Delete; LoadAgricultureInformation; except end; end; {btnDeleteSoilClick} {============================================================================} Procedure TAgricultureSubform.FormClose( Sender: TObject; var Action: TCloseAction); begin try tbAgriculture.Post; except end; CloseTablesForForm(Self); end; {============================================================================} Procedure TAgricultureSubform.AgValueEditExit(Sender: TObject); begin DisplaySoilTotals; end; end.
unit u_FrameMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, u_FrameUart, System.Actions, Vcl.ActnList, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ToolWin, Data.DB, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, u_Frame_WeightInfo, u_frame_MainfestVerify, u_WeightComm, u_FrameWeightNum; type TframeMain = class(TframeUart) pnlBottom: TPanel; pnlDB: TPanel; pnlRight: TPanel; mmoLog: TMemo; pnlMain: TPanel; Panel1: TPanel; frameMainfrestVerify1: TframeMainfrestVerify; frameWeightInfo1: TframeWeightInfo; pnlTop: TPanel; dbgrdWeightInfo: TDBGrid; Splitter1: TSplitter; Splitter2: TSplitter; actDoAuth: TAction; Splitter3: TSplitter; frameWeightNum1: TframeWeightNum; pnlWeightNum: TPanel; pnlWeightType: TPanel; rbGross: TRadioButton; rbTare: TRadioButton; actSelGrossWeight: TAction; btnSample: TButton; actSampleWeight: TAction; actSelTareWeight: TAction; pnlPlaceHolder: TPanel; actDoCommit: TAction; procedure actDoAuthExecute(Sender: TObject); procedure actDBData22UIExecute(Sender: TObject); procedure actDoAuthUpdate(Sender: TObject); procedure dbgrdWeightInfoDblClick(Sender: TObject); procedure actSelGrossWeightExecute(Sender: TObject); procedure actSampleWeightUpdate(Sender: TObject); procedure actSampleWeightExecute(Sender: TObject); procedure actDoCommitExecute(Sender: TObject); procedure frameMainfrestVerify1edtMainfestNoChange(Sender: TObject); private { Private declarations } Procedure HandleLogProc(const Str: String); Procedure DoRecvWeightData(Weight_KG: Single); Procedure DoCheckSelWeight(Sender: TObject); Procedure DoMainrestChanged; public { Public declarations } Constructor Create(AOwner: TComponent); Override; Procedure ProcessBuffer(var Buf: AnsiString); Override; end; var frameMain: TframeMain; implementation {$R *.dfm} uses u_DMWeight, u_SolidWastte_Upload, u_Log, PlumUtils, AnsiStrings; procedure TframeMain.actDBData22UIExecute(Sender: TObject); var AInfo: TWeightInfo; begin inherited; if dmWeight.DB_2Record(AInfo) then begin self.frameMainfrestVerify1.WeightAuth:= AInfo.Auth; self.frameWeightInfo1.WeightMeasure:= AInfo.Mesure; DoCheckSelWeight(Nil); end; end; procedure TframeMain.actDoAuthExecute(Sender: TObject); var AuthInfo: TWeightAuth; Ret: Integer; begin inherited; AuthInfo:= frameMainfrestVerify1.WeightAuth; Ret:= u_SolidWastte_Upload.SolidWaste_Auth(AuthInfo); if Ret = 1 then begin u_log.Log('认证成功,准备保存到数据库....'); dmWeight.DB_InsertAuthInfo(AuthInfo); u_log.Log('数据库保存完成。'); end else begin u_log.Log('认证失败,请重新认证。'); end; DoCheckSelWeight(Nil); end; procedure TframeMain.actDoAuthUpdate(Sender: TObject); begin inherited; if Sender is TAction then begin TAction(Sender).Enabled:= (frameMainfrestVerify1.edtMainfestNo.Text <> '') and (Not dmWeight.DB_MainfestExist(frameMainfrestVerify1.edtMainfestNo.Text)); end; end; procedure TframeMain.actDoCommitExecute(Sender: TObject); var MainfestNo: String; BridgeNoEmpty: Boolean; NewBridgeNo: String; WeightInfo: TWeightInfo; WeightUpdated: Integer; CommitRet: Integer; begin inherited; WeightUpdated:= 0; MainfestNo:= frameMainfrestVerify1.edtMainfestNo.Text; NewBridgeNo:= frameWeightInfo1.edtWeighBridgeNo.Text; dmWeight.FDQuery1.DisableControls; try if dmWeight.DB_Mainfest2Record(MainfestNo, WeightInfo) then begin BridgeNoEmpty:= WeightInfo.Mesure.WeightBridge = ''; if BridgeNoEmpty and (NewBridgeNo <> '') then begin dmWeight.DB_UpdateBridgeNo(MainfestNo, NewBridgeNo); end; if rbGross.Checked and (Not WeightInfo.Mesure.Gross.Valid) then begin Inc(WeightUpdated); dmWeight.DB_SaveGross(MainfestNo, StrToFloat(frameWeightInfo1.edtGrossWeight.Text), _StrToDateTime(frameWeightInfo1.edtGrossWeightTime.Text)) end else if rbTare.Checked and (Not WeightInfo.Mesure.Tare.Valid) then begin Inc(WeightUpdated); dmWeight.DB_SaveTare(MainfestNo, StrToFloat(frameWeightInfo1.edtTareWeight.Text), _StrToDateTime(frameWeightInfo1.edtTareWeightTime.Text)) end; dmWeight.FDQuery1.Refresh; dmWeight.FDQuery1.Locate(CONST_FIELDNAME_MANIFESTNO, MainfestNo); dmWeight.DB_Mainfest2Record(MainfestNo, WeightInfo); Log(Format('更新了%s 的 %d 条重量数据', [MainfestNo, WeightUpdated])); DoCheckSelWeight(Nil); if Not WeightInfo.Commited and WeightInfo.Mesure.Gross.Valid and WeightInfo.Mesure.Tare.Valid then begin Log('数据采集完成,准备提交'); CommitRet:= u_SolidWastte_Upload.SolidWaste_Commit(WeightInfo); if CommitRet = 1 then begin u_log.Log('提交成功,更新提交标志....'); dmWeight.DB_SetMainfestCommited(WeightInfo.Auth.MainfestNo); u_log.Log('标志提交完成'); end else begin u_log.Log('提交失败,请重新提交。'); end; end; end; finally dmWeight.FDQuery1.EnableControls; end; end; procedure TframeMain.actSampleWeightExecute(Sender: TObject); var NewTime: String; begin inherited; NewTime:= frameWeightNum1.lbWeightTime.Caption; if rbGross.Checked then begin frameWeightInfo1.edtGrossWeight.Text:= frameWeightNum1.lblNum.Caption; frameWeightInfo1.edtGrossWeightTime.Text:= NewTime; end else if rbTare.Checked then begin frameWeightInfo1.edtTareWeight.Text:= frameWeightNum1.lblNum.Caption; frameWeightInfo1.edtTareWeightTime.Text:= NewTime; end; end; procedure TframeMain.actSampleWeightUpdate(Sender: TObject); var Selected: Integer; WeightInfo: TWeightInfo; begin inherited; //毛重和皮重只且只有一项是选中的才可以进行操作 Selected:= 0; if rbGross.Checked then Inc(Selected); if rbTare.Checked then Inc(Selected); if Sender = actSampleWeight then begin TAction(Sender).Enabled:= (Selected = 1) and (rbGross.Enabled or rbTare.Enabled) and dmWeight.DB_Mainfest2Record(frameMainfrestVerify1.edtMainfestNo.Text, WeightInfo) and Not frameWeightNum1.WeightOutofdated; end; end; procedure TframeMain.actSelGrossWeightExecute(Sender: TObject); begin inherited; DoCheckSelWeight(Sender); end; constructor TframeMain.Create(AOwner: TComponent); begin inherited; u_Log.g_dele_Log_Proc:= HandleLogProc; {$IFDEF FILL_TEST_DATA} With frameMainfrestVerify1 do begin edtMainfestNo.Text:= '20181304000684'; edtPlateNo.Text:= '冀FN6981'; edtDriverName.Text:= '姚文全'; edtDriverIDC.Text:= '130283197307044223'; end; With frameWeightInfo1 do begin edtGrossWeight.Text:= '5000'; edtGrossWeightTime.Text:= '2016-09-05 11:11:38'; edtTareWeight.Text:= '4000'; edtTareWeightTime.Text:= '2016-09-05 12:11:38'; edtNote.Text:= 'rem'; edtWeighBridgeNo.Text:= '02'; end; {$ENDIF} pnlWeightNum.BevelOuter:= bvNone; //pnlWeightType.BevelOuter:= bvNone; pnlPlaceHolder.BevelOuter:= bvNone; //禁止重量手动输入 frameWeightInfo1.grpWeightData.Enabled:= False; lOG('载入完成'); end; procedure TframeMain.dbgrdWeightInfoDblClick(Sender: TObject); begin inherited; actDBData22UIExecute(Nil); end; procedure TframeMain.DoCheckSelWeight(Sender: TObject); var DBWeightInfo: TWeightInfo; begin //检测到的重量是什么类型的检查。 //1 如果数据库中联单不存在,则两者都可以选 //2 如果数据库联单存在, 则只能选择数据库中无效的选项, // 如果有效项只有一项,则自动选中这一项。 if dmWeight.DB_Mainfest2Record(frameMainfrestVerify1.edtMainfestNo.Text, DBWeightInfo) then begin frameWeightInfo1.WeightMeasure:= DBWeightInfo.Mesure; rbGross.Enabled:= Not DBWeightInfo.Mesure.Gross.Valid; rbTare.Enabled := Not DBWeightInfo.Mesure.Tare.Valid; if rbGross.Enabled <> rbTare.Enabled then begin rbGross.Checked:= rbGross.Enabled; rbTare.Checked:= rbTare.Enabled; end; end else begin frameWeightInfo1.UIClear; rbGross.Enabled:= True; rbGross.Enabled:= True; end; end; procedure TframeMain.DoMainrestChanged; begin {TODO: 根据联单有无及情况更新界面数据} DoCheckSelWeight(Nil); end; procedure TframeMain.DoRecvWeightData(Weight_KG: Single); begin frameWeightNum1.SampleWeight:= Weight_KG / 1000; end; procedure TframeMain.frameMainfrestVerify1edtMainfestNoChange(Sender: TObject); begin inherited; DoMainrestChanged(); end; procedure TframeMain.HandleLogProc(const Str: String); begin mmoLog.Lines.Add(Str); end; procedure TframeMain.ProcessBuffer(var Buf: AnsiString); function SearchFrameHead: Boolean; const const_head_str: Array[0..0] of AnsiString = ( #$02 ); var i: Integer; newLen: Integer; var Head_Str: AnsiString; begin Result:= False; Head_Str:= const_head_str[0]; i:= Pos(Head_Str, Buf); if i > 0 then begin newLen:= Length(Buf) - i + 1; System.Move((PAnsiChar(Buf) + i - 1)^, PAnsiChar(Buf)^, newLen); SetLength(Buf, newLen); Result:= True; end else begin Buf:= ''; end; end; function GetVerify(Ptr: PByte): Byte; var i: Integer; begin Result:= 0; for i := 0 to 7 do begin Result:= Result xor Ptr^; Inc(Ptr); end; end; Procedure ProcessData; var NumStr: AnsiString; SignStr: AnsiChar; DotPosStr: AnsiChar; Num: Single; DotPos: Integer; begin SetLength(NumStr, 6); SignStr:= Buf[2]; Move(Buf[3], NumStr[1], 6); DotPosStr:= Buf[9]; try if SignStr in [#$2B, #$2D] then begin Num:= StrToInt(String(NumStr)); DotPos:= StrToInt(String(DotPosStr)); While(DotPos > 0) do begin Num:= Num / 10; Dec(DotPos); end; if SignStr = #$2D then Num:= -Num; DoRecvWeightData(Num); end else begin raise Exception.Create('符号位不能识别'); end; except on E: Exception do begin With MultiLineLog do begin AddLine('数据解析失败: '); AddLine(Format('%s: %s', [E.ClassName, E.Message])); AddLine(Format('数据: %s', [Buf2Hex(Buf)])); end; end; end; end; var FrameLen: Byte; begin inherited; //共12字节 //起始 符号字节 N6 N5 N4 N3 N2 N1 DOTPOS XOR 结束 // 02 2B 30 30 32 30 30 30 32 31 42 03 // 校验方法:前九个字节进行XOR,得到一字节,转换成2字节ASC码 FrameLen:= 12; while (Length(Buf) >= 12) and (SearchFrameHead()) do begin if Length(Buf) >= FrameLen then begin if FrameLen < 50{最长帧长不超过50} then begin if Length(Buf) >= FrameLen {连头尾算在内的总长度字节} then begin if (GetVerify(@Buf[2]) = StrToIntDef('$' + String( Buf[10] + Buf[11]), $00)){ or True{不校验} and (Buf[12] = #$03) //帧尾正确 then begin ProcessData; Buf:= RightStr(Buf, Length(buf) - FrameLen); end else begin Buf:= RightStr(Buf, Length(buf) - 1); end; end else begin break; ///等数据 end; end else begin Buf:= RightStr(Buf, Length(buf) - 1); end; end else begin break; ///等数据 end; end; end; end.
unit MidiDevices; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MidiClasses, StdCtrls, SyncObjs, CheckLst; type TFormMidiDevices = class(TForm) Label1: TLabel; Label2: TLabel; memLog: TMemo; Label3: TLabel; lbxInputDevices: TCheckListBox; lbxOutputDevices: TCheckListBox; Label4: TLabel; edtSysExData: TEdit; btnSendSysEx: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lbxInputDevicesClickCheck(Sender: TObject); procedure lbxOutputDevicesClickCheck(Sender: TObject); procedure btnSendSysExClick(Sender: TObject); private fCriticalSection: TCriticalSection; public procedure DoMidiInData( const aDeviceIndex: integer; const aStatus, aData1, aData2: byte ); procedure DoSysExData( const aDeviceIndex: integer; const aStream: TMemoryStream ); end; var FormMidiDevices: TFormMidiDevices; implementation {$R *.dfm} procedure TFormMidiDevices.DoMidiInData(const aDeviceIndex: integer; const aStatus, aData1, aData2: byte); var i: integer; begin // skip active sensing signals from keyboard if aStatus = $FE then Exit; fCriticalSection.Acquire; memLog.Lines.BeginUpdate; try // send the messages on to the selected output devices for i:=MidiOutput.Devices.COunt - 1 downto 0 do if lbxOUtputDevices.Checked[i] then begin MidiOutput.Send( i, aStatus, aData1, aData2 ); memLog.Lines.Insert( 0, ' -->' + MidiOutput.Devices[i] ); end; // print the message log memLog.Lines.Insert( 0, Format( '[%s] %s: <Status> %.2x, <Data 1> %.2x <Data 2> %.2x', [ FormatDateTime( 'HH:NN:SS.ZZZ', now ), MidiInput.Devices[aDeviceIndex], aStatus, aData1, aData2 ] )); finally memLog.Lines.EndUpdate; fCriticalSection.Leave; end; end; procedure TFormMidiDevices.FormCreate(Sender: TObject); begin fCriticalSection := TCriticalSection.Create; lbxInputDevices.Items.Assign( MidiInput.Devices ); lbxOutputDevices.Items.Assign( MidiOutput.Devices ); MidiInput.OnMidiData := DoMidiInData; MidiInput.OnSysExData := DoSysExData; end; procedure TFormMidiDevices.FormDestroy(Sender: TObject); begin FreeAndNil( fCriticalSection ); end; procedure TFormMidiDevices.lbxInputDevicesClickCheck(Sender: TObject); begin if lbxINputDevices.Checked[ lbxInputDevices.ItemIndex ] then MidiInput.Open( lbxInputDevices.ItemIndex ) else MidiInput.Close( lbxInputDevices.ItemIndex ) end; procedure TFormMidiDevices.lbxOutputDevicesClickCheck(Sender: TObject); begin if lbxOutputDevices.Checked[ lbxOutputDevices.ItemIndex ] then MidiOutput.Open( lbxOutputDevices.ItemIndex ) else MidiOutput.Close( lbxOutputDevices.ItemIndex ) end; procedure TFormMidiDevices.DoSysExData(const aDeviceIndex: integer; const aStream: TMemoryStream); begin fCriticalSection.Acquire; memLog.Lines.BeginUpdate; try // print the message log memLog.Lines.Insert( 0, Format( '[%s] %s: <Bytes> %d <SysEx> %s', [ FormatDateTime( 'HH:NN:SS.ZZZ', now ), MidiInput.Devices[aDeviceIndex], aStream.Size, SysExStreamToStr( aStream ) ] )); finally memLog.Lines.EndUpdate; fCriticalSection.Leave; end; end; procedure TFormMidiDevices.btnSendSysExClick(Sender: TObject); var i: integer; begin for i:=MidiOutput.Devices.COunt - 1 downto 0 do if lbxOUtputDevices.Checked[i] then begin MidiOutput.SendSysEx( i, edtSysExData.Text ); memLog.Lines.Insert( 0, ' --> ' + MidiOutput.Devices[i] + ' ' + edtSysExData.Text ); end; end; end.
unit uMembersClass; interface uses {The various uses which the unit may require are loaded.} SysUtils, Classes; {Class is created as TSpeeches.} type TMembers = class {The Private attributes are added.} private mMemberID : integer; mName : string; mSurname : string; mBlock : string; mHouse : string; mPosition : string; mYearJoined : integer; {The public methods are added.} public {The class constructor is described.} constructor Create(id : integer; name, surname, block, house, pos : string; year : integer); {The functions which return values.} function getID : integer; function getName : string; function getSurname : string; function getBlock : string; function getHouse : string; function getPosition : string; function getYearJoined : integer; {AddSpaces function allows for equal spacing between strings.} function addSpaces(s : String; i : integer) : string; {ToString function converts all the data to a single string and retsurns it.} function toString : string; function toNameString : string; {The procedures which allow values in the class to be set to a specific value.} procedure setID(id : integer); procedure setName(name : string); procedure setSurname(surname : string); procedure setBlock(block : string); procedure setHouse(house : string); procedure setPosition(pos : string); procedure setYearJoined(year : integer); end; implementation { TMembers } {Allows strings to fill a preset number of spaces (i) and appends the string with spaces if it is less than that lenght (i).} function TMembers.addSpaces(s: String; i: integer): String; var counter : integer; begin Result := s; for counter := 1 to i - length(s) do begin Result := Result + ' '; end; end; constructor TMembers.Create(id: integer; name, surname, block, house, pos: string; year: integer); begin mMemberID := id; mName := name; mSurname := surname; mBlock := block; mHouse := house; mPosition := pos; mYearJoined := year; end; {The following functions return the values found in the attributes of the class.} function TMembers.getBlock: string; begin Result := mBlock; end; function TMembers.getHouse: string; begin Result := mHouse; end; function TMembers.getID: integer; begin Result := mMemberID; end; function TMembers.getName: string; begin Result := mName; end; function TMembers.getPosition: string; begin Result := mPosition; end; function TMembers.getSurname: string; begin Result := mSurname; end; function TMembers.getYearJoined: integer; begin Result := mYearJoined end; {The following procedures set the attributes of the class to the values that are entered into the procedure.} procedure TMembers.setBlock(block: string); begin mBlock := block; end; procedure TMembers.setHouse(house: string); begin mHouse := house; end; procedure TMembers.setID(id: integer); begin mMemberID := id; end; procedure TMembers.setName(name: string); begin mName := name; end; procedure TMembers.setPosition(pos: string); begin mPosition := pos; end; procedure TMembers.setSurname(surname: string); begin mSurname := surname; end; procedure TMembers.setYearJoined(year: integer); begin mYearJoined := year; end; {A function that compiles the crucial information in the class and returns it as a single, formatted string displaying only fullname for output purposes.} function TMembers.toNameString: string; var name, surname : string; begin name := mName; surname := mSurname; Result := name + ' ' + surname; end; {A function that compiles the crucial information in the class and returns it as a single, formatted string for output purposes.} function TMembers.toString: string; var name : string; surname : string; begin name := mName; surname := mSurname; {Ensure name does not exceed character display limit, else it is cut and indicated with ellipsis.} if length(name) > 12 then begin name := Copy(name, 1, 7) + ' ... '; end; {Ensure surname does not exceed character display limit, else it is cut and indicated with ellipsis.} if length(surname) > 12 then begin surname := Copy(surname, 1, 7) + ' ... '; end; Result := addSpaces(name, 12) + addSpaces(surname, 13) + addSpaces(mBlock, 3) + addSpaces(mHouse, 10); if mPosition <> 'Member' then begin Result := Result + addSpaces(mPosition, 7); end; end; end.
unit fMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, SHDocVw, ExtCtrls, StdCtrls, uWebBrowser; type TfrmMain = class(TForm) WebBrowser1: TWebBrowser; Timer1: TTimer; btnInject: TButton; procedure Timer1Timer(Sender: TObject); procedure btnInjectClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } fWBWrapper: TWBWrapper; public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.dfm} procedure TfrmMain.btnInjectClick(Sender: TObject); function GetResourceAsString(const resource_name: String): String; var rs: TResourceStream; ss: TStringStream; begin rs := TResourceStream.Create(hInstance, resource_name, RT_RCDATA); try ss := TStringStream.Create(''); try rs.SaveToStream(ss); ss.Seek(0, soBeginning); Result := ss.DataString; finally ss.Free; end; finally rs.Free; end; end; var exe_file: String; begin fWBWrapper.ExecJS(GetResourceAsString('JQUERY')); fWBWrapper.ExecJS(GetResourceAsString('JQCSSRULE')); exe_file := ExtractFileName(Forms.Application.ExeName); fWBWrapper.ExecJS( Format( '$.cssRule({"table.tablesorter thead tr .header": "background-image: url(res|//%s/IMAGEBG); ' + 'background-repeat: no-repeat; ' + 'background-position: center right; ' + 'cursor: pointer; ' + 'padding-right: 20px; ' + 'border-right: 1px solid #dad9c7; ' + 'margin-left: -1px;", ' + '"table.tablesorter thead tr th.headerSortUp": "background-image: url(res|//%s/IMAGEASC);", ' + '"table.tablesorter thead tr th.headerSortDown": "background-image: url(res|//%s/IMAGEDESC);" });', [exe_file,exe_file,exe_file]) ); fWBWrapper.ExecJS('$("#t1").addClass("tablesorter");'); fWBWrapper.ExecJS(GetResourceAsString('TABLESORT')); fWBWrapper.ExecJS('$("#t1").tablesorter();'); end; procedure TfrmMain.FormCreate(Sender: TObject); begin fWBWrapper := TWBWrapper.Create(WebBrowser1); end; procedure TfrmMain.FormDestroy(Sender: TObject); begin fWBWrapper.Free; end; procedure TfrmMain.Timer1Timer(Sender: TObject); const html_doc = '<html> '#13#10 + '<body> '#13#10 + ' <table id="t1" border="1"> '#13#10 + ' <thead> '#13#10 + ' <tr> '#13#10 + ' <th class="header">number</th> '#13#10 + ' <th class="header">letter</th> '#13#10 + ' <th class="header">name</th> '#13#10 + ' </tr> '#13#10 + ' </thead> '#13#10 + ' <tbody> '#13#10 + ' <tr> '#13#10 + ' <td>1</td> '#13#10 + ' <td>a</td> '#13#10 + ' <td>zood</td> '#13#10 + ' </tr> '#13#10 + ' <tr> '#13#10 + ' <td>2</td> '#13#10 + ' <td>c</td> '#13#10 + ' <td>craig</td> '#13#10 + ' </tr> '#13#10 + ' <tr> '#13#10 + ' <td>3</td> '#13#10 + ' <td>b</td> '#13#10 + ' <td>joe</td> '#13#10 + ' </tr> '#13#10 + ' </tbody> '#13#10 + ' </table> '#13#10 + '</body> '#13#10 + '</html> '; begin TTimer(Sender).Enabled := false; fWBWrapper.LoadHTML(html_doc); end; end.
unit Test.Devices.Ancom; interface uses TestFrameWork, Devices.Ancom, GMGlobals; type TAncomTest = class(TTestCase) private buf: array [0..25] of byte; procedure ZeroBuf; procedure DoCheck(n: int); protected published procedure CheckId; end; implementation uses DateUtils, SysUtils, GMConst; { TAncomTest } procedure TAncomTest.ZeroBuf(); var i: int; begin for i := 0 to High(buf) do buf[i] := 0; end; procedure TAncomTest.DoCheck(n: int); var res: int; begin res := ReadAncomID(buf, Length(buf)); Check(res = n, 'res = ' + IntToStr(res) + ' <> ' + IntToStr(n)); end; procedure TAncomTest.CheckId; begin ZeroBuf(); WriteString(buf, 0, '111'); DoCheck(111); ZeroBuf(); WriteString(buf, 1, '111'); DoCheck(-1); ZeroBuf(); WriteString(buf, 0, '111222'); DoCheck(111222); ZeroBuf(); WriteString(buf, 0, '111A222'); DoCheck(-1); ZeroBuf(); WriteString(buf, 0, '111222333'); DoCheck(-1); ZeroBuf(); WriteString(buf, 0, '12345678'); DoCheck(12345678); ZeroBuf(); WriteString(buf, 0, '12345678'); buf[20] := 1; DoCheck(12345678); end; initialization RegisterTest('GMIOPSrv/Devices/Ancom', TAncomTest.Suite); end.
unit uSystemUtils; interface function MsgConfirm(aMessage: string): boolean; procedure MsgWarning(aMessage: string); function ENumeroDecimal(Key: Char): boolean; implementation uses Vcl.Forms, Winapi.Windows, System.SysUtils; function MsgConfirm(aMessage: string): boolean; begin Result := Application.MessageBox(PWideChar(aMessage), 'Universidade', MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2) = ID_YES; end; procedure MsgWarning(aMessage: string); begin Application.MessageBox(PWideChar(aMessage), 'Universidade', MB_OK + MB_ICONWARNING); end; function ENumeroDecimal(Key: Char): boolean; begin Result := CharInSet(Key, ['0'..'9',',']); end; end.
unit fRenewOutMed; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ComCtrls, ORFn, rOrders, Mask, ORCtrls, ExtCtrls, fBase508Form, VA508AccessibilityManager, VA508AccessibilityRouter, rODBase, rODMeds; type TfrmRenewOutMed = class(TfrmBase508Form) memOrder: TCaptionMemo; pnlButtons: TPanel; cmdOK: TButton; cmdCancel: TButton; pnlMiddle: TPanel; cboPickup: TORComboBox; lblPickup: TLabel; txtRefills: TCaptionEdit; lblRefills: TLabel; VA508ComponentAccessibility1: TVA508ComponentAccessibility; procedure FormCreate(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); procedure VA508ComponentAccessibility1StateQuery(Sender: TObject; var Text: string); procedure FormShow(Sender: TObject); private OKPressed: Boolean; end; function ExecuteRenewOutMed(var Refills: Integer; var Comments, Pickup: string; AnOrder: TOrder): Boolean; implementation {$R *.DFM} uses VAUtils; var MaxRefills: Integer; const TX_ERR_REFILL = 'The number of refills must be in the range of 0 through '; TC_ERR_REFILL = 'Refills'; function ExecuteRenewOutMed(var Refills: Integer; var Comments, Pickup: string; AnOrder: TOrder): Boolean; var frmRenewOutMed: TfrmRenewOutMed; DestList: TList; HasObject: Boolean; i: Integer; Drug, Days, OrID: string; begin Result := False; DestList := TList.Create(); try LoadResponses(DestList, 'X' + AnOrder.ID, HasObject); for I := 0 to DestList.Count - 1 do begin if TResponse(DestList.Items[i]).PromptID = 'DRUG' then Drug := TResponse(DestList.Items[i]).IValue else if TResponse(DestList.Items[i]).PromptID = 'SUPPLY' then Days := TResponse(DestList.Items[i]).IValue else if TResponse(DestList.Items[i]).PromptID = 'ORDERABLE' then OrID := TResponse(DestList.Items[i]).IValue; end; MaxRefills := CalcMaxRefills(Drug, StrToIntDef(Days, 0), StrToInt(OrID), AnOrder.EventName = 'D'); frmRenewOutMed := TfrmRenewOutMed.Create(Application); try ResizeFormToFont(TForm(frmRenewOutMed)); frmRenewOutMed.memOrder.SetTextBuf(PChar(AnOrder.Text)); frmRenewOutMed.txtRefills.Text := IntToStr(Refills); frmRenewOutMed.cboPickup.SelectByID(Pickup); frmRenewOutMed.ShowModal; if frmRenewOutMed.OKPressed then begin Result := True; Refills := StrToIntDef(frmRenewOutMed.txtRefills.Text, Refills); Pickup := frmRenewOutMed.cboPickup.ItemID; end; finally frmRenewOutMed.Release; end; finally DestList.Free; end; end; procedure TfrmRenewOutMed.FormCreate(Sender: TObject); begin inherited; OKPressed := False; with cboPickup.Items do begin Add('W^at Window'); Add('M^by Mail'); Add('C^in Clinic'); end; end; procedure TfrmRenewOutMed.FormShow(Sender: TObject); begin inherited; if ScreenReaderSystemActive then begin memOrder.TabStop := true; memOrder.SetFocus; end; end; procedure TfrmRenewOutMed.VA508ComponentAccessibility1StateQuery( Sender: TObject; var Text: string); begin inherited; Text := memOrder.Text; end; procedure TfrmRenewOutMed.cmdOKClick(Sender: TObject); var NumRefills: Integer; begin inherited; NumRefills := StrToIntDef(txtRefills.Text, -1); if (NumRefills < 0) or (NumRefills > MaxRefills) then begin InfoBox(TX_ERR_REFILL + IntToStr(MaxRefills), TC_ERR_REFILL, MB_OK); Exit; end; OKPressed := True; Close; end; procedure TfrmRenewOutMed.cmdCancelClick(Sender: TObject); begin inherited; Close; end; end.
unit WordList; interface uses Word, System.Generics.Collections, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Math, System.Variants, FMX.Objects, FMX.StdCtrls, FMX.Types, FMX.Layouts; type TWordList = class private Flist: TList<TWord>; FcomputedPos: integer; FForbiddenCase: TLetterPosition; FCaseLength: integer; procedure Sort; function WordIntersection(s1: string; s2: string): TLetterPosition; function ComputePosFirstWord: TLetterPosition; function ComputeWordPosition(interindex: integer; index: integer; inter: TPoint): boolean; function CheckConsistency(tlp: TLetterPosition; s: string; sens: TSens): boolean; function GridTopLeft: TPoint; function GridBottomRight: TPoint; public Constructor Create; overload; Constructor Create(words: TStrings; defs: TStrings); overload; Destructor destroy; procedure FromTstringList(words: TStrings; defs: TStrings); procedure Execute; procedure Display(base: TRectangle); procedure DisplayCorrect(base: TRectangle); procedure DisplayDef(l1, l2: TLayout); published property List: TList<TWord> read Flist write Flist; property CaseLength: integer read FCaseLength write FCaseLength default 22; end; implementation Constructor TWordList.Create; begin Flist := TList<TWord>.Create; end; Constructor TWordList.Create(words: TStrings; defs: TStrings); begin Flist := TList<TWord>.Create; FromTstringList(words, defs); end; destructor TWordList.destroy; begin Flist.Free; end; procedure TWordList.FromTstringList(words: TStrings; defs: TStrings); var w: TWord; I: integer; begin for I := 0 to words.Count - 1 do begin w := TWord.Create; w.str := words.Strings[I]; if I < defs.Count then w.def := defs.Strings[I]; w.num := I; List.Add(w); end; end; procedure TWordList.Sort; // tri par longueur var j, I, m: integer; copyWordList: TList<TWord>; listLengths: array of integer; begin copyWordList := TList<TWord>.Create; SetLength(listLengths, List.Count); for j := 0 to List.Count - 1 do begin listLengths[j] := List.Items[j].str.Length; end; j := List.Count - 1; while j <> -1 do begin m := MaxIntValue(listLengths); for I := 0 to List.Count - 1 do begin if listLengths[I] = m then begin listLengths[I] := 0; copyWordList.Add(List.Items[I]); j := j - 1; break; end; end; end; List.Clear; for I := 0 to copyWordList.Count - 1 do List.Add(copyWordList.Items[I]); end; function TWordList.ComputePosFirstWord: TLetterPosition; var I, l, j, alea: integer; begin l := self.List.Items[0].str.Length; SetLength(Result, l); alea := random(1000); // alea mod 2 = 0 => vertical, alea mod 2 = 1 => horizontal if alea mod 2 = 0 then begin Result[l div 2].P := Point(0, 0); Result[l div 2].TC := TNormal; j := -1; for I := l div 2 + 1 to l - 1 do begin Result[I].P := Point(0, j); j := j - 1; if I <> l - 1 then Result[I].TC := TNormal else Result[I].TC := TEnd; end; j := 1; for I := l div 2 - 1 downto 0 do begin Result[I].P := Point(0, j); j := j + 1; if I <> 0 then Result[I].TC := TNormal else Result[I].TC := TEnd; end; self.List[0].sens := TVertical; end else begin Result[l div 2].P := Point(0, 0); Result[l div 2].TC := TNormal; j := 1; for I := l div 2 + 1 to l - 1 do begin Result[I].P := Point(j, 0); j := j + 1; if I <> l - 1 then Result[I].TC := TNormal else Result[I].TC := TEnd; end; j := -1; for I := l div 2 - 1 downto 0 do begin Result[I].P := Point(j, 0); j := j - 1; if I <> 0 then Result[I].TC := TNormal else Result[I].TC := TEnd; end; self.List[0].sens := THorizontal; end; end; procedure TWordList.Execute; var I, j, k: integer; bo: boolean; tlp: TLetterPosition; begin Sort; tlp := ComputePosFirstWord; self.List[0].pos := tlp; FcomputedPos := 1; SetLength(FForbiddenCase, 0); I := 1; while I < self.List.Count do begin j := FcomputedPos - 1; while j > -1 do begin SetLength(tlp, 0); tlp := WordIntersection(List.Items[j].str, List.Items[I].str); RandSort(tlp); if Length(tlp) <> 0 then begin bo := true; for k := 0 to Length(tlp) - 1 do begin if ComputeWordPosition(j, I, tlp[k].P) then begin I := I + 1; j := FcomputedPos - 1; if I = self.List.Count then exit; bo := true; break; end else bo := false; end; if bo = false then j := j - 1; end else j := j - 1; end; if j = -1 then break; end; end; function TWordList.WordIntersection(s1: string; s2: string): TLetterPosition; var I, j: integer; begin SetLength(Result, 0); for I := 1 to s1.Length do begin for j := 2 to s2.Length do begin if s1[I] = s2[j] then begin SetLength(Result, Length(Result) + 1); Result[Length(Result) - 1].P := Point(I, j); end; end; end; end; function TWordList.ComputeWordPosition(interindex: integer; index: integer; inter: TPoint): boolean; // calcule la position du mot index avec l'intersection interindex et la position de l'intersection inter var b: TSens; tlp, fc: TLetterPosition; I, j: integer; begin SetLength(tlp, List.Items[index].str.Length); // on calcule la position de la case interceptée tlp[inter.Y - 1].P.X := List.Items[interindex].pos[inter.X - 1].P.X; tlp[inter.Y - 1].P.Y := List.Items[interindex].pos[inter.X - 1].P.Y; tlp[inter.Y - 1].TC := TCommun; // fc = ForbiddenCase SetLength(fc, 6); fc[0].P := Point(tlp[inter.Y - 1].P.X - 1, tlp[inter.Y - 1].P.Y - 1); fc[1].P := Point(tlp[inter.Y - 1].P.X + 1, tlp[inter.Y - 1].P.Y - 1); fc[2].P := Point(tlp[inter.Y - 1].P.X - 1, tlp[inter.Y - 1].P.Y + 1); fc[3].P := Point(tlp[inter.Y - 1].P.X + 1, tlp[inter.Y - 1].P.Y + 1); if self.List.Items[interindex].sens = THorizontal then begin b := TVertical; j := tlp[inter.Y - 1].P.Y + 1; for I := inter.Y - 2 downto 0 do begin tlp[I].P := Point(tlp[inter.Y - 1].P.X, j); j := j + 1; if I = inter.Y - 2 then tlp[I].TC := TTypeCase.TTopCommun else if I = 0 then tlp[I].TC := TEnd else tlp[I].TC := TNormal; end; fc[4].P := Point(tlp[inter.Y - 1].P.X, j); j := tlp[inter.Y - 1].P.Y - 1; for I := inter.Y to Length(tlp) - 1 do begin tlp[I].P := Point(tlp[inter.Y - 1].P.X, j); j := j - 1; if I = inter.Y then tlp[I].TC := TTypeCase.TBottomCommun else if I = Length(tlp) - 1 then tlp[I].TC := TEnd else tlp[I].TC := TNormal; end; fc[5].P := Point(tlp[inter.Y - 1].P.X, j); end else begin b := THorizontal; j := tlp[inter.Y - 1].P.X - 1; for I := inter.Y - 2 downto 0 do begin tlp[I].P := Point(j, tlp[inter.Y - 1].P.Y); j := j - 1; if I = inter.Y - 2 then tlp[I].TC := TTypeCase.TLeftCommun else if I = 0 then tlp[I].TC := TEnd else tlp[I].TC := TNormal; end; fc[4].P := Point(j, tlp[inter.Y - 1].P.Y); j := tlp[inter.Y - 1].P.X + 1; for I := inter.Y to Length(tlp) - 1 do begin tlp[I].P := Point(j, tlp[inter.Y - 1].P.Y); j := j + 1; if I = inter.Y then tlp[I].TC := TTypeCase.TRightCommun else if I = Length(tlp) - 1 then tlp[I].TC := TEnd else tlp[I].TC := TNormal; end; fc[5].P := Point(j, tlp[inter.Y - 1].P.Y); end; if CheckConsistency(tlp, List.Items[index].str, b) then begin List.Items[index].pos := tlp; List.Items[index].sens := b; List.Items[interindex].pos[inter.X - 1].TC := TCommun; if self.List.Items[interindex].sens = THorizontal then begin if inter.X - 2 >= 0 then if List.Items[interindex].pos[inter.X - 2].TC = TRightCommun then List.Items[interindex].pos[inter.X - 2].TC := TRightLeftCommun else List.Items[interindex].pos[inter.X - 2].TC := TLeftCommun; if inter.X < Length(List.Items[interindex].pos) then if List.Items[interindex].pos[inter.X].TC = TLeftCommun then List.Items[interindex].pos[inter.X].TC := TRightLeftCommun else List.Items[interindex].pos[inter.X].TC := TRightCommun; end else begin if inter.X - 2 >= 0 then if List.Items[interindex].pos[inter.X - 2].TC = TBottomCommun then List.Items[interindex].pos[inter.X - 2].TC := TBottomTopCommun else List.Items[interindex].pos[inter.X - 2].TC := TTopCommun; if inter.X < Length(List.Items[interindex].pos) then if List.Items[interindex].pos[inter.X].TC = TTopCommun then List.Items[interindex].pos[inter.X].TC := TBottomTopCommun else List.Items[interindex].pos[inter.X].TC := TBottomCommun; end; SetLength(FForbiddenCase, Length(FForbiddenCase) + 6); FForbiddenCase[Length(FForbiddenCase) - 1] := fc[3]; FForbiddenCase[Length(FForbiddenCase) - 2] := fc[2]; FForbiddenCase[Length(FForbiddenCase) - 3] := fc[1]; FForbiddenCase[Length(FForbiddenCase) - 4] := fc[0]; FForbiddenCase[Length(FForbiddenCase) - 5] := fc[4]; FForbiddenCase[Length(FForbiddenCase) - 6] := fc[5]; FcomputedPos := FcomputedPos + 1; Result := true; end else Result := false; end; function TWordList.CheckConsistency(tlp: TLetterPosition; s: string; sens: TSens): boolean; var I, j, k: integer; t1, t2: TPoint; begin Result := true; if sens = THorizontal then begin t1.X := tlp[0].P.X - 1; t1.Y := tlp[0].P.Y; t2.X := tlp[Length(tlp) - 1].P.X + 1; t2.Y := t1.Y; end else begin t1.X := tlp[0].P.X; t1.Y := tlp[0].P.Y + 1; t2.X := t1.X; t2.Y := tlp[Length(tlp) - 1].P.Y - 1; end; for I := 0 to FcomputedPos - 1 do begin for j := 0 to Length(List.Items[I].pos) - 1 do begin for k := 0 to Length(tlp) - 1 do begin if (tlp[k].P = List.Items[I].pos[j].P) and (s[k + 1] <> List.Items[I].str[j + 1]) then begin Result := false; exit; end; end; if t1 = List.Items[I].pos[j].P then begin Result := false; exit; end; if t2 = List.Items[I].pos[j].P then begin Result := false; exit; end; end; end; for I := 0 to Length(tlp) - 1 do begin for j := 0 to Length(FForbiddenCase) - 1 do begin if tlp[I].P = FForbiddenCase[j].P then begin Result := false; exit; end; end; end; end; procedure TWordList.Display(base: TRectangle); var I, j: integer; t, s: TPoint; r: TRectangle; t1, t2: integer; l: tLabel; P: TList<TPoint>; begin t := GridTopLeft; for I := base.ChildrenCount - 1 downto 0 do begin base.Children.Items[I].Free; end; P := TList<TPoint>.Create; try for I := 0 to List.Count - 1 do begin if Length(List.Items[I].pos) > 0 then begin t1 := abs(t.X - List.Items[I].pos[0].P.X) * self.FCaseLength; t2 := abs(t.Y - List.Items[I].pos[0].P.Y) * FCaseLength; s.X := t1; s.Y := t2; r := TRectangle.Create(base); r.Parent := base; r.Position.X := t1; r.Position.Y := t2; r.Height := FCaseLength; r.Width := FCaseLength; r.Fill.Color := TAlphaColorRec.white; l := tLabel.Create(r); l.Parent := r; l.Align := TAlignLayout.top; l.Margins.Left := 1; l.Text := IntToStr(List.Items[I].num + 1); l.StyledSettings := []; l.FontColor := TAlphaColor($FF000001); l.Font.Size := 8; if List.Items[I].sens = THorizontal then begin if List.Items[I].pos[0].TC <> TCommun then r.Sides := r.Sides - [TSide.Right]; end else begin if List.Items[I].pos[0].TC <> TCommun then r.Sides := r.Sides - [TSide.Bottom]; end; P.Add(s); end; for j := 1 to Length(List.Items[I].pos) - 2 do begin t1 := abs(t.X - List.Items[I].pos[j].P.X) * self.FCaseLength; t2 := abs(t.Y - List.Items[I].pos[j].P.Y) * FCaseLength; s.X := t1; s.Y := t2; if inList(s, P) = false then begin r := TRectangle.Create(base); r.Parent := base; r.Position.X := abs(t.X - List.Items[I].pos[j].P.X) * FCaseLength; r.Position.Y := abs(t.Y - List.Items[I].pos[j].P.Y) * FCaseLength; r.Height := FCaseLength; r.Width := FCaseLength; r.Fill.Color := TAlphaColorRec.white; P.Add(s); r.Sides := []; if List.Items[I].sens = THorizontal then begin if (List.Items[I].pos[j].TC = TRightCommun) or (List.Items[I].pos[j].TC = TRightLeftCommun) then begin r.Sides := [TSide.top] + [TSide.Bottom]; end else if List.Items[I].pos[j].TC = TCommun then begin r.Sides := [TSide.top] + [TSide.Bottom] + [TSide.Right] + [TSide.Left]; end else begin r.Sides := [TSide.top] + [TSide.Bottom] + [TSide.Left]; end; end else begin if (List.Items[I].pos[j].TC = TBottomCommun) or (List.Items[I].pos[j].TC = TBottomTopCommun) then begin r.Sides := [TSide.Left] + [TSide.Right]; end else if List.Items[I].pos[j].TC = TCommun then begin r.Sides := [TSide.top] + [TSide.Bottom] + [TSide.Right] + [TSide.Left]; end else begin r.Sides := [TSide.top] + [TSide.Left] + [TSide.Right]; end; end; end; end; if Length(List.Items[I].pos) > 0 then begin j := Length(List.Items[I].pos) - 1; t1 := abs(t.X - List.Items[I].pos[j].P.X) * self.FCaseLength; t2 := abs(t.Y - List.Items[I].pos[j].P.Y) * FCaseLength; s.X := t1; s.Y := t2; if inList(s, P) = false then begin r := TRectangle.Create(base); r.Parent := base; r.Position.X := abs(t.X - List.Items[I].pos[j].P.X) * FCaseLength; r.Position.Y := abs(t.Y - List.Items[I].pos[j].P.Y) * FCaseLength; r.Height := FCaseLength; r.Width := FCaseLength; r.Fill.Color := TAlphaColorRec.white; P.Add(s); if List.Items[I].sens = THorizontal then begin if List.Items[I].pos[j].TC = TRightCommun then r.Sides := r.Sides - [TSide.Left]; end else begin if List.Items[I].pos[j].TC = TBottomCommun then r.Sides := r.Sides - [TSide.top]; end; end; end; end; finally P.Free; end; end; procedure TWordList.DisplayCorrect(base: TRectangle); var I, j: integer; t, s: TPoint; r: TRectangle; t1, t2, fontsize: integer; l: tLabel; P: TList<TPoint>; begin t := GridTopLeft; fontsize := 8 + self.FCaseLength - 22; for I := base.ChildrenCount - 1 downto 0 do begin base.Children.Items[I].Free; end; P := TList<TPoint>.Create; try for I := 0 to List.Count - 1 do begin if Length(List.Items[I].pos) > 0 then begin t1 := abs(t.X - List.Items[I].pos[0].P.X) * self.FCaseLength; t2 := abs(t.Y - List.Items[I].pos[0].P.Y) * FCaseLength; s.X := t1; s.Y := t2; r := TRectangle.Create(base); r.Parent := base; r.Position.X := t1; r.Position.Y := t2; r.Height := FCaseLength; r.Width := FCaseLength; r.Fill.Color := TAlphaColorRec.white; l := tLabel.Create(r); l.Parent := r; l.Align := TAlignLayout.Client; // l.Margins.Left := self.FCaseLength div 3; l.Text := self.List.Items[I].str[1]; l.StyledSettings := []; l.FontColor := TAlphaColor($FF000001); l.Font.Size := fontsize; l.TextSettings.HorzAlign := TTextAlign.Center; l.TextSettings.VertAlign := TTextAlign.Center; if List.Items[I].sens = THorizontal then begin if List.Items[I].pos[0].TC <> TCommun then r.Sides := r.Sides - [TSide.Right]; end else begin if List.Items[I].pos[0].TC <> TCommun then r.Sides := r.Sides - [TSide.Bottom]; end; P.Add(s); end; for j := 1 to Length(List.Items[I].pos) - 2 do begin t1 := abs(t.X - List.Items[I].pos[j].P.X) * self.FCaseLength; t2 := abs(t.Y - List.Items[I].pos[j].P.Y) * FCaseLength; s.X := t1; s.Y := t2; if inList(s, P) = false then begin r := TRectangle.Create(base); r.Parent := base; r.Position.X := abs(t.X - List.Items[I].pos[j].P.X) * FCaseLength; r.Position.Y := abs(t.Y - List.Items[I].pos[j].P.Y) * FCaseLength; r.Height := FCaseLength; r.Width := FCaseLength; r.Fill.Color := TAlphaColorRec.white; l := tLabel.Create(r); l.Parent := r; l.Align := TAlignLayout.Client; l.Text := self.List.Items[I].str[j + 1]; l.StyledSettings := []; l.FontColor := TAlphaColor($FF000001); l.Font.Size := fontsize; l.TextSettings.HorzAlign := TTextAlign.Center; l.TextSettings.VertAlign := TTextAlign.Center; P.Add(s); r.Sides := []; if List.Items[I].sens = THorizontal then begin if (List.Items[I].pos[j].TC = TRightCommun) or (List.Items[I].pos[j].TC = TRightLeftCommun) then begin r.Sides := [TSide.top] + [TSide.Bottom]; end else if List.Items[I].pos[j].TC = TCommun then begin r.Sides := [TSide.top] + [TSide.Bottom] + [TSide.Right] + [TSide.Left]; end else begin r.Sides := [TSide.top] + [TSide.Bottom] + [TSide.Left]; end; end else begin if (List.Items[I].pos[j].TC = TBottomCommun) or (List.Items[I].pos[j].TC = TBottomTopCommun) then begin r.Sides := [TSide.Left] + [TSide.Right]; end else if List.Items[I].pos[j].TC = TCommun then begin r.Sides := [TSide.top] + [TSide.Bottom] + [TSide.Right] + [TSide.Left]; end else begin r.Sides := [TSide.top] + [TSide.Left] + [TSide.Right]; end; end; end; end; if Length(List.Items[I].pos) > 0 then begin j := Length(List.Items[I].pos) - 1; t1 := abs(t.X - List.Items[I].pos[j].P.X) * self.FCaseLength; t2 := abs(t.Y - List.Items[I].pos[j].P.Y) * FCaseLength; s.X := t1; s.Y := t2; if inList(s, P) = false then begin r := TRectangle.Create(base); r.Parent := base; r.Position.X := abs(t.X - List.Items[I].pos[j].P.X) * FCaseLength; r.Position.Y := abs(t.Y - List.Items[I].pos[j].P.Y) * FCaseLength; r.Height := FCaseLength; r.Width := FCaseLength; r.Fill.Color := TAlphaColorRec.white; l := tLabel.Create(r); l.Parent := r; l.Align := TAlignLayout.Client; // l.Margins.Left := self.FCaseLength div 3; l.Text := self.List.Items[I].str[j + 1]; l.StyledSettings := []; l.FontColor := TAlphaColor($FF000001); l.TextSettings.HorzAlign := TTextAlign.Center; l.TextSettings.VertAlign := TTextAlign.Center; l.Font.Size := fontsize; if List.Items[I].sens = THorizontal then begin if List.Items[I].pos[j].TC = TRightCommun then r.Sides := r.Sides - [TSide.Left]; end else begin if List.Items[I].pos[j].TC = TBottomCommun then r.Sides := r.Sides - [TSide.top]; end; P.Add(s); end; end; end; finally P.Free; end; end; function TWordList.GridTopLeft: TPoint; var minX, maxY, I: integer; begin minX := 0; maxY := 0; for I := 0 to List.Count - 1 do begin if Length(List.Items[I].pos) > 0 then begin if List.Items[I].pos[0].P.X < minX then minX := List.Items[I].pos[0].P.X; if List.Items[I].pos[0].P.Y > maxY then maxY := List.Items[I].pos[0].P.Y; if List.Items[I].pos[Length(List.Items[I].pos) - 1].P.X < minX then minX := List.Items[I].pos[Length(List.Items[I].pos) - 1].P.X; if List.Items[I].pos[Length(List.Items[I].pos) - 1].P.Y > maxY then maxY := List.Items[I].pos[Length(List.Items[I].pos) - 1].P.Y; end; end; Result := Point(minX - 1, maxY + 1); end; function TWordList.GridBottomRight: TPoint; var maxX, minY, I, j: integer; begin minY := 0; maxX := 0; for I := 0 to List.Count - 1 do begin for j := 0 to Length(List.Items[I].pos) - 1 do begin if List.Items[I].pos[j].P.Y < minY then minY := List.Items[I].pos[j].P.Y; if List.Items[I].pos[j].P.X > maxX then maxX := List.Items[I].pos[j].P.X; end; end; Result := Point(maxX + 1, minY - 1); end; procedure TWordList.DisplayDef(l1, l2: TLayout); var I: integer; lab: tLabel; begin for I := l1.ChildrenCount - 1 downto 0 do begin l1.Children.Items[I].Free; end; for I := l2.ChildrenCount - 1 downto 0 do begin l2.Children.Items[I].Free; end; for I := 0 to List.Count - 1 do begin if List.Items[I].sens = TVertical then begin lab := tLabel.Create(l1); lab.Parent := l1; lab.Text := IntToStr(List.Items[I].num + 1) + ' - ' + List.Items[I].def; lab.Align := TAlignLayout.top; lab.StyledSettings := []; lab.FontColor := TAlphaColor($FF000001); lab.Margins.Left := 2; end else begin lab := tLabel.Create(l2); lab.Parent := l2; lab.Text := IntToStr(List.Items[I].num + 1) + ' - ' + List.Items[I].def; lab.Align := TAlignLayout.top; lab.StyledSettings := []; lab.FontColor := TAlphaColor($FF000001); lab.Margins.Left := 2; end; end; end; end.
unit hammingdistances; {$mode objfpc}{$H+} interface uses Classes, SysUtils; function GetHammingDistance(First, Second: string): integer; implementation function GetHammingDistance(First, Second: string): integer; var index, distance: integer; begin if (Length(First) = Length(Second)) and (Length(First) > 0) then begin distance := 0; for Index := 1 to Length(First) do begin if First[Index] <> Second[Index] then Inc(distance); end; end else distance := -1; Result := distance; end; end.
unit ReduceBIEExemptions; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids, Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, RPCanvas, RPrinter, RPDefine, RPBase, RPFiler, locatdir; type TReduceBIEExemptionsForm = class(TForm) Panel1: TPanel; Panel2: TPanel; ScrollBox1: TScrollBox; CloseButton: TBitBtn; TitleLabel: TLabel; StartButton: TBitBtn; ReportFiler: TReportFiler; PrintDialog: TPrintDialog; ReportPrinter: TReportPrinter; ExemptionTable: TTable; AssessmentYearRadioGroup: TRadioGroup; TrialRunCheckBox: TCheckBox; cbxUseCalculatedAmounts: TCheckBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure StartButtonClick(Sender: TObject); procedure ReportPrintHeader(Sender: TObject); procedure ReportPrint(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } UnitName : String; ProcessingType : Integer; TrialRun, ReportCancelled, bUseCalculatedAmounts : Boolean; Procedure InitializeForm; {Open the tables and setup.} end; implementation uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils, Prog, Preview, Types, PASTypes, UtilEXSD; {$R *.DFM} {========================================================} Procedure TReduceBIEExemptionsForm.FormActivate(Sender: TObject); begin SetFormStateMaximized(Self); end; {========================================================} Procedure TReduceBIEExemptionsForm.InitializeForm; begin UnitName := 'ReduceBIEExemptions'; end; {InitializeForm} {===================================================================} Procedure TReduceBIEExemptionsForm.ReportPrintHeader(Sender: TObject); begin with Sender as TBaseReport do begin {Print the date and page number.} SectionTop := 0.25; SectionLeft := 0.5; SectionRight := PageWidth - 0.5; SetFont('Times New Roman',8); PrintHeader('Page: ' + IntToStr(CurrentPage), pjRight); PrintHeader('Date: ' + DateToStr(Date) + ' Time: ' + TimeToStr(Now), pjLeft); SectionTop := 0.5; SetFont('Arial',12); Bold := True; Home; PrintCenter('Reduce BIE Exemptions', (PageWidth / 2)); SetFont('Times New Roman', 9); CRLF; Println(''); Print(' Assessment Year: '); case ProcessingType of ThisYear : Println(' This Year'); NextYear : Println(' Next Year'); end; If TrialRun then Println('Trial run.'); Println(''); Bold := True; ClearTabs; SetTab(0.3, pjCenter, 1.2, 5, BOXLINEALL, 25); {Parcel ID} SetTab(1.5, pjCenter, 0.8, 5, BOXLINEALL, 25); {Original amount} SetTab(2.3, pjCenter, 0.8, 5, BOXLINEALL, 25); {Previous amount} SetTab(3.1, pjCenter, 0.8, 5, BOXLINEALL, 25); {New amount} SetTab(3.9, pjCenter, 0.6, 5, BOXLINEALL, 25); {Difference} SetTab(4.5, pjCenter, 0.6, 5, BOXLINEALL, 25); {Initial Date} SetTab(5.1, pjCenter, 0.6, 5, BOXLINEALL, 25); {Termination date} SetTab(5.7, pjCenter, 2.0, 5, BOXLINEALL, 25); {Notes} Println(#9 + 'Parcel ID' + #9 + 'Original Amt' + #9 + 'Current Amt' + #9 + 'New Amount' + #9 + 'Difference' + #9 + 'Init Date' + #9 + 'End Date' + #9 + 'Notes'); Bold := False; ClearTabs; SetTab(0.3, pjLeft, 1.2, 5, BOXLINEALL, 0); {Parcel ID} SetTab(1.5, pjRight, 0.8, 5, BOXLINEALL, 0); {Original amount} SetTab(2.3, pjRight, 0.8, 5, BOXLINEALL, 0); {Previous amount} SetTab(3.1, pjRight, 0.8, 5, BOXLINEALL, 0); {New amount} SetTab(3.9, pjRight, 0.6, 5, BOXLINEALL, 0); {Difference} SetTab(4.5, pjLeft, 0.6, 5, BOXLINEALL, 0); {Initial Date} SetTab(5.1, pjLeft, 0.6, 5, BOXLINEALL, 0); {Termination date} SetTab(5.7, pjLeft, 2.0, 5, BOXLINEALL, 0); {Notes} end; {with Sender as TBaseReport do} end; {ReportPrintHeader} {===================================================================} Procedure TReduceBIEExemptionsForm.ReportPrint(Sender: TObject); var Done, FirstTimeThrough, Quit : Boolean; NumberReduced : Integer; OriginalBIEAmount, NewBIEAmount, OriginalExemptionAmount, TotalOriginalExemptionAmount, TotalNewBIEAmount, iCalculatedNewBIEAmount, iYearsDifference : LongInt; ExemptionAppliesArray : ExemptionAppliesArrayType; ExemptionCode, sMessage : String; wInitialYear, wCurrentYear, wMonth, wDay : Word; begin NumberReduced := 0; FirstTimeThrough := True; Quit := False; TotalOriginalExemptionAmount := 0; TotalNewBIEAmount := 0; ExemptionTable.First; with Sender as TBaseReport, ExemptionTable do begin repeat If FirstTimeThrough then FirstTimeThrough := False else Next; Done := EOF; ProgressDialog.Update(Self, ConvertSwisSBLToDashDot(FieldByName('SwisSBLKey').Text)); ProgressDialog.UserLabelCaption := 'Number BIE Exemptions Reduced = ' + IntToStr(NumberReduced); Application.ProcessMessages; ExemptionCode := FieldByName('ExemptionCode').Text; If ((not Done) and IsBIEExemptionCode(ExemptionCode)) then begin If _Compare(LinesLeft, 5, coLessThan) then NewPage; OriginalBIEAmount := 0; NewBIEAmount := 0; OriginalExemptionAmount := 0; Inc(NumberReduced); try Edit; OriginalBIEAmount := FieldByName('OriginalBIEAmount').AsInteger; NewBIEAmount := FieldByName('Amount').AsInteger - Round(OriginalBIEAmount / 10); OriginalExemptionAmount := FieldByName('Amount').AsInteger; sMessage := 'Reduced.'; If bUseCalculatedAmounts then begin DecodeDate(FieldByName('InitialDate').AsDateTime, wInitialYear, wMonth, wDay); DecodeDate(StrToDate('1/1/' + FieldByName('TaxRollYr').AsString), wCurrentYear, wMonth, wDay); iYearsDifference := wCurrentYear - wInitialYear; If _Compare(iYearsDifference, 0, coLessThan) then iYearsDifference := 0; iCalculatedNewBIEAmount := FieldByName('OriginalBIEAmount').AsInteger - (iYearsDifference * Round(OriginalBIEAmount / 10)); If _Compare(iCalculatedNewBIEAmount, NewBIEAmount, coNotEqual) then sMessage := 'Reduced, normal reduction = ' + FormatFloat(IntegerDisplay, NewBIEAmount); NewBIEAmount := iCalculatedNewBIEAmount; end; {If bUseCalculatedAmounts} FieldByName('Amount').AsInteger := NewBIEAmount; ExemptionAppliesArray := ExApplies(ExemptionCode, FieldByName('ApplyToVillage').AsBoolean); If ExemptionAppliesArray[exMunicipal] then FieldByName('TownAmount').AsInteger := NewBIEAmount; If ExemptionAppliesArray[exCounty] then FieldByName('CountyAmount').AsInteger := NewBIEAmount; If ExemptionAppliesArray[exSchool] then FieldByName('SchoolAmount').AsInteger := NewBIEAmount; If ExemptionAppliesArray[exVillage] then FieldByName('VillageAmount').AsInteger := NewBIEAmount; If TrialRun then Cancel else Post; except Quit := True; SystemSupport(80, ExemptionTable, 'Error updating BIE amount.', UnitName, GlblErrorDlgBox); end; Inc(TotalOriginalExemptionAmount, OriginalExemptionAmount); Inc(TotalNewBIEAmount, NewBIEAmount); {If the new BIE amount is 0, then delete it.} If (_Compare(NewBIEAmount, 0, coLessThanOrEqual) or (_Compare(FieldByName('TerminationDate').AsString, coNotBlank) and _Compare(FieldByName('TerminationDate').AsDateTime, Date, coLessThan))) then begin try Println(#9 + ConvertSwisSBLToDashDot(FieldByName('SwisSBLKey').Text) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, OriginalBIEAmount) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, OriginalExemptionAmount) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, NewBIEAmount) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, (NewBIEAmount - OriginalExemptionAmount)) + #9 + FieldByName('InitialDate').AsString + #9 + FieldByName('TerminationDate').AsString + #9 + 'Deleted.'); If not TrialRun then begin Delete; Prior; end; except Quit := True; SystemSupport(80, ExemptionTable, 'Error deleting exemption.', UnitName, GlblErrorDlgBox); end; end else Println(#9 + ConvertSwisSBLToDashDot(FieldByName('SwisSBLKey').Text) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, OriginalBIEAmount) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, OriginalExemptionAmount) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, NewBIEAmount) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, (NewBIEAmount - OriginalExemptionAmount)) + #9 + FieldByName('InitialDate').AsString + #9 + FieldByName('TerminationDate').AsString + #9 + sMessage); end; {If ((not Done) and ...} ReportCancelled := ProgressDialog.Cancelled; until (Done or ReportCancelled or Quit); Println(#9 + #9 + #9 + #9 + #9 + #9 + #9); Bold := True; ClearTabs; SetTab(0.3, pjLeft, 1.5, 5, BOXLINEALL, 25); {Parcel ID} SetTab(1.8, pjRight, 0.8, 5, BOXLINEALL, 25); {Original amount} SetTab(2.6, pjRight, 0.8, 5, BOXLINEALL, 25); {Previous Amount} SetTab(3.4, pjRight, 0.8, 5, BOXLINEALL, 25); {New amount} SetTab(4.2, pjRight, 0.8, 5, BOXLINEALL, 25); {Difference} SetTab(5.0, pjLeft, 0.8, 5, BOXLINEALL, 25); {Termination date} SetTab(5.8, pjLeft, 2.0, 5, BOXLINEALL, 25); {Notes} Println(#9 + 'Total' + #9 + #9 + FormatFloat(CurrencyDisplayNoDollarSign, TotalOriginalExemptionAmount) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, TotalNewBIEAmount) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, (TotalNewBIEAmount - TotalOriginalExemptionAmount)) + #9 + #9); ClearTabs; Println(''); Println(#9 + 'Number reduced = ' + IntToStr(NumberReduced)); end; {with Sender as TBaseReport do} end; {ReportPrint} {===================================================================} Procedure TReduceBIEExemptionsForm.StartButtonClick(Sender: TObject); var Quit : Boolean; NewFileName : String; TempFile : File; begin Quit := False; ReportCancelled := False; TrialRun := TrialRunCheckBox.Checked; ProcessingType := NextYear; bUseCalculatedAmounts := cbxUseCalculatedAmounts.Checked; case AssessmentYearRadioGroup.ItemIndex of 0 : ProcessingType := ThisYear; 1 : ProcessingType := NextYear; end; StartButton.Enabled := False; Application.ProcessMessages; Quit := False; SetPrintToScreenDefault(PrintDialog); If PrintDialog.Execute then begin OpenTableForProcessingType(ExemptionTable, ExemptionsTableName, ProcessingType, Quit); AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptLaser], False, Quit); ProgressDialog.Start(GetRecordCount(ExemptionTable), True, True); {Now print the report.} If not (Quit or ReportCancelled) then begin If PrintDialog.PrintToFile then begin NewFileName := GetPrintFileName(Self.Caption, True); ReportFiler.FileName := NewFileName; try PreviewForm := TPreviewForm.Create(self); PreviewForm.FilePrinter.FileName := NewFileName; PreviewForm.FilePreview.FileName := NewFileName; ReportFiler.Execute; {FXX10111999-3: Make sure they know its done.} ProgressDialog.StartPrinting(PrintDialog.PrintToFile); PreviewForm.ShowModal; finally PreviewForm.Free; {Now delete the file.} try AssignFile(TempFile, NewFileName); OldDeleteFile(NewFileName); finally {We don't care if it does not get deleted, so we won't put up an error message.} ChDir(GlblProgramDir); end; end; {try PreviewForm := ...} end {If PrintDialog.PrintToFile} else ReportPrinter.Execute; ResetPrinter(ReportPrinter); end; {If not Quit} ProgressDialog.Finish; {FXX10111999-3: Tell people that printing is starting and done.} DisplayPrintingFinishedMessage(PrintDialog.PrintToFile); end; {If PrintDialog.Execute} StartButton.Enabled := True; end; {StartButtonClick} {===================================================================} Procedure TReduceBIEExemptionsForm.FormClose( Sender: TObject; var Action: TCloseAction); begin CloseTablesForForm(Self); {Free up the child window and set the ClosingAForm Boolean to true so that we know to delete the tab.} Action := caFree; GlblClosingAForm := True; GlblClosingFormCaption := Caption; end; {FormClose} end.
unit Hash; interface const // CALG_* //MAC: LongWord = $8005; //HMAC: LongWord = $8009; MD2: LongWord = $8001; MD4: LongWord = $8002; MD5: LongWord = $8003; SHA: LongWord = $8004; SHA1: LongWord = $8004; SHA256: LongWord = $800C; SHA384: LongWord = $800D; SHA512: LongWord = $800E; MD2_SIZE: byte = 16; MD4_SIZE: byte = 16; MD5_SIZE: byte = 16; SHA_SIZE: byte = 20; SHA1_SIZE: byte = 20; SHA256_SIZE: byte = 32; SHA384_SIZE: byte = 48; SHA512_SIZE: byte = 64; procedure InitHash(Algorithm: LongWord; out hHash, {hKey,} hProv: LongWord); procedure CalculateHash(Data: pointer; DataSize: LongWord; HashSize: LongWord; hHash: LongWord; var ResultHash: string); procedure FreeHash(var hHash, {hKey,} hProv: LongWord); function HashString(Data: string; Algorithm: LongWord; HashSize: LongWord): string; procedure LoadFileToMemory(FilePath: PAnsiChar; out Size: LongWord; out FilePtr: pointer); function HashFile(Path: string; Algorithm: LongWord; HashSize: LongWord): string; implementation const Advapi32 = 'Advapi32.dll'; kernel32 = 'kernel32.dll'; GENERIC_READ = LongWord($80000000); OPEN_EXISTING = 3; FILE_ATTRIBUTE_NORMAL = $00000080; type PLPSTR = ^PAnsiChar; POverlapped = ^TOverlapped; _OVERLAPPED = record Internal: LongWord; InternalHigh: LongWord; Offset: LongWord; OffsetHigh: LongWord; hEvent: THandle; end; TOverlapped = _OVERLAPPED; PSecurityAttributes = ^TSecurityAttributes; _SECURITY_ATTRIBUTES = record nLength: LongWord; lpSecurityDescriptor: Pointer; bInheritHandle: LongBool; end; TSecurityAttributes = _SECURITY_ATTRIBUTES; function CreateFile(lpFileName: PChar; dwDesiredAccess, dwShareMode: LongWord; lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: LongWord; hTemplateFile: THandle): THandle; stdcall; external kernel32 name 'CreateFileA'; function ReadFile(hFile: THandle; var Buffer; nNumberOfBytesToRead: LongWord; var lpNumberOfBytesRead: LongWord; lpOverlapped: POverlapped): LongBool; stdcall; external kernel32 name 'ReadFile'; function GetFileSize(hFile: THandle; lpFileSizeHigh: Pointer): LongWord; stdcall; external kernel32 name 'GetFileSize'; function CloseHandle(hObject: THandle): LongBool; stdcall; external kernel32 name 'CloseHandle'; //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH function CryptAcquireContext( out phProv: LongWord; pszContainer: PAnsiChar; pszProvider: PAnsiChar; dwProvType: LongWord; dwFlags: LongWord ): LongBool; stdcall; external Advapi32 name 'CryptAcquireContextA'; { function CryptGenKey( hProv: THandle; ALG_ID: LongWord; dwFlags: LongWord; out hKey: LongWord ): LongBool; stdcall; external Advapi32 name 'CryptGenKey'; } function CryptCreateHash( hProv: THandle; ALG_ID: LongWord; hKey: THandle; dwFlags: LongWord; out hHash: THandle ): LongBool; stdcall; external Advapi32 name 'CryptCreateHash'; function CryptHashData( hHash: THandle; pbData: pointer; dwDataLen: LongWord; dwFlags: LongWord ): LongBool; stdcall; external Advapi32 name 'CryptHashData'; function CryptGetHashParam( hHash: THandle; dwParam: LongWord; pbData: pointer; var pbDataLen: LongWord; dwFlags: LongWord ): LongBool; stdcall; external Advapi32 name 'CryptGetHashParam'; //function CryptDestroyKey(hKey: THandle): LongBool; stdcall; external Advapi32 name 'CryptDestroyKey'; function CryptDestroyHash(hHash: THandle): LongBool; stdcall; external Advapi32 name 'CryptDestroyHash'; function CryptReleaseContext(hProv: THandle; dwFlags: LongWord): LongBool; stdcall; external Advapi32 name 'CryptReleaseContext'; const PROV_RSA_FULL: LongWord = 1; //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH function LowerCase(const S: string): string; asm {Size = 134 Bytes} push ebx push edi push esi test eax, eax {Test for S = NIL} mov esi, eax {@S} mov edi, edx {@Result} mov eax, edx {@Result} jz @@Null {S = NIL} mov edx, [esi-4] {Length(S)} test edx, edx je @@Null {Length(S) = 0} mov ebx, edx call system.@LStrSetLength {Create Result String} mov edi, [edi] {@Result} mov eax, [esi+ebx-4] {Convert the Last 4 Characters of String} mov ecx, eax {4 Original Bytes} or eax, $80808080 {Set High Bit of each Byte} mov edx, eax {Comments Below apply to each Byte...} sub eax, $5B5B5B5B {Set High Bit if Original <= Ord('Z')} xor edx, ecx {80h if Original < 128 else 00h} or eax, $80808080 {Set High Bit} sub eax, $66666666 {Set High Bit if Original >= Ord('A')} and eax, edx {80h if Orig in 'A'..'Z' else 00h} shr eax, 2 {80h > 20h ('a'-'A')} add ecx, eax {Set Bit 5 if Original in 'A'..'Z'} mov [edi+ebx-4], ecx sub ebx, 1 and ebx, -4 jmp @@CheckDone @@Null: pop esi pop edi pop ebx jmp System.@LStrClr @@Loop: {Loop converting 4 Character per Loop} mov eax, [esi+ebx] mov ecx, eax {4 Original Bytes} or eax, $80808080 {Set High Bit of each Byte} mov edx, eax {Comments Below apply to each Byte...} sub eax, $5B5B5B5B {Set High Bit if Original <= Ord('Z')} xor edx, ecx {80h if Original < 128 else 00h} or eax, $80808080 {Set High Bit} sub eax, $66666666 {Set High Bit if Original >= Ord('A')} and eax, edx {80h if Orig in 'A'..'Z' else 00h} shr eax, 2 {80h > 20h ('a'-'A')} add ecx, eax {Set Bit 5 if Original in 'A'..'Z'} mov [edi+ebx], ecx @@CheckDone: sub ebx, 4 jnc @@Loop pop esi pop edi pop ebx end; procedure CvtInt; { IN: EAX: The integer value to be converted to text ESI: Ptr to the right-hand side of the output buffer: LEA ESI, StrBuf[16] ECX: Base for conversion: 0 for signed decimal, 10 or 16 for unsigned EDX: Precision: zero padded minimum field width OUT: ESI: Ptr to start of converted text (not start of buffer) ECX: Length of converted text } asm OR CL,CL JNZ @CvtLoop @C1: OR EAX,EAX JNS @C2 NEG EAX CALL @C2 MOV AL,'-' INC ECX DEC ESI MOV [ESI],AL RET @C2: MOV ECX,10 @CvtLoop: PUSH EDX PUSH ESI @D1: XOR EDX,EDX DIV ECX DEC ESI ADD DL,'0' CMP DL,'0'+10 JB @D2 ADD DL,('A'-'0')-10 @D2: MOV [ESI],DL OR EAX,EAX JNE @D1 POP ECX POP EDX SUB ECX,ESI SUB EDX,ECX JBE @D5 ADD ECX,EDX MOV AL,'0' SUB ESI,EDX JMP @z @zloop: MOV [ESI+EDX],AL @z: DEC EDX JNZ @zloop MOV [ESI],AL @D5: end; function IntToHex(Value: Integer; Digits: Integer): string; // FmtStr(Result, '%.*x', [Digits, Value]); asm CMP EDX, 32 // Digits < buffer length? JBE @A1 XOR EDX, EDX @A1: PUSH ESI MOV ESI, ESP SUB ESP, 32 PUSH ECX // result ptr MOV ECX, 16 // base 16 EDX = Digits = field width CALL CvtInt MOV EDX, ESI POP EAX // result ptr CALL System.@LStrFromPCharLen ADD ESP, 32 POP ESI end; //============================================================================== procedure InitHash(Algorithm: LongWord; out hHash, {hKey,} hProv: LongWord); begin CryptAcquireContext(hProv, nil, nil, PROV_RSA_FULL, $0); //CryptGenKey(hProv, Algorithm, 1024, hKey); CryptCreateHash(hProv, Algorithm, 0, 0, hHash); end; procedure CalculateHash(Data: pointer; DataSize: LongWord; HashSize: LongWord; hHash: LongWord; var ResultHash: string); var pbData: array of byte; I: byte; begin SetLength(pbData, HashSize); CryptHashData(hHash, Data, DataSize, 0); CryptGetHashParam(hHash, $2, @pbData[0], HashSize, 0); ResultHash := ''; for I := 0 to HashSize - 1 do begin ResultHash := ResultHash + IntToHex(pbData[I], 2); end; ResultHash := LowerCase(ResultHash); end; procedure FreeHash(var hHash, {hKey,} hProv: LongWord); begin CryptDestroyHash(hHash); //CryptDestroyKey(hKey); CryptReleaseContext(hProv, 0); asm xor eax, eax mov hHash, eax mov hProv, eax end; end; //============================================================================== function HashString(Data: string; Algorithm: LongWord; HashSize: LongWord): string; var hProv: LongWord; hHash: LongWord; begin InitHash(Algorithm, hHash, hProv); Result := ''; CalculateHash(@Data[1], Length(Data), HashSize, hHash, Result); FreeHash(hHash, hProv); end; procedure LoadFileToMemory(FilePath: PAnsiChar; out Size: LongWord; out FilePtr: pointer); var hFile: THandle; BytesRead: LongWord; begin hFile := CreateFile( FilePath, GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); Size := GetFileSize(hFile, nil); GetMem(FilePtr, Size); ReadFile(hFile, FilePtr^, Size, BytesRead, nil); CloseHandle(hFile); end; function HashFile(Path: string; Algorithm: LongWord; HashSize: LongWord): string; var Buffer: pointer; Size: LongWord; hHash, hProv: LongWord; begin LoadFileToMemory(@Path[1], Size, Buffer); InitHash(Algorithm, hHash, hProv); CalculateHash(Buffer, Size, HashSize, hHash, Result); FreeHash(hHash, hProv); FreeMem(Buffer); end; end.
unit Getter.VolumeBitmap; interface uses SysUtils, Windows, OSFile.Handle, OSFile.IoControl, OS.Handle; const BitmapSizePerBuffer = 16384; type TBitmapBuffer = Array[0..BitmapSizePerBuffer - 1] of Cardinal; TBitmapPositionSize = record StartingLCN: LARGE_INTEGER; BitmapSize: LARGE_INTEGER; end; TVolumeBitmapBufferWithErrorCode = record PositionSize: TBitmapPositionSize; Buffer: TBitmapBuffer; LastError: Cardinal; end; TVolumeBitmapGetter = class(TIoControlFile) public constructor Create(const FileToGetAccess: String); override; function GetVolumeBitmap(const StartingLCN: LARGE_INTEGER): TVolumeBitmapBufferWithErrorCode; protected function GetMinimumPrivilege: TCreateFileDesiredAccess; override; private type TVolumeBitmapInput = record StartingLCN: LARGE_INTEGER; end; private InnerInput: TVolumeBitmapInput; function GetIOBuffer(const ResultBufferPointer: Pointer): TIoControlIOBuffer; end; implementation { TVolumeBitmapGetter } constructor TVolumeBitmapGetter.Create(const FileToGetAccess: String); begin inherited; CreateHandle(FileToGetAccess, DesiredReadOnly); end; function TVolumeBitmapGetter.GetIOBuffer(const ResultBufferPointer: Pointer): TIoControlIOBuffer; begin result.InputBuffer.Buffer := @InnerInput; result.InputBuffer.Size := SizeOf(InnerInput); result.OutputBuffer.Buffer := ResultBufferPointer; result.OutputBuffer.Size := SizeOf(TBitmapPositionSize) + SizeOf(TBitmapBuffer); end; function TVolumeBitmapGetter.GetVolumeBitmap( const StartingLCN: LARGE_INTEGER): TVolumeBitmapBufferWithErrorCode; begin InnerInput.StartingLCN := StartingLCN; result.LastError := ExceptionFreeIoControl( TIoControlCode.GetVolumeBitmap, GetIOBuffer(@result)); end; function TVolumeBitmapGetter.GetMinimumPrivilege: TCreateFileDesiredAccess; begin result := TCreateFileDesiredAccess.DesiredReadOnly; end; end.
program Sample; type RType = record A : Integer; B : Integer; end; var X : RType; begin X.A := 1; X.B := 2; WriteLn('X.A = ', X.A, ', X.B = ', X.B); end.
unit Extenso; interface uses sysutils; function ExtensoSt(Valor: Extended; DinSing, DinPlural, CentSing, CentPlural: String): String; const milst: array[1..3, Boolean] of string = (('milhao', 'milhoes'), ('mil', 'mil'), ('', '')); mildiv : Array[1..3] of integer = (1000000, 1000, 1); palavras: Array[1..3, 1..9] of String = (('cento', 'duzentos', 'trezentos', 'quatrocentos', 'quinhentos', 'seiscentos', 'setecentos', 'oitocentos', 'novecentos'), ('dez', 'vinte', 'trinta', 'quarenta', 'cinquenta', 'sessenta', 'setenta', 'oitenta', 'noventa'), ('um', 'dois', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove')); divcasas : array[1..3] of byte = (100, 10, 1); onzedezenove : Array[11..19] of String = ('onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove'); implementation function ExtensoSt(Valor: Extended; DinSing, DinPlural, CentSing, CentPlural: String): String; var V, VAntes, Inteiro, C, D, I, IAntes, mil: Integer; St: String; Dinheiro, Centavos, CentSt: String; procedure AddE(S: String); begin if St > '' then St := St + ' e ' + S else St := S; end; begin Str(Valor:0:4, St); I := Pos('.', St); V := StrToIntDef(Copy(St, 1, pred(I)), 0); C := StrToIntDef(Copy(St, succ(I), 2), 0); Result := ''; if V = 1 then Dinheiro := DinSing else Dinheiro := DinPlural; for mil := 1 to 3 do begin Inteiro := V div mildiv[mil]; St := ''; if inteiro > 0 then begin IAntes := Inteiro; if (IAntes <> 1) or (Result <> '') or (mil <> 2) then for I := 1 to 3 do begin D := inteiro div divcasas[I]; if D > 0 then begin if inteiro in [11..19] then begin AddE(onzedezenove[inteiro]); inteiro := 0; end else if (inteiro=100) then AddE('cem') else AddE(palavras[I, D]); end; inteiro := inteiro mod divcasas[I]; end; if mil < 3 then St := St + ' ' + milst[mil, (IAntes>1)]; if Result > '' then begin if ((V mod mildiv[mil]) = 0) then begin if (IAntes mod 100 = 0) or (V=1) or (V<100) then Result := Result + ' e ' + St else Result := Result + ' , ' + St; end else Result := Result + ' , ' + St; end else Result := St; end; VAntes := V div mildiv[mil]; V := V mod mildiv[mil]; end; if Result > '' then begin Result := Result + ' ' + Dinheiro; if C > 0 then Result := Result + ' e ' + ExtensoSt(C, CentSing, CentPlural, '', ''); end else if C > 0 then Result := ExtensoSt(C, CentSing, CentPlural, '', ''); end; end.
unit UFtpFileDownloadfrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, UniCodeStdCtrls, ccuLabel, Mask, ccuMaskEdit, ccuCustomComboEdit, ccuDropDownEdit, ccuButtonEdit, ccuGrids, ccuDataStringGrid, ExtCtrls, ccuUtils, IniFiles, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdFTP; type TFtpFileDownloadForm = class(TForm) dgDetail: TccuDataStringGrid; bedtFTP: TccuButtonEdit; bedtUser: TccuButtonEdit; bedtPassword: TccuButtonEdit; bedtLocalPath: TccuButtonEdit; bedtPort: TccuButtonEdit; bedt6: TccuButtonEdit; lblFTP: TccuLabel; lblUser: TccuLabel; lblPassword: TccuLabel; lblLocalPath: TccuLabel; lblPort: TccuLabel; btnStart: TButton; pnlTop: TPanel; btnSaveSet: TButton; procedure btnStartClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSaveSetClick(Sender: TObject); private { Private declarations } CurrExePath: WideString; iniFileName: WideString; procedure LoadSet; procedure SaveSet; public { Public declarations } end; var FtpFileDownloadForm: TFtpFileDownloadForm; implementation {$R *.dfm} procedure TFtpFileDownloadForm.btnStartClick(Sender: TObject); var Row: Integer; FileName, LocalPath, LocalName: string; IdFtpDownload: TIdFTP; begin //本地文件夹路径 LocalPath := GetStdDirectoryW(bedtLocalPath.Text); if not DirectoryExists(LocalPath) then ForceDirectories(LocalPath); for Row := 1 to dgDetail.RowProps.Count - 1 do begin //服务器上的文件名 FileName := dgDetail.CellByField2['Path', Row]; if Trim(FileName) = '' then Continue; // FileName := GetStdDirectoryW(FileName); // FileName := StringReplace(FileName, '\', '/', [rfReplaceAll]); // FileName := StringReplace(FileName, '//', '/', [rfReplaceAll]); // FileName := StringReplace(FileName, '//', '/', [rfReplaceAll]); //下载文件 IdFtpDownload := TIdFTP.Create(self); try IdFtpDownload.User := bedtUser.Text; IdFtpDownload.Password := bedtPassword.Text; IdFtpDownload.Host := bedtFTP.Text; IdFtpDownload.Port := StrToIntDef(bedtPort.Text, 21); IdFtpDownload.Passive := True; if (not IdFtpDownload.Connected) then IdFtpDownload.Connect; IdFtpDownload.ChangeDirUp; IdFtpDownload.ChangeDirUp; LocalName := LocalPath + dgDetail.CellByField2['LocalName', Row]; IdFtpDownload.TransferType := ftbinary; //下载模式 try IdFtpDownload.Get(FileName, LocalName, true); //开始下载 IdFtpDownload.Quit; dgDetail.CellByField2['Stat', Row] := '成功'; except dgDetail.CellByField2['Stat', Row] := '失败'; end; finally IdFtpDownload.Free; end; end; end; procedure TFtpFileDownloadForm.LoadSet; var iniFile: TIniFile; I, J, K: Integer; begin inifile := TIniFile.Create(CurrExePath + '\' + iniFileName); bedtFTP.Text := iniFile.ReadString('CLASSSET', 'bedtFTP', ''); bedtPort.Text := iniFile.ReadString('CLASSSET', 'bedtPort', ''); bedtUser.Text := iniFile.ReadString('CLASSSET', 'bedtUser', ''); bedtPassword.Text := iniFile.ReadString('CLASSSET', 'bedtPassword', ''); bedtLocalPath.Text := iniFile.ReadString('CLASSSET', 'bedtLocalPath', ''); // bedtFTP.Text := iniFile.ReadString('CLASSSET', 'bedtFTP', ''); // bedtFTP.Text := iniFile.ReadString('CLASSSET', 'bedtFTP', ''); // bedtFTP.Text := iniFile.ReadString('CLASSSET', 'bedtFTP', ''); end; procedure TFtpFileDownloadForm.SaveSet; var inifile: TIniFile; I, J, K: Integer; begin inifile := TIniFile.Create(CurrExePath + '\' + iniFileName); iniFile.WriteString('CLASSSET', 'bedtFTP', bedtFTP.Text); iniFile.WriteString('CLASSSET', 'bedtPort', bedtPort.Text); iniFile.WriteString('CLASSSET', 'bedtUser', bedtUser.Text); iniFile.WriteString('CLASSSET', 'bedtPassword', bedtPassword.Text); iniFile.WriteString('CLASSSET', 'bedtLocalPath', bedtLocalPath.Text); end; procedure TFtpFileDownloadForm.FormShow(Sender: TObject); begin //得到当前程序运行目录,尾部带'\' CurrExePath := IncludeTrailingBackSlash(ExtractFilePath(Application.ExeName)); iniFileName := '文件下载.ini'; LoadSet; end; procedure TFtpFileDownloadForm.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveSet; end; procedure TFtpFileDownloadForm.btnSaveSetClick(Sender: TObject); begin SaveSet; end; end.
PROGRAM PseudoGraphicCharacterPrinting(INPUT, OUTPUT); CONST Min = 1; Max = 25; TYPE MaxMinCoordinates = SET OF Min..Max; VAR LetterCoordinates: MaxMinCoordinates; Ch: CHAR; i: INTEGER; PROCEDURE ReadLetter(VAR Ch: CHAR); BEGIN READ(Ch); CASE Ch OF 'A': LetterCoordinates := [3, 7, 9, 11, 15..20, 21, 25]; 'B': LetterCoordinates := [1..4, 6, 10..14, 16, 20..24]; 'C': LetterCoordinates := [2..6, 11, 16, 22..25]; 'D': LetterCoordinates := [1..4, 6, 10..11, 15..16, 20..24]; 'E': LetterCoordinates := [1..6, 11..16, 21..25]; 'F': LetterCoordinates := [1..6, 11..13, 16, 21]; 'G': LetterCoordinates := [2..4, 6, 11, 13..16, 20, 22..24]; 'H': LetterCoordinates := [1, 5, 6, 10..16, 20, 21, 25]; 'I': LetterCoordinates := [1..5, 8, 13, 18, 21..25]; 'J': LetterCoordinates := [1..5, 8, 13, 16, 18, 22]; 'K': LetterCoordinates := [1, 4, 6, 8, 11..12, 16, 18, 21, 24]; 'L': LetterCoordinates := [1, 6, 11, 16, 21..25]; 'M': LetterCoordinates := [1, 5, 6, 7, 9, 10..11, 13, 15..16, 20..21, 25]; 'N': LetterCoordinates := [1, 5..7, 10..11, 13, 15..16, 19..21, 25]; 'O': LetterCoordinates := [2..4, 6, 10..11, 15..16, 20, 22..24]; 'P': LetterCoordinates := [1..3, 6, 9, 11..12, 13, 16, 21]; 'Q': LetterCoordinates := [2..4, 6, 10..11, 15..16, 19, 22..23, 25]; 'R': LetterCoordinates := [1..3, 6, 9, 11..13, 16, 18, 21, 24]; 'S': LetterCoordinates := [2..5, 6, 12, 13..14, 20..24]; 'T': LetterCoordinates := [1..5, 8, 13, 18, 23]; 'U': LetterCoordinates := [1, 5..6, 10..11, 15..16, 20, 22..24]; 'V': LetterCoordinates := [1, 5, 7, 9, 12, 14, 18]; 'W': LetterCoordinates := [1, 5..6, 10, 11, 13, 15..16, 18, 20, 22, 24]; 'X': LetterCoordinates := [1, 5, 7, 9, 13, 17, 19, 21, 25]; 'Y': LetterCoordinates := [1, 5, 7, 9, 13, 18, 23]; 'Z': LetterCoordinates := [1..5, 9, 13, 17, 21..25]; ' ': LetterCoordinates := [] ELSE WRITELN('Sorry, invalid character entered') END; END; PROCEDURE PrintLetter(VAR LetterCoordinates: MaxMinCoordinates; i: integer); BEGIN IF LetterCoordinates <> [] THEN BEGIN FOR i := Min TO Max DO BEGIN IF i IN LetterCoordinates THEN WRITE('X') ELSE WRITE(' '); IF i mod 5 = 0 THEN BEGIN WRITELN(''); IF i = 25 THEN WRITELN('') END END END; END; BEGIN WHILE NOT EOLN DO BEGIN ReadLetter(Ch); PrintLetter(LetterCoordinates, i) END END.
unit frmReflectorEditorU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, VCL.Graphics, VCL.Controls, VCL.Forms, VCL.Dialogs, VCL.ComCtrls, VCL.StdCtrls, VCL.ExtCtrls, System.Actions, VCL.ActnList, VCL.Buttons, ReflectorsU, VCL.ToolWin, System.UITypes; type TfrmReflectorEditor = class(TForm) ActionList: TActionList; ActionSave: TAction; ActionCancel: TAction; ActionAddBinding: TAction; ActionRemoveBinding: TAction; NukePanel2: TPanel; BitBtn1: TBitBtn; BitBtn2: TBitBtn; NukePanel1: TPanel; cbEnabled: TCheckBox; radiogroupType: TRadioGroup; NukeLabelPanel2: TPanel; Label2: TLabel; editMappedHost: TEdit; NukeLabelPanel3: TPanel; ToolBar1: TToolBar; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ListViewBindings: TListView; NukeLabelPanel1: TPanel; Label3: TLabel; editMappedPort: TEdit; NukeLabelPanel4: TPanel; Label1: TLabel; editReflectorName: TEdit; procedure ActionSaveExecute(Sender: TObject); procedure ActionCancelExecute(Sender: TObject); procedure ActionRemoveBindingExecute(Sender: TObject); procedure ActionRemoveBindingUpdate(Sender: TObject); procedure ActionAddBindingExecute(Sender: TObject); private FReflectorSettings: TReflectorSettings; procedure UpdatingBindings; procedure LoadSettings; procedure SaveSettings; function Validate(var AMessage: string): boolean; public function Edit(AReflectorSettings: TReflectorSettings): boolean; end; implementation {$R *.dfm} uses dmReflectorU, frmBindingEditorU, ToolsU; { TfrmReflectorEditor } procedure TfrmReflectorEditor.ActionAddBindingExecute(Sender: TObject); var LfrmBindingEditor: TfrmBindingEditor; LIP: string; LPort: integer; begin LfrmBindingEditor := TfrmBindingEditor.Create(Self); try LIP := '0.0.0.0'; LPort := StrToIntDef(editMappedPort.Text, 0); if LfrmBindingEditor.Execute(LIP, LPort) then begin FReflectorSettings.AddBindings(LIP, LPort); end; finally FreeAndNil(LfrmBindingEditor); end; UpdatingBindings; end; procedure TfrmReflectorEditor.ActionCancelExecute(Sender: TObject); begin Self.ModalResult := mrCancel; end; procedure TfrmReflectorEditor.ActionRemoveBindingExecute(Sender: TObject); begin ListViewBindings.Selected.Delete; end; procedure TfrmReflectorEditor.ActionRemoveBindingUpdate(Sender: TObject); begin ActionRemoveBinding.Enabled := Assigned(ListViewBindings.Selected); end; procedure TfrmReflectorEditor.ActionSaveExecute(Sender: TObject); var LMessage: string; begin if Validate(LMessage) then begin SaveSettings; Self.ModalResult := mrOk; end else begin MessageDlg(LMessage, mtError, [mbOK], 0); end; end; function TfrmReflectorEditor.Edit(AReflectorSettings : TReflectorSettings): boolean; begin Result := False; FReflectorSettings := AReflectorSettings; try LoadSettings; if Self.ShowModal = mrOk then begin Result := True; end; finally FReflectorSettings := nil; end; end; procedure TfrmReflectorEditor.LoadSettings; begin editMappedHost.Text := FReflectorSettings.MappedHost; editMappedPort.Text := FReflectorSettings.MappedPort.ToString; cbEnabled.Checked := FReflectorSettings.Enabled; radiogroupType.ItemIndex := integer(FReflectorSettings.ReflectorType); editReflectorName.Text := FReflectorSettings.ReflectorName; UpdatingBindings; end; procedure TfrmReflectorEditor.SaveSettings; var LIdx: integer; begin FReflectorSettings.MappedHost := editMappedHost.Text; FReflectorSettings.MappedPort := StrToIntDef(editMappedPort.Text, 0); FReflectorSettings.Enabled := cbEnabled.Checked; FReflectorSettings.ReflectorType := TReflectorType(radiogroupType.ItemIndex); FReflectorSettings.ReflectorName := editReflectorName.Text; FReflectorSettings.Bindings.Clear; For LIdx := 0 to Pred(ListViewBindings.Items.Count) do begin FReflectorSettings.AddBindings(ListViewBindings.Items[LIdx].Caption, StrToIntDef(ListViewBindings.Items[LIdx].SubItems[0], 0)); end; end; procedure TfrmReflectorEditor.UpdatingBindings; var LReflectorBinding: TReflectorBinding; begin ListViewBindings.Items.Clear; ListViewBindings.Items.BeginUpdate; try For LReflectorBinding in FReflectorSettings.Bindings do begin with ListViewBindings.Items.Add do begin Caption := LReflectorBinding.IP; SubItems.Add(IntToStr(LReflectorBinding.Port)); end; end; finally ListViewBindings.Items.EndUpdate; end; end; function TfrmReflectorEditor.Validate(var AMessage: string): boolean; begin Result := True; if IsEmptyString(editReflectorName.Text) then begin AMessage := 'Please specify a valid name'; Result := False; end; if IsEmptyString(editMappedHost.Text) then begin AMessage := 'Please specify a mapped host'; Result := False; end; if radiogroupType.ItemIndex = -1 then begin AMessage := 'Please specify a valid type'; Result := False; end; if StrToIntDef(editMappedPort.Text, 0) <= 0 then begin AMessage := 'Please specify a valid port'; Result := False; end; if ListViewBindings.Items.Count = 0 then begin AMessage := 'Please specify port bindings'; Result := False; end; end; end.
{*************************************************************** * * Project : TFTPServer * Unit Name: main * Purpose : Simple demo of using the TrivialFTPServer * Version : 1.0 * Date : Wed 25 Apr 2001 - 01:39:41 * Author : <unknown> * History : * Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com> * ****************************************************************} unit main; interface uses {$IFDEF Linux} QForms, QControls, QStdCtrls, QExtCtrls, {$ELSE} Forms, Controls, StdCtrls, ExtCtrls, {$ENDIF} IdTrivialFTPServer, Classes, transfer; type TfrmMain = class(TForm) memLog: TMemo; Panel1: TPanel; edtRootDir: TEdit; Label1: TLabel; Label2: TLabel; lblCount: TLabel; btnBrowse: TButton; procedure FormCreate(Sender: TObject); procedure btnBrowseClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private FTransferList: TList; procedure TFTPReadFile(Sender: TObject; var FileName: string; const PeerInfo: TPeerInfo; var GrantAccess: Boolean; var AStream: TStream; var FreeStreamOnComplete: Boolean); procedure TFTPWriteFile(Sender: TObject; var FileName: string; const PeerInfo: TPeerInfo; var GrantAccess: Boolean; var AStream: TStream; var FreeStreamOnComplete: Boolean); procedure TFTPTransferComplete(Sender: TObject; const Success: Boolean; const PeerInfo: TPeerInfo; AStream: TStream; const WriteOperation: Boolean); function CheckAccess(var FileName: string; RootDir: string): Boolean; procedure AddTransfer(const FileName: string; const FileMode: Word; AStream: TProgressStream); public end; var frmMain: TfrmMain; implementation {$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF} uses FileCtrl, SysUtils; procedure TfrmMain.FormCreate(Sender: TObject); begin FTransferList := TList.Create; edtRootDir.Text := GetCurrentDir; with TIdTrivialFTPServer.Create(self) do begin OnReadFile := TFTPReadFile; OnWriteFile := TFTPWriteFile; OnTransferComplete := TFTPTransferComplete; Active := True; end; end; procedure TfrmMain.TFTPReadFile(Sender: TObject; var FileName: string; const PeerInfo: TPeerInfo; var GrantAccess: Boolean; var AStream: TStream; var FreeStreamOnComplete: Boolean); var s: string; begin FreeStreamOnComplete := False; s := 'denied'; GrantAccess := CheckAccess(FileName, edtRootDir.Text); try if GrantAccess then begin AStream := TProgressStream.Create(FileName, fmOpenRead or fmShareDenyWrite); AddTransfer(FileName, fmOpenRead, TProgressStream(AStream)); s := 'granted'; lblCount.Caption := IntToStr(succ(StrToInt(lblCount.Caption))); end; finally memLog.Lines.Add(Format('%s:%d - Read access to %s %s', [PeerInfo.PeerIP, PeerInfo.PeerPort, FileName, s])); end; end; procedure TfrmMain.TFTPTransferComplete(Sender: TObject; const Success: Boolean; const PeerInfo: TPeerInfo; AStream: TStream; const WriteOperation: Boolean); var s: string; i: integer; begin try if Success then s := 'completed' else s := 'aborted'; memLog.Lines.Add(Format('%s:%d - Transfer %s - %d bytes transferred', [PeerInfo.PeerIp, PeerInfo.PeerPort, s, AStream.Position])); finally for i := FTransferList.Count - 1 downto 0 do if TfrmTransfer(FTransferList[i]).Stream = AStream then begin TfrmTransfer(FTransferList[i]).Free; FTransferList.Delete(i); end; AStream.Free; lblCount.Caption := IntToStr(pred(StrToInt(lblCount.Caption))); end; end; procedure TfrmMain.TFTPWriteFile(Sender: TObject; var FileName: string; const PeerInfo: TPeerInfo; var GrantAccess: Boolean; var AStream: TStream; var FreeStreamOnComplete: Boolean); var s: string; begin FreeStreamOnComplete := False; GrantAccess := CheckAccess(FileName, edtRootDir.Text); s := 'denied'; try if GrantAccess then begin AStream := TProgressStream.Create(FileName, fmCreate); AddTransfer(FileName, fmCreate, TProgressStream(AStream)); s := 'granted'; lblCount.Caption := IntToStr(StrToInt(lblCount.Caption) + 1); end; finally memLog.Lines.Add(Format('%s:%d - Write access to %s %s', [PeerInfo.PeerIP, PeerInfo.PeerPort, FileName, s])); end; end; procedure TfrmMain.btnBrowseClick(Sender: TObject); var s: string; begin s := edtRootDir.Text; if SelectDirectory(s, [sdAllowCreate, sdPerformCreate, sdPrompt], 0) then edtRootDir.Text := s; end; function TfrmMain.CheckAccess(var FileName: string; RootDir: string): Boolean; var s: string; begin RootDir := ExtractFileDir(ExpandFileName(IncludeTrailingBackslash(RootDir) + 'a.b')); FileName := ExpandFileName(IncludeTrailingBackslash(RootDir) + FileName); s := FileName; SetLength(s, Length(RootDir)); Result := AnsiCompareText(RootDir, s) = 0; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin FTransferList.Free; end; procedure TfrmMain.AddTransfer(const FileName: string; const FileMode: Word; AStream: TProgressStream); begin with TfrmTransfer(FTransferList[FTransferList.Add(TfrmTransfer.Create(self, AStream, FileName, FileMode))]) do begin Parent := Self; Show; end; end; end.
unit dm.tcpip.tcp.proxy; interface uses WinApi.Windows, WinApi.Winsock2, System.SysUtils, AnsiStrings, System.Classes, superobject, org.utilities, org.utilities.buffer, org.tcpip, org.tcpip.tcp, org.tcpip.tcp.proxy; type TDMTCPProxyClientSocket = class(TTCPProxyClientSocket) protected procedure ParseProtocol; override; procedure FillProtocol(pHead: PTCPSocketProtocolHead); override; procedure ParseAndProcessBody; override; procedure ParseAndProcessBodyEx; override; procedure NotifyBodyExProgress; override; public constructor Create(AOwner: TTCPIOManager); override; end; TDMTCPProxyServerClientSocket = class(TTCPProxyServerClientSocket) protected procedure ParseProtocol; override; procedure FillProtocol(pHead: PTCPSocketProtocolHead); override; procedure ParseAndProcessBody; override; procedure ParseAndProcessBodyEx; override; procedure NotifyBodyExProgress; override; public constructor Create(AOwner: TTCPIOManager); override; end; TDMTCPProxy = class(TTCPProxy) private FSocket: TSocket; // 监听套接字 FLocalPort: Word; FLocalIP: string; FPreAcceptCount: Integer; // 当前预连接数 protected function DoAcceptEx(IOBuffer: PTCPIOBuffer): Boolean; override; function DoConnectEx(IOBuffer: PTCPIOBuffer): Boolean; override; public constructor Create; procedure Start; override; procedure Stop; override; property Socket: TSocket read FSocket; property LocalIP: string read FLocalIP write FLocalIP; property LocalPort: Word read FLocalPort write FLocalPort; property PreAcceptCount: Integer read FPreAcceptCount; end; implementation { TDMTCPProxyClientSocket } constructor TDMTCPProxyClientSocket.Create(AOwner: TTCPIOManager); begin inherited; end; procedure TDMTCPProxyClientSocket.FillProtocol(pHead: PTCPSocketProtocolHead); begin inherited; end; procedure TDMTCPProxyClientSocket.NotifyBodyExProgress; begin inherited; end; procedure TDMTCPProxyClientSocket.ParseAndProcessBody; begin inherited; end; procedure TDMTCPProxyClientSocket.ParseAndProcessBodyEx; begin inherited; end; procedure TDMTCPProxyClientSocket.ParseProtocol; begin inherited; end; { TDMTCPProxyServerClientSocket } constructor TDMTCPProxyServerClientSocket.Create(AOwner: TTCPIOManager); begin inherited; end; procedure TDMTCPProxyServerClientSocket.FillProtocol(pHead: PTCPSocketProtocolHead); begin inherited; end; procedure TDMTCPProxyServerClientSocket.NotifyBodyExProgress; begin inherited; end; procedure TDMTCPProxyServerClientSocket.ParseAndProcessBody; begin inherited; end; procedure TDMTCPProxyServerClientSocket.ParseAndProcessBodyEx; begin inherited; end; procedure TDMTCPProxyServerClientSocket.ParseProtocol; begin inherited; end; { TDMTCPProxy } constructor TDMTCPProxy.Create; begin Inherited; FSocket := INVALID_SOCKET; FLocalIP := '0.0.0.0'; FLocalPort := 0; FPreAcceptCount := 0; end; function TDMTCPProxy.DoAcceptEx(IOBuffer: PTCPIOBuffer): Boolean; var LocalSockaddr: TSockAddrIn; PLocalSockaddr: PSockAddr; RemoteSockaddr: TSockAddrIn; PRemoteSockaddr: PSockAddr; LocalSockaddrLength, RemoteSockaddrLength: Integer; RemoteIP: array[0..15] of AnsiChar; PC: PAnsiChar; Len: Integer; iRet: Integer; dwRet: DWORD; ErrDesc: string; IOContext: TDMTCPProxyServerClientSocket; begin // dxm 2018.11.1 // 1. 判断IO是否出错 // 2. 初始化套接字上下文 // 3. 关联通信套接字与IO完成端口 // 4. 补充预连接 // dxm 2018.11.2 // 当AcceptEx重叠IO通知到达时: // 1. ERROR_IO_PENDING 重叠IO初始化成功,稍后通知完成 [------][调用时][正常] // 2. WSAECONNRESET 对端提交连接请求后,随即又终止了该请求 [通知时][------][正常][可重用][说明一旦收到连接请求,后续对端即使取消,本地也只是标记而已] Result := False; IOContext := IOBuffer^.Context as TDMTCPProxyServerClientSocket; if IOBuffer^.LastErrorCode <> WSAECONNRESET then begin {$region [IO 正常]} // 初始化地址信息 org.tcpip.lpfnGetAcceptExSockaddrs(IOBuffer^.Buffers[0].buf, 0, // 调用AccpetEx时约定不传输连接数据 Sizeof(TSockAddrIn) + 16, Sizeof(TSockAddrIn) + 16, PLocalSockaddr, // [out] LocalSockaddrLength, // [out] PRemoteSockaddr, // [out] RemoteSockaddrLength); // [out] Move(PLocalSockaddr^, LocalSockaddr, LocalSockaddrLength); Move(PRemoteSockaddr^, RemoteSockaddr, RemoteSockaddrLength); IOContext.FRemotePort := ntohs(RemoteSockaddr.sin_port); PC := inet_ntoa(in_addr(RemoteSockaddr.sin_addr)); if PC <> nil then begin Len := AnsiStrings.StrLen(PC); if Len > 15 then Len := 15; // RemoteIP: array[0..15] of AnsiChar; Move(PC^, RemoteIP[0], Len); RemoteIP[Len] := #0; IOContext.FRemoteIP := string(AnsiStrings.StrPas(RemoteIP)); end else begin IOContext.FRemoteIP := ''; end; // dxm 2018.11.1 // 设置通信套接字属性同监听套接字 // dxm 2018.11.2 // 本函数不应该错误,否则要么是参数设置有问题,要么是理解偏差 // 如果出错暂时定为 [致命][不可重用 ] iRet := setsockopt(IOContext.FSocket, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, @FSocket, SizeOf(TSocket)); if iRet <> SOCKET_ERROR then begin {$region [更新套接字属性成功]} // 关联完成端口 dwRet := FIOHandle.AssociateDeviceWithCompletionPort(IOContext.FSocket, 0); if dwRet = 0 then begin // 设置最终处理结果 Result := True; IOContext.FStatus := IOContext.FStatus or $00000002; // [连接中][已连接] // dxm 2018.12.17 if IOContext.RemoteIP <> '127.0.0.1' then begin ErrDesc := Format('[%d][%d]<%s.DoAcceptEx> Refuse [%s:%d]', [ FSocket, GetCurrentThreadId(), ClassName, IOContext.FRemoteIP, IOContext.FRemotePort]); WriteLog(llWarning, ErrDesc); IOContext.HardCloseSocket(); end; end else begin IOContext.Set80000000Error(); ErrDesc := Format('[%d][%d]<%s.DoAcceptEx.AssociateDeviceWithCompletionPort> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, dwRet, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); end; {$endregion} end else begin IOContext.Set80000000Error(); iRet := WSAGetLastError(); ErrDesc := Format('[%d][%d]<%s.DoAcceptEx.setsockopt> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llFatal, ErrDesc); end; {$endregion} end else begin // dxm 2018.11.2 // [个人理解]此时套接字是可重用的 // 本来既然套接字可重用,那么在补充预连接时是可复用的,但考虑到: // 1. 连接成功后,后续其它操作也可能错误 // 2. 补充预连接操作不一定发生 // 所有就直接将IOBuffer和Context回收算了,如果真的需要补充预连接在向TTCPIOManager要相关资源 ErrDesc := Format('[%d][%d]<%s.DoAcceptEx> IO内部错误: LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOBuffer^.LastErrorCode, IOContext.StatusString()]); WriteLog(llError, ErrDesc); end; EnqueueIOBuffer(IOBuffer); // dxm 2018.11.24 // 此时,并没有触发任何后续操作,直接回收上下文即可 if not Result then EnqueueFreeContext(IOContext); // 补充预连接 InterlockedDecrement(FPreAcceptCount); if FIOHandle.Status = tssRunning then begin iRet := PostSingleAccept(FSocket); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin ErrDesc := Format('[%d]<%s.DoAcceptEx.PostSingleAccept> LastErrorCode=%d', [ GetCurrentThreadId(), ClassName, iRet]); WriteLog(llNormal, ErrDesc); end else InterlockedIncrement(FPreAcceptCount); end; end; function TDMTCPProxy.DoConnectEx(IOBuffer: PTCPIOBuffer): Boolean; var iRet: Integer; ErrDesc: string; IOStatus: Int64; IOContext: TDMTCPProxyClientSocket; begin // dxm 2018.11.1 // 1. 判断IO是否出错 // 2. 初始化套接字上下文 // 3. 关联通信套接字与IO完成端口 // dxm 2018.11.13 // 当ConnectEx重叠IO通知到达时: // 1. WSAECONNREFUSED 10061 通常是对端服务器未启动 [通知时][调用时][正常][可重用] // 2. WSAENETUNREACH 10051 网络不可达,通常是路由无法探知远端 [通知时][调用时][正常][可重用] // 3. WSAETIMEDOUT 10060 连接超时 [通知时][------][正常][可重用][分析:服务端投递的预连接太少,需动态设置预投递上限] Result := True; IOContext := IOBuffer^.Context as TDMTCPProxyClientSocket; if IOBuffer^.LastErrorCode = 0 then begin {$region [IO 正常]} // dxm 2018.11.13 // 激活套接字之前的属性 // dxm 2018.11.13 // 本函数不应该错误,否则要么是参数设置有问题,要么是理解偏差 // 如果出错暂时定为 [致命][不可重用 ] iRet := setsockopt(IOContext.FSocket, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, nil, 0); if iRet <> SOCKET_ERROR then begin IOContext.FStatus := IOContext.FStatus or $00000002; // [连接中][已连接] end else begin //if iRet = SOCKET_ERROR then begin // [更新套接字属性失败] Result := False; IOContext.Set80000000Error(); iRet := WSAGetLastError(); ErrDesc := Format('[%d][%d]<%s.DoConnectEx.setsockopt> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llFatal, ErrDesc); end; {$endregion} end else begin // dxm 2018.11.13 // 当ConnectEx重叠IO通知到达时: // 1. WSAECONNREFUSED 10061 通常是对端服务器未启动 [通知时][调用时][正常][可重用] // 2. WSAENETUNREACH 10051 网络不可达,通常是路由无法探知远端 [通知时][调用时][正常][可重用] // 3. WSAETIMEDOUT 10060 连接超时 [通知时][------][正常][可重用] Result := False; iRet := IOBuffer^.LastErrorCode; if (iRet <> WSAECONNREFUSED) or (iRet <> WSAENETUNREACH) or (iRet <> WSAETIMEDOUT) then IOContext.Set80000000Error(); ErrDesc := Format('[%d][%d]<%s.DoConnectEx> IO内部错误: LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOBuffer^.LastErrorCode, IOContext.StatusString()]); WriteLog(llError, ErrDesc); end; EnqueueIOBuffer(IOBuffer); if Result then begin // 连接正常 // dxm 2018.11.28 // 删除[CONNECT]并检查返回的IOStatus // [1].如果有[ERROR],只可能是通知IO返回时添加,当通知IO由于感知到有[CONNECT],故直接退出了 // 因此,此处要负责归还本端上下文,并同S端解耦,如果时机恰当还应归还S端上下文,同时将Result置为False以切断后续流程 // [2].如果没有[ERROR]但是有[NOTIFY],说明S端出错后,发出了通知IO,但通知IO还未返回,此处只需切断后续逻辑,其它事情由通知IO处理 // [3].如果没有[ERROR],也没有[NOTIFY],说明S端正常,本端也正常 // dxm 2018.11.28 // [情景1] CONNECT成功 // [情景1-1] // C端----<NOTIFY><NOCOUPLING>----<NOTIFY 返回>----[CONNECT 返回]------- // S端----[解耦]-[定时器]------------------------------------------------------- // [情景1-2] // C端----<NOTIFY><NOCOUPLING>----[CONNECT 返回]---<NOTIFY 返回>-------- // S端----[解耦]-[定时器]------------------------------------------------------- // [情景1-3] // C端----[CONNECT 返回]------------------------------------------------ // S端------------------------------------------------------------------ IOStatus := InterlockedAnd64(IOContext.FIOStatus, PROXY_IO_STATUS_DEL_CONNECT); if not IOContext.HasNotify(IOStatus) then begin // [情景1-1][情景1-3] if not IOContext.HasCoupling(IOStatus) then begin // [情景1-1] Result := False; IOContext.DecouplingWithCorr(False); // dxm 2018.12.01 // 因为C端才成功建立连接,没有后续其它任何操作,故可直接关闭套接字然后归还 IOContext.HardCloseSocket(); EnqueueFreeContext(IOContext); end else begin // [情景1-3] // 正常 end; end else begin // [情景1-2] Result := False; end; end else begin // [情景2] CONNECT失败 // [情景2-1] // C端----<NOTIFY><NOCOUPLING>----<NOTIFY 返回>----[CONNECT 返回]----[解耦]--- // S端----[解耦]-------------------------------------------------------------- // [情景2-2] // C端----<NOTIFY><NOCOUPLING>----[CONNECT 返回]---<NOTIFY 返回>-----[解耦]--- // S端----[解耦]-[定时器]------------------------------------------------------------- // [情景2-3] // C端----[CONNECT 返回]-----[解耦]-[定时器]------------------------------------------ // S端------------------------<NOTIFY>------------------------------------------------ IOStatus := InterlockedAnd64(IOContext.FIOStatus, PROXY_IO_STATUS_DEL_CONNECT_ADD_ERROR); if not IOContext.HasNotify(IOStatus) then begin // [情景2-1][情景2-3] IOContext.DecouplingWithCorr(IOContext.HasCoupling(IOStatus)); if IOContext.HasCoupling(IOStatus) then begin // [情景2-3] //{$IfDef DEBUG} // ErrDesc := Format('[%d][%d]<%s.DoConnectEx> be to enqueue TimeWheel for <WaitToEnqueueFreeIOContext> ExpireTime=%ds, Status=%s', // [ IOContext.FSocket, // GetCurrentThreadId(), // ClassName, // 30, // IOContext.StatusString()]); // WriteLog(llDebug, ErrDesc); //{$Endif} FTimeWheel.StartTimer(IOContext, 30 * 1000, DoWaitNotify); end else begin // [情景2-1] EnqueueFreeContext(IOContext); end; end else begin //[情景2-2] // 由通知IO处理线程负责归还本端 end; end; end; procedure TDMTCPProxy.Start; var iRet: Integer; begin inherited; FSocket := ListenAddr(FLocalIP, FLocalPort); if FSocket = INVALID_SOCKET then raise Exception.Create('服务启动失败.'); //投递预连接 iRet := PostMultiAccept(FSocket, FMaxPreAcceptCount); if iRet = 0 then begin raise Exception.Create('投递预连接失败'); end else begin InterlockedAdd(FPreAcceptCount, iRet); end; end; procedure TDMTCPProxy.Stop; begin inherited; end; end.
uses SysUtils, STRobot; const angle90 = 90; wall = 10; var robot: SROBOT; touch: STOUCHSENSOR; light: SLIGHTSENSOR; sonicl, sonicr: SULTRASONICSENSOR; pilot: SPILOT; color: SCOLORSENSOR; procedure MoveForward(l:longint); begin if l >= 99999 then writeln('Victory') else if l = 0 then writeln('Move Forward with Unknown Distance') else writeln('Move Forward: ',l,'cm'); if l > 0 then pilotForwardbyDistance(pilot,l,TYPE_POWER,50) else pilotForward(pilot,TYPE_POWER,50); end; procedure MoveBackward(l:longint); begin if l >= 99999 then writeln('Victory') else if l = 0 then writeln('Move Backward with Unknown Distance') else writeln('Move Backward: ',l,'cm'); if l > 0 then pilotBackwardbyDistance(pilot,l,TYPE_POWER,50) else pilotBackward(pilot,TYPE_POWER,50); end; procedure TurnLeft; begin writeln('Turn Left'); pilotTurnLeftbyAngle(pilot,angle90,TYPE_POWER,50); end; procedure TurnRight; begin writeln('Turn Right'); pilotTurnRightbyAngle(pilot,angle90,TYPE_POWER,50); end; procedure TurnAround; begin writeln('Turn Around'); pilotTurnRightbyAngle(pilot,angle90*2,TYPE_POWER,50); end; begin robot:= createRobot('NXT2', 'robot', 35, 112, -90); touch:=robotGetTouchSensor(robot,PORT_S1); color:=robotGetColorSensor(robot,PORT_S2); sonicl:=robotGetUltrasonicSensor(robot,port_S3); sonicr:=robotGetUltrasonicSensor(robot,port_S4); pilot:=robotGetPilot(robot); repeat while not TouchSensorIsPressed(touch) do MoveForward(0); if colorSensorGetColor(color) = COLOR_BLUE then begin MoveBackward(5); TurnLeft; end; if colorSensorGetColor(color) = COLOR_YELLOW then begin MoveBackward(5); TurnRight; end; until colorSensorGetColor(color) = COLOR_GREEN; end.
unit SMCnst; interface {Portuguese strings} {translated by Augusto Campos, augcampos@augcampos.com} const strMessage = 'Imprimir...'; strSaveChanges = 'Deseja mesmo guardar as alterações na base de Dados ?'; strErrSaveChanges = 'Não é possivel guardar a informação ! Veja a ligação ao servidor ou regras de validação.'; strDeleteWarning = 'Deseja mesmo apagar a tabela %s?'; strEmptyWarning = 'Deseja mesmo limpar a tabela %s?'; const PopUpCaption: array [0..22] of string[33] = ('Adicionar registo', 'Inserir Registo', 'Editar registo', 'Apagar Registo', '-', 'Imprimir ...', 'Exportar ...', '-', 'Guardar alterações', 'Não Guardar alterações', 'Refrescar', '-', 'selecionar/deselecionar registos', 'Selecionar registo', 'Selecionar todos os registos', '-', 'Deselecionar registo', 'deselecionar todos registos', '-', 'salvar formato da coluna', 'resturar formato da coluna', '-', 'Config...'); const //for TSMSetDBGridDialog SgbTitle = ' Titulo '; SgbData = ' Data '; STitleCaption = 'Titulo'; STitleAlignment = 'Alinhamento :'; STitleColor = 'Fundo:'; STitleFont = 'Fonte:'; SWidth = 'Largura:'; SWidthFix = 'characteres'; SAlignLeft = 'esquerda'; SAlignRight = 'direita'; SAlignCenter = 'centro'; const //for TSMDBFilterDialog strEqual = 'igual'; strNonEqual = 'diferente'; strNonMore = 'nao maior'; strNonLess = 'nao menor'; strLessThan = 'menor que'; strLargeThan = 'maior que'; strExist = 'vazio'; // exist = existe strNonExist = 'nao vazio'; // nonexit = Nao existe strIn = 'Na Lista'; strBetween = 'entre'; strOR = 'OU'; strAND = 'E'; strField = 'Campo'; strCondition = 'Condição'; strValue = 'Valor'; strAddCondition = ' Define a condicao addicional:'; strSelection = ' Selecione os Registos pela seguinte(s) Condições:'; strAddToList = 'Adicionar a Lista'; strEditInList = 'Editar da lista'; strDeleteFromList = 'Apagar Da Lista'; strTemplate = 'Filtrar por Dialogo'; strFLoadFrom = 'Obter de...'; strFSaveAs = 'Gravar Como..'; strFDescription = 'Descrição'; strFFileName = 'Nome do Cheiro'; strFCreate = 'Criado: %s'; strFModify = 'Modificado: %s'; strFProtect = 'Protegido Contra Escrita'; strFProtectErr = 'Ficheiro Protegido!'; const //for SMDBNavigator SFirstRecord = 'primeiro registo'; SPriorRecord = 'registo anterior'; SNextRecord = 'proximo registo'; SLastRecord = 'ultimo registo'; SInsertRecord = 'Inserir registo'; SCopyRecord = 'Copiar registo'; SDeleteRecord = 'Apagar registo'; SEditRecord = 'Editar registo'; SFilterRecord = 'condições de filtro'; SFindRecord = 'procurar registos'; SPrintRecord = 'imprimir registos'; SExportRecord = 'Exportar registos'; SPostEdit = 'guardar alterações'; SCancelEdit = 'Cancelar alterações'; SRefreshRecord = 'Refrescar dados'; SChoice = 'escolher um registo'; SClear = 'limpar escolha de registo'; SDeleteRecordQuestion = 'apagar registo?'; SDeleteMultipleRecordsQuestion = 'deseja mesmo apagar os registos selecionados ?'; SRecordNotFound = 'Não existe dados '; SFirstName = 'primeiro'; SPriorName = 'anterior'; SNextName = 'proximo'; SLastName = 'ultimo'; SInsertName = 'Inserir'; SCopyName = 'Copiar'; SDeleteName = 'apagar'; SEditName = 'Editar'; SFilterName = 'Filtrar'; SFindName = 'Localizar'; SPrintName = 'imprimir'; SExportName = 'Exportar'; SPostName = 'guardar'; SCancelName = 'Cancelar'; SRefreshName = 'Refrescar'; SChoiceName = 'escolher'; SClearName = 'limpar'; SBtnOk = '&OK'; SBtnCancel = '&Cancelar'; SBtnLoad = 'Carregar'; SBtnSave = 'guardar'; SBtnCopy = 'Copiar'; SBtnPaste = 'colar'; SBtnClear = 'limpar'; SRecNo = 'reg.'; SRecOf = ' de '; const //for EditTyped etValidNumber = 'número válido'; etValidInteger = 'número inteiro válido'; etValidDateTime = 'data/hora válida'; etValidDate = 'data válida'; etValidTime = 'hora válida'; etValid = 'válido'; etIsNot = 'não é um'; etOutOfRange = 'Valor %s está fora dos limites %s..%s'; implementation end.
{----------------------------------------------------------------------------- Unit Name: Author: Roman Purpose: History: -----------------------------------------------------------------------------} unit FC.Trade.Trader.Uni; {$I Compiler.inc} interface uses Classes, Math,Contnrs, Controls, SysUtils, BaseUtils, Properties.Obj, Properties.Definitions, StockChart.Definitions, Properties.Controls, StockChart.Indicators, Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties; type //Пока здесь объявлен. Потом как устоится, вынести в Definitions IStockTraderUni = interface ['{F5CEB066-F287-452C-B5D3-67F33B32283B}'] end; TStockTraderUni = class (TStockTraderBase,IStockTraderUni) private //Свойства (настраиваемые) FPropExpertWeighingType: TSCTraderPropertyExpertWeighingType; FPropExperts: TPropertyExperts; protected procedure GetProperties(aList: TPropertyList); override; procedure OnPropertyChanged(aNotifier:TProperty); override; public //Посчитать procedure UpdateStep2(const aTime: TDateTime); override; procedure Dispose; override; constructor Create; override; destructor Destroy; override; end; implementation uses Variants,FC.Trade.OrderCollection, FC.Trade.Trader.Message, StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory, StockChart.Obj, FC.DataUtils; { TStockTraderUni } constructor TStockTraderUni.Create; begin inherited Create; FPropExpertWeighingType:=TSCTraderPropertyExpertWeighingType.Create(self); FPropExpertWeighingType.Value:=ewtAllEqual; FPropExperts:=TPropertyExperts.Create('Method','Experts',self); RegisterProperties([FPropExpertWeighingType,FPropExperts]); end; destructor TStockTraderUni.Destroy; begin inherited; end; procedure TStockTraderUni.Dispose; begin inherited; FreeAndNil(FPropExpertWeighingType); FreeAndNil(FPropExperts); end; procedure TStockTraderUni.GetProperties(aList: TPropertyList); var aExperts: ISCIndicatorCollection; i: integer; begin inherited; FPropExperts.EventHandler:=nil; try aExperts:=TSCIndicatorCollection.Create(); for i:=0 to ExpertCount-1 do aExperts.Add(GetExpert(i)); FPropExperts.Value:=aExperts; finally FPropExperts.EventHandler:=self; end; end; procedure TStockTraderUni.OnPropertyChanged(aNotifier: TProperty); var aExperts: ISCIndicatorCollection; i: integer; begin inherited; if (aNotifier=FPropExperts) and not (isReading in State) then begin while ExpertCount>0 do DeleteExpert(0); aExperts:=FPropExperts.Value; for i:=0 to aExperts.Count-1 do AddExpert(aExperts.Items[i] as ISCExpert); end; end; procedure TStockTraderUni.UpdateStep2(const aTime: TDateTime); var i: integer; j: integer; aGuessOpenBuy,aGuessCloseBuy,aGuessOpenSell,aGuessCloseSell : TStockExpertGuess; aX: TStockExpertGuess; kOpenBuy,kCloseBuy, kOpenSell,kCloseSell : integer; aWeight: integer; aExpert: ISCExpert; aChart : IStockChart; aInputData : ISCInputDataCollection; aPropExpertWeighingType : TTraderExpertWeighingType; begin aGuessOpenBuy:=0; aGuessCloseBuy:=0; aGuessOpenSell:=0; aGuessCloseSell:=0; kOpenBuy:=0; kCloseBuy:=0; kOpenSell:=0; kCloseSell:=0; aPropExpertWeighingType:=FPropExpertWeighingType.Value; for i:=0 to ExpertCount-1 do begin aExpert:=GetExpert(i); aChart:=GetParentStockChart(aExpert); aInputData:=aChart.GetInputData; j:=aChart.FindBar(aTime); if j<>-1 then begin case aPropExpertWeighingType of ewtAllEqual: aWeight:=1; ewtTimeFrame:aWeight:=StockTimeIntervalValues[aChart.StockSymbol.TimeInterval]; ewtSeniority:aWeight:=integer(aChart.StockSymbol.TimeInterval)-integer(Low(TStockTimeInterval))+1; else raise EAlgoError.Create; end; aX:=aExpert.GetGuessOpenBuy(j); aGuessOpenBuy:=aGuessOpenBuy+aX*aWeight; inc(kOpenBuy,aWeight); aX:=aExpert.GetGuessCloseBuy(j); aGuessCloseBuy:=aGuessCloseBuy+aX*aWeight; inc(kCloseBuy,aWeight); aX:=aExpert.GetGuessOpenSell(j); aGuessOpenSell:=aGuessOpenSell+aX*aWeight; inc(kOpenSell,aWeight); aX:=aExpert.GetGuessCloseSell(j); aGuessCloseSell:=aGuessCloseSell+aX*aWeight; inc(kCloseSell,aWeight); end; end; //--- Анализируем экcпертные оценки --- //Есть ли сигнал на закрытие if kCloseBuy>0 then begin aGuessCloseBuy:=Round(aGuessCloseBuy/kCloseBuy); if aGuessCloseBuy>eg70 then begin if LastOrderType = lotBuy then CloseLastOrder('Expert: time to close'); end end; if kCloseSell>0 then begin aGuessCloseSell:=Round(aGuessCloseSell/kCloseSell); if aGuessCloseSell>eg70 then begin if LastOrderType = lotSell then CloseLastOrder('Expert: time to close'); end end; //Есть ли сигнал на открытие if kOpenBuy>0 then begin aGuessOpenBuy:=Round(aGuessOpenBuy/kOpenBuy); if aGuessOpenBuy>eg70 then begin case LastOrderType of //Автоматически закрываем предыдущий противоположный ордер lotSell: begin CloseLastOrder('Expert: open opposite'); OpenOrder(okBuy); end; lotBuy:{OpenOrder(okBuy)}; //Мы уже и так открыты в эту же сторону. Второй раз открываться не будем lotNone: OpenOrder(okBuy); end; end end; //Есть ли сигнал на открытие if kOpenSell>0 then begin aGuessOpenSell:=Round(aGuessOpenSell/kOpenSell); if aGuessOpenSell>eg70 then begin case LastOrderType of //Автоматически закрываем предыдущий противоположный ордер lotBuy: begin CloseLastOrder('Expert: open opposite'); OpenOrder(okSell); end; lotSell:{OpenOrder(okSell)}; //Мы уже и так открыты в эту же сторону. Второй раз открываться не будем lotNone: OpenOrder(okSell); end; end end; end; initialization FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','Universal',TStockTraderUni,IStockTraderUni); end.
unit uIOPortForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ExtCtrls, Grids, uResourceStrings, uView, uProcessor, StdCtrls, Menus, uMisc, Registry; type TIOPortsRefreshRequestEvent = procedure(Listener: IIOPorts) of object; TIOPortsUpdateRequestEvent = procedure(PortNo: Byte; Value: Byte) of object; TIOPortsActiveRequestEvent = procedure(Active: Boolean) of object; TIOPortsFileRequestEvent = procedure(Filename: TFilename) of object; TIOPortsFileResetRequestEvent = procedure of object; TIOPortForm = class(TForm, ILanguage, IRadixView, IIOPorts, IRegistry, IProcessor) sgIOPort: TStringGrid; PopupMenu: TPopupMenu; miClose: TMenuItem; N1: TMenuItem; miStayOnTop: TMenuItem; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; gbPortFile: TGroupBox; cbPortActive: TCheckBox; sbFile: TSpeedButton; sbClose: TSpeedButton; iIN: TImage; iOUT: TImage; iOUTClose: TImage; iINClose: TImage; sbResetFile: TSpeedButton; procedure FormCreate(Sender: TObject); procedure sgIOPortDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure miCloseClick(Sender: TObject); procedure miStayOnTopClick(Sender: TObject); procedure sgIOPortKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure sgIOPortDblClick(Sender: TObject); procedure sgIOPortSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); procedure cbPortActiveClick(Sender: TObject); procedure sbFileClick(Sender: TObject); procedure sbCloseClick(Sender: TObject); procedure sbResetFileClick(Sender: TObject); private _Block: Boolean; _BlockActive: Boolean; _Width: Integer; _PortType: TPortType; _CanEdit: Boolean; _Radix: TRadix; _ARow: Integer; _ACol: Integer; _OnIPortsRefreshRequest: TIOPortsRefreshRequestEvent; _OnIPortsUpdateRequest: TIOPortsUpdateRequestEvent; _OnOPortsRefreshRequest: TIOPortsRefreshRequestEvent; _OnPortsActiveRequest: TIOPortsActiveRequestEvent; _OnPortsFileRequest: TIOPortsFileRequestEvent; _OnPortFileResetRequest: TIOPortsFileResetRequestEvent; procedure setPortType(Value: TPortType); procedure setCanEdit(Value: Boolean); procedure RefreshObject(Sender: TObject); procedure Reset(Sender: TObject); procedure PortUpdate(Sender: TObject; Index: Byte; Value: Byte); procedure PortAction(Sender: TObject; Active: Boolean); procedure BeforeCycle(Sender: TObject); procedure AfterCycle(Sender: TObject); procedure StateChange(Sender: TObject; Halt: Boolean); procedure LoadData(RegistryList: TRegistryList); procedure SaveData(RegistryList: TRegistryList); property CanEdit: Boolean read _CanEdit write setCanEdit; public procedure LoadLanguage; procedure RadixChange(Radix: TRadix; View: TView); property PortType: TPortType read _PortType write setPortType; property OnIPortsRefreshRequest: TIOPortsRefreshRequestEvent read _OnIPortsRefreshRequest write _OnIPortsRefreshRequest; property OnIPortsUpdateRequest: TIOPortsUpdateRequestEvent read _OnIPortsUpdateRequest write _OnIPortsUpdateRequest; property OnOPortsRefreshRequest: TIOPortsRefreshRequestEvent read _OnOPortsRefreshRequest write _OnOPortsRefreshRequest; property OnPortsActiveRequest: TIOPortsActiveRequestEvent read _OnPortsActiveRequest write _OnPortsActiveRequest; property OnPortsFileRequest: TIOPortsFileRequestEvent read _OnPortsFileRequest write _OnPortsFileRequest; property OnPortFileResetRequest: TIOPortsFileResetRequestEvent read _OnPortFileResetRequest write _OnPortFileResetRequest; end; var IPortForm: TIOPortForm; OPortForm: TIOPortForm; implementation uses uEditForm; {$R *.dfm} procedure TIOPortForm.FormCreate(Sender: TObject); begin _BlockActive:= false; _Block:= false; _Radix:= rOctal; sgIOPort.ColCount:= 3; sgIOPort.ColWidths[0]:= 70; sgIOPort.ColWidths[1]:= 70; sgIOPort.ColWidths[2]:= 0; sgIOPort.Cells[2,0]:= ''; ClientHeight:= sgIOPort.RowHeights[0] * 9 + gbPortFile.Height; _ARow:= -1; _ACol:= -1; LoadLanguage; PortType:= ptUnknown; end; procedure TIOPortForm.FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); begin if not _Block then NewWidth:= _Width; end; procedure TIOPortForm.sgIOPortDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin if (ARow = 0) or (ACol = 0) then sgIOPort.Canvas.Brush.Color:= sgIOPort.FixedColor else sgIOPort.Canvas.Brush.Color:= sgIOPort.Color; sgIOPort.Canvas.FillRect(Rect); if (ACol = 1) and (sgIOPort.Cells[2,ARow] <> '') then sgIOPort.Canvas.Font.Color:= clRed else if (ACol = 1) and (ARow = 0) and not CanEdit then sgIOPort.Canvas.Font.Color:= clGrayText else sgIOPort.Canvas.Font.Color:= clWindowText; Rect.Top:= Rect.Top + ((sgIOPort.RowHeights[ARow] - sgIOPort.Canvas.TextHeight(sgIOPort.Cells[ACol,ARow]))) div 2; if ARow = 0 then Rect.Left:= Rect.Left + (sgIOPort.ColWidths[ACol] - sgIOPort.Canvas.TextWidth(sgIOPort.Cells[ACol,ARow])) div 2 else Rect.Left:= Rect.Right - 4 - sgIOPort.Canvas.TextWidth(sgIOPort.Cells[ACol,ARow]); sgIOPort.Canvas.TextOut(Rect.Left,Rect.Top,sgIOPort.Cells[ACol,ARow]); end; procedure TIOPortForm.miCloseClick(Sender: TObject); begin Close; end; procedure TIOPortForm.miStayOnTopClick(Sender: TObject); begin if miStayOnTop.Checked then FormStyle:= fsNormal else FormStyle:= fsStayOnTop; miStayOnTop.Checked:= not miStayOnTop.Checked; end; procedure TIOPortForm.sgIOPortSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin CanSelect:= ACol < 2; if CanSelect then begin _ARow:= ARow; _ACol:= ACol; end; end; procedure TIOPortForm.sgIOPortDblClick(Sender: TObject); var C: Boolean; P: TPoint; begin if (_ARow > 0) and (_ACol = 1) and (PortType = ptIN) and CanEdit then begin P.X:= Mouse.CursorPos.X; P.Y:= Mouse.CursorPos.Y; EditForm.Value:= RadixToWord(sgIOPort.Cells[_ACol,_ARow],_Radix,vLong,C); if (EditForm.ShowModal(_Radix,vLong,8,P) = mrOk) and Assigned(OnIPortsUpdateRequest) then OnIPortsUpdateRequest(_ARow-1+Ti8008IPorts.FirstPortNo,EditForm.Value); end; end; procedure TIOPortForm.sgIOPortKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then sgIOPortDblClick(Sender); end; procedure TIOPortForm.cbPortActiveClick(Sender: TObject); begin if not _BlockActive and Assigned(OnPortsActiveRequest) then OnPortsActiveRequest(cbPortActive.Checked); end; procedure TIOPortForm.sbResetFileClick(Sender: TObject); begin if Assigned(OnPortFileResetRequest) then OnPortFileResetRequest; end; procedure TIOPortForm.sbFileClick(Sender: TObject); var Filename: TFilename; begin case PortType of ptIN : if Assigned(OnPortsFileRequest) and OpenDialog.Execute then begin Filename:= ChangeFileExt(OpenDialog.FileName,'.pin'); OnPortsFileRequest(Filename); sbFile.Enabled:= false; sbResetFile.Enabled:= true; sbClose.Enabled:= true; cbPortActive.Enabled:= true; end; ptOUT : if Assigned(OnPortsFileRequest) and SaveDialog.Execute then begin Filename:= ChangeFileExt(SaveDialog.FileName,'.pout'); OnPortsFileRequest(FileName); sbFile.Enabled:= false; sbClose.Enabled:= true; cbPortActive.Enabled:= true; end; end end; procedure TIOPortForm.sbCloseClick(Sender: TObject); begin if Assigned(OnPortsFileRequest) then begin OnPortsFileRequest(''); sbFile.Enabled:= true; sbResetFile.Enabled:= false; sbClose.Enabled:= false; cbPortActive.Enabled:= false; end; end; procedure TIOPortForm.setPortType(Value: TPortType); begin _Block:= true; _PortType:= Value; case PortType of ptIN : begin Caption:= 'i8008 IN - Ports'; sgIOPort.RowCount:= Ti8008IPorts.Count + 1; sgIOPort.FixedRows:= 1; ClientWidth:= 160; _Width:= Width; iIN.Visible:= false; iINClose.Visible:= false; iOUT.Visible:= false; iOUTClose.Visible:= false; sbFile.Glyph:= iIN.Picture.Bitmap; sbClose.Glyph:= iINClose.Picture.Bitmap; sbFile.Enabled:= true; sbClose.Enabled:= false; sbResetFile.Visible:= true; sbResetFile.Enabled:= false; cbPortActive.Enabled:= false; CanEdit:= true; end; ptOUT : begin Caption:= 'i8008 OUT - Ports'; sgIOPort.RowCount:= Ti8008OPorts.Count + 1; sgIOPort.FixedRows:= 1; ClientWidth:= 160; _Width:= Width; iIN.Visible:= false; iINClose.Visible:= false; iOUT.Visible:= false; iOUTClose.Visible:= false; sbFile.Glyph:= iOUT.Picture.Bitmap; sbClose.Glyph:= iOUTClose.Picture.Bitmap; sbFile.Enabled:= true; sbClose.Enabled:= false; sbResetFile.Visible:= false; cbPortActive.Enabled:= false; CanEdit:= false; end; else begin Caption:= 'i8008 Ports'; sgIOPort.RowCount:= 1; ClientWidth:= 160; _Width:= Width; iIN.Visible:= false; iINClose.Visible:= false; iOUT.Visible:= false; iOUTClose.Visible:= false; sbFile.Enabled:= false; sbClose.Enabled:= false; CanEdit:= false; end; end; if (PortType = ptIN) and Assigned(OnIPortsRefreshRequest) then OnIPortsRefreshRequest(Self); if (PortType = ptOUT) and Assigned(OnOPortsRefreshRequest) then OnOPortsRefreshRequest(Self); _Block:= false; end; procedure TIOPortForm.setCanEdit(Value: Boolean); begin _CanEdit:= (Porttype = ptIn) and Value; sgIOPort.Invalidate; end; procedure TIOPortForm.RefreshObject(Sender: TObject); var i, iFirstPortNo: Integer; Bits: Byte; begin if (Sender is TIOPorts) and ((Sender as TIOPorts).PortType = PortType) and not (PortType = ptUnknown) then begin case (Sender as TIOPorts).PortType of ptIN : Bits:= 3; ptOUT : Bits:= 5; else Bits:= 16; end; iFirstPortNo:= (Sender as TIOPorts).FirstPortNo; for i:= 0 to (Sender as TIOPorts).Count-1 do begin sgIOPort.Cells[0,i+1]:= WordToRadix(i+iFirstPortNo,_Radix,vLong,Bits); sgIOPort.Cells[1,i+1]:= WordToRadix((Sender as TIOPorts).Value[i+iFirstPortNo], _Radix,vLong,8); end; end; sgIOPort.Invalidate; end; procedure TIOPortForm.Reset(Sender: TObject); var i, iFirstPortNo: Integer; Bits: Byte; begin if (Sender is TIOPorts) and ((Sender as TIOPorts).PortType = PortType) and not (PortType = ptUnknown) then begin case (Sender as TIOPorts).PortType of ptIN : Bits:= 3; ptOUT : Bits:= 5; else Bits:= 16; end; iFirstPortNo:= (Sender as TIOPorts).FirstPortNo; for i:= 0 to (Sender as TIOPorts).Count-1 do begin sgIOPort.Cells[2,i+1]:= ''; sgIOPort.Cells[0,i+1]:= WordToRadix(i+iFirstPortNo,_Radix,vLong,Bits); sgIOPort.Cells[1,i+1]:= WordToRadix((Sender as TIOPorts).Value[i+iFirstPortNo], _Radix,vLong,8); end; end; end; procedure TIOPortForm.PortUpdate(Sender: TObject; Index: Byte; Value: Byte); var sValue: String; begin if (Sender is TIOPorts) and ((Sender as TIOPorts).PortType = PortType) and not (PortType = ptUnknown) then begin Index:= Index - (Sender as TIOPorts).FirstPortNo; sValue:= WordToRadix(Value,_Radix,vLong,8); if sValue <> sgIOPort.Cells[1,Index+1] then sgIOPort.Cells[2,Index+1]:= '*'; sgIOPort.Cells[1,Index+1]:= sValue; end end; procedure TIOPortForm.PortAction(Sender: TObject; Active: Boolean); begin _BlockActive:= true; cbPortActive.Checked:= Active; CanEdit:= not Active; _BlockActive:= false; end; procedure TIOPortForm.BeforeCycle(Sender: TObject); var i: Integer; begin for i:= 1 to sgIOPort.RowCount-1 do begin sgIOPort.Cells[2,i]:= ''; sgIOPort.Cells[1,i]:= sgIOPort.Cells[1,i]; end; end; procedure TIOPortForm.AfterCycle(Sender: TObject); begin end; procedure TIOPortForm.StateChange(Sender: TObject; Halt: Boolean); begin end; procedure TIOPortForm.LoadData(RegistryList: TRegistryList); begin if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,false) then RegistryList.LoadFormSettings(Self,true); end; procedure TIOPortForm.SaveData(RegistryList: TRegistryList); begin if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,true) then RegistryList.SaveFormSettings(Self,true); end; procedure TIOPortForm.LoadLanguage; begin sgIOPort.Cells[0,0]:= getString(rsPortAddress); sgIOPort.Cells[1,0]:= getString(rsValue); miClose.Caption:= getString(rsClose); miStayOnTop.Caption:= getString(rsStayOnTop); gbPortFile.Caption:= ' '+getString(rs_p_File)+' '; cbPortActive.Caption:= getString(rs_p_Active); sbResetFile.Hint:= getString(rs_p_ResetFile); case PortType of ptIN : sbFile.Caption:= getString(rs_p_Open); ptOUT : sbFile.Caption:= getString(rs_p_Save); else sbFile.Caption:= ''; end; sbClose.Caption:= getString(rs_p_Close); OpenDialog.Title:= getString(rs_p_OpenDialog); SaveDialog.Title:= getString(rs_p_SaveDialog); OpenDialog.Filter:= getString(rs_p_OpenFilter); SaveDialog.Filter:= getString(rs_p_SaveFilter); end; procedure TIOPortForm.RadixChange(Radix: TRadix; View: TView); begin if Radix = rDecimalNeg then Radix:= rDecimal; _Radix:= Radix; end; end.
unit Analyser; interface uses Parser, SymbolTable, Token; type TAnalyser = class(TParser) public constructor Create(MaxErrors : integer = 10 ; Includes : AnsiString = ''; SilentMode : integer = 2 ; LanguageMode : AnsiString = ''; NotShow : AnsiString = ''); protected SymbolTable : TSymbolTable; Operand : TToken; procedure Analyse(Symbol : char); override; procedure PushScope; procedure PopScope; procedure AddModule; procedure AddSymbol; procedure SetType; procedure GetSymbol; end; implementation uses CompilerUtils;//, Generator; const SemanticAction : array[#0..#5] of pointer = ( @TAnalyser.PushScope, @TAnalyser.PopScope, @TAnalyser.AddModule, @TAnalyser.AddSymbol, @TAnalyser.SetType, @TAnalyser.GetSymbol); constructor TAnalyser.Create(MaxErrors : integer; Includes : AnsiString; SilentMode : integer; LanguageMode : AnsiString; NotShow : AnsiString); begin inherited; SymbolTable := TSymbolTable.Create; end; procedure TAnalyser.Analyse(Symbol : char); begin Call(SemanticAction, Symbol); end; procedure TAnalyser.PushScope; begin SymbolTable.PushScope; end; procedure TAnalyser.PopScope; begin try SymbolTable.PopScope; except on E : EFatal do ShowMessage('Fatal', E.Message); end; end; procedure TAnalyser.AddModule; begin Token.Kind := StringToTokenKind(LastLexeme); //MakeModule(Token); AddSymbol; end; procedure TAnalyser.AddSymbol; begin try SymbolTable.Add(Token); Token := TToken.Create; except on E : EFatal do ShowMessage('Fatal', E.Message); on E : EError do Error(E.Message); end; end; procedure TAnalyser.SetType; var T : TToken; L : string; begin L := Token.Lexeme; T := SymbolTable.Last; while (T <> nil) and (T.Kind = tkIdentifier) do begin T.Type_ := SymbolTable.Get(L); if T.Type_ = nil then T.Kind := StringToTokenKind(L, tkIdentifier); T := SymbolTable.Previous; end; end; procedure TAnalyser.GetSymbol; begin Operand := SymbolTable.Get(Token.Lexeme); if Operand = nil then Error('Undeclared Identifier "' + Token.Lexeme + '"'); end; end.
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info) unit SMARTSupport.Sandforce; interface uses BufferInterpreter, Device.SMART.List, SMARTSupport, Support; type TSandforceSMARTSupport = class(TSMARTSupport) private function ModelHasSandforceString(const Model: String): Boolean; function SMARTHasSandforceCharacteristics( const SMARTList: TSMARTValueList): Boolean; function CheckSpecificCharacteristics1( const SMARTList: TSMARTValueList): Boolean; function CheckSpecificCharacteristics2( const SMARTList: TSMARTValueList): Boolean; function CheckToshibaSandforceCharacteristics( const SMARTList: TSMARTValueList): Boolean; function IsNotSandforceBug(const Entry: TSMARTValueEntry): Boolean; function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite; const EntryID = $E7; public function IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; override; function GetTypeName: String; override; function IsSSD: Boolean; override; function IsInsufficientSMART: Boolean; override; function GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; override; function IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; override; protected function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer; override; function InnerIsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsCautionAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; function InnerIsCaution(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; end; implementation { TSandforceSMARTSupport } function TSandforceSMARTSupport.GetTypeName: String; begin result := 'SmartSandForce'; end; function TSandforceSMARTSupport.IsSSD: Boolean; begin result := true; end; function TSandforceSMARTSupport.IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := ModelHasSandforceString(IdentifyDevice.Model) or SMARTHasSandforceCharacteristics(SMARTList); end; function TSandforceSMARTSupport.ModelHasSandforceString(const Model: String): Boolean; begin result := Find('SandForce', Model); end; function TSandforceSMARTSupport.SMARTHasSandforceCharacteristics( const SMARTList: TSMARTValueList): Boolean; begin result := CheckSpecificCharacteristics1(SMARTList) or CheckSpecificCharacteristics2(SMARTList) or CheckToshibaSandforceCharacteristics(SMARTList); end; function TSandforceSMARTSupport.CheckSpecificCharacteristics1( const SMARTList: TSMARTValueList): Boolean; begin result := (SMARTList.Count >= 7) and (SMARTList[0].Id = $01) and (SMARTList[1].Id = $05) and (SMARTList[2].Id = $09) and (SMARTList[3].Id = $0C) and (SMARTList[4].Id = $0D) and (SMARTList[5].Id = $64) and (SMARTList[6].Id = $AA); end; function TSandforceSMARTSupport.CheckSpecificCharacteristics2( const SMARTList: TSMARTValueList): Boolean; begin result := (SMARTList.Count >= 6) and (SMARTList[0].Id = $01) and (SMARTList[1].Id = $05) and (SMARTList[2].Id = $09) and (SMARTList[3].Id = $0C) and (SMARTList[4].Id = $AB) and (SMARTList[5].Id = $AC); end; function TSandforceSMARTSupport.CheckToshibaSandforceCharacteristics( const SMARTList: TSMARTValueList): Boolean; begin // TOSHIBA + SandForce // http://crystalmark.info/bbs/c-board.cgi?cmd=one;no=1116;id=diskinfo#1116 // http://crystalmark.info/bbs/c-board.cgi?cmd=one;no=1136;id=diskinfo#1136 result := (SMARTList.Count >= 16) and (SMARTList[0].Id = $01) and (SMARTList[1].Id = $02) and (SMARTList[2].Id = $03) and (SMARTList[3].Id = $05) and (SMARTList[4].Id = $07) and (SMARTList[5].Id = $08) and (SMARTList[6].Id = $09) and (SMARTList[7].Id = $0A) and (SMARTList[8].Id = $0C) and (SMARTList[9].Id = $A7) and (SMARTList[10].Id = $A8) and (SMARTList[11].Id = $A9) and (SMARTList[12].Id = $AA) and (SMARTList[13].Id = $AD) and (SMARTList[14].Id = $AF) and (SMARTList[15].Id = $B1); end; function TSandforceSMARTSupport.ErrorCheckedGetLife( const SMARTList: TSMARTValueList): Integer; begin result := SMARTList[SMARTList.GetIndexByID($E7)].Current; end; function TSandforceSMARTSupport.InnerIsErrorAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TSandforceSMARTSupport.InnerIsCautionAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TSandforceSMARTSupport.IsInsufficientSMART: Boolean; begin result := false; end; function TSandforceSMARTSupport.IsNotSandforceBug( const Entry: TSMARTValueEntry): Boolean; begin result := (Entry.ID = 1) and (Entry.Current = 0) and ((Entry.RAW and $FFFF) = 0); end; function TSandforceSMARTSupport.InnerIsError( const SMARTList: TSMARTValueList): TSMARTErrorResult; var CurrentEntry: TSMARTValueEntry; begin result.Override := true; result.Status := false; for CurrentEntry in SMARTList do if not IsNotSandforceBug(CurrentEntry) then if CurrentEntry.ID <> $C2 then if CurrentEntry.Threshold > CurrentEntry.Current then begin result.Status := true; exit; end; result.Status := result.Status or InnerCommonIsError(EntryID, SMARTList).Status; end; function TSandforceSMARTSupport.InnerIsCaution( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result := InnerCommonIsCaution(EntryID, SMARTList, CommonLifeThreshold); end; function TSandforceSMARTSupport.IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; const WriteID = $F1; begin try SMARTList.GetIndexByID(WriteID); result := true; except result := false; end; end; function TSandforceSMARTSupport.GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; const ReadError = true; EraseError = false; UsedHourID = $09; ThisErrorType = ReadError; ErrorID = $BB; ReplacedSectorsID = $05; begin FillChar(result, SizeOf(result), 0); result.UsedHour := UINT16(SMARTList.ExceptionFreeGetRAWByID(UsedHourID)); result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError; result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID); result.ReplacedSectors := SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID); result.TotalWrite := GetTotalWrite(SMARTList); end; function TSandforceSMARTSupport.GetTotalWrite( const SMARTList: TSMARTValueList): TTotalWrite; function LBAToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shr 1; end; function GBToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shl 10; end; const HostWrite = true; NANDWrite = false; WriteID = $F1; begin result.InValue.TrueHostWriteFalseNANDWrite := HostWrite; result.InValue.ValueInMiB := GBToMB(SMARTList.ExceptionFreeGetRAWByID(WriteID)); end; end.