text
stringlengths
14
6.51M
unit session; {$mode objfpc}{$H+} interface uses DmDatabase, sqldb, Classes, fpjson, jsonparser, lazutf8sysutils, user, BrookLogger, SysUtils; type { TSession } TSession = class private FSessionDatabase: TSQLConnection; FToken: string; FExpire: TDateTime; FUser: TUser; procedure ParseSessionData(ASessionData: string); procedure DeleteExpiredSessions; procedure ExecQuery(ASql: string); function Match(ASql: string): boolean; public constructor Create(ADatabase: TSQLConnection); destructor Destroy; override; function NewSession(ASessionData: string): string; function FindSessionRecord(ASessionId: string): boolean; function GetSessionData(ASessionId: string): string; procedure DeleteSession(ASessionId: string); procedure UpdateExpiration; property Token: String read FToken write FToken; property Expire: TDateTime read FExpire; property User: TUser read FUser; end; implementation uses dateutils; constructor TSession.Create(ADatabase: TSQLConnection); begin inherited Create; FSessionDatabase := ADatabase; FUser := TUser.Create; end; destructor TSession.Destroy; begin FUser.Free; inherited Destroy; end; procedure TSession.ExecQuery(ASql: string); begin datamodule1.ExecQuery(ASql); end; function TSession.NewSession(ASessionData: string): string; var lSql: string; SID: LongInt; begin //Delete any expired sessions before createing a new one DeleteExpiredSessions; randomize; SID := Random(2000000000); FToken := IntToStr(SID); FExpire := IncMinute(NowUTC(), 30); lSql := 'INSERT INTO sessions(SESSIONID,SESSIONTIMESTAMP,SESSIONDATA)' + 'VALUES (%d, ''%s'', ''%s'')'; lSql := Format(lSql, [SID, FormatDateTime('yyyy-mm-dd hh:mm:ss', FExpire), ASessionData]); ParseSessionData(ASessionData); ExecQuery(lSql); Result := FToken; end; procedure TSession.ParseSessionData(ASessionData: string); var lJson: TJSONObject; lParser: TJSONParser; begin if ASessionData = '' then exit; lParser := TJSONParser.Create(ASessionData); lJson := TJSONObject(lParser.Parse); try FUser.IdUser:= lJson.Integers['id']; finally lJson.Free; lParser.Free; end; end; procedure TSession.DeleteExpiredSessions; var lSql: string; begin lSql := 'DELETE From sessions WHERE (SESSIONTIMESTAMP < '; lSql := lSql + '''' + FormatDateTime('yyyy-mm-dd hh:nn:ss', Now) + ''' '; lSql := lSql + ')'; ExecQuery(lSql); end; function TSession.Match(ASql: string): boolean; var lQuery: TSQLQuery; begin lQuery := TSQLQuery.Create(nil); try lQuery.DataBase := FSessionDatabase; lQuery.SQL.Text:= ASql; lQuery.Open; Result := lQuery.RecordCount > 0; finally lQuery.Free; end; end; function TSession.FindSessionRecord(ASessionId: string): boolean; var lSql: string; begin try Result := False; DeleteExpiredSessions; lSql := Format('select SESSIONID, SESSIONTIMESTAMP, SESSIONDATA from sessions Where SESSIONID = ''%s''', [ASessionID]); Result := Match(lSql); if Result then begin lSql := 'update sessions set SESSIONTIMESTAMP = ''%s'' where sessionid=''%s'''; lSql := Format(lSql, [ FormatDateTime('yyyy-mm-dd hh:mm:ss', IncMinute(Now, 30)), ASessionId]); ExecQuery(lSql); GetSessionData(ASessionId); end; except on E: Exception do raise Exception.Create(E.message); end; end; function TSession.GetSessionData(ASessionId: string): string; var lQuery: TSQLQuery; begin lQuery := TSQLQuery.Create(nil); try lQuery.DataBase := FSessionDatabase; FSessionDatabase.Transaction.StartTransaction; lQuery.SQL.Text:= Format('select SESSIONID, SESSIONTIMESTAMP, SESSIONDATA from sessions Where SESSIONID = ''%s''', [ASessionID]); lQuery.Open; if lQuery.RecordCount > 0 then begin Result := lQuery.FieldByName('SESSIONDATA').AsString; ParseSessionData(Result); end; finally FSessionDatabase.Transaction.Commit; lQuery.Free; end; end; procedure TSession.DeleteSession(ASessionId: string); var lSql: string; begin lSql := 'DELETE From sessions WHERE sessionid=''%s'''; lSql := Format(lSql, [ASessionId]); ExecQuery(lSql); end; procedure TSession.UpdateExpiration; begin FExpire := IncMinute(NowUTC(), 30); end; end.
{*******************************************************} { } { Borland Delphi Sample } { } { Copyright (c) 2001 Inprise Corporation } { } {*******************************************************} unit DrawBtn; interface uses Windows, Messages, SysUtils, Classes; function DrawButton(Params: TStrings; var ContentType: string): TStream; const sTxt = 'Txt'; sFontName = 'FontName'; sFontSize = 'FontSize'; sFontColor = 'FontColor'; sColor = 'Color'; sTLColor = 'TLColor'; sBRColor = 'BRColor'; sFocusColor = 'FocusColor'; sWidth = 'Width'; sHeight = 'Height'; sUp = 'Up'; sEnabled = 'Enabled'; sFocused = 'Focused'; sBackground = 'Background'; sGlyph = 'Glyph'; sFontBold = 'FontBold'; sFontItalic = 'FontItalic'; sFontUnderline = 'FontUnderline'; sFontStrikeOut = 'FontStrikeOut'; implementation uses ExtCtrls, StdCtrls, Controls, Forms, Graphics, JPEG; function GetIntegerValue(const Value : String; Default : Integer) : Integer; begin if Value = '' then Result := Default else try Result := StrToInt(Value); except Result := Default; end; end; function GetBooleanValue(const Value : String; Default : Boolean) : Boolean; begin if Value = '' then Result := Default else try Result := StrToBool(Value); except Result := Default; end; end; function GetColorValue(const Value : String; Default : TColor) : TColor; function HTMLColor(const S : String) : String; begin if S = '' then Result := '' else if S[1] = '#' then Result := '$'+S[6]+S[7]+S[4]+S[5]+S[2]+S[3] else Result := S; end; begin if Value = '' then Result := Default else try Result := StringToColor(HTMLColor(Value)); except Result := Default; end; end; function DrawButton(Params: TStrings; var ContentType: string): TStream; var Txt, FontName, Background, Glyph : String; FontColor, Color, TLColor, BRColor, FocusColor : TColor; FontSize, ButtonWidth, ButtonHeight : Integer; FontBold, FontItalic, FontUnderline, FontStrikeOut, Up, Enabled, Focused : Boolean; Bitmap, BMP : TBitmap; begin // Get parameter values and set defaults if required with Params do begin Txt := Values[sTxt]; FontName := Values[sFontName]; FontSize := GetIntegerValue(Values[sFontSize],8); FontColor := GetColorValue(Values[sFontColor],clBlack); Color := GetColorValue(Values[sColor],clBtnFace); TLColor := GetColorValue(Values[sTLColor],clWhite); BRColor := GetColorValue(Values[sBRColor],clGray); FocusColor := GetColorValue(Values[sFocusColor],clYellow); ButtonWidth := GetIntegerValue(Values[sWidth],75); ButtonHeight := GetIntegerValue(Values[sHeight],25); Up := GetBooleanValue(Values[sUp],True); Enabled := GetBooleanValue(Values[sEnabled],True); Focused := GetBooleanValue(Values[sFocused],False); Background := Values[sBackground]; Glyph := Values[sGlyph]; FontBold := GetBooleanValue(Values[sFontBold],False); FontItalic := GetBooleanValue(Values[sFontItalic],False); FontUnderline := GetBooleanValue(Values[sFontUnderline],False); FontStrikeOut := GetBooleanValue(Values[sFontStrikeOut],False); end; Bitmap := TBitmap.Create; try with Bitmap do begin Width := ButtonWidth; Height := ButtonHeight; with Canvas do begin with Font do begin Name := FontName; Size := FontSize; Color := FontColor; Style := []; if FontBold then Style := Style+[fsBold]; if FontItalic then Style := Style+[fsItalic]; if FontUnderline then Style := Style+[fsUnderline]; if FontStrikeOut then Style := Style+[fsStrikeOut]; end; if not Enabled then begin // Draw the background area for the button Brush.Color := Color; FillRect(Rect(0,0,Width,Height)); // Draw the background { if Background <> '' then begin BMP := TBitmap.Create; BMP.LoadFromFile('buttons'+PathDelim+Background+'.bmp'); StretchDraw(Rect(1,1,Width-2,Height-2),BMP); BMP.Free; end; } // Draw the glyph if Glyph <> '' then begin BMP := TBitmap.Create; try BMP.LoadFromFile('buttons'+PathDelim+Glyph+'.bmp'); BMP.Canvas.CopyRect(Rect(0,0,16,16),BMP.Canvas,Rect(16,0,32,16)); BMP.Transparent := True; BMP.Width := 16; // Clip off the disabled piece Draw(8,(Height div 2)-8,BMP); except end; BMP.Free; end; // Draw the left and top edges Brush.Color := TLColor; FrameRect(Rect(0,0,Width,1)); FrameRect(Rect(0,1,Width-1,2)); FrameRect(Rect(0,0,1,Height)); FrameRect(Rect(1,0,2,Height-1)); // Draw the right and bottom edges Brush.Color := BRColor; FrameRect(Rect(Width,0,Width,Height)); FrameRect(Rect(Width-1,1,Width-1,Height)); FrameRect(Rect(1,Height,Width,Height)); FrameRect(Rect(2,Height-1,Width,Height-1)); // Draw the caption Brush.Style := bsClear; Font.Color := clGray; TextOut((Width-Canvas.TextWidth(Txt)) div 2,(Height-Canvas.TextHeight(Txt)) div 2,Txt); end else if Up then begin // Draw the background area for the button Brush.Color := Color; FillRect(Rect(0,0,Width,Height)); // Draw the background if Background <> '' then begin BMP := TBitmap.Create; try BMP.LoadFromFile('buttons'+PathDelim+Background+'.bmp'); StretchDraw(Rect(1,1,Width-2,Height-2),BMP); except end; BMP.Free; end; // Draw the glyph if Glyph <> '' then begin BMP := TBitmap.Create; try BMP.LoadFromFile('buttons'+PathDelim+Glyph+'.bmp'); BMP.Transparent := True; BMP.Width := 16; // Clip off the disabled piece Draw(8,(Height div 2)-8,BMP); except end; BMP.Free; end; // Draw the left and top edges Brush.Color := TLColor; FrameRect(Rect(0,0,Width,1)); FrameRect(Rect(0,1,Width-1,2)); FrameRect(Rect(0,0,1,Height)); FrameRect(Rect(1,0,2,Height-1)); // Draw the right and bottom edges Brush.Color := BRColor; FrameRect(Rect(Width,0,Width,Height)); FrameRect(Rect(Width-1,1,Width-1,Height)); FrameRect(Rect(1,Height,Width,Height)); FrameRect(Rect(2,Height-1,Width,Height-1)); // Draw the caption Brush.Style := bsClear; TextOut((Width-Canvas.TextWidth(Txt)) div 2,(Height-Canvas.TextHeight(Txt)) div 2,Txt); // Draw the focus rect if Focused then begin Brush.Style := bsSolid; Brush.Color := FocusColor; FrameRect(Rect(0,0,Width,Height)); end; end else begin // Draw the background area for the button Brush.Color := Color; FillRect(Rect(0,0,Width,Height)); // Draw the background if Background <> '' then begin BMP := TBitmap.Create; try BMP.LoadFromFile('buttons'+PathDelim+Background+'.bmp'); StretchDraw(Rect(2,2,Width-1,Height-1),BMP); except end; BMP.Free; end; // Draw the glyph if Glyph <> '' then begin BMP := TBitmap.Create; try BMP.LoadFromFile('buttons'+PathDelim+Glyph+'.bmp'); BMP.Transparent := True; BMP.Width := 16; // Clip off the Draw(9,(Height div 2)-7,BMP); except end; BMP.Free; end; // Draw the left and top edges Brush.Color := BRColor; FrameRect(Rect(0,0,Width,1)); FrameRect(Rect(0,1,Width-1,2)); FrameRect(Rect(0,0,1,Height)); FrameRect(Rect(1,0,2,Height-1)); // Draw the right and bottom edges Brush.Color := BRColor; FrameRect(Rect(Width,0,Width,Height)); FrameRect(Rect(Width-1,1,Width-1,Height)); FrameRect(Rect(1,Height,Width,Height)); FrameRect(Rect(2,Height-1,Width,Height-1)); // Draw the caption Brush.Style := bsClear; TextOut(((Width-Canvas.TextWidth(Txt)) div 2)+1,((Height-Canvas.TextHeight(Txt)) div 2)+1,Txt); end; end; end; except Bitmap.Free; raise; end; Result := TMemoryStream.Create; try with TJPEGImage.Create do begin try CompressionQuality := 100; Assign(Bitmap); SaveToStream(Result); finally Free; end; end; except Result.Free; raise; end; ContentType := 'image/jpeg'; end; end.
unit Test.Devices.Base.ReqCreator; interface uses TestFrameWork, GMGlobals, GM485, GMGenerics, Generics.Collections, SysUtils, GMSqlQuery, ActiveX, GMConst, Devices.ReqCreatorBase; type T485RequestCreatorForTest = class(T485RequestCreator) protected function GetDevReqCreatorClass(ID_DevType: int): TDevReqCreatorClass; override; end; TDeviceReqCreatorTestBase = class(TTestCase) private function GetReqString(Index: int): string; protected ReqCreator: T485RequestCreatorForTest; ReqList: TList<TRequestDetails>; procedure ArchRequest(ReqDetails: TRequestDetails); property ReqString[Index: int]: string read GetReqString; procedure CheckReqString(Index: int; const origin: string); procedure CheckReqHexString(Index: int; const origin: string); procedure ClearObjectStates; procedure SetUp(); override; procedure TearDown(); override; function GetDevType(): int; virtual; abstract; procedure DoCheckRequests(); virtual; abstract; function GetID_Device: int; virtual; published procedure CheckRequests(); virtual; end; implementation { TDeviceReqCreatorTestBase } uses Devices.Tecon, Test.Devices.Tecon19.ReqCreator, Test.Devices.Mercury.ReqCreator, Test.Devices.Logica.SPT941.ReqCreator, Test.Devices.Logica.SPT943.ReqCreator; procedure TDeviceReqCreatorTestBase.ArchRequest(ReqDetails: TRequestDetails); begin ReqList.Add(ReqDetails); end; procedure TDeviceReqCreatorTestBase.CheckReqString(Index: int; const origin: string); begin Check(ReqString[Index] = origin, '[' + IntToStr(Index) + '] good = ' + origin + ' bad = ' + ReqString[Index]); end; procedure TDeviceReqCreatorTestBase.CheckRequests; begin ClearObjectStates(); ReqCreator.AddDeviceToSendBuf(); DoCheckRequests(); end; procedure TDeviceReqCreatorTestBase.CheckReqHexString(Index: int; const origin: string); var bufOrigin: ArrayOfbyte; res: TRequestDetails; i: int; begin bufOrigin := TextNumbersStringToArray(origin); res := ReqList[Index]; Check(Length(bufOrigin) = res.BufCnt, IntToStr(Index) + ' Wrong length: actual ' + IntToStr(res.BufCnt) + ' expected ' + IntToStr(Length(bufOrigin))); for i := 0 to res.BufCnt - 1 do Check(res.buf[i] = bufOrigin[i], '[' + IntToStr(Index) + '] expected: ' + ArrayToString(bufOrigin, Length(bufOrigin), false, true) + #13#10'actual: ' + ArrayToString(res.buf, Length(bufOrigin), false, true) + ', Wrong byte ' + IntToStr(i)); end; function TDeviceReqCreatorTestBase.GetReqString(Index: int): string; begin Result := StringArrayToString(ReqList[Index].BufToArray(), ReqList[Index].BufCnt); end; procedure TDeviceReqCreatorTestBase.ClearObjectStates(); begin ExecSQL('delete from ObjectStates'); end; function TDeviceReqCreatorTestBase.GetID_Device(): int; begin Result := 1000 + GetDevType(); end; procedure TDeviceReqCreatorTestBase.SetUp; begin inherited; ReqCreator := T485RequestCreatorForTest.Create(ArchRequest); ReqCreator.ReqDetails.DevNumber := GetDevType(); ReqCreator.ReqDetails.ID_DevType := GetDevType(); ReqCreator.ReqDetails.ID_Device := GetID_Device(); ReqCreator.ReqDetails.ID_Obj := 3; // ID_Obj = 3 - объект для всех мыслимых типов приборов ReqList := TList<TRequestDetails>.Create(); end; procedure TDeviceReqCreatorTestBase.TearDown; begin ReqCreator.Free(); ReqList.Free(); inherited; end; { T485RequestCreatorForTest } function T485RequestCreatorForTest.GetDevReqCreatorClass(ID_DevType: int): TDevReqCreatorClass; begin if ID_DevType in Tecon19_Family then Result := TTecon19ReqCreatorForTest else case ID_DevType of DEVTYPE_MERCURY_230: Result := TMercury230ReqCreatorForTest; DEVTYPE_SPT_941: Result := TSPT941ReqCreatorFortest; DEVTYPE_SPT_943: Result := TSPT943ReqCreatorFortest; else Result := inherited GetDevReqCreatorClass(ID_DevType); end; end; end.
unit SMCnst; interface {Polish strings} const strMessage = 'Wydruk...'; strSaveChanges = 'Proszę potwierdzić zapis zmian na serwerze.'; strErrSaveChanges = 'Brak możliwości zapisu danych! Sprawdź połączenie z serwerem lub poprawność danych.'; strDeleteWarning = 'Proszę potwierdzić usunięcie tabeli %s.'; strEmptyWarning = 'Proszę potwierdzić usunięcie rekordów z tabeli %s.'; const PopUpCaption: array [0..24] of string[40] = ('Dodawanie rekordu', 'Wstawianie rekordu', 'Edycja rekordu', 'Kasowanie rekordu', '-', 'Wydruk ...', 'Eksport ...', 'Filtr ...', 'Wyszukiwanie ...', '-', 'Zapis zmian', 'Odrzucenie zmian', 'Odświeżenie', '-', 'Wybór/Odrzucenie wyboru rekordów', 'Wybór rekordu', 'Wybór wszystkich rekordów', '-', 'Odrzucenie wyboru rekordu', 'Odrzucenie wyboru wszystkich rekordów', '-', 'Zapis układu kolumn', 'Przywrócenie układu kolumn', '-', 'Ustawienia...'); const //for TSMSetDBGridDialog SgbTitle = ' Tytuł '; SgbData = ' Data '; STitleCaption = 'Napis:'; STitleAlignment = 'Wyrównanie:'; STitleColor = 'Tło:'; STitleFont = 'Czcionka:'; SWidth = 'Szerokość:'; SWidthFix = 'znaki'; SAlignLeft = 'Do lewej'; SAlignRight = 'Do prawej'; SAlignCenter = 'Wyśrodkowanie'; const //for TSMDBFilterDialog strEqual = 'równy'; strNonEqual = 'różny'; strNonMore = 'nie większy niż'; strNonLess = 'nie mniejszy niż'; strLessThan = 'mniejszy niż'; strLargeThan = 'większy niż'; strExist = 'pusty'; strNonExist = 'nie pusty'; strIn = 'na liście'; strBetween = 'pomiędzy'; strLike = 'zawiera'; strOR = 'OR'; strAND = 'AND'; strField = 'Pole'; strCondition = 'Warunek'; strValue = 'Wartość'; strAddCondition = ' Zdefiniuj warunek dodatkowy:'; strSelection = ' Wybierz rekordy za pomocą dodatkowych warunków:'; strAddToList = 'Dodaj do listy'; strEditInList = 'Edytuj w liście'; strDeleteFromList = 'Usuń z listy'; strTemplate = 'Okno do określenia szablonu filtra'; strFLoadFrom = 'Wprowadź z ...'; strFSaveAs = 'Zapisz jako...'; strFDescription = 'Opis'; strFFileName = 'Nazwa zbioru'; strFCreate = 'Utworzono: %s'; strFModify = 'Zmodyfikowano: %s'; strFProtect = 'Zabezpieczenie przed zapisem'; strFProtectErr = 'Zbiór jest zabezpieczony!'; const //for SMDBNavigator SFirstRecord = 'Pierwszy rekord'; SPriorRecord = 'Poprzedni rekord'; SNextRecord = 'Następny rekord'; SLastRecord = 'Ostatni rekord'; SInsertRecord = 'Wstawianie rekordu'; SCopyRecord = 'Kopiowanie rekordu'; SDeleteRecord = 'Kasowanie rekordu'; SEditRecord = 'Edycja rekordu'; SFilterRecord = 'Warunki filtra'; SFindRecord = 'Wyszukanie rekordu'; SPrintRecord = 'Wydruk rekordów'; SExportRecord = 'Eksport rekordów'; SImportRecord = 'Import rekordów'; SPostEdit = 'Zapis zmian'; SCancelEdit = 'Unieważnienie zmian'; SRefreshRecord = 'Odświeżenie danych'; SChoice = 'Wybierz rekord'; SClear = 'Unieważnij wybór rekordu'; SDeleteRecordQuestion = 'Proszę potwierdzić usunięcie rekordu.'; SDeleteMultipleRecordsQuestion = 'Proszę potwierdzić usunięcie wybranych rekordów.'; SRecordNotFound = 'Nie znaleziono rekordu.'; SFirstName = 'Pierwszy'; SPriorName = 'Poprzedni'; SNextName = 'Następny'; SLastName = 'Ostatni'; SInsertName = 'Wstawienie'; SCopyName = 'Kopiowanie'; SDeleteName = 'Kasowanie'; SEditName = 'Edycja'; SFilterName = 'Filtr'; SFindName = 'Wyszukanie'; SPrintName = 'Wydruk'; SExportName = 'Eksport'; SImportName = 'Import'; SPostName = 'Zapis'; SCancelName = 'Anulowanie'; SRefreshName = 'Odświeżenie'; SChoiceName = 'Wybór'; SClearName = 'Wyzerowanie'; SBtnOk = '&OK'; SBtnCancel = '&Anuluj'; SBtnLoad = 'Otwarcie'; SBtnSave = 'Zapis'; SBtnCopy = 'Kopiowanie'; SBtnPaste = 'Wklejenie'; SBtnClear = 'Wyzerowanie'; SRecNo = 'rek.'; SRecOf = ' z '; const //for EditTyped etValidNumber = 'poprawna liczba'; etValidInteger = 'poprawna liczba całkowita'; etValidDateTime = 'poprawna data/czas'; etValidDate = 'poprawna data'; etValidTime = 'poprawny czas'; etValid = 'poprawny'; etIsNot = 'nie jest'; etOutOfRange = 'Wartość %s jest poza zakresem %s..%s'; //by RTS SPrevYear = 'poprzedni rok'; SPrevMonth = 'poprzedni miesiąc'; SNextMonth = 'następny miesiąc'; SNextYear = 'następny rok'; const //for DMDBAccessNavigator dbanOf = 'z'; SApplyAll = 'Zastosuj do całości'; SNoDataToDisplay = '<Brak danych do wyświetlenia>'; implementation end.
unit f16_exitprogram; interface uses buku_handler, user_handler, peminjaman_Handler, pengembalian_Handler, kehilangan_handler, f14_save; { DEKLARASI FUNGSI DAN PROSEDUR } procedure exitprogram(var data_buku : tabel_buku; data_user : tabel_user; data_peminjaman : tabel_peminjaman; data_pengembalian : tabel_pengembalian; data_kehilangan : tabel_kehilangan); { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation procedure exitprogram(var data_buku : tabel_buku; data_user : tabel_user; data_peminjaman : tabel_peminjaman; data_pengembalian : tabel_pengembalian; data_kehilangan : tabel_kehilangan); { DESKRIPSI : Prosedur untuk keluar dari program utama } { PARAMETER : semua tabel data } { KAMUS LOKAL } var c : Char; { ALGORITMA } begin writeln('Apakah anda mau melakukan penyimpanan file yang sudah dilakukan (Y/N) ?'); readln(c); while((c <> 'Y') and (c <> 'N')) do begin writeln('Masukan tidak valid! (Y/N)'); readln(c); end; if (c = 'Y') then save(data_buku, data_user, data_peminjaman, data_pengembalian, data_kehilangan) else writeln('Terima kasih telah berkunjung ke Wan Shi Tong''s Library!'); end; end.
unit snippet_file; {$Mode objfpc} {$PACKRECORDS 1} interface uses classes; type tswagheader = record sign:array[1..7] of char; title:string[80]; desc :string[255]; date :tdatetime; author:string[30]; link:string[255]; email:string[255]; tags:string[255]; lang:string[20]; master:boolean; locked:boolean; totalrec:integer; lastupdate:tdatetime; crc:string[10]; reserved:array[1..50] of byte; end; tswagrec = record id:integer; title:string[80]; desc :string[255]; date :tdatetime; author:string[30]; link:string[255]; email:string[255]; tags:string[255]; filename:string[255]; textpos:longint; textsize:longint; crc:string[10]; deleted:boolean; compress:boolean; end; tswagfile = class f : tfilestream; header:tswagheader; rec:tswagrec; constructor create(fn:string; mode:word); destructor destroy; Override; function open:boolean; function first:boolean; function next:boolean; function last:boolean; function gotorec(i:integer):boolean; function appendrec(r:tswagrec; fl:string):boolean; function updaterec(r:tswagrec; i:integer):boolean; function copyrecfrom(var w:tswagfile; var arec:tswagrec):boolean; function delete(i:integer):boolean; function delete(crc:string):boolean; overload; function extracttext(r:tswagrec; fn:string):boolean; function iscrc(crc:string):boolean; function importfrom(s:string):boolean; procedure initnext; procedure writeheader; end; procedure createswagfile(fn:string; var header:tswagheader); function isswagfile(fn:string):boolean; implementation uses dos,sysutils,snippet_compress,crt; Function FileExist (Str: String) : Boolean; Var DF : File; Attr : Word; Begin Assign (DF, Str); GetFattr (DF, Attr); Result := (DosError = 0) and (Attr And Directory = 0); End; constructor tswagfile.create(fn:string; mode:word); begin Inherited Create; f:=tfilestream.create(fn,mode); f.read(header,sizeof(header)); end; destructor tswagfile.destroy; begin Inherited Destroy; f.free; end; function tswagfile.open:boolean; begin if header.sign='SWGEX01' then result:=true else result:=false; end; function tswagfile.first:boolean; begin result:=true; try f.seek(sizeof(header),soFromBeginning); f.read(rec,sizeof(rec)); except result:=false; end; end; function tswagfile.next:boolean; begin result:=true; try repeat f.seek(rec.textpos+rec.textsize,soFromBeginning); f.read(rec,sizeof(rec)); until rec.deleted=false; except result:=false; end; end; function tswagfile.last:boolean; begin result:=true; try first; While F.Position < f.size Do Begin next; end; except result:=false; end; end; {function tswagfile.gotorec(i:integer):boolean; var r:tswagrec; d:integer; begin result:=false; if i>header.totalrec then exit; f.seek(sizeof(header),0); try for d:=1 to i do begin f.read(r,sizeof(r)); f.seek(r.textpos+r.textsize,0); end; except exit; end; rec:=r; result:=true; end;} function tswagfile.gotorec(i:integer):boolean; var r:tswagrec; d:integer; begin result:=false; if i>header.totalrec then exit; f.seek(sizeof(header),0); d:=0; try while f.position < f.size do begin f.read(r,sizeof(r)); if r.deleted=false then d:=d+1; f.seek(r.textpos+r.textsize,0); if d=i then break; end; except exit; end; rec:=r; result:=true; end; function tswagfile.delete(i:integer):boolean; begin result:=false; if i>header.totalrec then exit; if gotorec(i)=false then exit; rec.deleted:=true; f.seek(rec.textpos-sizeof(rec),0); f.write(rec,sizeof(rec)); dec(header.totalrec); writeheader; result:=true; end; function tswagfile.delete(crc:string):boolean; overload; begin result:=iscrc(crc); if result then begin rec.deleted:=true; f.seek(rec.textpos-sizeof(rec),0); f.write(rec,sizeof(rec)); dec(header.totalrec); writeheader; end; end; function tswagfile.appendrec(r:tswagrec; fl:string):boolean; var rf : tfilestream; buf : byte; rd : tswagrec; zf : string; begin result:=false; try rd:=r; zf:=fl+'.zz'; result:=rawzipstream(fl,zf); rf:=tfilestream.create(zf,fmopenread+fmShareDenyNone); rf.seek(0,0); rd.textsize:=rf.size; rd.filename:=extractfilename(fl); f.seek(f.size,0); rd.textpos:=f.position+sizeof(rd); f.write(rd,sizeof(rd)); while rf.position<rf.size do begin rf.read(buf,1); f.write(buf,1); end; rf.free; header.totalrec:=header.totalrec+1; writeheader; except result:=false; exit; end; deletefile(zf); end; procedure createswagfile(fn:string; var header:tswagheader); var f:tfilestream; begin f:=tfilestream.create(fn, fmcreate); header.sign:='SWGEX01'; f.write(header,sizeof(header)); f.free; end; procedure tswagfile.writeheader; begin f.seek(0,0); f.write(header,sizeof(header)); end; procedure tswagfile.initnext; begin f.seek(sizeof(header),0); end; function tswagfile.updaterec(r:tswagrec; i:integer):boolean; begin result:=false; if not gotorec(i) then exit; f.seek(rec.textpos-sizeof(rec),0); f.write(r,sizeof(r)); result:=true; end; function tswagfile.extracttext(r:tswagrec; fn:string):boolean; var ft:tfilestream; buf:byte; d:integer; begin result:=true; try ft:=tfilestream.create(fn+'.z', fmCreate); f.seek(rec.textpos,0); for d:=1 to rec.textsize do begin f.read(buf,1); ft.write(buf,1); end; ft.free; result:=rawunzipStream(fn+'.z',fn); deletefile(fn+'.z'); except result:=false; end; end; function tswagfile.iscrc(crc:string):boolean; begin result:=false; f.seek(sizeof(header),0); while f.position < f.size do begin f.read(rec,sizeof(rec)); if rec.deleted=false then if rec.crc=crc then begin result:=true; break; end; f.seek(rec.textpos+rec.textsize,0); end; end; function tswagfile.copyrecfrom(var w:tswagfile; var arec:tswagrec):boolean; begin try result:=false; f.seek(f.size,0); f.write(arec,sizeof(arec)); w.f.seek(arec.textpos,0); f.copyfrom(w.f,arec.textsize); except result:=false; end; result:=true; end; function tswagfile.importfrom(s:string):boolean; var w:tfilestream; buf:byte; wh:tswagheader; wr:tswagrec; i:longint; begin result:=false; if not fileexist(s) then exit; if not isswagfile(s) then exit; w:=tfilestream.create(s,fmopenread+fmShareDenyNone); w.read(wh,sizeof(wh)); f.seek(f.size,0); while w.position < w.size do begin w.read(wr,sizeof(wr)); if wr.deleted=false then begin wr.textpos:=f.position+sizeof(wr); f.write(wr,sizeof(wr)); for i:=1 to wr.textsize do begin w.read(buf,1); f.write(buf,1); end; inc(header.totalrec); end else w.seek(wr.textpos+wr.textsize,0); end; f.seek(0,0); f.write(header,sizeof(header)); w.free; result:=true; end; function isswagfile(fn:string):boolean; var g:tswagfile; begin result:=false; if not fileexist(fn) then exit; g:=tswagfile.create(fn,fmopenread+fmShareDenyNone); result:=g.open; g.destroy; end; end.
unit AEstagioCelulaTrabalho; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, Buttons, Grids, CGrades, Componentes1, ExtCtrls, UnDadosProduto, UnProdutos, PainelGradiente, Localizacao, UnOrdemProducao; type TFEstagioCelulaTrabalho = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; Grade: TRBStringGridColor; BGravar: TBitBtn; BCancelar: TBitBtn; EEstagio: TEditLocaliza; Localiza: TConsultaPadrao; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BCancelarClick(Sender: TObject); procedure BGravarClick(Sender: TObject); procedure GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); procedure GradeKeyPress(Sender: TObject; var Key: Char); procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure GradeNovaLinha(Sender: TObject); procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure EEstagioCadastrar(Sender: TObject); procedure EEstagioRetorno(Retorno1, Retorno2: String); procedure GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } VprAcao : Boolean; VprDCelula : TRBDCelulaTrabalho; VprDEstagio : TRBDEstagioCelula; FunOrdemProducao : TRBFuncoesOrdemProducao; procedure CarTitulosGrade; procedure CarDEstagio; function ExisteEstagio : Boolean; public { Public declarations } function EstagiosCelula(VpaDCelula : TRBDCelulaTrabalho):Boolean; end; var FEstagioCelulaTrabalho: TFEstagioCelulaTrabalho; implementation uses APrincipal,ConstMsg, AEstagioProducao; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFEstagioCelulaTrabalho.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } FunOrdemProducao := TRBFuncoesOrdemProducao.Cria(FPrincipal.BaseDados); CarTitulosGrade; VprAcao :=false; end; { ******************* Quando o formulario e fechado ************************** } procedure TFEstagioCelulaTrabalho.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FunOrdemProducao.free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFEstagioCelulaTrabalho.CarTitulosGrade; begin Grade.Cells[1,0] := 'Código'; Grade.Cells[2,0] := 'Estágio'; Grade.Cells[3,0] := 'Principal'; Grade.Cells[4,0] := 'Capacidade Produtiva'; end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.CarDEstagio; begin VprDEstagio.CodEstagio := StrToInt(Grade.Cells[1,Grade.ALinha]); VprDEstagio.NomEstagio := Grade.Cells[2,Grade.ALinha]; VprDEstagio.IndPrincipal := UpperCase(Grade.Cells[3,Grade.ALinha]) = 'S'; VprDEstagio.ValCapacidadeProdutiva := StrToInt(Grade.Cells[4,Grade.ALinha]); end; {******************************************************************************} function TFEstagioCelulaTrabalho.ExisteEstagio : Boolean; begin result := false; if Grade.Cells[1,Grade.ALinha] <> '' then begin result := FunProdutos.ExisteEstagio(Grade.Cells[1,Grade.Alinha],VprDEstagio.NomEstagio); if result then Grade.Cells[2,Grade.ALinha] := VprDestagio.NomEstagio else Grade.cells[2,Grade.ALinha] := ''; end; end; {******************************************************************************} function TFEstagioCelulaTrabalho.EstagiosCelula(VpaDCelula : TRBDCelulaTrabalho):Boolean; begin VprDCelula := VpaDCelula; Grade.ADados := VprDCelula.Estagios; Grade.CarregaGrade; Showmodal; result := vprAcao; end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.BCancelarClick(Sender: TObject); begin VprAcao := false; close; end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.BGravarClick(Sender: TObject); Var VpfResultado : String; begin VpfResultado := FunOrdemProducao.GravaDEstagioCelulaTrabalho(VprDCelula); if VpfResultado = '' then begin VprAcao := true; close; end else Aviso(VpfResultado); end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDEstagio := TRBDEstagioCelula(VprDCelula.Estagios.Items[Vpalinha-1]); if VprDEstagio.CodEstagio <> 0 then Grade.Cells[1,VpaLinha] := InttoStr(VprDEstagio.CodEstagio) else Grade.Cells[1,VpaLinha] := ''; Grade.cells[2,VpaLinha] := VprDEstagio.NomEstagio; if VprDEstagio.IndPrincipal then Grade.Cells[3,VpaLinha] := 'S' else Grade.Cells[3,VpaLinha] := 'N'; if VprDEstagio.ValCapacidadeProdutiva <> 0 then Grade.Cells[4,VpaLinha] := InttoStr(VprDEstagio.ValCapacidadeProdutiva) else Grade.Cells[4,VpaLinha] := ''; end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos := false; if (Grade.Cells[1,Grade.ALinha] = '') then begin aviso('ESTÁGIO NÃO PREENCHIDO!!!'#13'É necessário preencher o código do estagio.'); Grade.Col := 1; end else if not ExisteEstagio then begin aviso('ESTÁGIO INVÁLIDO!!!'#13'O estágio preenchido não existe cadastrado.'); Grade.Col := 1; end else if (Grade.Cells[3,Grade.ALinha] = '') then begin aviso('INDICADOR DE PRIORIDADE NÃO PREENCHIDO!!!'#13'É necessário preencher o indicador se a celula é principal.'); Grade.Col := 3; end else if (Grade.Cells[4,Grade.ALinha] = '') then begin aviso('CAPACIDADE PRODUTIVA NÃO PREENCHIDO!!!'#13'É necessário preencher a capacidade produtiva da celula.'); Grade.Col := 4; end else VpaValidos := true; if VpaValidos then begin CarDEstagio; if VprDEstagio.ValCapacidadeProdutiva <=0 then begin aviso('CAPACIDADE PRODUTIVA INVÁLIDA!!!'#13'Valor preenchido da capacidade produtiva inváido.'); Grade.Col := 4; VpaValidos := false; end else if FunOrdemProducao.ExisteEstagioCelulaDuplicado(VprDCelula) then begin Aviso('ESTÁGIO DUPLICADO!!!'#13'O estágio digitado já foi cadastrado para essa celula de trabalho.'); Grade.Col := 1; VpaValidos := false; end; end; end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); begin case ACol of 1,4 : Value := '0000;0; '; end; end; procedure TFEstagioCelulaTrabalho.GradeKeyPress(Sender: TObject; var Key: Char); begin if Grade.Col = 2 then Key := #0; end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprDCelula.Estagios.Count >0 then VprDEstagio := TRBDEstagioCelula(VprDCelula.Estagios.Items[VpaLinhaAtual-1]); end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.GradeNovaLinha(Sender: TObject); begin VprDEstagio := VprDCelula.addEstagio; VprDEstagio.ValCapacidadeProdutiva := 100; end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if Grade.AEstadoGrade in [egInsercao,EgEdicao] then if Grade.AColuna <> ACol then begin case Grade.AColuna of 1 : if Grade.Cells[1,Grade.Alinha] <> '' then begin if not existeEstagio then begin if not EEstagio.AAbreLocalizacao then begin Aviso('ESTÁGIO INVÁLIDO!!!'#13'O estágio digitado não existe cadastrado.'); Grade.Col := 1; abort; end; end; end else EEstagio.AAbreLocalizacao; end; end; end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.EEstagioCadastrar(Sender: TObject); begin FEstagioProducao := TFEstagioProducao.CriarSDI(application,'', FPrincipal.VerificaPermisao('FEstagioProducao')); FEstagioProducao.BotaoCadastrar1.Click; FEstagioProducao.Showmodal; FEstagioProducao.free; Localiza.AtualizaConsulta; end; {******************************************************************************} procedure TFEstagioCelulaTrabalho.EEstagioRetorno(Retorno1, Retorno2: String); begin if Retorno1 <> '' then begin Grade.Cells[1,Grade.ALinha] := EEstagio.Text; Grade.Cells[2,Grade.ALinha] := retorno1; end; end; procedure TFEstagioCelulaTrabalho.GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of 114 : begin // F3 case Grade.Col of 1 : EEstagio.AAbreLocalizacao; end; end; end; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFEstagioCelulaTrabalho]); end.
{ *************************************************************************** } { } { Delphi and Kylix Cross-Platform Visual Component Library } { Internet Application Runtime } { } { Copyright (C) 1995, 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. } { } { *************************************************************************** } unit BrkrConst; interface resourcestring sOnlyOneDataModuleAllowed = 'Only one data module per application'; sNoDataModulesRegistered = 'No data modules registered'; sNoDispatcherComponent = 'No dispatcher component found on data module'; sNoWebModulesActivated = 'No automatically activated data modules'; sTooManyActiveConnections = 'Maximum number of concurrent connections exceeded. ' + 'Please try again later'; sInternalServerError = '<html><title>Internal Server Error 500</title>'#13#10 + '<h1>Internal Server Error 500</h1><hr>'#13#10 + 'Exception: %s<br>'#13#10 + 'Message: %s<br></html>'#13#10; sDocumentMoved = '<html><title>Document Moved 302</title>'#13#10 + '<body><h1>Object Moved</h1><hr>'#13#10 + 'This Object may be found <a HREF="%s">here.</a><br>'#13#10 + '<br></body></html>'#13#10; implementation end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, View.WebCharts, Vcl.StdCtrls, Vcl.OleCtrls, SHDocVw, Vcl.ExtCtrls, Data.DB, Datasnap.DBClient, RESTRequest4D.Request, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Grids, Vcl.DBGrids, System.Json, Finance.Interfaces; type TForm4 = class(TForm) Panel1: TPanel; Panel2: TPanel; WebBrowser1: TWebBrowser; Button1: TButton; WebCharts1: TWebCharts; ClientDataSet1: TClientDataSet; ClientDataSet1Label: TStringField; ClientDataSet1Value: TStringField; ClientDataSet1RGB: TStringField; ClientDataSet2: TClientDataSet; StringField1: TStringField; StringField2: TStringField; StringField3: TStringField; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } function GerarCardStock(value : iFinanceStock) : string; function CSSPersonalizado: String; function GerarWebChartAlert(value : string) : string; public { Public declarations } end; var Form4: TForm4; implementation uses Winapi.ActiveX, Charts.Types, Finance, System.SysUtils, DataSet.Serialize; {$R *.dfm} procedure TForm4.Button1Click(Sender: TObject); var Finance : IFinance; begin Finance := TFinance.New.Key('7cd596af').Get; ClientDataSet1.EmptyDataSet; ClientDataSet1.AppendRecord([Finance.Currencies.GetUSD.Code, Finance.Currencies.GetUSD.Buy, '']); ClientDataSet1.AppendRecord([Finance.Currencies.GetEUR.Code, Finance.Currencies.GetEUR.Buy, '']); ClientDataSet1.AppendRecord([Finance.Currencies.GetGBP.Code, Finance.Currencies.GetGBP.Buy, '']); ClientDataSet1.AppendRecord([Finance.Currencies.GetAUD.Code, Finance.Currencies.GetAUD.Buy, '']); ClientDataSet1.AppendRecord([Finance.Currencies.GetARS.Code, Finance.Currencies.GetARS.Buy, '']); ClientDataSet1.AppendRecord([Finance.Currencies.GetCAD.Code, Finance.Currencies.GetCAD.Buy, '']); ClientDataSet1.AppendRecord([Finance.Currencies.GetJPY.Code, Finance.Currencies.GetJPY.Buy, '']); ClientDataSet1.AppendRecord([Finance.Currencies.GetCNY.Code, Finance.Currencies.GetCNY.Buy, '']); ClientDataSet2.EmptyDataSet; ClientDataSet2.AppendRecord([Finance.Currencies.GetUSD.Code, Finance.Currencies.GetUSD.Variation, '']); ClientDataSet2.AppendRecord([Finance.Currencies.GetEUR.Code, Finance.Currencies.GetEUR.Variation, '']); ClientDataSet2.AppendRecord([Finance.Currencies.GetGBP.Code, Finance.Currencies.GetGBP.Variation, '']); ClientDataSet2.AppendRecord([Finance.Currencies.GetAUD.Code, Finance.Currencies.GetAUD.Variation, '']); ClientDataSet2.AppendRecord([Finance.Currencies.GetAUD.Code, Finance.Currencies.GetAUD.Variation, '']); ClientDataSet2.AppendRecord([Finance.Currencies.GetARS.Code, Finance.Currencies.GetARS.Variation, '']); ClientDataSet2.AppendRecord([Finance.Currencies.GetCAD.Code, Finance.Currencies.GetCAD.Variation, '']); ClientDataSet2.AppendRecord([Finance.Currencies.GetJPY.Code, Finance.Currencies.GetJPY.Variation, '']); ClientDataSet2.AppendRecord([Finance.Currencies.GetCNY.Code, Finance.Currencies.GetCNY.Variation, '']); WebCharts1 .BackgroundColor('#23272b') .FontColor('#8f9894') .AddResource(Self.CSSPersonalizado) .Container(Fluid) .NewProject .Rows .HTML('<div class="title"><h3>BOLSA DE VALORES</h3></div>') .&End .Rows ._Div .ColSpan(3) .Add(GerarCardStock(Finance.Stocks.GetIBOVESPA)) .&End ._Div .ColSpan(3) .Add(GerarCardStock(Finance.Stocks.GetNASDAQ)) .&End ._Div .ColSpan(3) .Add(GerarCardStock(Finance.Stocks.GetCAC)) .&End ._Div .ColSpan(3) .Add(GerarCardStock(Finance.Stocks.GetNIKKEI)) .&End .&End .Rows .HTML('<div class="title"><h3>CÂMBIO</h3></div>') .&End .Rows ._Div .ColSpan(6) .Add( WebCharts1 .ContinuosProject .Charts ._ChartType(horizontalBar) .Attributes .Name('MoedasValores') .ColSpan(12) .DataSet .textLabel('Meu DataSet 1') .DataSet(ClientDataSet1) .BackgroundColor('101,198,134') .&End .Labelling .Format('$0,0.0000') .PaddingX(30) .Padding(-7) .&End .Options .Title .text('Cotação') .fontSize(15) .&End .Tooltip .Format('$0,0.0000') .&End .Legend .display(false) .&End .&End .&End .&End .&End .HTML ) .&End ._Div .ColSpan(6) .Add( WebCharts1 .ContinuosProject .Charts ._ChartType(Line) .Attributes .Name('MoedasVariacao') .ColSpan(12) .DataSet .textLabel('Meu DataSet 1') .DataSet(Clientdataset2) .BackgroundColor('250,92,124') .BorderColor('250,92,124') .LineTension(0) .&End .Labelling .Format('0,0.0000') .&End .Options .Title .text('Variação Diária') .fontSize(15) .&End .Tooltip .Format('0,0.0000') .&End .Legend .display(false) .&End .&End .&End .&End .&End .HTML ) .&End .&End .Rows .HTML('<div class="title"><h3>ÍNDICES ECONÔMICOS</h3></div>') .&End .Rows ._Div .ColSpan(3) .Add( GerarWebChartAlert('SELIC ' + Finance.Taxes.GetSelic + ' %') ) .&End ._Div .ColSpan(3) .Add( GerarWebChartAlert('CDI ' + Finance.Taxes.GetCdi + ' %') ) .&End ._Div .ColSpan(3) .Add( GerarWebChartAlert('SELIC Diária' + Finance.Taxes.GetSelicDaily + ' %') ) .&End ._Div .ColSpan(3) .Add( GerarWebChartAlert('CDI Diária ' + Finance.Taxes.GetCdiDaily + ' %') ) .&End .&End .WebBrowser(WebBrowser1) .Generated; end; function TForm4.gerarCardStock(value: iFinanceStock): string; var Variation : string; begin if (value.Variation.IndexOf('-')) > -1 then Variation := '<i class="red"><i class="fa fa-angle-down"></i></i>' else Variation := '<i class="green"><i class="fa fa-angle-up"></i></i>'; Result := '<div class="box primary"> ' + '<span class="count_top">' + value.Code + '</span>' + '<div class="count" > ' + Variation + ' ' + value.Variation + '%' + '</div>' + '</div>'; end; function TForm4.gerarWebChartAlert(value: string): string; begin Result := WebCharts1 .ContinuosProject .Alerts .Title(value) .AlertsClass .success .&End .&End .HTML; end; function TForm4.CSSPersonalizado: String; begin Result := Result + '<style>'; Result := Result + '.title {padding-left: 0.75rem; padding-top: 0.75rem;}'; Result := Result + '.box {'; Result := Result + 'background-color: #FFFFFF;'; Result := Result + 'border-radius: 2px;'; Result := Result + 'width: 100%;'; Result := Result + 'margin: auto;'; Result := Result + 'padding: 0.75rem;'; Result := Result + 'text-align: center;'; Result := Result + '}'; Result := Result + '.red {color : #fa5c7c;}'; Result := Result + '.green {color : #0acf97;}'; Result := Result + '.primary {'; Result := Result + 'background-color: #5273E9;'; Result := Result + 'color: #FFFFFF;'; Result := Result + '}'; Result := Result + '.count {'; Result := Result + 'font-size: 20px;'; Result := Result + '}'; Result := Result + '</style>'; end; procedure TForm4.FormCreate(Sender: TObject); begin ReportMemoryLeaksOnShutdown := true; end; end.
unit udatamhs; interface const NMadata : integer = 100; type dataMhs = record NIM:string;{ Kode kategori produk } KdKul:string;{ Kode produk } Nilai:integer; { Hasil Penjualan } end; tabNilaiMhs = record TMhs : array [1..101] of dataMhs; Neff : integer; { 0..100, nilai efektif, 0 jika tabel kosong } end; function EOP (rek : dataMhs) : boolean; { Menghasilkan true jika rek = mark } procedure LoadDataNilai (filename : string; var T : tabNilaiMhs); { I.S. : filename terdefinisi, T sembarang } { F.S. : Tabel T terisi nilai mahasiswa dengan data yang dibaca dari file dg nama = filename T.Neff = 0 jika tidak ada file kosong; T diisi dengan seluruh isi file atau sampai T penuh. } procedure UrutNIMAsc (var T : tabNilaiMhs); { I.S. : T terdefinisi; T mungkin kosong } { F.S. : Isi tabel T terurut membesar menurut NIM. T tetap jika T kosong. } { Proses : Gunakan salah satu algoritma sorting yang diajarkan di kelas. Tuliskan nama algoritmanya dalam bentuk komentar. } procedure HitungRataRata (T : tabNilaiMhs); { I.S. : T terdefinisi; T mungkin kosong } { F.S. : Menampilkan nilai rata-rata setiap mahasiswa yang ada dalam tabel dengan format: <NIM>=<rata-rata> Nilai rata-rata dibulatkan ke integer terdekat. Gunakan fungsi round. Jika tabel kosong, tuliskan "Data kosong" } { Proses : Menggunakan ide algoritma konsolidasi tanpa separator pada file eksternal, hanya saja diberlakukan pada tabel. } procedure SaveDataNilai (filename : string; T : tabNilaiMhs); { I.S. : T dan filename terdefinisi; T mungkin kosong } { F.S. : Isi tabel T dituliskan pada file dg nama = filename } implementation function EOP (rek : dataMhs) : boolean; begin if (rek.NIM='99999999') and (rek.KdKul='datadata9999') and (rek.Nilai=-999) then EOP:=true else EOP:=false; end; procedure LoadDataNilai (filename : string; var T : tabNilaiMhs); var stream:file of dataMhs; data:dataMhs; begin assign(stream,filename); reset(stream); read(stream,data); T.Neff:=0; while (not(EOP(data)) and (T.Neff < NMadata)) do begin T.Neff:=T.Neff+1; T.TMhs[T.Neff]:=data; read(stream,data); end; close(stream); end; procedure UrutNIMAsc (var T : tabNilaiMhs); //bubble var i,j:integer; temp:dataMhs; begin if (T.Neff>=2) then begin for i:=T.Neff downto 2 do begin for j:=1 to i-1 do begin if T.TMhs[j].NIM>T.TMhs[j+1].NIM then begin temp := T.TMhs[j+1]; T.TMhs[j+1] :=T.TMhs[j]; T.TMhs[j] :=temp; end; end; end; end; end; procedure HitungRataRata (T : tabNilaiMhs); var sum,cnt,i:integer; begin if (T.Neff=0) then begin writeln('Data kosong'); end else begin sum:=0; cnt:=0; T.TMhs[T.Neff+1].NIM:='99999999'; T.TMhs[T.Neff+1].KdKul:='datadata9999'; T.TMhs[T.Neff+1].Nilai:=-999; for i:= 1 to T.Neff do begin sum:=sum+T.TMhs[i].Nilai; cnt:=cnt+1; if (T.TMhs[i].NIM<>T.TMhs[i+1].NIM) then begin writeln(T.TMhs[i].NIM,'=',round(sum/cnt)); sum:=0; cnt:=0; end end; end; end; procedure SaveDataNilai (filename : string; T : tabNilaiMhs); var stream:file of dataMhs; i:integer; data:dataMhs; begin assign(stream,filename); rewrite(stream); for i:=1 to T.Neff do begin write(stream,T.TMhs[i]); end; data.NIM:='99999999'; data.KdKul:='datadata9999'; data.Nilai:=-999; write(stream,data); close(stream); end; end.
unit proc_type_obj_2; interface implementation uses System; type TProc = procedure(V: Int32) of object; TC = class private FData: Int32; procedure SetData(Value: Int32); end; procedure TC.SetData(Value: Int32); begin FData := Value; end; procedure Test; var obj: TC; p: TProc; G: Int32; begin obj := TC.Create(); p := obj.SetData; p(12); G := obj.FData; Assert(G = 12); end; initialization Test(); finalization end.
unit FIToolkit.Commons.Consts; interface uses FIToolkit.Localization; const { Common consts } sDualBreak = sLineBreak + sLineBreak; { FixInsight registry consts. Do not localize! } STR_FIXINSIGHT_REGKEY = 'Software\FixInsight'; STR_FIXINSIGHT_REGVALUE = 'Path'; STR_FIXINSIGHT_EXENAME = 'FixInsightCL.exe'; resourcestring {$IF LANGUAGE = LANG_EN_US} {$INCLUDE 'Locales\en-US.inc'} {$ELSEIF LANGUAGE = LANG_RU_RU} {$INCLUDE 'Locales\ru-RU.inc'} {$ELSE} {$MESSAGE FATAL 'No language defined!'} {$ENDIF} implementation end.
FbException = class(Exception) public constructor create(status: IStatus); virtual; destructor Destroy(); override; function getStatus: IStatus; class procedure checkException(status: IStatus); class procedure catchException(status: IStatus; e: Exception); class procedure setVersionError(status: IStatus; interfaceName: AnsiString; currentVersion, expectedVersion: NativeInt); private status: IStatus; end; ISC_DATE = Integer; ISC_TIME = Integer; ISC_QUAD = array [1..2] of Integer; FB_DEC16 = array [1..1] of Int64; FB_DEC34 = array [1..2] of Int64; FB_I128 = array [1..2] of Int64; isc_tr_handle = ^Integer; isc_stmt_handle = ^Integer; ISC_USHORT = word; { 16 bit unsigned } ISC_SHORT = smallint; { 16 bit signed } ISC_TIME_TZ = record utc_time: ISC_TIME; time_zone: ISC_USHORT; end; ISC_TIME_TZ_EX = record utc_time: ISC_TIME; time_zone: ISC_USHORT; ext_offset: ISC_SHORT; end; ISC_TIMESTAMP = record timestamp_date: ISC_DATE; timestamp_time: ISC_TIME; end; ISC_TIMESTAMP_TZ = record utc_timestamp: ISC_TIMESTAMP; time_zone: ISC_USHORT; end; ISC_TIMESTAMP_TZ_EX = record utc_timestamp: ISC_TIMESTAMP; time_zone: ISC_USHORT; ext_offset: ISC_SHORT; end; ntrace_relation_t = Integer; TraceCounts = Record trc_relation_id : ntrace_relation_t; trc_relation_name : PAnsiChar; trc_counters : ^Int64; end; TraceCountsPtr = ^TraceCounts; PerformanceInfo = Record pin_time : Int64; pin_counters : ^Int64; pin_count : NativeUInt; pin_tables : TraceCountsPtr; pin_records_fetched : Int64; end; Dsc = Record dsc_dtype, dsc_scale: Byte; dsc_length, dsc_sub_type, dsc_flags: Int16; dsc_address: ^Byte; end;
unit UPessoa; interface uses DateUtils, SysUtils, UEndereco; type Pessoa = class protected Id : Integer; Nome_RazaoSoCial : string[100]; RG_IE : string[10]; CPF_CNPJ : string[18]; DataNasc_Fund : TDateTime; umEndereco : Endereco; Email : string[100]; Telefone : string[13]; Celular : string[13]; Observacao : string[255]; DataCadastro : TDateTime; DataUltAlteracao : TDateTime; public Constructor CrieObjeto; Destructor Destrua_Se; Procedure setId (vId : Integer); Procedure setNome_RazaoSoCial (vNome_RazaoSoCial : string); Procedure setRG_IE (vRG_IE : string); procedure setCPF_CNPJ (vCPF_CNPJ : string); procedure setumEndereco (vEndereco : Endereco); procedure setEmail (vEmail : string); procedure setDataNasc_Fund (vDataNasc_Fund : TDateTime); procedure setTelefone (vTelefone : string); procedure setCelular (vCelular : string); Procedure setDataCadastro (vDataCadastro : TDateTime); Procedure setDataUltAlteracao (vDataUltAlteracao : TDateTime); Procedure setObservacao (vObservacao : string); Function getId : Integer; Function getNome_RazaoSoCial : string; Function getRG_IE : string; Function getCPF_CNPJ : string; Function getumEndereco : Endereco; Function getEmail : string; Function getDataNasc_Fund : TDateTime; Function getTelefone : string; Function getCelular : string; Function getDataCadastro :TDateTime; Function getDataUltAlteracao : TDateTime; Function getObservacao : string; end; implementation { Pessoa } constructor Pessoa.CrieObjeto; var dataAtual : TDateTime; begin dataAtual := Date; Id := 0; Nome_RazaoSoCial := ''; RG_IE := ''; CPF_CNPJ := ''; DataNasc_Fund := dataAtual; umEndereco := Endereco.CrieObjeto; Email := ''; Telefone := ''; Celular := ''; Observacao := ''; DataCadastro := dataAtual; DataUltAlteracao := dataAtual; end; destructor Pessoa.Destrua_Se; begin end; function Pessoa.getCelular: string; begin Result := Celular; end; function Pessoa.getCPF_CNPJ: String; begin Result := CPF_CNPJ; end; function Pessoa.getDataCadastro: TDateTime; begin Result := DataCadastro; end; function Pessoa.getDataNasc_Fund: TDateTime; begin Result := DataNasc_Fund; end; function Pessoa.getDataUltAlteracao: TDateTime; begin Result := DataUltAlteracao; end; function Pessoa.getEmail: string; begin Result := Email; end; function Pessoa.getId: Integer; begin Result := Id; end; function Pessoa.getNome_RazaoSoCial: string; begin Result := Nome_RazaoSoCial; end; function Pessoa.getRG_IE: string; begin Result := RG_IE; end; function Pessoa.getTelefone: string; begin Result := Telefone; end; function Pessoa.getObservacao: string; begin Result := Observacao; end; function Pessoa.getumEndereco: Endereco; begin Result := umEndereco; end; procedure Pessoa.setCelular(vCelular: string); begin Celular := vCelular; end; procedure Pessoa.setCPF_CNPJ(vCPF_CNPJ: String); begin CPF_CNPJ := vCPF_CNPJ; end; procedure Pessoa.setDataCadastro(vDataCadastro: TDateTime); begin DataCadastro := vDataCadastro; end; procedure Pessoa.setDataNasc_Fund(vDataNasc_Fund: TDateTime); begin DataNasc_Fund := vDataNasc_Fund; end; procedure Pessoa.setDataUltAlteracao(vDataUltAlteracao: TDateTime); begin DataUltAlteracao := vDataUltAlteracao; end; procedure Pessoa.setEmail(vEmail: string); begin Email := vEmail; end; procedure Pessoa.setId(vId: Integer); begin Id := vId; end; procedure Pessoa.setRG_IE(vRG_IE: string); begin RG_IE := vRG_IE; end; procedure Pessoa.setNome_RazaoSoCial(vNome_RazaoSoCial: string); begin Nome_RazaoSoCial := vNome_RazaoSoCial; end; procedure Pessoa.setTelefone(vTelefone: string); begin Telefone := vTelefone; end; procedure Pessoa.setObservacao(vObservacao: string); begin Observacao := vObservacao; end; procedure Pessoa.setumEndereco(vEndereco: Endereco); begin umEndereco := vEndereco; end; end.
unit Nathan.Firebird.Validator.Syntax.Keywords.Intf; interface uses System.Generics.Collections, Nathan.Firebird.Validator.Syntax.Keywords.Types; {$M+} type {$REGION 'IFb25Token'} IFb25Token = interface ['{49F44C5D-CE08-4C77-B33E-6DC1238A9A9F}'] function GetToken(): TFb25TokenKind; function GetValue(): string; property Token: TFb25TokenKind read GetToken; property Value: string read GetValue; end; {$ENDREGION} {$REGION 'IFb25Scanner'} IFb25Scanner = interface ['{5D5B1813-B45D-4B04-99CB-2866DDA21049}'] function GetStatement(): string; procedure SetStatement(const Value: string); function GetTokens(): TList<IFb25Token>; function Execute(): IFb25Scanner; property Statement: string read GetStatement write SetStatement; property Tokens: TList<IFb25Token> read GetTokens; end; {$ENDREGION} {$REGION 'IFb25Parser'} TFb25ParserNotifyEvent = reference to procedure(Token: IFb25Token); IFb25Parser = interface; IVisitor = interface ['{1BAA5277-A327-4B58-BED8-4B964E90D949}'] procedure Visit(Instance: IFb25Parser); end; IFb25Parser = interface ['{09CA22CD-0900-4D58-8DC5-D567073C5C07}'] function GetTokens(): TList<IFb25Token>; procedure SetTokens(Value: TList<IFb25Token>); function GetOnNotify(): TFb25ParserNotifyEvent; procedure SetOnNotify(Value: TFb25ParserNotifyEvent); procedure Accept(Visitor: IVisitor); property Tokens: TList<IFb25Token> read GetTokens write SetTokens; property OnNotify: TFb25ParserNotifyEvent read GetOnNotify write SetOnNotify; end; {$ENDREGION} {$M+} implementation end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFilePNG<p> <b>History : </b><font size=-1><ul> <li>23/08/10 - Yar - Replaced OpenGL1x to OpenGLTokens <li>31/05/10 - Yar - Fixes for Linux x64 <li>08/05/10 - Yar - Removed check for residency in AssignFromTexture <li>22/04/10 - Yar - Fixes after GLState revision <li>16/03/10 - Yar - Improved FPC compatibility <li>05/03/10 - Yar - Creation </ul><p> } unit GLFilePNG; interface {$I GLScene.inc} uses System.Classes, System.SysUtils, GLCrossPlatform, OpenGLTokens, GLContext, GLGraphics, GLTextureFormat, GLApplicationFileIO; type TGLPNGImage = class(TGLBaseImage) private public class function Capabilities: TDataFileCapabilities; override; procedure LoadFromFile(const filename: string); override; procedure SaveToFile(const filename: string); override; procedure LoadFromStream(stream: TStream); override; procedure SaveToStream(stream: TStream); override; {: Assigns from any Texture.} procedure AssignFromTexture(textureContext: TGLContext; const textureHandle: TGLuint; textureTarget: TGLTextureTarget; const CurrentFormat: Boolean; const intFormat: TGLInternalFormat); reintroduce; end; implementation uses LIBPNG; resourcestring sLIBPNGerror = 'LIBPNG error'; // ------------------ // ------------------ TGLPNGImage ------------------ // ------------------ // LoadFromFile // procedure TGLPNGImage.LoadFromFile(const filename: string); var fs: TStream; begin if FileStreamExists(fileName) then begin fs := CreateFileStream(fileName, fmOpenRead); try LoadFromStream(fs); finally fs.Free; ResourceName := filename; end; end else raise EInvalidRasterFile.CreateFmt('File %s not found', [filename]); end; // SaveToFile // procedure TGLPNGImage.SaveToFile(const filename: string); var fs: TStream; begin fs := CreateFileStream(fileName, fmOpenWrite or fmCreate); try SaveToStream(fs); finally fs.Free; end; ResourceName := filename; end; // LoadFromStream // procedure TGLPNGImage.LoadFromStream(stream: TStream); var sig: array[0..7] of Byte; png_ptr: png_structp; info_ptr: png_infop; colorType, bitDepth: Integer; rowBytes: Cardinal; rowPointers: array of PGLUbyte; ii: Integer; use16: Boolean; begin stream.Read(sig, 8); if _png_sig_cmp(@sig, 0, 8) <> 0 then raise EInvalidRasterFile.Create('Invalid PNG file'); png_ptr := _png_create_read_struct(ZLIB_VERSION, nil, pngErrorFn, pngWarnFn); if not Assigned(png_ptr) then raise EInvalidRasterFile.Create(sLIBPNGerror); info_ptr := _png_create_info_struct(png_ptr); if not Assigned(png_ptr) then begin _png_destroy_read_struct(@png_ptr, nil, nil); raise EInvalidRasterFile.Create(sLIBPNGerror); end; UnMipmap; try {: Need to override the standard I/O methods since libPNG may be linked against a different run-time } _png_set_read_fn(png_ptr, stream, pngReadFn); // skip the sig bytes _png_set_sig_bytes(png_ptr, 8); // automagically read everything to the image data _png_read_info(png_ptr, info_ptr); FLOD[0].Width := _png_get_image_width(png_ptr, info_ptr); FLOD[0].Height := _png_get_image_height(png_ptr, info_ptr); // using the convention of depth = 0 for 2D images FLOD[0].Depth := 0; colorType := _png_get_color_type(png_ptr, info_ptr); bitDepth := _png_get_bit_depth(png_ptr, info_ptr); {: Setup the read transforms expand palette images to RGB and low-bit-depth grayscale images to 8 bits convert transparency chunks to full alpha channel } if colorType = PNG_COLOR_TYPE_PALETTE then _png_set_palette_to_rgb(png_ptr); if (colorType = PNG_COLOR_TYPE_GRAY) and (bitDepth < 8) then {$IFDEF FPC} _png_set_gray_1_2_4_to_8(png_ptr); {$ELSE} _png_set_expand_gray_1_2_4_to_8(png_ptr); {$ENDIF} if _png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) <> 0 then _png_set_tRNS_to_alpha(png_ptr); // now configure for reading, and allocate the memory _png_read_update_info(png_ptr, info_ptr); rowBytes := _png_get_rowbytes(png_ptr, info_ptr); UpdateLevelsInfo; ReallocMem(fData, rowBytes * Cardinal(GetHeight)); SetLength(rowPointers, GetHeight); // set up the row pointers for ii := 0 to FLOD[0].Height - 1 do rowPointers[ii] := PGLUbyte(PtrUInt(fData) + Cardinal(FLOD[0].Height - 1 - ii) * rowBytes); // read the image _png_read_image(png_ptr, @rowPointers[0]); use16 := bitDepth > 8; if use16 then fDataType := GL_UNSIGNED_SHORT else fDataType := GL_UNSIGNED_BYTE; case _png_get_channels(png_ptr, info_ptr) of 1: begin fColorFormat := GL_LUMINANCE; if use16 then begin fInternalFormat := tfLUMINANCE16; fElementSize := 2; end else begin fInternalFormat := tfLUMINANCE8; fElementSize := 1; end; end; 2: begin fColorFormat := GL_LUMINANCE_ALPHA; if use16 then begin fInternalFormat := tfLUMINANCE16_ALPHA16; fElementSize := 4; end else begin fInternalFormat := tfLUMINANCE8_ALPHA8; fElementSize := 2; end; end; 3: begin fColorFormat := GL_RGB; if use16 then begin fInternalFormat := tfR16G16B16; fElementSize := 6; end else begin fInternalFormat := tfRGB8; fElementSize := 3; end; end; 4: begin fColorFormat := GL_RGBA; if use16 then begin fInternalFormat := tfR16G16B16A16; fElementSize := 8; end else begin fInternalFormat := tfRGBA8; fElementSize := 4; end; end; end; fCubeMap := false; fTextureArray := false; _png_read_end(png_ptr, nil); finally _png_destroy_read_struct(@png_ptr, @info_ptr, nil); end; end; // SaveToStream // procedure TGLPNGImage.SaveToStream(stream: TStream); var png_ptr: png_structp; info_ptr: png_infop; bit_depth, color_type: Integer; rowBytes: Cardinal; canSave: Boolean; rowPointers: array of PGLUbyte; ii: Integer; begin png_ptr := _png_create_write_struct(ZLIB_VERSION, nil, pngErrorFn, pngWarnFn); if not Assigned(png_ptr) then raise EInvalidRasterFile.Create(sLIBPNGerror); info_ptr := _png_create_info_struct(png_ptr); if not Assigned(png_ptr) then begin _png_destroy_write_struct(@png_ptr, nil); raise EInvalidRasterFile.Create(sLIBPNGerror); end; try {: Need to override the standard I/O methods since libPNG may be linked against a different run-time } _png_set_write_fn(png_ptr, stream, pngWriteFn, nil); bit_depth := fElementSize * 8; color_type := PNG_COLOR_TYPE_GRAY; rowBytes := GetWidth * fElementSize; canSave := true; case fDataType of GL_UNSIGNED_BYTE: bit_depth := 8; GL_UNSIGNED_SHORT: bit_depth := 16; else canSave := false; end; case fColorFormat of GL_LUMINANCE: color_type := PNG_COLOR_TYPE_GRAY; GL_LUMINANCE_ALPHA: color_type := PNG_COLOR_TYPE_GRAY_ALPHA; GL_RGB: color_type := PNG_COLOR_TYPE_RGB; GL_RGBA: color_type := PNG_COLOR_TYPE_RGB_ALPHA; else canSave := false; end; if not canSave then raise EInvalidRasterFile.Create('These image format do not match the PNG format specification.'); _png_set_IHDR(png_ptr, info_ptr, GetWidth, GetHeight, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); // write the file header information _png_write_info(png_ptr, info_ptr); SetLength(rowPointers, GetHeight); // set up the row pointers for ii := 0 to GetHeight - 1 do rowPointers[ii] := PGLUbyte(PtrUInt(fData) + Cardinal(GetHeight - 1 - ii) * rowBytes); _png_write_image(png_ptr, @rowPointers[0]); _png_write_end(png_ptr, info_ptr); finally _png_destroy_write_struct(@png_ptr, @info_ptr); end; end; // AssignFromTexture // procedure TGLPNGImage.AssignFromTexture(textureContext: TGLContext; const textureHandle: TGLuint; textureTarget: TGLTextureTarget; const CurrentFormat: Boolean; const intFormat: TGLInternalFormat); var oldContext: TGLContext; contextActivate: Boolean; texFormat: Cardinal; residentFormat: TGLInternalFormat; glTarget: TGLEnum; begin if not ((textureTarget = ttTexture2D) or (textureTarget = ttTextureRect)) then Exit; oldContext := CurrentGLContext; contextActivate := (oldContext <> textureContext); if contextActivate then begin if Assigned(oldContext) then oldContext.Deactivate; textureContext.Activate; end; glTarget := DecodeGLTextureTarget(textureTarget); try textureContext.GLStates.TextureBinding[0, textureTarget] := textureHandle; fLevelCount := 0; fCubeMap := false; fTextureArray := false; // Check level existence GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_INTERNAL_FORMAT, @texFormat); if texFormat > 1 then begin GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_WIDTH, @FLOD[0].Width); GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_HEIGHT, @FLOD[0].Height); FLOD[0].Depth := 0; residentFormat := OpenGLFormatToInternalFormat(texFormat); if CurrentFormat then fInternalFormat := residentFormat else fInternalFormat := intFormat; FindCompatibleDataFormat(fInternalFormat, fColorFormat, fDataType); Inc(fLevelCount); end; if fLevelCount > 0 then begin fElementSize := GetTextureElementSize(fColorFormat, fDataType); ReallocMem(FData, DataSize); GL.GetTexImage(glTarget, 0, fColorFormat, fDataType, fData); end else fLevelCount := 1; GL.CheckError; finally if contextActivate then begin textureContext.Deactivate; if Assigned(oldContext) then oldContext.Activate; end; end; end; // Capabilities // class function TGLPNGImage.Capabilities: TDataFileCapabilities; begin Result := [dfcRead, dfcWrite]; end; initialization { Register this Fileformat-Handler with GLScene } RegisterRasterFormat('png', 'Portable Network Graphic', TGLPNGImage); end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 16384,0,100000} { by Behdad Esfahbod Algorithmic Problems Book April '2000 Problem 157 O(M2) Dynamic Method } program LahimKari; uses Graph; const MaxM = 100; type TComponent = record S, F, E, R, P : Integer; D : array [0 .. MaxM] of Integer; end; var N, M : Integer; A : array [0 .. MaxM, 1 .. 4] of Integer; Comp, Col : array [0 .. MaxM] of Integer; Component : array [1 .. MaxM] of TComponent; CNum : Integer; Stack : array [1 .. 2, 1 .. MaxM] of Integer; SN : array [1 .. 2] of Integer; Ans : Integer; I, J, K : Integer; procedure ReadInput; begin Assign(Input, 'input.txt'); Reset(Input); Readln(N, M); for I := 1 to M do begin Readln(A[I, 1], A[I, 2]); A[I, 4] := I; end; Close(Input); for I := 1 to M do if A[I, 1] > A[I, 2] then begin J := A[I, 1]; A[I, 1] := A[I, 2]; A[I, 2] := J; end; end; procedure NoSolution; begin Assign(Output, 'output.txt'); Rewrite(Output); Writeln('No Solution'); Close(Output); Halt; end; procedure WriteOutput; begin Assign(Output, 'output.txt'); Rewrite(Output); for I := 1 to M do Writeln(A[I, 1], ' ', A[I, 2], ' ', A[I, 3]); Writeln('Maximum absolute value of heights = ', Ans); Close(Output); end; procedure Sort(l, r: Integer); var i, j, x: integer; begin i := l; j := r; x := a[(l+r) DIV 2, 1]; repeat while a[i, 1] < x do i := i + 1; while x < a[j, 1] do j := j - 1; if i <= j then begin a[0] := a[i]; a[i] := a[j]; a[j] := a[0]; i := i + 1; j := j - 1; end; until i > j; if l < j then Sort(l, j); if i < r then Sort(i, r); end; function Intersect (AS, AF, BS, BF : Integer) : Boolean; begin Intersect := ((AS < BS) and (BS < AF) and (AF < BF)) or ((BS < AS) and (AS < BF) and (BF < AF)); end; procedure Dfs (V, C : Integer); var I : Integer; begin Col[V] := C; Comp[V] := CNum; with Component[CNum] do begin if F < A[V, 2] then F := A[V, 2]; if A[R, 1] < A[V, 1] then R := V; end; for I := 1 to M do if (I <> V) and Intersect(A[V, 1], A[V, 2], A[I, 1], A[I, 2]) then if Col[I] = 0 then Dfs(I, 3 - C) else if Col[I] = C then NoSolution; end; procedure FindComponents; begin A[0, 1] := 0; A[0, 2] := 0; CNum := 0; for I := 1 to M do if Col[I] = 0 then begin Inc(CNum); with Component[CNum] do begin S := A[I, 1]; F := 0; {Will be updated in dfs} E := I; R := 0; {Will be updated in dfs} P := 0; for J := CNum - 1 downto 1 do if S < Component[J].F then begin P := J; Break; end; end; Dfs(I, 1); end; for I := 1 to CNum do begin J := I; while (Component[J].P <> 0) and (Component[Component[J].P].R < Component[J].R) do with Component[J] do begin Component[P].R := R; J := P; end; end; end; function Max (A, B : Integer) : Integer; begin if A >= B then Max := A else Max := B; end; procedure Dynamic (V : Integer); var H, I : Integer; procedure Pop (X : Integer); begin Dec(SN[X]); end; procedure Push (I : Integer); begin Inc(SN[Col[I]]); Stack[Col[I], SN[Col[I]]] := I; end; begin {Dynamic} with Component[V] do begin for H := E to R do if Comp[H] <> V then Dynamic(Comp[H]); if E = R then begin for H := 0 to M do D[H] := 0; Exit; end; for H := 0 to M do begin SN[1] := 0; SN[2] := 0; I := E; D[H] := 0; while I <= R do begin while (SN[1] > 0) and (A[I, 1] > A[Stack[1, SN[1]], 2]) do Pop(1); while (SN[2] > 0) and (A[I, 1] > A[Stack[2, SN[2]], 2]) do Pop(2); if Comp[I] = V then begin Push(I); if SN[1] > H then begin D[H] := MaxInt div 2; Break; end; D[H] := Max(D[H], SN[2]); end else begin J := Component[Comp[I]].D[H - SN[1]]; for K := 0 to M do if Component[Comp[I]].D[K] <= H - SN[1] then begin if (K > 0) and (K < J) then J := K; Break; end; if J >= MaxInt div 2 then begin D[H] := MaxInt div 2; Break; end; D[H] := Max(D[H], J + SN[2]); if D[H] >= MaxInt div 2 then Break; I := Component[Comp[I]].R; end; Inc(I); end; if (H > 0) and (D[H] < MaxInt div 2) and (D[H] = D[H - 1]) then begin for I := H + 1 to M do D[I] := D[H]; Break; end; end; end; end; procedure FindMinHeight; begin Ans := 0; for I := 1 to CNum do with Component[I] do if P = 0 then begin Dynamic(I); K := MaxInt div 2; for J := 0 to M do begin if J > K then Break; if K > Max(J, D[J]) then K := Max(J, D[J]); end; if Ans < K then Ans := K; end; end; procedure FindDir (V, H, Coef : Integer); var I, J : Integer; W : array [1 .. 2] of Integer; procedure Pop (X : Integer); begin Dec(SN[X]); Dec(W[X]); end; procedure Push (I : Integer); var J : Integer; begin J := Col[I]; if Coef = -1 then J := 3 - J; case Col[I] of 1 : A[I, 3] := Coef * (H - W[J]); 2 : A[I, 3] := Coef * -(Component[V].D[H] - W[J]); end; Inc(W[J]); Inc(SN[J]); Stack[J, SN[J]] := I; end; begin {FindDir} with Component[V] do begin W[1] := 0; W[2] := 0; while (H > 0) and (D[H] = D[H - 1]) do Dec(H); I := E; while I <= R do begin while (SN[1] > 0) and (A[I, 1] > A[Stack[1, SN[1]], 2]) do Pop(1); while (SN[2] > 0) and (A[I, 1] > A[Stack[2, SN[2]], 2]) do Pop(2); if Comp[I] = V then Push(I) else begin J := 1; if Coef = -1 then J := 2; if (H >= W[J]) and (Component[Comp[I]].D[H - W[J]] <= D[H] - W[3 - J]) then FindDir(Comp[I], H - W[J], Coef) else FindDir(Comp[I], D[H] - W[3 - J], - Coef); I := Component[Comp[I]].R; end; Inc(I); end; while (SN[1] > 0) and (F >= A[Stack[1, SN[1]], 2]) do Pop(1); while (SN[2] > 0) and (F >= A[Stack[2, SN[2]], 2]) do Pop(2); end; end; procedure FindDirections; begin SN[1] := 0; SN[2] := 0; for I := 1 to CNum do with Component[I] do if P = 0 then FindDir(I, Ans, 1); end; procedure Solve; begin Sort(1, M); FindComponents; FindMinHeight; FindDirections; end; procedure Draw; var GD, GM : Integer; begin GD := Detect; InitGraph(GD, GM, ''); J := 640 div (N + 1); if J > 10 then SetLineStyle(0, 0, 3); for I := 1 to M do begin SetColor((A[I, 4] - 1) mod 16 + 1); Circle(A[I, 1] * J, 240, 2); Circle(A[I, 2] * J, 240, 2); Line(A[I, 1] * J, 240, A[I, 1] * J, 240 - A[I, 3] * J); Line(A[I, 1] * J, 240 - A[I, 3] * J, A[I, 2] * J, 240 - A[I, 3] * J); Line(A[I, 2] * J, 240, A[I, 2] * J, 240 - A[I, 3] * J); end; Assign(Output, ''); Rewrite(Output); Writeln(Ans); Assign(Input, ''); Reset(Input); Readln; CloseGraph; end; begin ReadInput; Solve; WriteOutput; Draw; end.
unit VersionUtils; interface uses SysUtils, Xml.xmldom, Xml.XMLIntf, Xml.Win.msxmldom, Xml.XMLDoc; const ACTUALVERSION: String = '1.0'; function UpgradeVersion(i: IXMLDocument): Boolean; function CheckVersion(i: IXMLDocument): Boolean; function GetVersion(i: IXMLDocument): String; implementation uses Logic, uLog; function CheckVersion(i: IXMLDocument): Boolean; begin result:=False; if GetVersion(i) <> ACTUALVERSION then begin log('Версия устарела. Обновляем.'); if not UpgradeVersion(i) then begin log('Обновление завершилось ошибкой. Всё пропало.'); exit; end else log('Обновление успешно'); end; Log('Версия базы актуальна'); result:=True; {$REGION '#Old'} //Версия самостоятельного обновления // if GetVersion(i) = CURRENTVERSION then // result:= True // else // result:= UpgradeVersion(i); {$ENDREGION} end; function UpgradeVersion(i: IXMLDocument): Boolean; begin result:=False; if GetVersion(i) = '1.0' then begin //Обновление до 0.9 //Exit //Неудача end; if GetVersion(i) = '0.9' then begin //Обновление до след и т д до последней... end; if GetVersion(i) = ACTUALVERSION then result:=True; end; function GetVersion(i: IXMLDocument): String; begin result:=i.DocumentElement.Attributes['version']; end; end.
unit UGameScriptBase; interface uses Windows,ULuaEngine,LuaLib,GD_Utils; type TLuaState = Lua_State; TGameScriptBase = class private mTypeName:String; public constructor Create(TypeName:String); Function RegisterMethod(FuncName,MethodName:String):Integer; Function ToInteger(n:Integer):Integer; Function ToString(n:Integer):String; end; implementation { TGameScript } constructor TGameScriptBase.Create(TypeName:String); begin mTypeName:= TypeName; end; function TGameScriptBase.RegisterMethod(FuncName, MethodName: String): Integer; begin Dbgprint('Reg Script Method:%s',[FuncName]); Result:= LuaEngine.RegisterMethod(FuncName, MethodName,Self); end; function TGameScriptBase.ToInteger(n: Integer): Integer; begin Result:=LuaEngine.GetValueToInteger(n); end; function TGameScriptBase.ToString(n: Integer): String; begin Result:=LuaEngine.GetValueToString(n); end; end.
{ Inicializacia spojenia : (S) -> 'CLIENTINFO' (C) -> 'CLIENTINFOBEGINname|company|serial|lastupdate|CLIENTINFOEND' Session info (S) -> 'SESSIONBEGIN1|1|1|newdate|SESSIONEND' (C) -> 'SESSIONOK' File rozvrh (S) -> 'FILEBEGINrozvrh|filename|data|FILEEND' (C) -> 'FILEOK' File listok (S) -> 'FILEBEGINlistok|min|norm|zlav|FILEEND' (C) -> 'FILEOK' File zastavky (S) -> 'FILEBEGINzastavky|data|FILEEND' (C) -> 'FILEOK' } unit ClassMHDserver; interface uses Classes, ScktComp, Winsock, Konstanty; type TClient = class; TMHDServer = class; TClientStatus = ( csNone, // default csConnecting, // ked sa client prave pripojil csGettingInfo, // po pripojeni si od neho vyziadam nejake info csBeginingSession, // inicializacia prenosu suborov csSendingFile, // posielanie suboru csFileOK, // subor odoslany csFinished, // vsetko islo OK a skoncil som csTransferError); // error TClientInfo = record Name : string; Company : string; Serial : string; IP : string; LastUpdate : string; Status : string; end; TFileType = (ftNone,ftRozvrh,ftListok,ftZastavky); TFile = record FileType : TFileType; Index : integer; Data : WideString; end; TMHDClientConnect = procedure( Sender : TClient; Info : TClientInfo ) of object; TMHDClientDisconnect = procedure( Sender : TClient ) of object; TStatusEvent = procedure( Sender : TClient ) of object; TClient = class private ServerClient : TServerClientWinSocket; SendingFile : TFile; FStatus : TClientStatus; FMHDClientConnect : TMHDClientConnect; FMHDClientDisconnect : TMHDClientDisconnect; FStatusEvent : TStatusEvent; procedure SetStatus( Value : TClientStatus ); procedure RequestClientInfo; procedure GetClientInfo; procedure RequestSessionAccept; procedure GetSessionAccept; procedure GetFileOK; procedure SendNextFile; function GetNextRozvrh( Index : integer ) : WideString; function GetNextListok( Index : integer ) : WideString; function GetNextZastavky : WideString; procedure SendFinish; procedure SocketEvent( Sender: TObject; Socket: TCustomWinSocket; SocketEvent: TSocketEvent ); procedure SocketError( Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer ); procedure StartWriting; procedure StartReading; property Status : TClientStatus read FStatus write SetStatus; public ClientInfo : TClientInfo; constructor Create( ClientSocket: TServerClientWinSocket ); property OnMHDClientConnect : TMHDClientConnect read FMHDClientConnect write FMHDClientConnect; property OnMHDClientDisconnect : TMHDClientDisconnect read FMHDClientDisconnect write FMHDClientDisconnect; property OnStatusChange : TStatusEvent read FStatusEvent write FStatusEvent; end; TListItemEvent = procedure( Sender : TObject; ClientIndex : integer ) of object; TMHDserver = class private Server : TServerSocket; FActive : boolean; FMHDClientConnect : TMHDClientConnect; FMHDClientDisconnect : TMHDClientDisconnect; FOnListChange : TNotifyEvent; FOnListItemChange : TListItemEvent; procedure SetActive( Value : boolean ); procedure GetSocket(Sender: TObject; Socket: TSocket; var ClientSocket: TServerClientWinSocket); procedure MHDClientConnect( Sender : TClient; Info : TClientInfo ); procedure MHDClientDisconnect( Sender : TClient ); procedure MHDClientStatusChange( Sender : TClient ); property OnMHDClientConnect : TMHDClientConnect read FMHDClientConnect write FMHDClientConnect; property OnMHDClientDisconnect : TMHDClientDisconnect read FMHDClientDisconnect write FMHDClientDisconnect; public Clients : TList; constructor Create; destructor Destroy; override; property Active : boolean read FActive write SetActive; property OnListChange : TNotifyEvent read FOnListChange write FOnListChange; property OnListItemChange : TListItemEvent read FOnListItemChange write FOnListItemChange; end; var MHDserver : TMHDserver; implementation uses SysUtils, ClassUpdates; //============================================================================== //============================================================================== // // C L I E N T // //============================================================================== //============================================================================== //============================================================================== // Constructor //============================================================================== constructor TClient.Create( ClientSocket : TServerClientWinSocket ); begin inherited Create; ServerClient := ClientSocket; ServerClient.OnSocketEvent := SocketEvent; ServerClient.OnErrorEvent := SocketError; Status := csConnecting; end; //============================================================================== // Properties //============================================================================== procedure TClient.SetStatus( Value : TClientStatus ); begin if (FStatus = Value) then exit; FStatus := Value; case FStatus of csNone : ClientInfo.Status := 'Unknown status'; csConnecting : ClientInfo.Status := 'Connecting ...'; csGettingInfo : ClientInfo.Status := 'Getting client info ...'; csBeginingSession : ClientInfo.Status := 'Initializing file transfer ...'; csSendingFile : ClientInfo.Status := 'Sending file ...'; csFileOK : ClientInfo.Status := 'File sent'; csFinished : ClientInfo.Status := 'Transfer finished'; csTransferError : ClientInfo.Status := 'Transfer error!'; end; if (Assigned( OnStatusChange )) then OnStatusChange( Self ); case FStatus of csGettingInfo : RequestClientInfo; csBeginingSession : RequestSessionAccept; csSendingFile : SendNextFile; csFileOK : Status := csSendingFile; csFinished : SendFinish; end; end; //============================================================================== // Reading / Writing //============================================================================== procedure TClient.StartWriting; begin case Status of csConnecting : Status := csGettingInfo; end; end; procedure TClient.StartReading; begin case Status of csGettingInfo : GetClientInfo; csSendingFile : GetFileOK; csBeginingSession : GetSessionAccept; end; end; //============================================================================== // Client Info //============================================================================== procedure TClient.RequestClientInfo; begin ServerClient.SendText( 'CLIENTINFO' ); end; procedure TClient.GetClientInfo; var Data : string; Zac, Kon : integer; I : integer; S : string; sy, sm, sd : integer; cy, cm, cd : integer; begin Data := ServerClient.ReceiveText; Zac := Pos( 'CLIENTINFOBEGIN' , Data ); Kon := Pos( 'CLIENTINFOEND' , Data ); if (Zac = 0) or (Kon = 0) then begin Status := csTransferError; exit; end; I := Zac+Length( 'CLIENTINFOBEGIN' ); // Name : ClientInfo.Name := ''; while (Data[I] <> '|') do begin ClientInfo.Name := ClientInfo.Name + Data[I]; Inc( I ); end; // Company : Inc( I ); ClientInfo.Company := ''; while (Data[I] <> '|') do begin ClientInfo.Company := ClientInfo.Company + Data[I]; Inc( I ); end; // Serial : Inc( I ); ClientInfo.Serial := ''; while (Data[I] <> '|') do begin ClientInfo.Serial := ClientInfo.Serial + Data[I]; Inc( I ); end; // Last update : Inc( I ); ClientInfo.LastUpdate := ''; while (Data[I] <> '|') do begin ClientInfo.LastUpdate := ClientInfo.LastUpdate + Data[I]; Inc( I ); end; // Je update potrebny ? // Ziadne novsie data neexistuju if (Updates.Active = -1) then begin Status := csFinished; exit; end; // Datum aktualneho (serverovskeho) update S := TUpdateItem( Updates.Items[Updates.Active] ).Datum; sd := StrToInt( S[1]+S[2] ); sm := StrToInt( S[3]+S[4] ); sy := StrToInt( S[5]+S[6]+S[7]+S[8] ); // Datum posledneho update u klienta S := ClientInfo.LastUpdate; cd := StrToInt( S[1]+S[2] ); cm := StrToInt( S[3]+S[4] ); cy := StrToInt( S[5]+S[6]+S[7]+S[8] ); // Klientovsky update je aktualny if (cy > sy) or ((cy = sy) and (cm > sm)) or ((cy = sy) and (cm = sm) and (cd >= sd)) then begin Status := csFinished; exit; end; // Treba spravit update Status := csBeginingSession; end; procedure TClient.RequestSessionAccept; var Data : string; begin Data := 'SESSIONBEGIN'; // Pocet novych rozvrhov Data := Data + IntToStr( TUpdateItem( Updates.Items[ Updates.Active ] ).RozvrhyFiles.Count )+'|'; // Pocet novych listkov Data := Data + IntToStr( Length( TUpdateItem( Updates.Items[ Updates.Active ] ).Listky ) )+'|'; // Novy subor so zastavkami if (TUpdateItem( Updates.Items[ Updates.Active ] ).ZastavkyFile = '') then Data := Data + '0|' else Data := Data + '1|'; Data := Data + TUpdateItem( Updates.Items[ Updates.Active ] ).Datum + '|'; Data := Data + 'SESSIONEND'; ServerClient.SendText( Data ); end; procedure TClient.GetSessionAccept; var Data : string; begin Data := ServerClient.ReceiveText; if (Data <> 'SESSIONOK') then begin Status := csTransferError; exit; end; SendingFile.FileType := ftNone; Status := csSendingFile; end; procedure TClient.GetFileOK; var Data : string; begin Data := ServerClient.ReceiveText; if (Data <> 'FILEOK') then begin Status := csTransferError; exit; end; Status := csFileOK; end; function TClient.GetNextRozvrh( Index : integer ) : WideString; var F : textfile; S : string; begin Result := 'FILEBEGINrozvrh|'+ExtractFileName( TUpdateItem( Updates.Items[Updates.Active] ).RozvrhyFiles[Index] )+'|'; AssignFile( F , TUpdateItem( Updates.Items[Updates.Active] ).RozvrhyFiles[Index] ); {$I-} Reset( F ); {$I+} if (IOResult <> 0) then begin Result := Result + 'ERROR|FILEEND'; exit; end; while not EoF( F ) do begin Readln( F , S ); Result := Result + S +#13#10; end; Result := Result + '|FILEEND'; CloseFile( F ); end; function TClient.GetNextListok( Index : integer ) : WideString; begin Result := 'FILEBEGINlistok|'; Result := Result + IntToStr( TUpdateItem( Updates.Items[Updates.Active] ).Listky[Index].Min )+'|'; Result := Result + IntToStr( TUpdateItem( Updates.Items[Updates.Active] ).Listky[Index].Norm )+'|'; Result := Result + IntToStr( TUpdateItem( Updates.Items[Updates.Active] ).Listky[Index].Zlav )+'|'; Result := Result + 'FILEEND'; end; function TClient.GetNextZastavky : WideString; var F : textfile; S : string; begin Result := 'FILEBEGINzastavky|'; AssignFile( F , TUpdateItem( Updates.Items[Updates.Active] ).ZastavkyFile ); {$I-} Reset( F ); {$I+} if (IOResult <> 0) then begin Result := Result + 'ERROR|FILEEND'; exit; end; while not EoF( F ) do begin Readln( F , S ); Result := Result + S +#13#10; end; Result := Result + '|FILEEND'; CloseFile( F ); end; procedure TClient.SendNextFile; var NewType : TFileType; NewIndex : integer; begin NewType := SendingFile.FileType; NewIndex := 0; case SendingFile.FileType of ftNone : begin if (TUpdateItem( Updates.Items[Updates.Active] ).RozvrhyFiles.Count > 0) then begin NewType := ftRozvrh; NewIndex := 0; end else if (Length( TUpdateItem( Updates.Items[Updates.Active] ).Listky ) > 0) then begin NewType := ftListok; NewIndex := 0; end else if (TUpdateItem( Updates.Items[Updates.Active] ).ZastavkyFile <> '') then begin NewType := ftZastavky; NewIndex := 0; end else begin NewType := ftNone; Status := csFinished; end; end; ftRozvrh : begin if (SendingFile.Index < TUpdateItem( Updates.Items[Updates.Active] ).RozvrhyFiles.Count-1) then NewIndex := SendingFile.Index+1 else if (Length( TUpdateItem( Updates.Items[Updates.Active] ).Listky ) > 0) then begin NewType := ftListok; NewIndex := 0; end else if (TUpdateItem( Updates.Items[Updates.Active] ).ZastavkyFile <> '') then begin NewType := ftZastavky; NewIndex := 0; end else begin NewType := ftNone; Status := csFinished; end; end; ftListok : begin if (SendingFile.Index < Length( TUpdateItem( Updates.Items[Updates.Active] ).Listky )-1) then NewIndex := SendingFile.Index+1 else if (TUpdateItem( Updates.Items[Updates.Active] ).ZastavkyFile <> '') then begin NewType := ftZastavky; NewIndex := 0; end else begin NewType := ftNone; Status := csFinished; end; end; ftZastavky : begin NewType := ftNone; NewIndex := 0; Status := csFinished; end; end; SendingFile.FileType := NewType; SendingFile.Index := NewIndex; case NewType of ftNone : exit; ftRozvrh : SendingFile.Data := GetNextRozvrh( NewIndex ); ftListok : SendingFile.Data := GetNextListok( NewIndex ); ftZastavky : SendingFile.Data := GetNextZastavky; end; ServerClient.SendText( SendingFile.Data ); end; procedure TClient.SendFinish; begin ServerClient.SendText( 'FINISH' ); end; procedure TClient.SocketError( Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer ); begin ErrorCode := 0; Status := csTransferError; end; procedure TClient.SocketEvent( Sender: TObject; Socket: TCustomWinSocket; SocketEvent: TSocketEvent); begin case SocketEvent of seWrite : StartWriting; seRead : StartReading; seDisconnect : if Assigned( OnMHDClientDisconnect ) then OnMHDClientDisconnect( Self ); end; end; //============================================================================== //============================================================================== // // S E R V E R // //============================================================================== //============================================================================== //============================================================================== // Constructor //============================================================================== constructor TMHDserver.Create; begin inherited; FActive := False; Clients := TList.Create; OnMHDClientConnect := MHDClientConnect; OnMHDClientDisconnect := MHDClientDisconnect; Server := TServerSocket.Create( nil ); with Server do begin Active := False; Port := 10000; ServerType := stNonBlocking; Service := ''; ThreadCacheSize := 10; OnGetSocket := GetSocket; end; end; //============================================================================== // Destructor //============================================================================== destructor TMHDserver.Destroy; var I : integer; begin Server.Free; for I := 0 to Clients.Count-1 do TClient( Clients[I] ).Free; Clients.Free; inherited; end; //============================================================================== // Server properties //============================================================================== procedure TMHDServer.SetActive( Value : boolean ); begin if (FActive = Value) then exit; FActive := Value; Server.Active := FActive; end; //============================================================================== // Server events //============================================================================== procedure TMHDServer.MHDClientConnect( Sender : TClient; Info : TClientInfo ); begin end; procedure TMHDServer.MHDClientDisconnect( Sender : TClient ); var Cislo : integer; begin Cislo := Clients.IndexOf( Sender ); TClient( Clients[ Cislo ] ).Free; Clients.Delete( Cislo ); if (Assigned( OnListChange )) then OnListChange( Self ); end; procedure TMHDServer.MHDClientStatusChange( Sender : TClient ); var Cislo : integer; begin Cislo := Clients.IndexOf( Sender ); if (Assigned( OnListItemChange )) then OnListItemChange( Self , Cislo ); end; procedure TMHDServer.GetSocket( Sender: TObject; Socket: TSocket; var ClientSocket: TServerClientWinSocket ); var NEWClientSocket : TServerClientWinSocket; NEWClient : TClient; begin NEWClientSocket := TServerClientWinSocket.Create( Socket , Server.Socket ); ClientSocket := NEWClientSocket; NEWClient := TClient.Create( NEWClientSocket ); NEWClient.OnMHDClientConnect := OnMHDClientConnect; NEWClient.OnMHDClientDisconnect := OnMHDClientDisconnect; NEWClient.OnStatusChange := MHDClientStatusChange; Clients.Add( NEWClient ); if (Assigned( OnListChange )) then OnListChange( Self ); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995-2002 Borland Software Corporation } { } {*******************************************************} unit XPActnCtrls; interface uses Windows, Messages, Controls, Classes, Graphics, Buttons, ActnMan, ActnMenus, ActnCtrls, ToolWin, ActnColorMaps, ShadowWnd; type { TXPStyleMenuItem } TXPStyleMenuItem = class(TCustomMenuItem) protected procedure DrawBackground(var PaintRect: TRect); override; procedure DrawGlyph(const Location: TPoint); override; procedure DrawSeparator(const Offset: Integer); override; procedure DrawSubMenuGlyph; override; procedure DrawText(var Rect: TRect; var Flags: Cardinal; Text: String); override; procedure DrawUnusedEdges; override; procedure DrawShadowedText(Rect: TRect; Flags: Cardinal; Text: String; TextColor: TColor; ShadowColor: TColor); override; procedure CalcLayout; override; public procedure CalcBounds; override; end; { TXPStyleMenuButton } TXPStyleMenuButton = class(TCustomMenuButton) protected procedure DrawBackground(var PaintRect: TRect); override; procedure DrawText(var ARect: TRect; var Flags: Cardinal; Text: String); override; end; { TXPStylePopupMenu } TXPStylePopupMenu = class(TCustomActionPopupMenu) private FBtnShadow: TShadowWindow; protected function GetExpandBtnClass: TCustomMenuExpandBtnClass; override; procedure NCPaint(DC: HDC); override; procedure PositionPopup(AnOwner: TCustomActionBar; ParentItem: TCustomActionControl); override; procedure VisibleChanging; override; procedure DisplayShadow; override; procedure HideShadow; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; { TXPStyleExpandBtn } TXPStyleExpandBtn = class(TCustomMenuExpandBtn) protected procedure DrawBackground(var PaintRect: TRect); override; procedure DrawFrame(ARect: TRect; Down: Boolean); override; end; { TXPStyleButton } TXPStyleButton = class(TCustomButtonControl) protected procedure DrawBackground(var PaintRect: TRect); override; procedure DrawFrame(ARect: TRect; Down: Boolean); override; procedure DrawGlyph(const Location: TPoint); override; procedure DrawText(var ARect: TRect; var Flags: Cardinal; Text: String); override; end; { TXPStyleDropDownBtn } TXPStyleDropDownBtn = class(TCustomDropDownButton) protected procedure DrawFrame(ARect: TRect; Down: Boolean); override; procedure DrawBackground(var PaintRect: TRect); override; function GetPopupClass: TCustomActionBarClass; override; procedure DrawGlyph(const Location: TPoint); override; end; { TXPStyleCustomizePopup } TXPStyleCustomizePopup = class(TCustomizeActionToolBar) protected procedure NCPaint(DC: HDC); override; function GetAddRemoveItemClass: TCustomAddRemoveItemClass; override; function GetDefaultColorMapClass: TCustomColorMapClass; override; public constructor Create(AOwner: TComponent); override; end; { TXPStyleToolScrollBtn } TXPStyleToolScrollBtn = class(TCustomToolScrollBtn) protected procedure DrawBackground(var PaintRect: TRect); override; end; { TXPStyleAddRemoveItem } TXPStyleAddRemoveItem = class(TCustomAddRemoveItem) protected procedure DrawBackground(var PaintRect: TRect); override; procedure DrawGlyph(const Location: TPoint); override; procedure DrawSeparator(const Offset: Integer); override; procedure DrawText(var Rect: TRect; var Flags: Cardinal; Text: String); override; procedure DrawUnusedEdges; override; public procedure CalcBounds; override; end; implementation uses SysUtils, Forms, Consts, ActnList, GraphUtil, Contnrs, ListActns, ImgList; function IsMouseButtonPressed: Boolean; begin Result := not (((GetAsyncKeyState(VK_RBUTTON)and $8000)=0) and ((GetAsyncKeyState(VK_LBUTTON)and $8000)=0)); end; { TXPStyleMenuItem } procedure TXPStyleMenuItem.CalcBounds; var NewTextPos: TRect; begin inherited; if Separator then Height := 3 else Height := Height + 2; if not HasGlyph then begin NewTextPos := TextBounds; NewTextPos.Top := NewTextPos.Top + 1; TextBounds := NewTextPos; end; end; procedure TXPStyleMenuItem.CalcLayout; begin inherited; GlyphPos := Point(GlyphPos.X, GlyphPos.Y + 1); end; procedure TXPStyleMenuItem.DrawBackground(var PaintRect: TRect); var BannerRect: TRect; BGRect: TRect; begin if (ActionClient = nil) then exit; if ActionClient.Color <> clDefault then Canvas.Brush.Color := ActionClient.Color; BGRect := PaintRect; if TextBounds.Left > GlyphPos.X then BGRect.Left := 0; BannerRect := PaintRect; if TextBounds.Left > GlyphPos.X then BannerRect.Right := TextBounds.Left - 3 else BannerRect.Right := TextBounds.Right + 3; BannerRect.Right := 25; BGRect.Left := BannerRect.Right - BannerRect.Left; if ActionClient.Unused then Canvas.Brush.Color := ActionBar.ColorMap.UnusedColor else Canvas.Brush.Color := ActionBar.ColorMap.Color; Canvas.FillRect(BannerRect); Canvas.Brush.Color := Menu.ColorMap.MenuColor; if (Selected and Enabled) or (Selected and not MouseSelected) then begin if Enabled and not ActionBar.DesignMode then Canvas.Brush.Color := Menu.ColorMap.SelectedColor; Dec(PaintRect.Right, 1); end; inherited DrawBackground(BGRect); if not Mouse.IsDragging and ((Selected and Enabled) or (Selected and not MouseSelected)) then begin Canvas.FillRect(PaintRect); Canvas.Brush.Color := ActionBar.ColorMap.BtnFrameColor; Inc(PaintRect.Right); Canvas.FrameRect(PaintRect); end; end; procedure TXPStyleMenuItem.DrawGlyph(const Location: TPoint); var OldColor, OldBrushColor: TColor; NewLocation: TPoint; FrameRect: TRect; SelBmp: TBitmap; ImageList: TCustomImageList; begin if (Assigned(ActionClient) and not ActionClient.HasGlyph) and ((Action is TCustomAction) and TCustomAction(Action).Checked) then begin if IsChecked then begin FrameRect := Rect(Location.X - 1, 1, Location.X + 20, Self.Height - 1); Canvas.Brush.Color := Menu.ColorMap.SelectedColor; Canvas.FillRect(FrameRect); Canvas.Pen.Color := ActionBar.ColorMap.BtnFrameColor; Canvas.Rectangle(FrameRect); end; Canvas.Pen.Color := ActionBar.ColorMap.FontColor; with Location do DrawCheck(Canvas, Point(X + 6, Y + 3), 2) end else begin if IsChecked then begin FrameRect := Rect(Location.X - 1, 1, Location.X + 20, Self.Height - 1); Canvas.Brush.Color := Menu.ColorMap.SelectedColor; Canvas.Pen.Color := ActionBar.ColorMap.BtnFrameColor; Canvas.Rectangle(FrameRect); end; OldColor := Canvas.Brush.Color; if (Selected and Enabled) or (Selected and not MouseSelected) then Canvas.Brush.Color := Menu.ColorMap.SelectedColor else Canvas.Brush.Color := Menu.ColorMap.ShadowColor; NewLocation := Location; if (Selected and Enabled and ActionClient.HasGlyph) then begin OldBrushColor := Canvas.Brush.Color; SelBmp := TBitmap.Create; try if Assigned(ActionClient.Action) and Assigned(ActionClient.Action.ActionList) then ImageList := ActionClient.Action.ActionList.Images else ImageList := ActionClient.OwningCollection.ActionManager.Images; if Assigned(ImageList) and ImageList.GetBitmap(ActionClient.ImageIndex, SelBmp) then begin Canvas.Brush.Color := GetShadowColor(Menu.ColorMap.SelectedColor); SelBmp.Width := ImageList.Width; SelBmp.Height := ImageList.Width; DrawState(Canvas.Handle, Canvas.Brush.Handle, nil, SelBmp.Handle, 0, NewLocation.X + 3, NewLocation.Y + 2, 0, 0, DST_BITMAP or DSS_MONO); end; finally SelBmp.Free; Canvas.Brush.Color := OldBrushColor; end; Inc(NewLocation.X, 1); inherited DrawGlyph(NewLocation); end else begin Inc(NewLocation.X, 2); Inc(NewLocation.Y, 1); inherited DrawGlyph(NewLocation); end; Canvas.Brush.Color := OldColor; end; end; procedure TXPStyleMenuItem.DrawSeparator(const Offset: Integer); var PaintRect: TRect; PR: TPenRecall; BR: TBrushRecall; begin if Selected then Canvas.FillRect(ClientRect); BR := TBrushRecall.Create(Canvas.Brush); PR := TPenRecall.Create(Canvas.Pen); try if Assigned(ActionClient) and ActionClient.Unused and not Transparent then Canvas.Brush.Style := bsSolid else begin Canvas.Brush.Color := Color; PaintRect := BoundsRect; Windows.DrawEdge(Canvas.Handle, PaintRect, BDR_RAISEDINNER, BF_LEFT); Windows.DrawEdge(Canvas.Handle, PaintRect, BDR_RAISEDINNER, BF_RIGHT); end; Canvas.Pen.Color := Menu.ColorMap.DisabledFontColor; Canvas.MoveTo(32, ClientHeight div 2); Canvas.LineTo(ClientWidth, ClientHeight div 2); finally BR.Free; PR.Free; end; end; type TCustomActionBarType = class(TCustomActionBar); procedure TXPStyleMenuItem.DrawShadowedText(Rect: TRect; Flags: Cardinal; Text: String; TextColor, ShadowColor: TColor); begin OffsetRect(Rect, 6, 0); inherited; end; procedure TXPStyleMenuItem.DrawSubMenuGlyph; const ArrowPos = 11; ArrowColor: array[Boolean] of Integer = (clBtnText, clWhite); begin inherited; with Canvas do begin Pen.Color := Menu.ColorMap.FontColor; Brush.Color := Pen.Color; end; DrawArrow(Canvas, sdRight, Point(Width - ArrowPos, Height div 2 - 3), 3); end; procedure TXPStyleMenuItem.DrawText(var Rect: TRect; var Flags: Cardinal; Text: String); begin OffsetRect(Rect, 6, 0); inherited DrawText(Rect, Flags, Text); end; procedure TXPStyleMenuItem.DrawUnusedEdges; begin end; { TXPStyleButton } type TActionMenuBarClass = class(TCustomActionMenuBar); procedure TXPStyleMenuButton.DrawBackground(var PaintRect: TRect); procedure DrawSelectedFrame; begin Canvas.Brush.Color := Menu.ColorMap.SelectedColor; Canvas.Pen.Color := ActionBar.ColorMap.BtnFrameColor; Canvas.Rectangle(0, 0, Width, Height); InflateRect(PaintRect, -1, -1); end; var Offset: TPoint; begin Canvas.Brush.Color := ActionBar.ColorMap.Color; if (ActionBar is TCustomActionMenuBar) and TCustomActionMenuBar(ActionBar).InMenuLoop then begin if Selected then if ActionClient.ChildActionBar = nil then begin if TActionMenuBarClass(Menu.RootMenu).PopupStack.Count = 1 then begin Canvas.Brush.Color := Menu.ColorMap.SelectedColor; DrawSelectedFrame; end; end else begin Canvas.Brush.Color := Menu.ColorMap.BtnSelectedColor; Canvas.Pen.Color := ActionBar.ColorMap.FrameTopLeftOuter; Canvas.Brush.Style := bsClear; Canvas.Rectangle(0, 0, Width, Height); Offset := Parent.ClientToScreen(BoundsRect.TopLeft); if Offset.Y >= ActionClient.ChildActionBar.BoundsRect.Bottom then Offset.Y := 0 else Offset.Y := Height - 1; Canvas.Pen.Color := ActionBar.ColorMap.BtnSelectedColor; Canvas.MoveTo(1, Offset.Y); Canvas.LineTo(Width - 1, Offset.Y); InflateRect(PaintRect, -1 , -1); end; end else if MouseInControl then DrawSelectedFrame; inherited DrawBackground(PaintRect); end; procedure TXPStyleMenuButton.DrawText(var ARect: TRect; var Flags: Cardinal; Text: String); begin OffsetRect(ARect, 1, 0); inherited DrawText(ARect, Flags, Text); end; { TXPStylePopupMenu } constructor TXPStylePopupMenu.Create(AOwner: TComponent); begin inherited Create(AOwner); VertMargin := 0; end; destructor TXPStylePopupMenu.Destroy; begin FreeAndNil(FBtnShadow); inherited; end; procedure TXPStylePopupMenu.DisplayShadow; begin inherited; if not Shadow or DesignMode then exit; if Assigned(ActionClient) and (ActionClient is TActionClientItem) and (TActionClientItem(ActionClient).Control is TCustomMenuButton) then if not Assigned(FBtnShadow) then FBtnShadow := TShadowWindow.CreateShadow(Self, csRight); if Assigned(FBtnShadow) then FBtnShadow.Control := TActionClientItem(ActionClient).Control; end; function TXPStylePopupMenu.GetExpandBtnClass: TCustomMenuExpandBtnClass; begin Result := TXPStyleExpandBtn; end; procedure TXPStylePopupMenu.HideShadow; begin inherited; if Assigned(FBtnShadow) then FBtnShadow.Hide; end; procedure TXPStylePopupMenu.NCPaint(DC: HDC); var RC, RW: TRect; OldHandle: THandle; Offset: TPoint; begin Windows.GetClientRect(Handle, RC); GetWindowRect(Handle, RW); MapWindowPoints(0, Handle, RW, 2); OffsetRect(RC, -RW.Left, -RW.Top); ExcludeClipRect(DC, RC.Left, RC.Top, RC.Right, RC.Bottom); { Draw border in non-client area } OffsetRect(RW, -RW.Left, -RW.Top); OldHandle := Canvas.Handle; try Canvas.Handle := DC; Canvas.Pen.Width := 1; Canvas.Pen.Color := ColorMap.FrameTopLeftOuter; Canvas.MoveTo(RW.Right, RW.Top); Canvas.LineTo(RW.Left, Rw.Top); Canvas.LineTo(RW.Left, RW.Bottom); Canvas.Pen.Color := ColorMap.FrameTopLeftInner; Canvas.MoveTo(RW.Right - 1, RW.Top + 1); Canvas.LineTo(RW.Left + 1, Rw.Top + 1); Canvas.LineTo(RW.Left + 1, RW.Bottom - 2); Canvas.Pen.Color := ColorMap.FrameBottomRightOuter; Canvas.MoveTo(RW.Right - 1, RW.Top); Canvas.LineTo(RW.Right - 1, RW.Bottom - 1); Canvas.LineTo(RW.Left - 1, RW.Bottom - 1); Canvas.Pen.Color := ColorMap.FrameBottomRightInner; Canvas.MoveTo(RW.Right - 2, RW.Top + 1); Canvas.LineTo(RW.Right - 2, RW.Bottom - 2); Canvas.LineTo(RW.Left, RW.Bottom - 2); if Assigned(ActionClient) and (ColorMap.BtnSelectedColor <> ColorMap.FrameTopLeftOuter) and (ParentControl is TXPStyleMenuButton) then begin Offset := ParentControl.Parent.ClientToScreen(ParentControl.BoundsRect.TopLeft); if BoundsRect.Bottom <= Offset.Y then Offset.Y := RW.Bottom - 1 else Offset.Y := 0; Canvas.MoveTo(Offset.X - Left + 1, Offset.Y); Canvas.Pen.Color := ColorMap.BtnSelectedColor; Canvas.LineTo(Offset.X - Left + ParentControl.Width - 1, Offset.Y); end; finally Canvas.Handle := OldHandle; end; end; procedure TXPStylePopupMenu.PositionPopup(AnOwner: TCustomActionBar; ParentItem: TCustomActionControl); begin inherited PositionPopup(AnOwner, ParentItem); if (ParentItem is TCustomMenuItem) and (Left > ParentItem.Parent.BoundsRect.Left) then Left := ParentItem.Parent.BoundsRect.Right - 1 else if ParentItem is TCustomMenuButton and (Left > ParentItem.BoundsRect.Left) then Left := Left - 1; end; procedure TXPStylePopupMenu.VisibleChanging; begin if ParentControl is TCustomButtonControl then ParentControl.Invalidate; inherited; end; { TXPStyleExpandBtn } procedure TXPStyleExpandBtn.DrawBackground(var PaintRect: TRect); var BannerRect: TRect; begin Canvas.Brush.Color := Menu.ColorMap.MenuColor; Canvas.FillRect(PaintRect); BannerRect := PaintRect; BannerRect.Right := 24; Canvas.Brush.Color := Menu.ColorMap.BtnSelectedColor; Canvas.FillRect(BannerRect); if ((FState = bsDown) or not Flat or MouseInControl or IsChecked) then begin OffsetRect(PaintRect, 0, 1); InflateRect(PaintRect, -2, -4); Canvas.Brush.Color := Menu.ColorMap.SelectedColor; Canvas.FillRect(PaintRect); end; end; procedure TXPStyleExpandBtn.DrawFrame(ARect: TRect; Down: Boolean); begin if Enabled and ((FState = bsDown) or not Flat or MouseInControl or IsChecked) then begin OffsetRect(ARect, 0, 1); InflateRect(ARect, -2, -4); Canvas.Pen.Color := ActionBar.ColorMap.BtnFrameColor; Canvas.Rectangle(ARect); end; end; { TXPStyleButton } procedure TXPStyleButton.DrawBackground(var PaintRect: TRect); begin if Enabled and not (ActionBar.DesignMode) then begin if (MouseInControl or IsChecked) and (Assigned(ActionClient) and not ActionClient.Separator) then Canvas.Brush.Color := ActionBar.ColorMap.SelectedColor else Canvas.Brush.Color := ActionBar.ColorMap.Color; end else Canvas.Brush.Color := ActionBar.ColorMap.Color; inherited DrawBackground(PaintRect); end; procedure TXPStyleButton.DrawFrame(ARect: TRect; Down: Boolean); begin if not ActionBar.DesignMode and Enabled and ((FState = bsDown) or not Flat or MouseInControl or IsChecked) then begin Canvas.Pen.Color := ActionBar.ColorMap.BtnFrameColor; Canvas.Brush.Style := bsClear; Canvas.Rectangle(ARect); end; end; procedure TXPStyleButton.DrawGlyph(const Location: TPoint); var OldBrushColor: TColor; SelBmp: TBitmap; NewLocation: TPoint; ActionList: TCustomActionList; begin NewLocation := Location; if not ActionBar.DesignMode and MouseInControl and not IsChecked and Enabled and ActionClient.HasGlyph then begin OldBrushColor := Canvas.Brush.Color; SelBmp := TBitmap.Create; try ActionList := ActionClient.Action.ActionList; if ActionList.Images.GetBitmap(ActionClient.ImageIndex, SelBmp) then begin Canvas.Brush.Color := GetShadowColor(ActionBar.ColorMap.SelectedColor); SelBmp.Width := ActionList.Images.Width; SelBmp.Height := ActionList.Images.Width; DrawState(Canvas.Handle, Canvas.Brush.Handle, nil, SelBmp.Handle, 0, NewLocation.X + 1, NewLocation.Y + 1, 0, 0, DST_BITMAP or DSS_MONO); end; finally SelBmp.Free; Canvas.Brush.Color := OldBrushColor; end; if not IsChecked then begin Dec(NewLocation.X); Dec(NewLocation.Y); end; end; if not (csDesigning in ComponentState) and ((FState = bsDown) and not IsChecked) and IsMouseButtonPressed then begin Inc(NewLocation.X); Inc(NewLocation.Y); end; inherited DrawGlyph(NewLocation); end; procedure TXPStyleButton.DrawText(var ARect: TRect; var Flags: Cardinal; Text: String); begin if MouseInControl and (ActionBar.ColorMap.HotFontColor <> clDefault) then Canvas.Font.Color := ActionBar.ColorMap.HotFontColor; inherited; end; { TXPStyleDropDownBtn } procedure TXPStyleDropDownBtn.DrawBackground(var PaintRect: TRect); begin if Enabled and not (ActionBar.DesignMode) then begin if (MouseInControl or IsChecked) and Assigned(ActionClient) then Canvas.Brush.Color := ActionBar.ColorMap.SelectedColor else Canvas.Brush.Color := ActionBar.ColorMap.Color; end else Canvas.Brush.Color := ActionBar.ColorMap.Color; inherited DrawBackground(PaintRect); end; procedure TXPStyleDropDownBtn.DrawFrame(ARect: TRect; Down: Boolean); begin if Enabled and not (ActionBar.DesignMode) then if (MouseInControl or IsChecked) and Assigned(ActionClient) then begin Canvas.Pen.Color := ActionBar.ColorMap.BtnFrameColor; Dec(ARect.Right, 9); Canvas.Rectangle(ARect); ARect.Left := ARect.Right - 1; Inc(ARect.Right, 9); Canvas.Rectangle(ARect); end; end; procedure TXPStyleDropDownBtn.DrawGlyph(const Location: TPoint); var OldBrushColor: TColor; SelBmp: TBitmap; NewLocation: TPoint; ActionList: TCustomActionList; begin NewLocation := Location; if not ActionBar.DesignMode and MouseInControl and not IsChecked and Enabled and ActionClient.HasGlyph then begin OldBrushColor := Canvas.Brush.Color; SelBmp := TBitmap.Create; try ActionList := TAction(Action).ActionList; if ActionList.Images.GetBitmap(ActionClient.ImageIndex, SelBmp) then begin Canvas.Brush.Color := GetShadowColor(ActionBar.ColorMap.SelectedColor); SelBmp.Width := ActionList.Images.Width; SelBmp.Height := ActionList.Images.Width; DrawState(Canvas.Handle, Canvas.Brush.Handle, nil, SelBmp.Handle, 0, NewLocation.X + 1, NewLocation.Y + 1, 0, 0, DST_BITMAP or DSS_MONO); end; finally SelBmp.Free; Canvas.Brush.Color := OldBrushColor; end; if not IsChecked then begin Dec(NewLocation.X); Dec(NewLocation.Y); end; end; if not (csDesigning in ComponentState) and ((FState = bsDown) and not IsChecked) and IsMouseButtonPressed then begin Inc(NewLocation.X); Inc(NewLocation.Y); end; inherited DrawGlyph(NewLocation); end; function TXPStyleDropDownBtn.GetPopupClass: TCustomActionBarClass; begin Result := TXPStylePopupMenu; end; { TXPStyleCustomizePopup } constructor TXPStyleCustomizePopup.Create(AOwner: TComponent); begin inherited Create(AOwner); VertMargin := 0; end; function TXPStyleCustomizePopup.GetAddRemoveItemClass: TCustomAddRemoveItemClass; begin Result := TXPStyleAddRemoveItem; end; function TXPStyleCustomizePopup.GetDefaultColorMapClass: TCustomColorMapClass; begin Result := TXPColorMap; end; procedure TXPStyleCustomizePopup.NCPaint(DC: HDC); var RC, RW: TRect; begin Windows.GetClientRect(Handle, RC); GetWindowRect(Handle, RW); MapWindowPoints(0, Handle, RW, 2); OffsetRect(RC, -RW.Left, -RW.Top); ExcludeClipRect(DC, RC.Left, RC.Top, RC.Right, RC.Bottom); { Draw border in non-client area } OffsetRect(RW, -RW.Left, -RW.Top); try Canvas.Handle := DC; Canvas.Pen.Color := ColorMap.FrameTopLeftOuter; Canvas.Brush.Color := ColorMap.Color; Canvas.Rectangle(RW); Canvas.Pen.Color := ColorMap.BtnSelectedColor; Canvas.MoveTo(1,1); Canvas.LineTo(1, Height - 1); finally IntersectClipRect(Canvas.Handle, RW.Left, RW.Top, RW.Right, RW.Bottom); Canvas.Handle := 0; end; end; { TXPStyleAddRemoveItem } procedure TXPStyleAddRemoveItem.CalcBounds; begin inherited; if Separator then Height := 3 else Height := Height + 2; end; procedure TXPStyleAddRemoveItem.DrawBackground(var PaintRect: TRect); var BannerRect: TRect; BGRect: TRect; begin if ActionClient = nil then exit; if ActionClient.Color <> clDefault then Canvas.Brush.Color := ActionClient.Color; BGRect := PaintRect; if TextBounds.Left > GlyphPos.X then BGRect.Left := 0; BannerRect := PaintRect; if TextBounds.Left > GlyphPos.X then BannerRect.Right := TextBounds.Left - 3 else BannerRect.Right := TextBounds.Right + 3; BannerRect.Right := 44; BGRect.Left := BannerRect.Right - BannerRect.Left; if ActionClient.Unused then Canvas.Brush.Color := Menu.ColorMap.UnusedColor else Canvas.Brush.Color := Menu.ColorMap.BtnSelectedColor; inherited DrawBackground(BannerRect); Canvas.Brush.Color := Menu.ColorMap.MenuColor; if ((Selected and Enabled) or (Selected and not MouseSelected)) then begin Canvas.Brush.Color := Menu.ColorMap.SelectedColor; Dec(PaintRect.Right, 1); end; inherited DrawBackground(BGRect); if (Selected and Enabled) or (Selected and not MouseSelected) then begin Canvas.FillRect(PaintRect); Canvas.Brush.Color := ActionBar.ColorMap.BtnFrameColor; Canvas.FrameRect(PaintRect); end; end; procedure TXPStyleAddRemoveItem.DrawGlyph(const Location: TPoint); var OldColor, OldBrushColor: TColor; NewLocation: TPoint; FrameRect: TRect; SelBmp: TBitmap; ActionList: TCustomActionList; begin if (Assigned(ActionClient) and not ActionClient.HasGlyph) and ((Action is TCustomAction) and TCustomAction(Action).Checked) then begin if IsChecked then begin FrameRect := Rect(Location.X - 1, 1, Location.X + 20, Self.Height - 1); Canvas.Brush.Color := Menu.ColorMap.SelectedColor; Canvas.FillRect(FrameRect); Canvas.Pen.Color := ActionBar.ColorMap.BtnFrameColor; Canvas.Rectangle(FrameRect); end; Canvas.Pen.Color := Menu.ColorMap.FontColor; with Location do DrawCheck(Canvas, Point(X + 6, Y + 3), 2) end else begin if IsChecked then begin FrameRect := Rect(Location.X - 1, 1, Location.X + 20, Self.Height - 1); Canvas.Brush.Color := Menu.ColorMap.SelectedColor; Canvas.Pen.Color := ActionBar.ColorMap.BtnFrameColor; Canvas.Rectangle(FrameRect); end; OldColor := Canvas.Brush.Color; if (Selected and Enabled) or (Selected and not MouseSelected) then Canvas.Brush.Color := Menu.ColorMap.SelectedColor else Canvas.Brush.Color := Menu.ColorMap.BtnSelectedColor; NewLocation := Location; if (Selected and Enabled and ActionClient.HasGlyph) then begin OldBrushColor := Canvas.Brush.Color; SelBmp := TBitmap.Create; try Canvas.Brush.Color := clBtnShadow; ActionList := TAction(Action).ActionList; if ActionList.Images.GetBitmap(ActionClient.ImageIndex, SelBmp) then begin SelBmp.Width := ActionList.Images.Width; SelBmp.Height := ActionList.Images.Width; DrawState(Canvas.Handle, Canvas.Brush.Handle, nil, SelBmp.Handle, 0, NewLocation.X + 3, NewLocation.Y + 2, 0, 0, DST_BITMAP or DSS_MONO); end; finally SelBmp.Free; Canvas.Brush.Color := OldBrushColor; end; Inc(NewLocation.X, 1); inherited DrawGlyph(NewLocation); end else begin Inc(NewLocation.X, 2); Inc(NewLocation.Y, 1); inherited DrawGlyph(NewLocation); end; Canvas.Brush.Color := OldColor; end; if Menu.RootMenu.ParentControl.ActionBar.ActionClient.Items[ActionClient.Index].Visible then begin FrameRect := Rect(2 - 1, 1, 18, Self.Height - 1); Canvas.Brush.Color := Menu.ColorMap.SelectedColor; Canvas.FillRect(FrameRect); Canvas.Pen.Color := ActionBar.ColorMap.BtnFrameColor; Canvas.Rectangle(FrameRect); Canvas.Pen.Color := Menu.ColorMap.FontColor; with Location do DrawCheck(Canvas, Point(FrameRect.Left + 5, Self.Height div 2 - 1), 2); end; end; procedure TXPStyleAddRemoveItem.DrawSeparator(const Offset: Integer); var PaintRect: TRect; PR: TPenRecall; BR: TBrushRecall; begin if Selected then Canvas.FillRect(ClientRect); BR := TBrushRecall.Create(Canvas.Brush); PR := TPenRecall.Create(Canvas.Pen); try if Assigned(ActionClient) and ActionClient.Unused and not Transparent then Canvas.Brush.Style := bsSolid else begin Canvas.Brush.Color := Color; PaintRect := BoundsRect; Windows.DrawEdge(Canvas.Handle, PaintRect, BDR_RAISEDINNER, BF_LEFT); Windows.DrawEdge(Canvas.Handle, PaintRect, BDR_RAISEDINNER, BF_RIGHT); end; Canvas.Pen.Color := clBtnShadow; Canvas.MoveTo(32, ClientHeight div 2); Canvas.LineTo(ClientWidth, ClientHeight div 2); finally BR.Free; PR.Free; end; end; procedure TXPStyleAddRemoveItem.DrawText(var Rect: TRect; var Flags: Cardinal; Text: String); var S: string; begin S := Text; if Parent is TCustomActionBar then if not TCustomActionBarType(Parent).PersistentHotkeys then begin if Pos('&', S) > 0 then Delete(S, Pos('&', S), 1); end; Text := S; OffsetRect(Rect, 6, 0); if Enabled then Canvas.Font.Color := Menu.ColorMap.FontColor else Canvas.Font.Color := Menu.ColorMap.DisabledFontColor; inherited DrawText(Rect, Flags, Text); end; procedure TXPStyleAddRemoveItem.DrawUnusedEdges; begin // This style of menu item does not have unused edges end; { TXPStyleToolScrollBtn } procedure TXPStyleToolScrollBtn.DrawBackground(var PaintRect: TRect); begin if Enabled and MouseInControl then Canvas.Brush.Color := ActionBar.ColorMap.SelectedColor else Canvas.Brush.Color := ActionBar.ColorMap.Color; inherited DrawBackground(PaintRect); if Enabled and MouseInControl then begin Canvas.Pen.Color := ActionBar.ColorMap.BtnFrameColor; Canvas.Rectangle(ClientRect); end; end; end.
unit Test.Devices.Base.ReqParser; interface uses Windows, TestFrameWork, GMGlobals, Threads.ResponceParser, GMBlockValues; type TResponceParserThreadForTest = class(TResponceParserThread) protected procedure Execute; override; end; TSQLWriteThreadForTestClass = class of TResponceParserThreadForTest; TDeviceReqParserTestBase = class(TTestCase) protected thread: TResponceParserThreadForTest; gbv: TGeomerBlockValues; procedure SetUp; override; procedure TearDown; override; function GetDevType(): int; virtual; abstract; function GetThreadClass(): TSQLWriteThreadForTestClass; virtual; function RecognizeAndCheckChannel(): TRecognizeChannelResult; end; implementation { TDeviceReqParserTestBase } function TDeviceReqParserTestBase.GetThreadClass: TSQLWriteThreadForTestClass; begin Result := TResponceParserThreadForTest; end; function TDeviceReqParserTestBase.RecognizeAndCheckChannel: TRecognizeChannelResult; begin Result := thread.RecognizeAndCheckChannel(gbv); end; procedure TDeviceReqParserTestBase.SetUp; begin inherited; gbv := TGeomerBlockValues.Create(); gbv.gbt := gbt485; gbv.gmTime := NowGM(); gbv.ReqDetails.ClearReqLink(); gbv.ReqDetails.ID_Device := 1000 + GetDevType(); gbv.ReqDetails.ID_DevType := GetDevType(); gbv.ReqDetails.DevNumber := GetDevType(); thread := GetThreadClass().Create(nil); thread.ChannelIDs.ID_Device := gbv.ReqDetails.ID_Device; thread.ChannelIDs.ID_DevType := gbv.ReqDetails.ID_DevType; thread.ChannelIDs.NDevNumber := gbv.ReqDetails.DevNumber; end; procedure TDeviceReqParserTestBase.TearDown; begin inherited; thread.Free(); gbv.Free(); end; { TSQLWriteThreadForTest } procedure TResponceParserThreadForTest.Execute; begin end; end.
unit BCEditor.Editor.SpecialChars.Selection; interface uses Classes, Graphics; type TBCEditorSpecialCharsSelection = class(TPersistent) strict private FColor: TColor; FOnChange: TNotifyEvent; FVisible: Boolean; procedure DoChange; procedure SetColor(const Value: TColor); procedure SetVisible(const Value: Boolean); public constructor Create; procedure Assign(Source: TPersistent); override; published property Color: TColor read FColor write SetColor default clBlack; property OnChange: TNotifyEvent read FOnChange write FOnChange; property Visible: Boolean read FVisible write SetVisible default False; end; implementation { TBCEditorSpecialCharsSelection } constructor TBCEditorSpecialCharsSelection.Create; begin inherited; FColor := clBlack; FVisible := False; end; procedure TBCEditorSpecialCharsSelection.Assign(Source: TPersistent); begin if Assigned(Source) and (Source is TBCEditorSpecialCharsSelection) then with Source as TBCEditorSpecialCharsSelection do begin Self.FColor := FColor; Self.FVisible := FVisible; Self.DoChange; end else inherited Assign(Source); end; procedure TBCEditorSpecialCharsSelection.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TBCEditorSpecialCharsSelection.SetColor(const Value: TColor); begin if Value <> FColor then begin FColor := Value; DoChange; end; end; procedure TBCEditorSpecialCharsSelection.SetVisible(const Value: Boolean); begin if Value <> FVisible then begin FVisible := Value; DoChange; end; end; end.
{******************************************} { TeeChart Pro ScrollBar component } { Copyright (c) 1997-2004 by David Berneda } { All Rights Reserved } {******************************************} unit TeeScroB; {$I TeeDefs.inc} interface { This unit implements the TChartScrollBar component. This is a specialized TScrollBar component to scroll Series points. Note: Do not modify the "Min" and "Max" properties of the ScrollBar, because they are overriden and calculated internally. Use the Axis Minimum and Maximum properties to change the ScrollBar position. } uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QControls, QStdCtrls, QForms, {$ELSE} Controls, StdCtrls, Forms, {$ENDIF} TeEngine, Chart; Const TeeMaxScrollPos=30000; type { Depending if the ScrollBar is Horizontal or Vertical: sbDefault: means Left or Bottom axis sbOther : means Right or Top axis sbBoth : (default) means Left and Bottom , or Right and Top axis } TScrollBarAxis=(sbDefault,sbOther,sbBoth); TChartScrollBar = class(TScrollBar) private { Private declarations } FAxis : TScrollBarAxis; FChart : TCustomChart; FInverted : Boolean; FOldOnPageChange:TNotifyEvent; FOldOnScroll : TNotifyEvent; FOldOnZoom : TNotifyEvent; FOldOnUndoZoom : TNotifyEvent; FPageSize : Integer; procedure SetPageSize(Value:Integer); Procedure SetChart(Value:TCustomChart); Procedure SetInverted(Value:Boolean); Procedure ChartOnPageChange(Sender:TObject); Procedure ChartOnScroll(Sender:TObject); Procedure ChartOnZoom(Sender:TObject); Procedure ChartOnUndoZoom(Sender:TObject); Procedure CalcTotals(Axis:TChartAxis; Var AMin,AMax:Double); protected { Protected declarations } Function AssociatedSeries(Axis:TChartAxis):Integer; procedure Change; override; procedure Notification( AComponent: TComponent; Operation: TOperation); override; public { Public declarations } constructor Create(AOwner : TComponent); override; Procedure RecalcPosition; published { Published declarations } property Align; property Axis:TScrollBarAxis read FAxis write FAxis default sbBoth; property Chart:TCustomChart read FChart write SetChart; property Enabled default False; property Inverted:Boolean read FInverted write SetInverted default False; property LargeChange default 500; property Max default TeeMaxScrollPos; property SmallChange default 50; property PageSize:integer read FPageSize write SetPageSize; end; implementation { TChartScrollBar } Constructor TChartScrollBar.Create(AOwner : TComponent); begin inherited; FAxis:=sbBoth; SetParams(0,0,TeeMaxScrollPos); LargeChange:=TeeMaxScrollPos div 10; SmallChange:=TeeMaxScrollPos div 100; Enabled:=False; FInverted:=False; end; { How many Series are associated to this Axis? } Function TChartScrollBar.AssociatedSeries(Axis:TChartAxis):Integer; var t : Integer; begin result:=0; With Axis.ParentChart do for t:=0 to SeriesCount-1 do if Series[t].AssociatedToAxis(Axis) then Inc(result); end; { When the ScrollBar changes, change the Chart Axis min and max } procedure TChartScrollBar.Change; var tmpPos : Integer; Procedure ScrollAxis(Axis:TChartAxis); var MidRange : Double; Middle : Double; TotalMin : Double; TotalMax : Double; begin if AssociatedSeries(Axis)>0 then begin if FChart.MaxPointsPerPage>0 then FChart.Page:=tmpPos else if not Axis.Automatic then begin tmpPos:=tmpPos+(FPageSize div 2); CalcTotals(Axis,TotalMin,TotalMax); Middle:=(TotalMax-TotalMin)*tmpPos/(Max-Min); MidRange:=(Axis.Maximum-Axis.Minimum)*0.5; Axis.SetMinMax(Middle-MidRange,Middle+MidRange); end; end; end; begin inherited; if Assigned(FChart) then if Kind=sbHorizontal then begin if Inverted then tmpPos:=Max-Position else tmpPos:=Position; if (FAxis=sbBoth) or (FAxis=sbDefault) then ScrollAxis(FChart.BottomAxis); if (FAxis=sbBoth) or (FAxis=sbOther) then ScrollAxis(FChart.TopAxis); end else begin if Inverted then tmpPos:=Position else tmpPos:=Max-Position; if (FAxis=sbBoth) or (FAxis=sbDefault) then ScrollAxis(FChart.LeftAxis); if (FAxis=sbBoth) or (FAxis=sbOther) then ScrollAxis(FChart.RightAxis); end; end; { When the Chart is removed at design-time or run-time } procedure TChartScrollBar.Notification( AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation=opRemove) and Assigned(FChart) and (AComponent=FChart) then Chart:=nil; end; Procedure TChartScrollBar.ChartOnPageChange(Sender:TObject); begin RecalcPosition; if Assigned(FOldOnPageChange) then FOldOnPageChange(FChart); end; { When the user scrolls the chart using the right mouse button } Procedure TChartScrollBar.ChartOnScroll(Sender:TObject); begin RecalcPosition; if Assigned(FOldOnScroll) then FOldOnScroll(FChart); end; { When the user zooms the chart using the left mouse button } Procedure TChartScrollBar.ChartOnZoom(Sender:TObject); begin RecalcPosition; if Assigned(FOldOnZoom) then FOldOnZoom(FChart); end; { When the user undoes any previous zoom using the left mouse button } Procedure TChartScrollBar.ChartOnUndoZoom(Sender:TObject); begin RecalcPosition; if Assigned(FOldOnUndoZoom) then FOldOnUndoZoom(FChart); end; { Calculate the lowest and highest possible values for the Axis } Procedure TChartScrollBar.CalcTotals(Axis:TChartAxis; Var AMin,AMax:Double); Var OldAuto : Boolean; OldMin : Double; OldMax : Double; // tmp : Double; begin OldAuto:=Axis.Automatic; OldMin:=Axis.Minimum; OldMax:=Axis.Maximum; Axis.Automatic:=True; try Axis.CalcMinMax(AMin,AMax); { tmp:=(Axis.Maximum-Axis.Minimum)*0.5; AMax:=AMax-tmp; AMin:=AMin+tmp;} finally Axis.Automatic:=OldAuto; if not Axis.Automatic then Axis.SetMinMax(OldMin,OldMax); end; end; { Change the scroll bar position and thumb size } Procedure TChartScrollBar.RecalcPosition; Procedure RecalcAxis(Axis:TChartAxis); var Range : Double; TotalMax : Double; TotalMin : Double; Middle : Double; tmpPosition : Integer; begin if AssociatedSeries(Axis)>0 then begin if FChart.MaxPointsPerPage>0 then begin Min:=1; Max:=FChart.NumPages; SmallChange:=1; LargeChange:=1; Position:=FChart.Page; PageSize:=1; end else if Axis.Automatic then { no scrolling } begin Position:=(Min+Max) div 2; { center scroll } PageSize:=Max-Min+1; end else begin CalcTotals(Axis,TotalMin,TotalMax); Range:=TotalMax-TotalMin; if Range>MinAxisRange then { 5.02 } begin Middle:=(Axis.Minimum+Axis.Maximum)*0.5; tmpPosition:=Round(Max*(Middle-TotalMin)/Range); if tmpPosition>Max then tmpPosition:=Max; if tmpPosition<Min then tmpPosition:=Min; if ((Kind=sbVertical) and (not FInverted)) or ((Kind=sbHorizontal) and (FInverted)) then tmpPosition:=Max-tmpPosition; PageSize:=Round((Axis.Maximum-Axis.Minimum)*(Max-Min)/Range); Position:=tmpPosition-(PageSize div 2); end; end; end; end; Procedure RecalcAxes(Axis1,Axis2:TChartAxis); begin if (FAxis=sbBoth) or (FAxis=sbDefault) then RecalcAxis(Axis1); if (FAxis=sbBoth) or (FAxis=sbOther) then RecalcAxis(Axis2); end; begin if Assigned(FChart) then With FChart do if Kind=sbHorizontal then RecalcAxes(BottomAxis,TopAxis) else RecalcAxes(LeftAxis,RightAxis); end; Procedure TChartScrollBar.SetChart(Value:TCustomChart); begin if FChart<>Value then begin FChart:=Value; if Assigned(FChart) then begin FOldOnPageChange:=FChart.OnPageChange; FChart.OnPageChange:=ChartOnPageChange; FOldOnScroll:=FChart.OnScroll; FChart.OnScroll:=ChartOnScroll; FOldOnZoom:=FChart.OnZoom; FChart.OnZoom:=ChartOnZoom; FOldOnUndoZoom:=FChart.OnUndoZoom; FChart.OnUndoZoom:=ChartOnUndoZoom; FChart.FreeNotification(Self); Enabled:=FChart.SeriesCount>0; RecalcPosition; end else begin Enabled:=False; FOldOnScroll:=nil; FOldOnZoom:=nil; FOldOnUndoZoom:=nil; FOldOnPageChange:=nil; end; end; end; Procedure TChartScrollBar.SetInverted(Value:Boolean); begin if FInverted<>Value then begin FInverted:=Value; RecalcPosition; end; end; { Change the scroll bar thumb size } procedure TChartScrollbar.SetPageSize(Value:Integer); {$IFDEF CLX} begin end; {$ELSE} var tmp : TScrollInfo; begin if FPageSize<>Value then begin FPageSize:=Value; tmp.nPage:=FPageSize; tmp.fMask:=SIF_PAGE; SetScrollInfo(Handle,SB_CTL,tmp,True); end; end; {$ENDIF} end.
unit ANovoPedidoCompra; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, PainelGradiente, ExtCtrls, Componentes1, StdCtrls, Buttons, Mask, Localizacao, ComCtrls, Grids, CGrades, UnDados, DBKeyViolation, UnPedidoCompra, numericos, FunData, UnDadosProduto, Constantes, Menus, Db, DBTables, UnSolicitacaoCompra, DBGrids, Tabela, IdBaseComponent, IdComponent, IdTCPConnection, UnDadosLocaliza, IdTCPClient, IdMessageClient, IdSMTP, FMTBcd, DBClient, SqlExpr, unOrcamentoCompra; type TFNovoPedidoCompra = class(TFormularioPermissao) PanelColor1: TPanelColor; PainelGradiente1: TPainelGradiente; BCadastrar: TBitBtn; BGravar: TBitBtn; BCancelar: TBitBtn; BEnviar: TBitBtn; BImprimir: TBitBtn; BFechar: TBitBtn; Localiza: TConsultaPadrao; ValidaGravacao: TValidaGravacao; PopupMenu1: TPopupMenu; VisualizarOrdemProduo1: TMenuItem; Aux: TSQLQuery; Estagios: TSQL; DataEstagios: TDataSource; EstagiosDATESTAGIO: TSQLTimeStampField; EstagiosDESMOTIVO: TWideStringField; EstagiosNOMEST: TWideStringField; EstagiosC_NOM_USU: TWideStringField; PageControl1: TPageControl; PPedidos: TTabSheet; PEstagio: TTabSheet; ScrollBox1: TScrollBox; GEstagios: TGridIndice; PopupMenu2: TPopupMenu; AdicionarTodososProdutosdoFornecedor1: TMenuItem; PanelColor4: TPanelColor; PanelCabecalho: TPanelColor; Label1: TLabel; Label2: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; BFornecedor: TSpeedButton; LFornecedor: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; LFilial: TLabel; BCondicoesPgto: TSpeedButton; LCondicoesPagto: TLabel; BFormaPagto: TSpeedButton; LFormaPagamento: TLabel; Label3: TLabel; LUsuario: TLabel; Bevel1: TBevel; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; Label14: TLabel; Label15: TLabel; Label19: TLabel; SpeedButton4: TSpeedButton; Label20: TLabel; Label21: TLabel; Label22: TLabel; Label23: TLabel; SpeedButton3: TSpeedButton; LDataRenegociado: TLabel; ENumero: TEditColor; EData: TMaskEditColor; EPrazo: TMaskEditColor; EFornecedor: TEditLocaliza; EContato: TEditColor; ECondicoesPagto: TEditLocaliza; EFormaPagto: TEditLocaliza; EHora: TMaskEditColor; EEmailComprador: TEditColor; EFilial: TEditLocaliza; EUsuario: TEditLocaliza; EComprador: TEditLocaliza; ETelefone: TEditColor; EFilialFaturamento: TEditLocaliza; EDatRenegociado: TMaskEditColor; PanelColor2: TPanelColor; Paginas: TPageControl; PProdutos: TTabSheet; ECor: TEditLocaliza; PFracaoOP: TTabSheet; GFracaoOP: TRBStringGridColor; PanelColor3: TPanelColor; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label16: TLabel; Label17: TLabel; Label18: TLabel; Label24: TLabel; Label25: TLabel; EObservacoes: TMemoColor; RDesconto: TRadioGroup; RTipoDesconto: TRadioGroup; EValTotal: Tnumerico; EValor: Tnumerico; EValorFrete: Tnumerico; EValProdutos: Tnumerico; EValIPI: Tnumerico; Label26: TLabel; SpeedButton5: TSpeedButton; LTransportadora: TLabel; ECodTransportadora: TRBEditLocaliza; Label28: TLabel; CEmitente: TRadioButton; CDestinatario: TRadioButton; ETamanho: TRBEditLocaliza; MImprimir: TPopupMenu; ExportarPDF1: TMenuItem; SaveDialog: TSaveDialog; CPedidoCompra: TRadioButton; CTerceirizacao: TRadioButton; BProdutosTerceirizados: TBitBtn; N1: TMenuItem; ImprimePedidoTerceirizao1: TMenuItem; PFracoes: TPanelColor; GMateriaPrima: TRBStringGridColor; PanelColor6: TPanelColor; PanelColor7: TPanelColor; GProdutos: TRBStringGridColor; PTituloMateriaPrima: TPanelColor; Label30: TLabel; Label29: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure BGravarClick(Sender: TObject); procedure GProdutosCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GProdutosDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure GProdutosGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); procedure GProdutosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ECorRetorno(Retorno1, Retorno2: String); procedure GProdutosKeyPress(Sender: TObject; var Key: Char); procedure GProdutosMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure GProdutosNovaLinha(Sender: TObject); procedure GProdutosSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure GFracaoOPCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GFracaoOPDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure GFracaoOPGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); procedure GFracaoOPMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure GFracaoOPNovaLinha(Sender: TObject); procedure EFornecedorRetorno(Retorno1, Retorno2: String); procedure RTipoDescontoClick(Sender: TObject); procedure EFornecedorChange(Sender: TObject); procedure EFornecedorCadastrar(Sender: TObject); procedure BImprimirClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EValorChange(Sender: TObject); procedure EFornecedorEnter(Sender: TObject); procedure BCadastrarClick(Sender: TObject); procedure VisualizarOrdemProduo1Click(Sender: TObject); procedure PageControl1Change(Sender: TObject); procedure GFracaoOPSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure ECompradorCadastrar(Sender: TObject); procedure BEnviarClick(Sender: TObject); procedure EEmailCompradorKeyPress(Sender: TObject; var Key: Char); procedure EFornecedorAlterar(Sender: TObject); procedure AdicionarTodososProdutosdoFornecedor1Click(Sender: TObject); procedure ECodTransportadoraCadastrar(Sender: TObject); procedure ETamanhoRetorno(VpaColunas: TRBColunasLocaliza); procedure EContatoChange(Sender: TObject); procedure ExportarPDF1Click(Sender: TObject); procedure BProdutosTerceirizadosClick(Sender: TObject); procedure CPedidoCompraClick(Sender: TObject); procedure ImprimePedidoTerceirizao1Click(Sender: TObject); procedure GMateriaPrimaCarregaItemGrade(Sender: TObject; VpaLinha: Integer); private VprAcao, VprIndSolicitacaoCompra, VprIndMapaCompras : Boolean; VprOperacao: TRBDOperacaoCadastro; VprCorAnterior, VprFornecedorAnterior, VprProdutoAnterior: String; VprTransacao : TTransactionDesc; VprProdutosPendentes, VprProdutosFinalizados : Tlist; VprDPedidoCorpo: TRBDPedidoCompraCorpo; VprDProdutoPedido: TRBDProdutoPedidoCompra; VprDFracaoOPPedido: TRBDFracaoOPPedidoCompra; VprDMateriaPrimaProduto : TRBDProdutoPedidoCompraMateriaPrima; VprDMapaCompras : TRBDOrcamentoCompraCorpo; VprDCliente : TRBDCliente; FunPedidoCompra: TRBFunPedidoCompra; FunSolicitacao: TRBFunSolicitacaoCompra; FunOrcamentoCompra : TRBFuncoesOrcamentoCompra; procedure EstadoBotoes(VpaEstado: Boolean); procedure CarTitulosGrade; procedure InicializaTela; function ExisteProduto: Boolean; function ExisteCor: Boolean; function ExisteFracao: Boolean; function ExisteClienteFracaoOP: Boolean; function FracaoOPJaUsada: Boolean; function LocalizaProduto: Boolean; function DadosValidosCorpo: String; procedure CarDClasseCorpo; procedure CarDClasseOP; procedure CarDClasseProdutos; procedure CarDTela; procedure CarDFornecedorTela(VpaDCliente : TRBDCliente); procedure BloquearTela; procedure VerificaPrecoFornecedor; procedure CalculaValorTotal; procedure CalculaValorTotalProduto; procedure CalculaValorUnitarioProduto; procedure CarDDesconto; procedure CarDValoresTela; procedure CarDValorTotal; procedure PosEstagios; procedure CarDProdutoOrcamentoTela(VpaProdutos: TList); procedure CarDFracoesOrcamentoTela(VpaFracoes : TList); procedure VerificaProdutoNaoRecebido(VpaDProdutoPedido: TRBDProdutoPedidoCompra); procedure AtualizaReferenciaFornecedor; procedure CarDChapaClasse; procedure CalculaKilosChapa; procedure CarDMapaComprasparaPedidoCompra(VpaDOrcamento : TRBDOrcamentoCompraCorpo;VpaDOrcamentoFornecedor : TRBDOrcamentoCompraFornecedor) ; function FinalizacoesSolicitacaoCompra : string; function FinalizacoesMapaCompras : string; function DadosNFEValidos : string; public function NovoPedido: Boolean; function NovoPedidoProdutosPendentes(VpaProdutos, VpaFracoesOP, VpaProdutosPendentes, VpaProdutosFinalizados: TList): Boolean; function NovoPedidoMapaCompras(VpaDOrcamentoFornecedor : TRBDOrcamentoCompraFornecedor; VpaProdutos : TList;VpaDOrcamentoCompra : TRBDOrcamentoCompraCorpo) : Boolean; function Alterar(VpaCodFilial, VpaSeqPedido: Integer): Boolean; function Duplicar(VpaCodFilial, VpaSeqPedido: Integer): Boolean; function Apagar(VpaCodFilial, VpaSeqPedido: Integer): Boolean; procedure Consultar(VpaCodFilial, VpaSeqPedido: Integer); end; var FNovoPedidoCompra: TFNovoPedidoCompra; implementation uses APrincipal, UnProdutos, ALocalizaProdutos, ConstMsg, FunString, FunObjeto, ANovoCliente, FunSQL, UnCrystal, AOrdemProducaoGenerica, UnClientes, ACompradores, ANovoProdutoPro, dmRave, AAdicionaProdutosTerceirizacao, ALocalizaFracaoOP; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFNovoPedidoCompra.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprIndSolicitacaoCompra := false; VprIndMapaCompras := false; if Varia.EstagioInicialCompras = 0 then aviso('ESTAGIO INICIAL COMPRAS NÃO PREENCHIDO!!!'#13'É necessário preencher nas configurações gerais o estagio inicial do pedido de compra.'); VprAcao:= False; VprDCliente := TRBDCliente.cria; VprDPedidoCorpo:= TRBDPedidoCompraCorpo.Cria; FunPedidoCompra:= TRBFunPedidoCompra.Cria(FPrincipal.BaseDados); FunSolicitacao := TRBFunSolicitacaoCompra.Cria(FPrincipal.BaseDados); FunOrcamentoCompra := TRBFuncoesOrcamentoCompra.cria(FPrincipal.BaseDados); CarTitulosGrade; GProdutos.ADados:= VprDPedidoCorpo.Produtos; GFracaoOP.ADados:= VprDPedidoCorpo.FracaoOP; GProdutos.CarregaGrade; GFracaoOP.CarregaGrade; PageControl1.ActivePage:= PPedidos; Paginas.ActivePage:= PProdutos; ActiveControl:= EFornecedor; end; { ******************* Quando o formulario e fechado ************************** } function TFNovoPedidoCompra.FinalizacoesMapaCompras: string; var VpfDOrcamentoCompra : TRBDOrcamentoCompraCorpo; begin result := ''; VpfDOrcamentoCompra := TRBDOrcamentoCompraCorpo.cria; FunOrcamentoCompra.CarDOrcamento(VprDMapaCompras.CodFilial,VprDMapaCompras.SeqOrcamento,VpfDOrcamentoCompra); FunOrcamentoCompra.MarcaProdutosComoComprado(VprDMapaCompras,VpfDOrcamentoCompra); result := FunOrcamentoCompra.GravaDOrcamento(VpfDOrcamentoCompra); if result = '' then begin result := FunOrcamentoCompra.GravaVinculoOrcamentoPedidoCompra(VprDPedidoCorpo,VpfDOrcamentoCompra); end; VpfDOrcamentoCompra.Free; end; {******************************************************************************} function TFNovoPedidoCompra.FinalizacoesSolicitacaoCompra: string; begin result := ''; FunSolicitacao.FinalizarProdutos(VprDPedidoCorpo.SeqPedido,VprDPedidoCorpo.Produtos,VprProdutosPendentes,VprProdutosFinalizados); result := FunSolicitacao.GravaVinculoPedidoOrcamento(VprProdutosFinalizados); if result = '' then begin result := FunSolicitacao.AtualizarEstagioOrcamentosFinalizados(VprProdutosFinalizados); if result = '' then result := FunSolicitacao.AtualizarQtdCompradaProdutosPendentes(VprProdutosPendentes); VprProdutosFinalizados.Clear; end; end; { ******************* Quando o formulario e fechado ************************** } procedure TFNovoPedidoCompra.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FunPedidoCompra.Free; FunSolicitacao.Free; FunOrcamentoCompra.Free; VprDPedidoCorpo.Free; Action:= CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFNovoPedidoCompra.BFecharClick(Sender: TObject); begin Close; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarTitulosGrade; begin GProdutos.Cells[1,0]:= 'Código'; GProdutos.Cells[2,0]:= 'Produto'; GProdutos.Cells[3,0]:= 'Código'; GProdutos.Cells[4,0]:= 'Cor'; GProdutos.Cells[5,0]:= 'Código'; GProdutos.Cells[6,0]:= 'Tamanho'; GProdutos.Cells[7,0]:= 'Qtd Chapa'; GProdutos.Cells[8,0]:= 'Largura'; GProdutos.Cells[9,0]:= 'Comprimento'; GProdutos.Cells[10,0]:= 'UM'; GProdutos.Cells[11,0]:= 'Qtd Solicitado'; GProdutos.Cells[12,0]:= 'Qtd Pedido'; GProdutos.Cells[13,0]:= 'Valor Unitário'; GProdutos.Cells[14,0]:= 'Valor Total'; GProdutos.Cells[15,0]:= 'Ref. Fornecedor'; GProdutos.Cells[16,0]:= '%IPI'; GMateriaPrima.Cells[1,0] := 'Codigo'; GMateriaPrima.Cells[2,0] := 'Descrição'; GMateriaPrima.Cells[3,0] := 'Qtd Chapa'; GMateriaPrima.Cells[4,0] := 'Largura'; GMateriaPrima.Cells[5,0] := 'Comprimento'; GMateriaPrima.Cells[6,0] := 'Peso'; GFracaoOP.Cells[1,0]:= 'Filial'; GFracaoOP.Cells[2,0]:= 'Ordem Produção'; GFracaoOP.Cells[3,0]:= 'Fração'; GFracaoOP.Cells[4,0]:= 'Cliente'; if not Config.EstoquePorCor then begin GProdutos.ColWidths[2] := 450; GProdutos.ColWidths[3] := -1; GProdutos.ColWidths[4] := -1; GProdutos.TabStops[3] := false; GProdutos.TabStops[4] := false; end; if not config.EstoquePorTamanho then begin GProdutos.ColWidths[5] := -1; GProdutos.ColWidths[6] := -1; GProdutos.TabStops[5] := false; GProdutos.TabStops[6] := false; end; if not config.ControlarEstoquedeChapas then begin GProdutos.ColWidths[7] := -1; GProdutos.ColWidths[8] := -1; GProdutos.ColWidths[9] := -1; GProdutos.TabStops[7] := false; GProdutos.TabStops[8] := false; GProdutos.TabStops[9] := false; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.ImprimePedidoTerceirizao1Click(Sender: TObject); begin dtRave := TdtRave.create(self); dtRave.ImprimePedidoTerceirizacao(VprDPedidoCorpo.CodFilial,VprDPedidoCorpo.SeqPedido,false); dtRave.free; end; {******************************************************************************} procedure TFNovoPedidoCompra.InicializaTela; begin Paginas.ActivePage:= PProdutos; ScrollBox1.VertScrollBar.Position := 0; AlterarVisibleDet([LDataRenegociado,EDatRenegociado],false); VprDCliente.Free; VprDCliente := TRBDCliente.cria; VprDPedidoCorpo.free; VprDPedidoCorpo := TRBDPedidoCompraCorpo.cria; GProdutos.ADados := VprDPedidoCorpo.Produtos; GFracaoOP.ADados := VprDPedidoCorpo.FracaoOP; GProdutos.CarregaGrade; GFracaoOP.CarregaGrade; VprDPedidoCorpo.CodFilial := varia.CodigoEmpFil; VprDPedidoCorpo.CodEstagio := varia.EstagioInicialCompras; VprDPedidoCorpo.CodUsuario:= Varia.CodigoUsuario; VprDPedidoCorpo.CodComprador:= Varia.CodComprador; VprDPedidoCorpo.CodFilialFaturamento := varia.CodFilialFaturamentoCompras; VprDPedidoCorpo.NumDiasAtraso:= 0; VprDPedidoCorpo.DesSituacao:= 'A'; VprDPedidoCorpo.IndCancelado:= 'N'; VprDPedidoCorpo.DatPedido:= Date; VprDPedidoCorpo.HorPedido:= now; EData.Text:= FormatDateTime('DD/MM/YYYY',VprDPedidoCorpo.DatPedido); EHora.Text:= FormatDateTime('HH:MM',VprDPedidoCorpo.HorPedido); EFilial.AInteiro:= VprDPedidoCorpo.CodFilial; EUsuario.AInteiro:= VprDPedidoCorpo.CodUsuario; EComprador.AInteiro:= VprDPedidoCorpo.CodComprador; EFilialFaturamento.AInteiro := VprDPedidoCorpo.CodFilialFaturamento; AtualizaLocalizas(PanelCabecalho); CPedidoCompra.Checked := True; RDesconto.ItemIndex:= 0; RTipoDesconto.ItemIndex:= 0; end; {******************************************************************************} function TFNovoPedidoCompra.ExisteProduto: Boolean; begin Result:= False; if GProdutos.Cells[1,GProdutos.ALinha] <> '' then begin if GProdutos.Cells[1,GProdutos.ALinha] = VprProdutoAnterior then Result:= True else begin Result:= FunProdutos.ExisteProduto(GProdutos.Cells[1,GProdutos.ALinha],VprDProdutoPedido); if Result then begin VprProdutoAnterior:= VprDProdutoPedido.CodProduto; VprCorAnterior:= ''; GProdutos.Cells[2,GProdutos.ALinha]:= VprDProdutoPedido.NomProduto; GProdutos.Cells[10,GProdutos.ALinha]:= VprDProdutoPedido.DesUM; GProdutos.Cells[11,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VprDProdutoPedido.Qtdproduto); GProdutos.Cells[13,GProdutos.ALinha]:= FormatFloat(Varia.MascaraValor,VprDProdutoPedido.ValUnitario); GProdutos.Cells[16,GProdutos.ALinha]:= FormatFloat('0.00',VprDProdutoPedido.PerIPI); VerificaPrecoFornecedor; end; end; end end; procedure TFNovoPedidoCompra.ExportarPDF1Click(Sender: TObject); begin SaveDialog.FileName := 'Pedido Compra '+IntToStr(VprDPedidoCorpo.SeqPedido); if SaveDialog.Execute then begin dtRave := TdtRave.Create(self); dtRave.VplArquivoPDF := SaveDialog.FileName; dtRave.ImprimePedidoCompra(VprDPedidoCorpo.CodFilial,VprDPedidoCorpo.SeqPedido,false); dtRave.free; end; end; {******************************************************************************} function TFNovoPedidoCompra.ExisteCor: Boolean; begin Result:= True; if GProdutos.Cells[3,GProdutos.ALinha] <> '' then begin if (GProdutos.Cells[3,GProdutos.ALinha] = VprCorAnterior) then Result:= True else begin Result:= FunProdutos.ExisteCor(GProdutos.Cells[3,GProdutos.ALinha],VprDProdutoPedido.NomCor); if Result then begin GProdutos.Cells[4,GProdutos.ALinha]:= VprDProdutoPedido.NomCor; VprCorAnterior:= GProdutos.Cells[3,GProdutos.ALinha]; VprDProdutoPedido.CodCor:= StrToInt(GProdutos.Cells[3,GProdutos.ALinha]); VprDPedidoCorpo.CodCliente:= EFornecedor.AInteiro; VerificaPrecoFornecedor; end; end; end; end; {******************************************************************************} function TFNovoPedidoCompra.LocalizaProduto: Boolean; var VpfClaFiscal: String; begin FLocalizaProduto:= TFLocalizaProduto.CriarSDI(Application,'',True); Result:= FLocalizaProduto.LocalizaProduto(VprDProdutoPedido,eFornecedor.Ainteiro); FLocalizaProduto.Free; if Result then begin VprProdutoAnterior := VprDProdutoPedido.CodProduto; VprCorAnterior:= ''; GProdutos.Cells[1,GProdutos.ALinha]:= VprDProdutoPedido.CodProduto; GProdutos.Cells[2,GProdutos.ALinha]:= VprDProdutoPedido.NomProduto; GProdutos.Cells[10,GProdutos.ALinha]:= VprDProdutoPedido.DesUM; GProdutos.Cells[11,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VprDProdutoPedido.QtdSolicitada); GProdutos.Cells[12,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VprDProdutoPedido.Qtdproduto); GProdutos.Cells[13,GProdutos.ALinha]:= FormatFloat(Varia.MascaraValor,VprDProdutoPedido.ValUnitario); GProdutos.Cells[16,GProdutos.ALinha]:= FormatFloat('0.00',VprDProdutoPedido.PerIPI); if config.EstoquePorTamanho then begin ETamanho.AInteiro := VprDProdutoPedido.CodTamanho; ETamanho.Atualiza; end; VerificaPrecoFornecedor; GProdutos.Col:= 3; end; end; {******************************************************************************} function TFNovoPedidoCompra.NovoPedido: Boolean; begin VprOperacao:= ocInsercao; EstadoBotoes(False); InicializaTela; ValidaGravacao.execute; ShowModal; Result:= VprAcao; end; {******************************************************************************} function TFNovoPedidoCompra.NovoPedidoMapaCompras(VpaDOrcamentoFornecedor : TRBDOrcamentoCompraFornecedor;VpaProdutos: TList;VpaDOrcamentoCompra: TRBDOrcamentoCompraCorpo): Boolean; begin VprIndMapaCompras := true; VprDMapaCompras := VpaDOrcamentoCompra; VprOperacao:= ocInsercao; EstadoBotoes(False); InicializaTela; CarDMapaComprasparaPedidoCompra(VpaDOrcamentoCompra,VpaDOrcamentoFornecedor); CarDProdutoOrcamentoTela(VpaProdutos); // CarDFracoesOrcamentoTela(VpaFracoesOP); ValidaGravacao.execute; Showmodal; result := VprAcao; end; {******************************************************************************} function TFNovoPedidoCompra.NovoPedidoProdutosPendentes(VpaProdutos, VpaFracoesOP, VpaProdutosPendentes, VpaProdutosFinalizados: TList): Boolean; begin VprIndSolicitacaoCompra := true; VprProdutosPendentes := VpaProdutosPendentes; VprProdutosFinalizados := VpaProdutosFinalizados; VprOperacao:= ocInsercao; EstadoBotoes(False); InicializaTela; CarDProdutoOrcamentoTela(VpaProdutos); CarDFracoesOrcamentoTela(VpaFracoesOP); ValidaGravacao.execute; ShowModal; Result:= VprAcao; end; {******************************************************************************} function TFNovoPedidoCompra.DadosNFEValidos: string; var VpfLaco : Integer; VpfDProPedido : TRBDProdutoPedidoCompra; begin result :=''; if (config.EmiteNFe) or (config.EmiteSped) then begin result := FunClientes.DadosSpedClienteValido(VprDCliente); if result = '' then begin for vpflaco := 0 to VprDPedidoCorpo.Produtos.Count - 1 do begin VpfDProPedido := TRBDProdutoPedidoCompra(VprDPedidoCorpo.Produtos.Items[VpfLaco]); if DeletaChars(VpfDProPedido.CodClassificacaoFiscal,' ') = '' then begin result := 'CODIGO NCM/CLASSIFICAÇÃO FISCAL NÃO PREENHCIDO!!!'#13'O produto "'+VpfDProPedido.CodProduto+'" não possui o código NCM cadastrado'; break; end else if VpfDProPedido.CodClassificacaoFiscal <> '' then begin if length(DeletaChars(VpfDProPedido.CodClassificacaoFiscal,' ')) < 8 then begin result := 'CODIGO NCM/CLASSIFICAÇÃO FISCAL INVÁLIDO!!!'#13'O produto "'+VpfDProPedido.CodProduto+'" possui o código NCM cadastrado errado "'+VpfDProPedido.CodClassificacaoFiscal+'"'; break; end; end; end; end; end; end; {******************************************************************************} function TFNovoPedidoCompra.DadosValidosCorpo: String; begin Result:= ''; try if DeletaChars(DeletaChars(EPrazo.Text,' '),'/') <> '' then StrToDate(EPrazo.Text); except Result:= 'PRAZO DE ENTREGA NÃO PREENCHIDO!!!'#13'É necessário preencher o prazo de entrega'; ActiveControl:= EPrazo; end; end; {******************************************************************************} function TFNovoPedidoCompra.Duplicar(VpaCodFilial, VpaSeqPedido: Integer): Boolean; begin VprOperacao:= ocConsulta; FunPedidoCompra.CarDPedidoCompra(VpaCodFilial,VpaSeqPedido,VprDPedidoCorpo); VprDPedidoCorpo.SeqPedido:= 0; VprDPedidoCorpo.DatPedido:= now; VprDPedidoCorpo.DatRenegociado:= 0; VprDPedidoCorpo.DatRenegociadoInicial:= 0; VprDPedidoCorpo.DatPrevista:= 0; VprDPedidoCorpo.DatEntrega:= 0; VprDPedidoCorpo.CodEstagio := varia.EstagioInicialCompras; VprDPedidoCorpo.CodUsuario := varia.CodigoUsuario; FunPedidoCompra.ZeraQtdBaixada(VprDPedidoCorpo); CarDTela; EstadoBotoes(false); VprOperacao:= ocInsercao; ShowModal; result := VprAcao; end; {******************************************************************************} procedure TFNovoPedidoCompra.BGravarClick(Sender: TObject); var VpfResultado: String; begin VpfResultado:= DadosValidosCorpo; if VpfResultado ='' then begin VpfResultado := DadosNFEValidos; end; if VpfResultado <> '' then aviso(VpfResultado) else begin CarDClasseCorpo; if FPrincipal.BaseDados.InTransaction then FPrincipal.BaseDados.Rollback(VprTransacao); VprTransacao.IsolationLevel := xilREADCOMMITTED; FPrincipal.BaseDados.StartTransaction(VprTransacao); VpfResultado:= FunPedidoCompra.GravaDPedidoCompra(VprDPedidoCorpo); ENumero.AInteiro:= VprDPedidoCorpo.SeqPedido; EstadoBotoes(True); if VpfResultado = '' then begin if VprIndSolicitacaoCompra then begin VpfResultado := FinalizacoesSolicitacaoCompra; end; if VprIndMapaCompras then begin VpfResultado := FinalizacoesMapaCompras; end; end; if VpfResultado = '' then begin FPrincipal.BaseDados.Commit(VprTransacao); end else begin FPrincipal.BaseDados.Rollback(VprTransacao); aviso(VpfResultado); end; EstadoBotoes(True); VprAcao:= True; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.EstadoBotoes(VpaEstado: Boolean); begin BCadastrar.Enabled:= VpaEstado; BGravar.Enabled:= not VpaEstado; BCancelar.Enabled:= not VpaEstado; BEnviar.Enabled:= VpaEstado; BImprimir.Enabled:= VpaEstado; BFechar.Enabled:= VpaEstado; end; {******************************************************************************} procedure TFNovoPedidoCompra.GProdutosCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDProdutoPedido:= TRBDProdutoPedidoCompra(VprDPedidoCorpo.Produtos.Items[VpaLinha-1]); GProdutos.Cells[1,GProdutos.ALinha]:= VprDProdutoPedido.CodProduto; GProdutos.Cells[2,GProdutos.ALinha]:= VprDProdutoPedido.NomProduto; if VprDProdutoPedido.CodCor <> 0 then GProdutos.Cells[3,GProdutos.ALinha]:= IntToStr(VprDProdutoPedido.CodCor) else GProdutos.Cells[3,GProdutos.ALinha]:= ''; GProdutos.Cells[4,GProdutos.ALinha]:= VprDProdutoPedido.NomCor; if VprDProdutoPedido.CodTamanho <> 0 then GProdutos.Cells[5,GProdutos.ALinha]:= IntToStr(VprDProdutoPedido.CodTamanho) else GProdutos.Cells[5,GProdutos.ALinha]:= ''; GProdutos.Cells[6,GProdutos.ALinha]:= VprDProdutoPedido.NomTamanho; if VprDProdutoPedido.QtdChapa <> 0 then GProdutos.Cells[7,GProdutos.ALinha]:= FormatFloat('#,###,###0',VprDProdutoPedido.QtdChapa) else GProdutos.Cells[7,GProdutos.ALinha]:= ''; if VprDProdutoPedido.LarChapa <> 0 then GProdutos.Cells[8,GProdutos.ALinha]:= FormatFloat('#,###,###0',VprDProdutoPedido.LarChapa) else GProdutos.Cells[8,GProdutos.ALinha]:= ''; if VprDProdutoPedido.ComChapa <> 0 then GProdutos.Cells[9,GProdutos.ALinha]:= FormatFloat('#,###,###0',VprDProdutoPedido.ComChapa) else GProdutos.Cells[9,GProdutos.ALinha]:= ''; GProdutos.Cells[10,GProdutos.ALinha]:= VprDProdutoPedido.DesUM; if VprDProdutoPedido.QtdSolicitada <> 0 then GProdutos.Cells[11,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VprDProdutoPedido.QtdSolicitada) else GProdutos.Cells[11,GProdutos.ALinha]:= ''; if VprDProdutoPedido.QtdProduto <> 0 then GProdutos.Cells[12,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VprDProdutoPedido.QtdProduto) else GProdutos.Cells[12,GProdutos.ALinha]:= ''; if VprDProdutoPedido.ValUnitario <> 0 then GProdutos.Cells[13,GProdutos.ALinha]:= FormatFloat(Varia.MascaraValor,VprDProdutoPedido.ValUnitario) else GProdutos.Cells[13,GProdutos.ALinha]:= ''; CalculaValorTotalProduto; CalculaValorTotal; if VprDProdutoPedido.ValTotal <> 0 then GProdutos.Cells[14,GProdutos.ALinha]:= FormatFloat(Varia.MascaraValor,VprDProdutoPedido.ValTotal) else GProdutos.Cells[14,GProdutos.ALinha]:= ''; GProdutos.Cells[15,GProdutos.ALinha]:= VprDProdutoPedido.DesReferenciaFornecedor; if VprDProdutoPedido.ValTotal <> 0 then GProdutos.Cells[16,GProdutos.ALinha]:= FormatFloat('0.00',VprDProdutoPedido.PerIPI) else GProdutos.Cells[16,GProdutos.ALinha]:= ''; end; {******************************************************************************} procedure TFNovoPedidoCompra.GProdutosDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos:= True; ExisteCor; if GProdutos.Cells[1,GProdutos.ALinha] = '' then begin VpaValidos:= False; aviso('PRODUTO NÃO PREENCHIDO!!!'#13'É necessário preencher o produto.'); GProdutos.Col:= 1; end else if not ExisteProduto then begin VpaValidos:= False; aviso('PRODUTO NÃO CADASTRADO!!!'#13'É necessário digitar um produto cadastrado.'); GProdutos.Col:= 1; end else if (GProdutos.Cells[3,GProdutos.ALinha] <> '') then begin if not Existecor then begin VpaValidos := false; Aviso(CT_CORINEXISTENTE); GProdutos.Col := 3; end; end else if config.ExigirCorNotaEntrada then begin // se a cor for igual a '' e estiver configurado para controlar estoque // pela cor, entao fazer checagem direta. VpaValidos := false; Aviso(CT_CORINEXISTENTE); GProdutos.Col := 3; end; if VpaValidos then begin if not ETamanho.AExisteCodigo(GProdutos.Cells[5,GProdutos.ALinha]) then begin VpaValidos := false; Aviso('TAMANHO NÃO CADASTRADO!!!'#13'É necessário digitar um tamanho cadastrado.'); GProdutos.Col := 5; end else if VprDProdutoPedido.UnidadesParentes.IndexOf(GProdutos.Cells[10,GProdutos.ALinha]) < 0 then begin VpaValidos:= False; aviso(CT_UNIDADEVAZIA); GProdutos.Col:= 10; end else if GProdutos.Cells[11,GProdutos.ALinha] = '' then begin VpaValidos:= False; aviso('QUANTIDADE SOLICITADA NÃO PREENCHIDA!!!'#13'É necessário preencher a quantidade solicitada.'); GProdutos.Col:= 11; end else if GProdutos.Cells[12,GProdutos.ALinha] = '' then begin VpaValidos:= False; aviso('QUANTIDADE NÃO PREENCHIDA!!!'#13'É necessário preencher a quantidade do produto.'); GProdutos.Col:= 12; end else begin CalculaValorTotalProduto; if GProdutos.Cells[14,GProdutos.ALinha] <> '' then if StrToFloat(DeletaChars(GProdutos.Cells[12,GProdutos.ALinha],'.')) <> 0 then CalculaValorUnitarioProduto; if GProdutos.Cells[13,GProdutos.ALinha] = '' then begin VpaValidos:= False; aviso('VALOR UNITÁRIO NÃO PREENCHIDO!!!'#13'É necessário preencher o valor unitário.'); GProdutos.Col:= 13; end; end; end; CalculaValorTotalProduto; if VpaValidos then begin CarDClasseProdutos; VerificaProdutoNaoRecebido(VprDProdutoPedido); if VprDProdutoPedido.QtdSolicitada = 0 then begin VpaValidos:= False; aviso('QUANTIDADE SOLICITADA NÃO PREENCHIDA!!!'#13'É necessário preencher a quantidade solicitada.'); GProdutos.Col:= 11; end else if VprDProdutoPedido.QtdProduto = 0 then begin VpaValidos:= False; aviso('QUANTIDADE NÃO PREENCHIDA!!!'#13'É necessário preencher a quantidade do produto'); GProdutos.Col:= 12; end else if VprDProdutoPedido.ValUnitario = 0 then begin VpaValidos:= False; aviso('VALOR UNITÁRIO NÃO PREENCHIDO!!!'#13'É necessário preencher o valor unitário.'); GProdutos.Col:= 13; end else if VprDProdutoPedido.PerIPI >100 then begin VpaValidos:= False; aviso('PERCENTUAL DE IPI INVÁLIDO!!!'#13'O percentual de IPI não pode ser maior que 99%'); GProdutos.Col:= 16; end; CalculaValorTotal; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.VerificaProdutoNaoRecebido(VpaDProdutoPedido: TRBDProdutoPedidoCompra); var VpfResultado: String; VpfQuantidade: Double; begin VpfResultado:= FunPedidoCompra.VerificaProdutoNaoRecebido(VprDPedidoCorpo.CodFilial, VprDPedidoCorpo.SeqPedido, VpaDProdutoPedido.SeqProduto, VpaDProdutoPedido.CodCor, VpfQuantidade); if VpfResultado <> '' then begin if Confirmacao(VpfResultado) then begin // adicionar a quantidade ao produto daquele pedido // se estiver gerando a partir de uma solicitacao entao // criar os vinculos // descontar ou remover o produto do pedido atual, dependendo da quantidade end; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.AtualizaReferenciaFornecedor; var VpfLaco : Integer; begin for VpfLaco := 0 to VprDPedidoCorpo.Produtos.Count - 1 do begin GProdutos.row := VpfLaco +1; VprDProdutoPedido := TRBDProdutoPedidoCompra(VprDPedidoCorpo.Produtos.Items[VpfLaco]); VerificaPrecoFornecedor; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDClasseProdutos; begin VprDProdutoPedido.CodProduto:= GProdutos.Cells[1,GProdutos.ALinha]; VprDProdutoPedido.NomProduto:= GProdutos.Cells[2,GProdutos.ALinha]; if GProdutos.Cells[3,GProdutos.ALinha] <> '' then VprDProdutoPedido.CodCor:= StrToInt(GProdutos.Cells[3,GProdutos.ALinha]) else VprDProdutoPedido.CodCor:= 0; VprDProdutoPedido.NomCor:= GProdutos.Cells[4,GProdutos.ALinha]; if GProdutos.Cells[5,GProdutos.ALinha] <> '' then VprDProdutoPedido.CodTamanho:= StrToInt(GProdutos.Cells[5,GProdutos.ALinha]) else VprDProdutoPedido.CodTamanho:= 0; VprDProdutoPedido.NomTamanho:= GProdutos.Cells[6,GProdutos.ALinha]; if GProdutos.Cells[7,GProdutos.ALinha] <> '' then VprDProdutoPedido.QtdChapa:= StrToFloat(DeletaChars(GProdutos.Cells[7,GProdutos.ALinha],'.')) else VprDProdutoPedido.QtdChapa := 0; if GProdutos.Cells[8,GProdutos.ALinha] <> '' then VprDProdutoPedido.LarChapa:= StrToFloat(DeletaChars(GProdutos.Cells[8,GProdutos.ALinha],'.')) else VprDProdutoPedido.LarChapa := 0; if GProdutos.Cells[9,GProdutos.ALinha] <> '' then VprDProdutoPedido.ComChapa:= StrToFloat(DeletaChars(GProdutos.Cells[9,GProdutos.ALinha],'.')) else VprDProdutoPedido.ComChapa := 0; VprDProdutoPedido.DesUM:= GProdutos.Cells[10,GProdutos.ALinha]; if GProdutos.Cells[11,GProdutos.ALinha] <> '' then VprDProdutoPedido.QtdSolicitada:= StrToFloat(DeletaChars(GProdutos.Cells[11,GProdutos.ALinha],'.')) else VprDProdutoPedido.QtdSolicitada:= 0; if GProdutos.Cells[12,GProdutos.ALinha] <> '' then VprDProdutoPedido.QtdProduto:= StrToFloat(DeletaChars(GProdutos.Cells[12,GProdutos.ALinha],'.')) else VprDProdutoPedido.QtdProduto:= 0; if GProdutos.Cells[13,GProdutos.ALinha] <> '' then VprDProdutoPedido.ValUnitario:= StrToFloat(DeletaChars(GProdutos.Cells[13,GProdutos.ALinha],'.')) else VprDProdutoPedido.ValUnitario:= 0; if GProdutos.Cells[14,GProdutos.ALinha] <> '' then VprDProdutoPedido.ValTotal:= StrToFloat(DeletaChars(GProdutos.Cells[14,GProdutos.ALinha],'.')) else VprDProdutoPedido.ValTotal:= 0; CalculaValorTotal; VprDProdutoPedido.DesReferenciaFornecedor:= GProdutos.Cells[15,GProdutos.ALinha]; if GProdutos.Cells[16,GProdutos.ALinha] <> '' then VprDProdutoPedido.PerIPI:= StrToFloat(DeletaChars(GProdutos.Cells[16,GProdutos.ALinha],'.')) else VprDProdutoPedido.PerIPI:= 0; if VprDProdutoPedido.QtdSolicitada > VprDProdutoPedido.QtdProduto then VprDProdutoPedido.QtdSolicitada := VprDProdutoPedido.QtdProduto; end; {******************************************************************************} procedure TFNovoPedidoCompra.GProdutosGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); begin case ACol of 3: Value:= '000000;0; '; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.GProdutosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = 114 then case GProdutos.Col of 1: LocalizaProduto; 3: ECor.AAbreLocalizacao; 5: ETamanho.AAbreLocalizacao; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.ECorRetorno(Retorno1, Retorno2: String); begin GProdutos.Cells[3,GProdutos.ALinha]:= Retorno1; GProdutos.Cells[4,GProdutos.ALinha]:= Retorno2; end; {******************************************************************************} procedure TFNovoPedidoCompra.GProdutosKeyPress(Sender: TObject; var Key: Char); begin if Key = '.' then case GProdutos.Col of 11,12,13,14: Key:= DecimalSeparator; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.GProdutosMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprDPedidoCorpo.Produtos.Count > 0 then begin VprDProdutoPedido:= TRBDProdutoPedidoCompra(VprDPedidoCorpo.Produtos.Items[VpaLinhaAtual-1]); VprProdutoAnterior:= VprDProdutoPedido.CodProduto; VprCorAnterior:= IntToStr(VprDProdutoPedido.CodCor); GMateriaPrima.ADados := VprDProdutoPedido.MateriaPrima; GMateriaPrima.CarregaGrade; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.GProdutosNovaLinha(Sender: TObject); begin VprDProdutoPedido:= VprDPedidoCorpo.AddProduto; end; {******************************************************************************} procedure TFNovoPedidoCompra.GProdutosSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if GProdutos.AEstadoGrade in [egEdicao,egInsercao] then begin if GProdutos.AColuna <> ACol then begin case GProdutos.AColuna of 1: if not ExisteProduto then if not LocalizaProduto then begin GProdutos.Cells[1,GProdutos.ALinha]:= ''; GProdutos.Cells[2,GProdutos.ALinha]:= ''; Abort; end; 3: if not ExisteCor then begin GProdutos.Cells[3,GProdutos.ALinha]:= ''; GProdutos.Cells[4,GProdutos.ALinha]:= ''; Abort; end; 5 : if not ETamanho.AExisteCodigo(GProdutos.Cells[5,GProdutos.ALinha]) then if not ETamanho.AAbreLocalizacao then begin GProdutos.Cells[5,GProdutos.ALinha]:= ''; GProdutos.Cells[6,GProdutos.ALinha]:= ''; Abort; end; 7,8,9 : CalculaKilosChapa; 12,13: begin CalculaValorTotalProduto; end; 14: begin CalculaValorUnitarioProduto; end; end; end; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.GFracaoOPCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDFracaoOPPedido:= TRBDFracaoOPPedidoCompra(VprDPedidoCorpo.FracaoOP.Items[VpaLinha-1]); if VprDFracaoOPPedido.CodFilialFracao <> 0 then GFracaoOP.Cells[1,GFracaoOP.ALinha]:= IntToStr(VprDFracaoOPPedido.CodFilialFracao) else GFracaoOP.Cells[1,GFracaoOP.ALinha]:= ''; if VprDFracaoOPPedido.SeqOrdem <> 0 then GFracaoOP.Cells[2,GFracaoOP.ALinha]:= IntToStr(VprDFracaoOPPedido.SeqOrdem) else GFracaoOP.Cells[2,GFracaoOP.ALinha]:= ''; if VprDFracaoOPPedido.SeqFracao <> 0 then GFracaoOP.Cells[3,GFracaoOP.ALinha]:= IntToStr(VprDFracaoOPPedido.SeqFracao) else GFracaoOP.Cells[3,GFracaoOP.ALinha]:= ''; GFracaoOP.Cells[4,GFracaoOP.ALinha]:= VprDFracaoOPPedido.NomCliente; end; {******************************************************************************} procedure TFNovoPedidoCompra.GFracaoOPDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos:= True; if GFracaoOP.Cells[1,GFracaoOP.ALinha] = '' then begin aviso('FILIAL NÃO PREENCHIDA!!!'#13'É necessário digitar a filial.'); VpaValidos:= False; GFracaoOP.Col:= 1; end else if GFracaoOP.Cells[2,GFracaoOP.ALinha] = '' then begin aviso('ORDEM DE PRODUÇÃO NÃO PREENCHIDA!!!'#13'É necessário digitar a ordem de produção.'); VpaValidos:= False; GFracaoOP.Col:= 2; end; if VpaValidos then begin if GFracaoOP.Cells[3,GFracaoOP.ALinha] <> '' then // verificar se é diferente de '' para não dar erro na conversão if StrToInt(GFracaoOP.Cells[3,GFracaoOP.ALinha]) = 0 then // checar aqui para ele não fazer a rotina ExisteFracao, pesquizando SEQFRACAO com 0 begin GFracaoOP.Cells[3,GFracaoOP.ALinha]:= ''; GFracaoOP.Col:= 3; end; if not ExisteFracao then begin aviso('FRAÇÃO NÃO CADASTRADA!!!'#13'Informe uma fração que esteja cadastrada.'); VpaValidos:= False; GFracaoOP.Col:= 1; end; end; if VpaValidos then begin CarDClasseOP; if FracaoOPJaUsada then begin aviso('FRACAO OP JÁ UTILIZADA!!!'#13'Informe uma fração op que ainda não esteja em uso.'); VpaValidos:= False; GFracaoOP.Col:= 1; end; if StrToInt(GFracaoOP.Cells[1,GFracaoOP.ALinha]) = 0 then begin GFracaoOP.Cells[1,GFracaoOP.ALinha]:= ''; GFracaoOP.Col:= 1; end else if StrToInt(GFracaoOP.Cells[2,GFracaoOP.ALinha]) = 0 then begin GFracaoOP.Cells[2,GFracaoOP.ALinha]:= ''; GFracaoOP.Col:= 2; end; end; end; {******************************************************************************} function TFNovoPedidoCompra.ExisteFracao: Boolean; begin Result:= False; if (GFracaoOP.Cells[1,GFracaoOP.ALinha] <> '') and (GFracaoOP.Cells[2,GFracaoOP.ALinha] <> '') and (GFracaoOP.Cells[3,GFracaoOP.ALinha] <> '') then Result:= FunPedidoCompra.ExisteFracaoOP(StrToInt(GFracaoOP.Cells[1,GFracaoOP.ALinha]), StrToInt(GFracaoOP.Cells[2,GFracaoOP.ALinha]), StrToInt(GFracaoOP.Cells[3,GFracaoOP.ALinha])) else {para verificar apenas pela op} if (GFracaoOP.Cells[1,GFracaoOP.ALinha] <> '') and (GFracaoOP.Cells[2,GFracaoOP.ALinha] <> '') then Result:= FunPedidoCompra.ExisteOP(StrToInt(GFracaoOP.Cells[1,GFracaoOP.ALinha]), StrToInt(GFracaoOP.Cells[2,GFracaoOP.ALinha])); end; {******************************************************************************} function TFNovoPedidoCompra.FracaoOPJaUsada: Boolean; var VpfLaco: Integer; VpfPedidoFracaoOP: TRBDFracaoOPPedidoCompra; begin Result:= False; for VpfLaco:= 0 to VprDPedidoCorpo.FracaoOP.Count - 1 do begin if VpfLaco+1 <> GFracaoOP.ALinha then // diferente da linha que estou modificando begin VpfPedidoFracaoOP:= TRBDFracaoOPPedidoCompra(VprDPedidoCorpo.FracaoOP[VpfLaco]); if (VpfPedidoFracaoOP.CodFilialFracao = VprDFracaoOPPedido.CodFilialFracao) and (VpfPedidoFracaoOP.SeqOrdem = VprDFracaoOPPedido.SeqOrdem) and (VpfPedidoFracaoOP.SeqFracao = VprDFracaoOPPedido.SeqFracao) then begin Result:= True; Break; end; end; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDClasseOP; begin if GFracaoOP.Cells[1,GFracaoOP.ALinha] <> '' then VprDFracaoOPPedido.CodFilialFracao:= StrToInt(GFracaoOP.Cells[1,GFracaoOP.ALinha]) else VprDFracaoOPPedido.CodFilialFracao:= 0; if GFracaoOP.Cells[2,GFracaoOP.ALinha] <> '' then VprDFracaoOPPedido.SeqOrdem:= StrToInt(GFracaoOP.Cells[2,GFracaoOP.ALinha]) else VprDFracaoOPPedido.SeqOrdem:= 0; if GFracaoOP.Cells[3,GFracaoOP.ALinha] <> '' then VprDFracaoOPPedido.SeqFracao:= StrToInt(GFracaoOP.Cells[3,GFracaoOP.ALinha]) else VprDFracaoOPPedido.SeqFracao:= 0; end; {******************************************************************************} procedure TFNovoPedidoCompra.GFracaoOPGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); begin case ACol of 1,2,3: Value:= '000000;0; '; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.GFracaoOPMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprDPedidoCorpo.FracaoOP.Count > 0 then VprDFracaoOPPedido:= TRBDFracaoOPPedidoCompra(VprDPedidoCorpo.FracaoOP.Items[VpaLinhaAtual-1]); end; {******************************************************************************} procedure TFNovoPedidoCompra.GFracaoOPNovaLinha(Sender: TObject); begin VprDFracaoOPPedido:= VprDPedidoCorpo.AddFracaoOP; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDChapaClasse; begin if GProdutos.Cells[7,GProdutos.ALinha] <> '' then VprDProdutoPedido.QtdChapa := StrToFloat(DeletaChars(GProdutos.Cells[7,GProdutos.ALinha],'.')) else VprDProdutoPedido.QtdChapa:= 0; if GProdutos.Cells[8,GProdutos.ALinha] <> '' then VprDProdutoPedido.LarChapa := StrToFloat(DeletaChars(GProdutos.Cells[8,GProdutos.ALinha],'.')) else VprDProdutoPedido.LarChapa:= 0; if GProdutos.Cells[9,GProdutos.ALinha] <> '' then VprDProdutoPedido.ComChapa := StrToFloat(DeletaChars(GProdutos.Cells[9,GProdutos.ALinha],'.')) else VprDProdutoPedido.ComChapa:= 0; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDClasseCorpo; begin VprDPedidoCorpo.CodFilial:= EFilial.AInteiro; VprDPedidoCorpo.CodFilialFaturamento := EFilialFaturamento.AInteiro; VprDPedidoCorpo.CodCliente:= EFornecedor.AInteiro; VprDPedidoCorpo.CodUsuario:= EUsuario.AInteiro; VprDPedidoCorpo.CodComprador:= EComprador.AInteiro; VprDPedidoCorpo.CodCondicaoPagto:= ECondicoesPagto.AInteiro; VprDPedidoCorpo.CodFormaPagto:= EFormaPagto.AInteiro; VprDPedidoCorpo.NomContato:= EContato.Text; VprDPedidoCorpo.DesEmailComprador:= EEmailComprador.Text; VprDPedidoCorpo.DesObservacao:= EObservacoes.Text; VprDPedidoCorpo.ValTotal:= EValTotal.AValor; VprDPedidoCorpo.ValFrete:= EValorFrete.AValor; VprDPedidoCorpo.CodTransportadora := ECodTransportadora.AInteiro; if CPedidoCompra.Checked then VprDPedidoCorpo.Tipopedido := tpPedidoCompra else VprDPedidoCorpo.Tipopedido := tpTerceirizacao; if CDestinatario.Checked then VprDPedidoCorpo.TipFrete := 2 else VprDPedidoCorpo.TipFrete := 1; CarDDesconto; try if DeletaEspaco(DeletaChars(EPrazo.Text,'/')) = '' then VprDPedidoCorpo.DatPrevista:= MontaData(1,1,1900) else VprDPedidoCorpo.DatPrevista:= StrToDate(EPrazo.Text); except aviso('PRAZO DE ENTREGA INVÁLIDA!!!'#13'Informe o prazo de entrega corretamente.'); ActiveControl:= EPrazo; end; if VprOperacao = ocinsercao then VprDPedidoCorpo.DatRenegociado := VprDPedidoCorpo.DatPrevista else begin try if DeletaEspaco(DeletaChars(EDatRenegociado.Text,'/')) = '' then VprDPedidoCorpo.DatRenegociado:= MontaData(1,1,1900) else VprDPedidoCorpo.DatRenegociado:= StrToDate(EDatRenegociado.Text); except aviso('PRAZO DE RENEGOCIADO INVÁLIDA!!!'#13'Informe a data renegociada corretamente.'); ActiveControl:= EDatRenegociado; end; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.EFornecedorRetorno(Retorno1, Retorno2: String); var VpfResultado : string; begin VpfResultado := ''; if VprOperacao in [ocinsercao,ocEdicao] then begin if Retorno1 <> '' then begin if EFornecedor.AInteiro <> VprDCliente.CodCliente then begin VprDCliente.CodCliente:= EFornecedor.AInteiro; FunClientes.CarDCliente(VprDCliente,True); VprDPedidoCorpo.CodCliente:= EFornecedor.AInteiro; VpfResultado := FunClientes.DadosSpedClienteValido(VprDCliente); if VpfResultado = '' then CarDFornecedorTela(VprDCliente); end; end else begin VprDCliente.CodCliente := 0; end; end; if VpfResultado <> '' then begin aviso(VpfResultado); EFornecedor.Clear; EFornecedor.Atualiza; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDFornecedorTela(VpaDCliente : TRBDCliente); begin if VpaDCliente.NumDiasEntrega <> 0 then EPrazo.Text := FormatDateTime('DD/MM/YYYY',IncDia(date,VpaDCliente.NumDiasEntrega)); EContato.Text:= VpaDCliente.NomContatoFornecedor; EEmailComprador.Text:= VpaDCliente.DesEmailFornecedor; ECondicoesPagto.AInteiro:= VpaDCliente.CodCondicaoPagamento; EFormaPagto.AInteiro:= VpaDCliente.CodFormaPagamento; ECondicoesPagto.Atualiza; EFormaPagto.Atualiza; EValorFrete.AValor:= VpaDCliente.ValFrete; ETelefone.Text := VpaDCliente.DesFone1; ECodTransportadora.AInteiro:= VpaDCliente.CodTransportadora; ECodTransportadora.Atualiza; AtualizaReferenciaFornecedor; end; {******************************************************************************} procedure TFNovoPedidoCompra.RTipoDescontoClick(Sender: TObject); begin if RTipoDesconto.ItemIndex = 0 then EValor.AMascara:= 'R$,0.00;-R$,0.00' else if RTipoDesconto.ItemIndex = 1 then EValor.AMascara:= ',0.00 %;,0.00 %'; EValorChange(nil); end; {******************************************************************************} procedure TFNovoPedidoCompra.EFornecedorChange(Sender: TObject); begin if VprOperacao in [ocInsercao,ocEdicao] then ValidaGravacao.execute; end; {******************************************************************************} function TFNovoPedidoCompra.Apagar(VpaCodFilial, VpaSeqPedido: Integer): Boolean; var VpfTransacao : TTransactionDesc; VpfResultado : string; begin Result:= False; VprOperacao := ocConsulta; EstadoBotoes(true); FunPedidoCompra.CarDPedidoCompra(VpaCodFilial,VpaSeqPedido,VprDPedidoCorpo); CarDTela; Show; if Confirmacao('Deseja excluir o pedido de compra número '+IntToStr(VprDPedidoCorpo.SeqPedido)+'?') then begin if FPrincipal.BaseDados.inTransaction then FPrincipal.BaseDados.Rollback(VpfTransacao); VpfTransacao.IsolationLevel :=xilDIRTYREAD; FPrincipal.BaseDados.StartTransaction(VpfTransacao); vpfresultado := FunPedidoCompra.ApagaPedido(VprDPedidoCorpo); if VpfResultado = '' then FPrincipal.BaseDados.Commit(VpfTransacao) else begin if FPrincipal.BaseDados.inTransaction then FPrincipal.BaseDados.Rollback(VpfTransacao); aviso(VpfResultado); end; Result:= True; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDTela; begin VprDCliente.CodCliente:= VprDPedidoCorpo.CodCliente; FunClientes.CarDCliente(VprDCliente,True); EFilial.AInteiro:= VprDPedidoCorpo.CodFilial; EFilialFaturamento.AInteiro := VprDPedidoCorpo.CodFilialFaturamento; ENumero.AInteiro:= VprDPedidoCorpo.SeqPedido; EFornecedor.AInteiro:= VprDPedidoCorpo.CodCliente; CPedidoCompra.Checked := VprDPedidoCorpo.Tipopedido = tpPedidoCompra; CTerceirizacao.Checked := VprDPedidoCorpo.Tipopedido = tpTerceirizacao; EUsuario.AInteiro:= VprDPedidoCorpo.CodUsuario; EComprador.AInteiro:= VprDPedidoCorpo.CodComprador; ECondicoesPagto.AInteiro:= VprDPedidoCorpo.CodCondicaoPagto; EFormaPagto.AInteiro:= VprDPedidoCorpo.CodFormaPagto; ETelefone.Text:= VprDPedidoCorpo.DesTelefone; ECodTransportadora.AInteiro := VprDPedidoCorpo.CodTransportadora; ECodTransportadora.Atualiza; if VprDPedidoCorpo.TipFrete = 2 then CDestinatario.Checked := true else CEmitente.Checked := true; //verificar EContato.Text:= VprDPedidoCorpo.NomContato; EEmailComprador.Text:= VprDPedidoCorpo.DesEmailComprador; EObservacoes.Text:= VprDPedidoCorpo.DesObservacao; EData.Text:= FormatDateTime('DD/MM/YYYY',VprDPedidoCorpo.DatPedido); EHora.Text:= FormatDateTime('HH:MM',VprDPedidoCorpo.HorPedido); if VprDPedidoCorpo.DatRenegociado > MontaData(1,1,1900) then EDatRenegociado.Text:= FormatDateTime('DD/MM/YYYY',VprDPedidoCorpo.DatRenegociado) else EDatRenegociado.clear; if VprDPedidoCorpo.DatPrevista > MontaData(1,1,1900) then EPrazo.Text:= FormatDateTime('DD/MM/YYYY',VprDPedidoCorpo.DatPrevista) else EPrazo.clear; GProdutos.ADados:= VprDPedidoCorpo.Produtos; GFracaoOP.ADados:= VprDPedidoCorpo.FracaoOP; GProdutos.CarregaGrade; GFracaoOP.CarregaGrade; EValTotal.AValor:= VprDPedidoCorpo.ValTotal; EValorFrete.AValor:= VprDPedidoCorpo.ValFrete; CarDValoresTela; AtualizaLocalizas(ScrollBox1); end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDDesconto; begin if VprOperacao in [ocInsercao,ocEdicao] then begin VprDPedidoCorpo.PerDesconto:= 0; VprDPedidoCorpo.ValDesconto:= 0; if RTipoDesconto.ItemIndex = 0 then begin VprDPedidoCorpo.ValDesconto:= EValor.AValor; if RDesconto.ItemIndex = 0 then VprDPedidoCorpo.ValDesconto:= VprDPedidoCorpo.ValDesconto * (-1); end else if RTipoDesconto.ItemIndex = 1 then begin VprDPedidoCorpo.PerDesconto:= EValor.AValor; if RDesconto.ItemIndex = 0 then VprDPedidoCorpo.PerDesconto:= VprDPedidoCorpo.PerDesconto * (-1); end; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDValoresTela; begin EValTotal.AValor:= VprDPedidoCorpo.ValTotal; EValProdutos.AValor := VprDPedidoCorpo.ValProdutos; EValIPI.AValor := VprDPedidoCorpo.ValIPI; if VprDPedidoCorpo.ValDesconto <> 0 then begin if VprDPedidoCorpo.ValDesconto > 0 then begin EValor.AValor:= VprDPedidoCorpo.ValDesconto; RDesconto.ItemIndex:= 1; end else begin EValor.AValor:= VprDPedidoCorpo.ValDesconto * (-1); RDesconto.ItemIndex:= 0; end; RTipoDesconto.ItemIndex:= 0; end else if VprDPedidoCorpo.PerDesconto <> 0 then begin if VprDPedidoCorpo.PerDesconto > 0 then begin EValor.AValor:= VprDPedidoCorpo.PerDesconto; RDesconto.ItemIndex:= 1; end else begin EValor.AValor:= VprDPedidoCorpo.PerDesconto * (-1); RDesconto.ItemIndex:= 0; end; RTipoDesconto.ItemIndex:= 1; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.Consultar(VpaCodFilial,VpaSeqPedido: Integer); begin VprOperacao:= ocConsulta; FunPedidoCompra.CarDPedidoCompra(VpaCodFilial,VpaSeqPedido,VprDPedidoCorpo); CarDTela; BloquearTela; EstadoBotoes(True); ShowModal; end; {******************************************************************************} procedure TFNovoPedidoCompra.CPedidoCompraClick(Sender: TObject); begin BProdutosTerceirizados.Enabled := CTerceirizacao.Checked; PFracoes.Visible := CTerceirizacao.Checked; PTituloMateriaPrima.Visible := CTerceirizacao.Checked; if CTerceirizacao.Checked then begin Paginas.Height := 370; end else begin Paginas.Height := 200; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.BloquearTela; begin AlteraReadOnlyDet(ScrollBox1,0,true); GProdutos.APermiteExcluir:= False; GProdutos.APermiteInserir:= False; GFracaoOP.APermiteExcluir:= False; GFracaoOP.APermiteInserir:= False; RDesconto.Enabled:= False; RTipoDesconto.Enabled:= False; EstadoBotoes(False); end; {******************************************************************************} function TFNovoPedidoCompra.Alterar(VpaCodFilial, VpaSeqPedido: Integer): Boolean; begin VprOperacao:= ocConsulta; FunPedidoCompra.CarDPedidoCompra(VpaCodFilial,VpaSeqPedido,VprDPedidoCorpo); CarDTela; EstadoBotoes(False); VprOperacao:= ocEdicao; ShowModal; result := VprAcao; end; {******************************************************************************} procedure TFNovoPedidoCompra.EFornecedorCadastrar(Sender: TObject); begin FNovoCliente:= TFNovoCliente.CriarSDI(Application,'',True); FNovoCliente.CadClientes.Insert; FNovoCliente.CadClientesC_IND_FOR.AsString := 'S'; FNovoCliente.CadClientesC_IND_CLI.AsString := 'N'; FNovoCliente.CadClientesC_IND_PRC.AsString := 'N'; FNovoCliente.ShowModal; FNovoCliente.Free; Localiza.AtualizaConsulta; end; {******************************************************************************} procedure TFNovoPedidoCompra.BImprimirClick(Sender: TObject); begin dtRave := TdtRave.create(self); dtRave.ImprimePedidoCompra(VprDPedidoCorpo.CodFilial,VprDPedidoCorpo.SeqPedido,false); dtRave.free; end; {******************************************************************************} procedure TFNovoPedidoCompra.BProdutosTerceirizadosClick(Sender: TObject); begin FLocalizaFracaoOP := tFLocalizaFracaoOP.CriarSDI(self,'',true); if FLocalizaFracaoOP.LocalizaFracao(VprDPedidoCorpo) then GProdutos.CarregaGrade; FLocalizaFracaoOP.Free; end; {******************************************************************************} procedure TFNovoPedidoCompra.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var VpfCodProduto, VpfSeqProduto,VpfNomProduto,VpfPath,VpfKit,VpfCifrao : String; begin if Key = VK_F4 then if (ActiveControl = GProdutos) or (ActiveControl = GFracaoOP) then ActiveControl:= EObservacoes; if Key = VK_F6 then begin if ExisteProduto then begin VpfCodProduto:= IntToStr(VprDProdutoPedido.SeqProduto); FNovoProdutoPro := TFNovoProdutoPro.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoProdutoPro')); if FNovoProdutoPro.AlterarProduto(varia.codigoEmpresa,varia.CodigoEmpFil,VprDProdutoPedido.SeqProduto) <> nil then begin VprProdutoAnterior:= ''; ExisteProduto; end; FNovoProdutoPro.free; VerificaPrecoFornecedor; end else begin aviso('PRODUTO NÃO PRENCHIDO!!!'#13'Informe um produto para alterar.'); ActiveControl:= GProdutos; end; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.VerificaPrecoFornecedor; begin VprDPedidoCorpo.CodCliente:= EFornecedor.AInteiro; FunProdutos.CarDProdutoFornecedor(VprDPedidoCorpo.CodCliente,VprDProdutoPedido); GProdutos.Cells[13,GProdutos.ALinha]:= FormatFloat(Varia.MascaraValor,VprDProdutoPedido.ValUnitario); GProdutos.Cells[15,GProdutos.ALinha]:= VprDProdutoPedido.DesReferenciaFornecedor; GProdutos.Cells[16,GProdutos.ALinha]:= FormatFloat('0.00',VprDProdutoPedido.PerIPI); end; {******************************************************************************} procedure TFNovoPedidoCompra.CalculaValorTotalProduto; begin if GProdutos.Cells[12,GProdutos.ALinha] <> '' then VprDProdutoPedido.QtdProduto:= StrToFloat(DeletaChars(GProdutos.Cells[12,GProdutos.ALinha],'.')) else VprDProdutoPedido.QtdProduto:= 0; if GProdutos.Cells[13,GProdutos.ALinha] <> '' then VprDProdutoPedido.ValUnitario:= StrToFloat(DeletaChars(GProdutos.Cells[13,GProdutos.ALinha],'.')) else VprDProdutoPedido.ValUnitario:= 0; VprDProdutoPedido.ValTotal:= VprDProdutoPedido.ValUnitario * VprDProdutoPedido.QtdProduto; GProdutos.Cells[12,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VprDProdutoPedido.QtdProduto); GProdutos.Cells[13,GProdutos.ALinha]:= FormatFloat(Varia.MascaraValorUnitario,VprDProdutoPedido.ValUnitario); GProdutos.Cells[14,GProdutos.ALinha]:= FormatFloat(varia.MascaraValor,VprDProdutoPedido.ValTotal); end; {******************************************************************************} procedure TFNovoPedidoCompra.CalculaValorUnitarioProduto; begin if GProdutos.Cells[12,GProdutos.ALinha] <> '' then VprDProdutoPedido.QtdProduto:= StrToFloat(DeletaChars(GProdutos.Cells[12,GProdutos.ALinha],'.')) else VprDProdutoPedido.QtdProduto:= 0; if GProdutos.Cells[14,GProdutos.ALinha] <> '' then VprDProdutoPedido.ValTotal:= StrToFloat(DeletaChars(GProdutos.Cells[14,GProdutos.ALinha],'.')) else VprDProdutoPedido.ValTotal:= 0; try VprDProdutoPedido.ValUnitario:= VprDProdutoPedido.ValTotal / VprDProdutoPedido.QtdProduto; except VprDProdutoPedido.ValUnitario:= 0; end; GProdutos.Cells[12,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VprDProdutoPedido.QtdProduto); GProdutos.Cells[13,GProdutos.ALinha]:= FormatFloat(Varia.MascaraValorUnitario,VprDProdutoPedido.ValUnitario); GProdutos.Cells[14,GProdutos.ALinha]:= FormatFloat(varia.MascaraValor,VprDProdutoPedido.ValTotal); end; {******************************************************************************} procedure TFNovoPedidoCompra.CalculaKilosChapa; begin if (GProdutos.Cells[7,GProdutos.ALinha] <> '') and (GProdutos.Cells[8,GProdutos.ALinha] <> '') and (GProdutos.Cells[9,GProdutos.ALinha] <> '') then begin CarDChapaClasse; VprDProdutoPedido.QtdProduto := FunProdutos.RQuilosChapa(VprDProdutoPedido.EspessuraAco,VprDProdutoPedido.LarChapa,VprDProdutoPedido.ComChapa, VprDProdutoPedido.QtdChapa,VprDProdutoPedido.DensidadeVolumetricaAco ); VprDProdutoPedido.QtdSolicitada := VprDProdutoPedido.QtdProduto; if VprDProdutoPedido.QtdProduto <> 0 then GProdutos.Cells[11,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VprDProdutoPedido.QtdProduto) else GProdutos.Cells[11,GProdutos.ALinha]:= ''; if VprDProdutoPedido.QtdProduto <> 0 then GProdutos.Cells[12,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VprDProdutoPedido.QtdSolicitada) else GProdutos.Cells[12,GProdutos.ALinha]:= ''; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.CalculaValorTotal; begin CarDValorTotal; FunPedidoCompra.CalculaValorTotal(VprDPedidoCorpo); CarDValoresTela; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDValorTotal; begin if VprOperacao in [ocEdicao,ocInsercao] then begin VprDPedidoCorpo.ValFrete:= EValorFrete.AValor; CarDDesconto; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.EValorChange(Sender: TObject); begin if (VprOperacao in [ocEdicao,ocInsercao]) then CalculaValorTotal; end; {******************************************************************************} procedure TFNovoPedidoCompra.EFornecedorEnter(Sender: TObject); begin VprFornecedorAnterior := EFornecedor.Text; end; {******************************************************************************} procedure TFNovoPedidoCompra.BCadastrarClick(Sender: TObject); begin VprOperacao:= ocInsercao; VprDPedidoCorpo.Free; VprDPedidoCorpo:= TRBDPedidoCompraCorpo.Cria; GProdutos.ADados:= VprDPedidoCorpo.Produtos; GFracaoOP.ADados:= VprDPedidoCorpo.FracaoOP; GProdutos.CarregaGrade; GFracaoOP.CarregaGrade; LimpaComponentes(ScrollBox1,0); EstadoBotoes(False); InicializaTela; ValidaGravacao.execute; end; {******************************************************************************} procedure TFNovoPedidoCompra.VisualizarOrdemProduo1Click(Sender: TObject); begin FOrdemProducaoGenerica := TFOrdemProducaoGenerica.CriarSDI(self,'',FPrincipal.VerificaPermisao('FOrdemProducaoGenerica')); FOrdemProducaoGenerica.ConsultaOps(VprDFracaoOPPedido.CodFilialFracao,VprDFracaoOPPedido.SeqOrdem,VprDFracaoOPPedido.SeqFracao); FOrdemProducaoGenerica.Free; end; {******************************************************************************} procedure TFNovoPedidoCompra.PosEstagios; begin AdicionaSQLAbreTabela(Estagios, 'SELECT EPC.DATESTAGIO, EPC.DESMOTIVO, EST.NOMEST, USU.C_NOM_USU'+ ' FROM ESTAGIOPEDIDOCOMPRA EPC, ESTAGIOPRODUCAO EST, CADUSUARIOS USU'+ ' WHERE EST.CODEST = EPC.CODESTAGIO'+ ' AND USU.I_COD_USU = EPC.CODUSUARIO'+ ' AND EPC.SEQPEDIDO = '+ENumero.Text+ ' AND EPC.CODFILIAL = ' +IntToStr(VprDPedidoCorpo.CodFilial)+ ' order by EPC.SEQESTAGIO '); end; {******************************************************************************} procedure TFNovoPedidoCompra.PageControl1Change(Sender: TObject); begin if PageControl1.ActivePage = PEstagio then if ENumero.AInteiro <> 0 then PosEstagios; end; {******************************************************************************} procedure TFNovoPedidoCompra.GFracaoOPSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if GFracaoOP.AEstadoGrade in [egInsercao, egEdicao] then begin case GFracaoOP.AColuna of 2: begin if ExisteClienteFracaoOP then begin GFracaoOP.Cells[4,GFracaoOP.ALinha]:= VprDFracaoOPPedido.NomCliente; end; end; end; end; end; procedure TFNovoPedidoCompra.GMateriaPrimaCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDMateriaPrimaProduto:= TRBDProdutoPedidoCompraMateriaPrima(VprDProdutoPedido.MateriaPrima.Items[VpaLinha -1]); GMateriaPrima.Cells[1,GMateriaPrima.ALinha]:= VprDMateriaPrimaProduto.CodProduto; GMateriaPrima.Cells[2,GMateriaPrima.ALinha]:= VprDMateriaPrimaProduto.NomProduto; if VprDMateriaPrimaProduto.QtdChapa <> 0 then GMateriaPrima.Cells[3,GMateriaPrima.ALinha]:= formatFloat('#,###,0',VprDMateriaPrimaProduto.QtdChapa) else GMateriaPrima.Cells[3,GMateriaPrima.ALinha]:= ''; if VprDMateriaPrimaProduto.LarChapa <> 0 then GMateriaPrima.Cells[4,GMateriaPrima.ALinha]:= formatFloat('#,###,0.00',VprDMateriaPrimaProduto.LarChapa) else GMateriaPrima.Cells[4,GMateriaPrima.ALinha]:= ''; if VprDMateriaPrimaProduto.QtdChapa <> 0 then GMateriaPrima.Cells[5,GMateriaPrima.ALinha]:= formatFloat('#,###,0.00',VprDMateriaPrimaProduto.ComChapa) else GMateriaPrima.Cells[5,GMateriaPrima.ALinha]:= ''; if VprDMateriaPrimaProduto.QtdProduto <> 0 then GMateriaPrima.Cells[6,GMateriaPrima.ALinha]:= formatFloat('#,###,0.00',VprDMateriaPrimaProduto.QtdProduto) else GMateriaPrima.Cells[6,GMateriaPrima.ALinha]:= ''; end; {******************************************************************************} function TFNovoPedidoCompra.ExisteClienteFracaoOP: Boolean; begin Result:= False; if GFracaoOP.Cells[1,GFracaoOP.ALinha] <> '' then VprDFracaoOPPedido.CodFilialFracao:= StrToInt(GFracaoOP.Cells[1,GFracaoOP.ALinha]) else VprDFracaoOPPedido.CodFilialFracao:= 0; if GFracaoOP.Cells[2,GFracaoOP.ALinha] <> '' then VprDFracaoOPPedido.SeqOrdem:= StrToInt(GFracaoOP.Cells[2,GFracaoOP.ALinha]) else VprDFracaoOPPedido.SeqOrdem:= 0; Result:= FunPedidoCompra.ExisteClienteFracaoOP(VprDFracaoOPPedido); end; {******************************************************************************} procedure TFNovoPedidoCompra.ECompradorCadastrar(Sender: TObject); begin FCompradores:= TFCompradores.CriarSDI(Application,'',True); FCompradores.BCadastrar.Click; FCompradores.ShowModal; FCompradores.Free; Localiza.AtualizaConsulta; end; procedure TFNovoPedidoCompra.EContatoChange(Sender: TObject); begin end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDProdutoOrcamentoTela(VpaProdutos: TList); var VpfLaco: Integer; VpfDProdutoPedidoCompra, VpfDProdutoPedidoCompraAux: TRBDProdutoPedidoCompra; begin for VpfLaco:= 0 to VpaProdutos.Count-1 do begin VpfDProdutoPedidoCompraAux:= TRBDProdutoPedidoCompra(VpaProdutos.Items[VpfLaco]); // fazer a importação dos produtos para a lista do pedido aqui, pois será // necessário fazer um controle externo na lista de produtos mais tarde. VpfDProdutoPedidoCompra:= VprDPedidoCorpo.AddProduto; VpfDProdutoPedidoCompra.SeqProduto:= VpfDProdutoPedidoCompraAux.SeqProduto; VpfDProdutoPedidoCompra.CodCor:= VpfDProdutoPedidoCompraAux.CodCor; VpfDProdutoPedidoCompra.CodProduto:= VpfDProdutoPedidoCompraAux.CodProduto; end; GProdutos.CarregaGrade; GProdutos.Col:= 1; for VpfLaco:= 1 to GProdutos.RowCount-1 do begin VpfDProdutoPedidoCompraAux:= TRBDProdutoPedidoCompra(VpaProdutos.Items[VpfLaco-1]); VprProdutoAnterior:= ''; VprCorAnterior:= ''; GProdutos.ALinha:= VpfLaco; VprDProdutoPedido:= TRBDProdutoPedidoCompra(VprDPedidoCorpo.Produtos.Items[VpfLaco-1]); ExisteProduto; ExisteCor; VprDProdutoPedido.QtdSolicitada:= VpfDProdutoPedidoCompraAux.QtdSolicitada; VprDProdutoPedido.QtdProduto:= VpfDProdutoPedidoCompraAux.QtdProduto; if VprIndMapaCompras then begin VprDProdutoPedido.ValUnitario := VpfDProdutoPedidoCompraAux.ValUnitario; VprDProdutoPedido.PerIPI := VpfDProdutoPedidoCompraAux.PerIPI; GProdutos.Cells[13,GProdutos.ALinha]:= FormatFloat(Varia.MascaraValor,VprDProdutoPedido.ValUnitario); GProdutos.Cells[16,GProdutos.ALinha]:= FormatFloat('0.00',VprDProdutoPedido.PerIPI); end; // carregar corretamente a quantidade do produto, já que ela é redefinida // para 1 dentro do ExisteProduto GProdutos.Cells[11,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VpfDProdutoPedidoCompraAux.QtdSolicitada); GProdutos.Cells[12,GProdutos.ALinha]:= FormatFloat(Varia.MascaraQtd,VpfDProdutoPedidoCompraAux.QtdProduto); CarDClasseProdutos; VprDProdutoPedido.QtdChapa:= VpfDProdutoPedidoCompraAux.QtdChapa; VprDProdutoPedido.LarChapa:= VpfDProdutoPedidoCompraAux.LarChapa; VprDProdutoPedido.ComChapa:= VpfDProdutoPedidoCompraAux.ComChapa; end; GProdutos.CarregaGrade; GProdutos.Col:= 1; CalculaValorTotal; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDFracoesOrcamentoTela(VpaFracoes : TList); var VpfLaco : Integer; VpfDFracaoOrcamento : TRBDSolicitacaoCompraFracaoOP; begin for VpfLaco := 0 to VpaFracoes.Count - 1 do begin VpfDFracaoOrcamento := TRBDSolicitacaoCompraFracaoOP(VpaFracoes.Items[VpfLaco]); VprDFracaoOPPedido := VprDPedidoCorpo.AddFracaoOP; VprDFracaoOPPedido.CodFilialFracao := VpfDFracaoOrcamento.CodFilialFracao; VprDFracaoOPPedido.SeqOrdem := VpfDFracaoOrcamento.SeqOrdem; VprDFracaoOPPedido.SeqFracao := VpfDFracaoOrcamento.SeqFracao; VprDFracaoOPPedido.NomCliente := VpfDFracaoOrcamento.NomCliente; end; GFracaoOP.CarregaGrade; end; {******************************************************************************} procedure TFNovoPedidoCompra.CarDMapaComprasparaPedidoCompra(VpaDOrcamento : TRBDOrcamentoCompraCorpo;VpaDOrcamentoFornecedor: TRBDOrcamentoCompraFornecedor); begin EFornecedor.AInteiro := VpaDOrcamentoFornecedor.CodFornecedor; EFornecedor.Atualiza; EContato.Text := VpaDOrcamentoFornecedor.NomContato; EEmailComprador.Text := VpaDOrcamentoFornecedor.DesEmailFornecedor; EComprador.AInteiro := VpaDOrcamento.CodComprador; EComprador.Atualiza; if VpaDOrcamento.CodCondicaoPagto <> 0 then begin ECondicoesPagto.AInteiro := VpaDOrcamento.CodCondicaoPagto; ECondicoesPagto.Atualiza; end; if VpaDOrcamento.CodFormaPagto <> 0 then begin EFormaPagto.AInteiro := VpaDOrcamento.CodFormaPagto; EFormaPagto.Atualiza; end; EValorFrete.AValor := VpaDOrcamentoFornecedor.ValFrete; end; {******************************************************************************} procedure TFNovoPedidoCompra.BEnviarClick(Sender: TObject); var VpfResultado : String; begin if Config.EnviarPedidoDeCompraemPDFparaFornecedor then VpfResultado:= FunPedidoCompra.EnviaEmailPDFFornecedor(VprDPedidoCorpo) else VpfResultado := FunPedidoCompra.EnviaEmailFornecedor(VprDPedidoCorpo); if VpfResultado <> '' then aviso(VpfResultado); end; {******************************************************************************} procedure TFNovoPedidoCompra.EEmailCompradorKeyPress(Sender: TObject; var Key: Char); begin if key in [' ','/','ç','\','ã',':'] then key := #0; end; {******************************************************************************} procedure TFNovoPedidoCompra.EFornecedorAlterar(Sender: TObject); begin if EFornecedor.ALocaliza.Loca.Tabela.FieldByName(EFornecedor.AInfo.CampoCodigo).AsInteger <> 0 then begin FNovoCliente := TFNovoCliente.criarSDI(Application,'',FPrincipal.VerificaPermisao('FNovoCliente')); AdicionaSQlAbreTabela(FNovoCliente.CadClientes,'Select * from CadClientes '+ ' Where I_COD_CLI = '+EFornecedor.ALocaliza.Loca.Tabela.FieldByName(EFornecedor.AInfo.CampoCodigo).asString); FNovoCliente.CadClientes.Edit; FNovoCliente.Paginas.ActivePage := FNovoCliente.PFornecedor; FNovoCliente.ShowModal; Localiza.AtualizaConsulta; FNovoCliente.free; end; end; {******************************************************************************} procedure TFNovoPedidoCompra.AdicionarTodososProdutosdoFornecedor1Click( Sender: TObject); begin FunPedidoCompra.AdicionaTodosProdutosFornecedor(EFornecedor.AInteiro,VprDPedidoCorpo); GProdutos.CarregaGrade; end; {******************************************************************************} procedure TFNovoPedidoCompra.ECodTransportadoraCadastrar(Sender: TObject); begin FNovoCliente := TFNovoCliente.criarSDI(Application,'',FPrincipal.VerificaPermisao('FNovoCliente')); FNovoCliente.CadClientes.Insert; FNovoCliente.CadClientesC_IND_TRA.AsString := 'S'; FNovoCliente.CadClientesC_IND_CLI.AsString := 'N'; FNovoCliente.showmodal; FNovoCliente.free; end; {******************************************************************************} procedure TFNovoPedidoCompra.ETamanhoRetorno( VpaColunas: TRBColunasLocaliza); begin if (VprOperacao in [ocinsercao,ocedicao]) and (VprDProdutoPedido <> nil) then begin if VpaColunas.items[0].AValorRetorno <> '' then begin VprDProdutoPedido.CodTamanho := StrToINt(VpaColunas.items[0].AValorRetorno); VprDProdutoPedido.NomTamanho := VpaColunas.items[1].AValorRetorno; GProdutos.Cells[5,GProdutos.ALinha] := VpaColunas.items[0].AValorRetorno; GProdutos.Cells[6,GProdutos.ALinha] := VpaColunas.items[1].AValorRetorno; end else begin VprDProdutoPedido.CodTamanho := 0; VprDProdutoPedido.NomTamanho := ''; end; end; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFNovoPedidoCompra]); end.
{------------------------------------------------------------------------------ // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2009 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com // EasyComponents是HhfComponents的升级版本,当前主版本号为2.0 // +2011-04-10 15:24:44 TEasyCustomTreeComboBox ------------------------------------------------------------------------------} unit untEasyTreeComboBox; interface uses Windows, Messages, StdCtrls, Classes, Graphics, Controls, SysUtils, Forms, Math, ComObj, untEasyAbout, untEasyCustomDropDownEdit, ComCtrls, Imglist, Menus; type TEasyCustomTreeComboBox = class; TEasySelectMode = (smSingleClick, smDblClick); TEasyDropPosition = (dpAuto, dpDown, dpUp); //acceptdrop=true allow tree dropping TEasyDropDown = procedure(Sender: TObject; var acceptdrop: boolean) of object; //canceled = true ignores SelecteItem and stores Old Edit caption //canceled = false on selection and true when Cancel (key=Esc, click outside of tree...) TEasyDropUp = procedure(Sender: TObject; canceled: boolean) of object; TEasyDropTreeForm = class(TForm) private FDeActivate: DWORD; procedure WMClose(var Msg: TMessage); message WM_CLOSE; procedure WMActivate(var Message: TWMActivate); message WM_ACTIVATE; function GetParentWnd: HWnd; published property DeActivateTime: DWORD read FDeActivate; end; { TEasyCustomTreeComboBox } TEasyCustomTreeComboBox = class(TEasyCustomDropDownEdit) private { Private declarations } FTreeView : TTreeview; FDropTreeForm : TEasyDropTreeForm; FDropWidth : integer; FDropHeight : integer; FEditorEnabled: boolean; FExpandOnDrop : boolean; FCollapseOnDrop: boolean; FDropPosition : TEasyDropPosition; FOldCaption : string; FOndropDown : TEasydropDown; FOndropUP : TEasydropUP; FAutoOpen : boolean; FSelectMode : TEasyselectMode; // FFlat : Boolean; function GetAbsoluteIndex: Integer; procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; function GetImages: TCustomImageList; function GetIndent: Integer; function GetReadOnlyTree: boolean; function GetRightClickSelect: Boolean; function GetRowSelect: Boolean; function GetSelection: Integer; function GetShowButtons: Boolean; function GetShowLines: Boolean; function GetShowRoot: Boolean; function GetSortType: TSortType; function GetStateImages: TCustomImageList; function GetTreeBorder: TBorderStyle; function GetTreeColor: TColor; function GetTreeFont: Tfont; function GetTreeNodes: TTreeNodes; function GetTreepopupmenu: Tpopupmenu; procedure SetCollapseOnDrop(const Value: boolean); procedure SetEditorEnabled(const Value: boolean); procedure SetExpandOnDrop(const Value: boolean); procedure SetImages(const Value: TCustomImageList); procedure SetIndent(const Value: Integer); procedure SetReadOnlyTree(const Value: boolean); procedure SetRightClickSelect(const Value: Boolean); procedure SetRowSelect(const Value: Boolean); procedure SetSelection(const Value: Integer); procedure SetShowButtons(const Value: Boolean); procedure SetShowLines(const Value: Boolean); procedure SetShowRoot(const Value: Boolean); procedure SetSortType(const Value: TSortType); procedure SetStateImages(const Value: TCustomImageList); procedure SetTreeBorder(const Value: TBorderStyle); procedure SetTreeColor(const Value: TColor); procedure SetTreeFont(const Value: Tfont); procedure SetTreeNodes(const Value: TTreeNodes); procedure SetTreepopupmenu(const Value: Tpopupmenu); protected procedure CreateParams(var Params: TCreateParams); override; procedure KeyPress(var Key: Char); override; procedure CreateWnd; override; procedure DestroyWnd; override; function CreateTreeview(AOwner: TComponent): TTreeView; virtual; procedure DropButtonClick(Sender: TObject); //树宿主窗体事件 procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure TreeViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TreeViewChange(Sender: TObject; Node: TTreeNode); procedure TreeViewKeyPress(Sender: TObject; var Key: Char); procedure TreeViewDblClick(Sender: TObject); procedure TreeViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure TreeViewBlockChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); procedure TreeViewExit(Sender: TObject); //隐藏树 procedure HideTree(canceled: boolean); procedure FindTextInNode; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; //显示树 procedure ShowTree; property AbsoluteIndex: Integer read GetAbsoluteIndex; property Treeview: TTreeview read FTreeView; { Extend Property } property Anchors; property EnterTAB; property BorderColor; property Color; property FocusColor; property AutoFocus; property AppereanceStyle; property Button; property Flat; property TextRightAlign; property EditLabel; property LabelPosition; property LabelSpacing; property SelectionColor; property SelectionColorTo; property SelectionGradient; property OnMouseEnter; property OnMouseLeave; property OnButtonClick; { Extend Property end } { property } property AutoOpen: boolean read FAutoOpen write FAutoOpen default True; property SelectMode: TEasySelectMode read FSelectMode write FSelectMode default smDblClick; property DropWidth: integer read FDropWidth write fDropWidth; property DropHeight: integer read FDropHeight write fDropHeight; property Items: TTreeNodes read GetTreeNodes write SetTreeNodes; property EditorEnabled: boolean read FEditorEnabled write SetEditorEnabled default true; property CollapseOnDrop: boolean read FCollapseOnDrop write SetCollapseOnDrop default false; property ExpandOnDrop: boolean read FExpandOnDrop write SetExpandOnDrop default false; property DropPosition: TEasyDropPosition read FDropPosition write FDropPosition default dpAuto; //----- Tree properties property ReadOnlyTree: boolean read GetReadOnlyTree write SetReadOnlyTree default true; property ShowButtons: Boolean read GetShowButtons write SetShowButtons default True; property ShowLines: Boolean read GetShowLines write SetShowLines default True; property ShowRoot: Boolean read GetShowRoot write SetShowRoot default True; property SortType: TSortType read GetSortType write SetSortType default stNone; property RightClickSelect: Boolean read GetRightClickSelect write SetRightClickSelect default False; property RowSelect: Boolean read GetRowSelect write SetRowSelect default False; property Indent: Integer read GetIndent write SetIndent; property Images: TCustomImageList read GetImages write SetImages; property StateImages: TCustomImageList read GetStateImages write SetStateImages; property TreeFont: Tfont read GetTreeFont write SetTreeFont; property TreeColor: TColor read GetTreeColor write SetTreeColor; property TreeBorder: TBorderStyle read GetTreeBorder write SetTreeBorder; property TreePopupMenu: Tpopupmenu read GetTreepopupmenu write SetTreepopupmenu; property Selection: Integer read GetSelection write SetSelection; //-------- property OnDropDown: TEasyDropDown read FOnDropDown write FOnDropDown; property OnDropUp: TEasyDropUp read FOnDropUP write FOnDropUp; property Align; //------- Edit Properties property Constraints; property DragKind; property AutoSelect; property AutoSize; property BorderStyle; property BevelKind; property BevelInner; property BevelOuter; property BevelEdges; property DragCursor; property DragMode; property Enabled; property Font; property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property Height; property Width; property Text; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnEndDock; property OnStartDock; end; { TEasyTreeComboBox } TEasyTreeComboBox = class(TEasyCustomTreeComboBox) published property Anchors; property EnterTAB; property BorderColor; property Color; property FocusColor; property AutoFocus; property AppereanceStyle; property Button; property Flat; property TextRightAlign; property EditLabel; property LabelPosition; property LabelSpacing; property SelectionColor; property SelectionColorTo; property SelectionGradient; property OnMouseEnter; property OnMouseLeave; property OnButtonClick; { Extend Property end } { property } property AutoOpen; property SelectMode; property DropWidth; property DropHeight; property Items; property EditorEnabled; property CollapseOnDrop; property ExpandOnDrop; property DropPosition; //----- Tree properties property ReadOnlyTree; property ShowButtons; property ShowLines; property ShowRoot; property SortType; property RightClickSelect; property RowSelect; property Indent; property Images; property StateImages; property TreeFont; property TreeColor; property TreeBorder; property TreePopupMenu; property Selection; //-------- property OnDropDown; property OnDropUp; property Align; //------- Edit Properties property Constraints; property DragKind; property AutoSelect; property AutoSize; property BorderStyle; property BevelKind; property BevelInner; property BevelOuter; property BevelEdges; property Ctl3D; property DragCursor; property DragMode; property Enabled; property Font; property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property Height; property Width; property Text; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnEndDock; property OnStartDock; end; implementation { TEasyDropTreeForm } function TEasyDropTreeForm.GetParentWnd: HWnd; var Last, P: HWnd; begin P := GetParent((Owner as TWinControl).Handle); Last := P; while P <> 0 do begin Last := P; P := GetParent(P); end; Result := Last; end; procedure TEasyDropTreeForm.WMActivate(var Message: TWMActivate); begin inherited; if Message.Active = integer(False) then begin if Visible then begin FDeActivate := GetTickCount; Hide; end; end else begin SendMessage(getParentWnd, WM_NCACTIVATE, 1, 0); end; end; procedure TEasyDropTreeForm.WMClose(var Msg: TMessage); begin inherited; // end; { TEasyCustomTreeComboBox } constructor TEasyCustomTreeComboBox.Create(AOwner: TComponent); begin inherited Create(AOwner); SetBounds(left, top, 200, 25); if not (csDesigning in ComponentState) then begin FDropTreeForm := TEasyDropTreeForm.CreateNew(self, 0); with FDropTreeForm do begin BorderStyle := bsNone; // FormStyle := fsStayOnTop; Visible := False; Width := FDropWidth; Height := FDropHeight; OnClose := FormClose; end; end; FTreeView := CreateTreeView(Self); with FTreeView do begin if not (csDesigning in ComponentState) then Parent := FDropTreeForm else Parent := Self; if not (csDesigning in ComponentState) then Align := alClient else Width := 0; ReadOnly := true; ShowButtons := True; ShowLines := True; ShowRoot := True; SortType := stNone; RightClickSelect := False; RowSelect := False; if not (csDesigning in ComponentState) then Visible := True else Visible := False; OnKeyDown := TreeViewKeyDown; OnChange := TreeViewChange; OnMouseDown := TreeViewMouseDown; OnDblClick := TreeViewDblClick; OnKeyPress := TreeViewKeyPress; end; ControlStyle := ControlStyle - [csSetCaption]; FDropHeight := 100; FDropWidth := self.width; FEditorEnabled := true; ReadOnly := false; FCollapseOnDrop := false; FExpandOnDrop := false; FDropPosition := dpAuto; FOldCaption := ''; FAutoOpen := true; FselectMode := smDblClick; OnButtonClick := DropButtonClick; end; procedure TEasyCustomTreeComboBox.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style or ES_MULTILINE or WS_CLIPCHILDREN; end; function TEasyCustomTreeComboBox.CreateTreeview( AOwner: TComponent): TTreeView; begin Result := TTreeView.Create(AOwner); end; procedure TEasyCustomTreeComboBox.CreateWnd; begin inherited CreateWnd; end; destructor TEasyCustomTreeComboBox.Destroy; begin if not (csDesigning in ComponentState) then FDropTreeForm.Free; inherited Destroy; end; procedure TEasyCustomTreeComboBox.DestroyWnd; begin inherited; // end; procedure TEasyCustomTreeComboBox.DropButtonClick(Sender: TObject); begin if csDesigning in ComponentState then Exit; if not FDropTreeForm.Visible and (GetTickCount - FDropTreeForm.DeActivateTime > 250) then ShowTree; end; procedure TEasyCustomTreeComboBox.FindTextInNode; var i: integer; itm, its: TTreenode; sfind, stext: string; found: boolean; function noopen(Node: TTreenode): boolean; begin result := true; if node = nil then exit; while Node.Parent <> nil do begin node := Node.Parent; if not node.Expanded then exit; end; Result := false; end; begin sfind := UpperCase(text); itm := nil; found := false; if FTreeview.Selected<> nil then begin itm := FTreeview.Selected; stext := UpperCase(itm.text); if AnsiPos(sfind, stext) = 1 then found := true; end; if not found then repeat for i := 0 to FTreeView.Items.count - 1 do begin // Don't search if AutoOpen disabled and the nodes are not open. if not AutoOpen then if noopen(FTreeView.items[i]) then continue; stext := UpperCase(FTreeView.Items[i].text); if AnsiPos(sfind, stext) = 1 then begin itm := FTreeView.items[i]; Break; end; end; if length(sfind) > 0 then delete(sfind, length(sfind), 1); until (itm <> nil) or (sfind = ''); if itm = nil then begin FTreeView.OnChanging := TreeViewBlockChanging; Exit; end; its := itm; if AutoOpen then begin while itm.Parent <> nil do begin itm := itm.Parent; itm.Expand(false); end; end; FTreeView.Selected := its; FTreeView.Selected.MakeVisible; end; procedure TEasyCustomTreeComboBox.FormClose(Sender: TObject; var Action: TCloseAction); begin // end; function TEasyCustomTreeComboBox.GetAbsoluteIndex: Integer; begin Result := -1; if Assigned(FTreeView.Selected) then Result := FTreeView.Selected.AbsoluteIndex; end; function TEasyCustomTreeComboBox.GetImages: TCustomImageList; begin result := FtreeView.Images; end; function TEasyCustomTreeComboBox.GetIndent: Integer; begin Result := FtreeView.Indent; end; function TEasyCustomTreeComboBox.GetReadOnlyTree: boolean; begin Result := FtreeView.ReadOnly; end; function TEasyCustomTreeComboBox.GetRightClickSelect: Boolean; begin Result := FtreeView.RightClickSelect; end; function TEasyCustomTreeComboBox.GetRowSelect: Boolean; begin Result := FtreeView.RowSelect; end; function TEasyCustomTreeComboBox.GetSelection: Integer; begin try if Assigned(FTreeView.Selected) then Result := FTreeView.Selected.AbsoluteIndex else Result := -1; except on Exception do Result := -1; end; end; function TEasyCustomTreeComboBox.GetShowButtons: Boolean; begin result := FtreeView.ShowButtons; end; function TEasyCustomTreeComboBox.GetShowLines: Boolean; begin result := FtreeView.ShowLines; end; function TEasyCustomTreeComboBox.GetShowRoot: Boolean; begin result := FtreeView.ShowRoot; end; function TEasyCustomTreeComboBox.GetSortType: TSortType; begin Result := FtreeView.SortType; end; function TEasyCustomTreeComboBox.GetStateImages: TCustomImageList; begin result := FtreeView.StateImages; end; function TEasyCustomTreeComboBox.GetTreeBorder: TBorderStyle; begin Result := FTreeView.BorderStyle; end; function TEasyCustomTreeComboBox.GetTreeColor: TColor; begin Result := FtreeView.Color; end; function TEasyCustomTreeComboBox.GetTreeFont: Tfont; begin result := FtreeView.Font; end; function TEasyCustomTreeComboBox.GetTreeNodes: TTreeNodes; begin Result := FTreeView.Items; end; function TEasyCustomTreeComboBox.GetTreepopupmenu: Tpopupmenu; begin result := FtreeView.PopupMenu; end; procedure TEasyCustomTreeComboBox.HideTree(canceled: boolean); begin if csDesigning in ComponentState then Exit; if not FdropTreeForm.Visible then Exit; FDropTreeForm.Hide; Application.CancelHint; if Canceled then begin Text := FOldCaption; end else begin if Assigned(FTreeView.Selected) then begin Text := FTreeView.Selected.Text; end; end; if Assigned(FOnDropUp) then FOnDropUP(self, Canceled); end; procedure TEasyCustomTreeComboBox.KeyPress(var Key: Char); begin inherited KeyPress(key); if (Key = Char(VK_RETURN)) then Key := #0; end; procedure TEasyCustomTreeComboBox.SetCollapseOnDrop(const Value: boolean); begin FCollapseOnDrop := Value; end; procedure TEasyCustomTreeComboBox.SetEditorEnabled(const Value: boolean); begin FEditorEnabled := Value; end; procedure TEasyCustomTreeComboBox.SetExpandOnDrop(const Value: boolean); begin FExpandOnDrop := Value; end; procedure TEasyCustomTreeComboBox.SetImages(const Value: TCustomImageList); begin FtreeView.Images := value; end; procedure TEasyCustomTreeComboBox.SetIndent(const Value: Integer); begin FtreeView.Indent := value; end; procedure TEasyCustomTreeComboBox.SetReadOnlyTree(const Value: boolean); begin FtreeView.ReadOnly := value; end; procedure TEasyCustomTreeComboBox.SetRightClickSelect( const Value: Boolean); begin FtreeView.RightClickSelect := value; end; procedure TEasyCustomTreeComboBox.SetRowSelect(const Value: Boolean); begin FtreeView.RowSelect := value; end; procedure TEasyCustomTreeComboBox.SetSelection(const Value: Integer); begin if (Value = -1) then begin FTreeView.Selected := nil; Text := ''; Exit; end; try FTreeView.Selected := FTreeView.Items[Value]; Text := FTreeView.Selected.Text; except on Exception do FTreeView.Selected := nil; end; end; procedure TEasyCustomTreeComboBox.SetShowButtons(const Value: Boolean); begin FtreeView.ShowButtons := value; end; procedure TEasyCustomTreeComboBox.SetShowLines(const Value: Boolean); begin FtreeView.ShowLines := value; end; procedure TEasyCustomTreeComboBox.SetShowRoot(const Value: Boolean); begin FtreeView.ShowRoot := value; end; procedure TEasyCustomTreeComboBox.SetSortType(const Value: TSortType); begin FtreeView.SortType := value; end; procedure TEasyCustomTreeComboBox.SetStateImages( const Value: TCustomImageList); begin FtreeView.StateImages := value; end; procedure TEasyCustomTreeComboBox.SetTreeBorder(const Value: TBorderStyle); begin FtreeView.BorderStyle := value; end; procedure TEasyCustomTreeComboBox.SetTreeColor(const Value: TColor); begin FtreeView.Color := value; end; procedure TEasyCustomTreeComboBox.SetTreeFont(const Value: Tfont); begin FtreeView.Font.Assign(value); end; procedure TEasyCustomTreeComboBox.SetTreeNodes(const Value: TTreeNodes); begin FTreeView.Items.Assign(Value); FTreeView.Update; end; procedure TEasyCustomTreeComboBox.SetTreepopupmenu( const Value: Tpopupmenu); begin FtreeView.PopupMenu := value; end; procedure TEasyCustomTreeComboBox.ShowTree; var p: TPoint; acpt: boolean; begin if csDesigning in ComponentState then Exit; if FDropTreeForm.Visible then Exit; FOldCaption := Caption; FDropTreeForm.Left := self.Left; FDropTreeForm.Top := self.Top; FDropTreeForm.Width := FDropWidth; FDropTreeForm.Height := FDropHeight; P := Point(0, 0); P := ClientToScreen(P); case FDropPosition of dpAuto: begin if P.y + fDropHeight >= GetSystemMetrics(SM_CYSCREEN) then begin //Up FdropTreeForm.Left := P.x; FdropTreeForm.Top := p.y - FDropHeight; end else begin //Down FdropTreeForm.Left := P.x; FdropTreeForm.Top := p.y + Height - 2; end; end; dpDown: begin FdropTreeForm.Left := P.x; FdropTreeForm.Top := p.y + Height - 2; end; dpUp: begin FdropTreeForm.Left := P.x; FdropTreeForm.Top := p.y - FDropHeight; end; end; if FCollapseOnDrop then FTreeView.FullCollapse; if FExpandOnDrop then FTreeView.FullExpand; acpt := true; FtreeView.Items.GetFirstNode; //Force return of correct items count FindTextInNode; if Assigned(FOnDropDown) then FOnDropdown(Self, acpt); if acpt then FDropTreeForm.Show; FTreeView.OnChanging := nil; // Please leave this here, otherwise procedure FindtextinNode must be modified end; procedure TEasyCustomTreeComboBox.TreeViewBlockChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); begin AllowChange := false; end; procedure TEasyCustomTreeComboBox.TreeViewChange(Sender: TObject; Node: TTreeNode); begin if csDesigning in ComponentState then Exit; if FDropTreeForm.Visible then begin if Assigned(Node) then Text := Node.Text; SelStart := 0; SelLength := Length(Text); end; end; procedure TEasyCustomTreeComboBox.TreeViewDblClick(Sender: TObject); begin if Fselectmode = smDblClick then HideTree(false); end; procedure TEasyCustomTreeComboBox.TreeViewExit(Sender: TObject); begin HideTree(False); end; procedure TEasyCustomTreeComboBox.TreeViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of VK_ESCAPE, VK_F4: begin HideTree(true); key := 0; end; VK_RETURN: begin HideTree(false); end; end; end; procedure TEasyCustomTreeComboBox.TreeViewKeyPress(Sender: TObject; var Key: Char); begin if key <= #27 then key := #0; // stop beeping end; procedure TEasyCustomTreeComboBox.TreeViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var AnItem: TTreeNode; HT: THitTests; begin if Fselectmode = smDblClick then exit; if FTreeView.Selected = nil then Exit; HT := FTreeView.GetHitTestInfoAt(X, Y); AnItem := FTreeView.GetNodeAt(X, Y); // We can add htOnLabel,htOnStateIcon,htOnItem,htOnLabel if (htOnitem in ht) and (AnItem <> nil) then begin HideTree(false); end; end; procedure TEasyCustomTreeComboBox.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; Message.Result := 1; // Message.Result and DLGC_WANTALLKEYS; end; procedure TEasyCustomTreeComboBox.WMKeyDown(var Message: TWMKeyDown); begin if csDesigning in ComponentState then Exit; inherited; case Message.CharCode of VK_DOWN: ShowTree; VK_F4: begin if FDropTreeForm.Visible then HideTree(False) else ShowTree; end; end; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Data.DBXMetaDataCommandFactory; interface uses Data.DBXCommon, Data.DBXPlatform, Data.DBXSqlScanner, Data.DBXCommonTable, Data.DBXMetaDataReader ; type TDBXMetaDataCommandFactory = class(TDBXCommandFactory) public class procedure RegisterMetaDataCommandFactory(const ObjectClass: TClass); static; class procedure UnRegisterMetaDataCommandFactory(const ObjectClass: TClass); static; function CreateCommand(DbxContext: TDBXContext; Connection: TDBXConnection; MorphicCommand: TDBXCommand): TDBXCommand; override; function CreateMetaDataReader: TDBXMetaDataReader; virtual; abstract; function GetProductName: string; virtual; end; TDBXDataExpressProviderContext = class(TDBXProviderContext) protected [Weak]FConnection: TDBXConnection; FScanner: TDBXSqlScanner; FParameterMarker: string; FMarkerIncludedInParameterName: Boolean; FUseAnsiStrings: Boolean; FRemoveIsNull: Boolean; private // procedure BindParametersByName(Command: TDBXCommand; ParameterNames: TDBXStringArray; ParameterValues: TDBXStringArray); procedure BindParametersByOrdinal(Command: TDBXCommand; ParameterNames: TDBXStringArray; ParameterValues: TDBXStringArray); function FindParameterByName(const ParameterName: string; ParameterNames: TDBXStringArray): Integer; public constructor Create; destructor Destroy; override; function GetPlatformTypeName(const DataType: Integer; const IsUnsigned: Boolean): string; override; function ExecuteQuery(const Sql: string; const ParameterNames: TDBXStringArray; const ParameterValues: TDBXStringArray): TDBXTable; override; function CreateTableStorage(const CollectionName: string; const Columns: TDBXValueTypeArray): TDBXTable; override; function CreateRowStorage(const CollectionName: string; const Columns: TDBXValueTypeArray): TDBXTableRow; override; procedure StartTransaction; override; procedure StartSerializedTransaction; override; procedure Commit; override; procedure Rollback; override; function GetVendorProperty(const name: string): string; override; protected function GetSqlParameterMarker: string; function GetMarkerIncludedInParameterName: Boolean; public property SqlParameterMarker: string read FParameterMarker; property IsMarkerIncludedInParameterName: Boolean read FMarkerIncludedInParameterName; property Connection: TDBXConnection read FConnection write FConnection; property UseAnsiStrings: Boolean read FUseAnsiStrings write FUseAnsiStrings; property RemoveIsNull: Boolean read FRemoveIsNull write FRemoveIsNull; end; TDBXMetaDataCommand = class(TDBXCommand) public constructor Create(DBXContext: TDBXContext; MorphicCommand: TDBXCommand; Provider: TDBXMetaDataReader); destructor Destroy; override; protected procedure SetRowSetSize(const RowSetSize: Int64); override; procedure SetMaxBlobSize(const MaxBlobSize: Int64); override; function GetRowsAffected: Int64; override; function DerivedGetNextReader: TDBXReader; override; procedure DerivedOpen; override; procedure DerivedClose; override; procedure DerivedPrepare; override; function DerivedExecuteQuery: TDBXReader; override; procedure DerivedExecuteUpdate; override; private function CreateValueType(Name: string; DataType: Integer; Size: Integer): TDBXValueType; function FetchDatabaseColumns: TDBXTable; private FQueryCommand: TDBXCommand; [Weak]FReader: TDBXMetaDataReader; end; TDBXReaderTableStorage = class(TDBXRowTable) private FLastNext: Boolean; FCommand: TDBXCommand; FReader: TDBXReader; FColumns: TDBXValueTypeArray; FNextCalled: Boolean; public constructor Create(Command: TDBXCommand; Reader: TDBXReader); destructor Destroy; override; function GetOrdinal(const ColumnName: string): Integer; override; function First: Boolean; override; function Next: Boolean; override; function InBounds: Boolean; override; procedure Close; override; protected function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override; function GetColumns: TDBXValueTypeArray; override; function GetStorage: TObject; override; function GetCommand: TObject; override; end; implementation uses Data.DBXClassRegistry, System.SysUtils, Data.DBXCommonResStrs ; const ParameterQuote = '"'; DatabaseCollectionName = 'Database'; QuoteCharOrdinal = 0; ProcedureQuoteCharOrdinal = 1; MaxCommandsOrdinal = 2; SupportsTransactionsOrdinal = 3; SupportsNestedTransactionsOrdinal = 4; SupportsRowSetSizeOrdinal = 5; ProductVersionOrdinal = 6; ProductNameOrdinal = 7; QuotePrefixOrdinal = 8; QuoteSuffixOrdinal = 9; SupportsLowerCaseIdentifiersOrdinal = 10; SupportsUpperCaseIdentifiersOrdinal = 11; SupportsSPReturnCode = 12; SupportsParameterMetadata = 13; SupportsCatalogFunctions = 14; SupportsCatalogs = 15; SupportsSchemas = 16; DatabaseColumnCount = 17; type TDBXMetaDataDbxReader = class; TDatabaseCursor = class; TDBXMetaDataRow = class; TDBXMetaDataDbxReader = class(TDBXReader) public constructor Create(DBXContext: TDBXContext; Row: TDBXMetaDataRow; Cursor: TDBXTable); destructor Destroy; override; protected function DerivedNext: Boolean; override; procedure DerivedClose; override; function GetByteReader: TDBXByteReader; override; private FByteReader: TDBXReaderByteReader; function MapToDBXType(ColumnType: Integer): Integer; private FCursor: TDBXTable; end; TDatabaseCursor = class(TDBXCustomMetaDataTable) private FDatabaseRow: TDBXSingleValueRow; public constructor Create(Columns: TDBXValueTypeArray; Provider: TDBXMetaDataReader; TypeNames: TDBXPlatformTypeNames); function Next: Boolean; override; destructor Destroy; override; protected function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override; private FReader: TDBXMetaDataReader; FRow: Integer; end; TDBXMetaDataRow = class(TDBXRow) protected constructor Create(DBXContext: TDBXContext; Row: TDBXTableRow); protected procedure GetWideString(DbxValue: TDBXWideStringValue; var WideStringBuilder: TDBXWideStringBuilder; var IsNull: LongBool); override; procedure GetBoolean(DbxValue: TDBXBooleanValue; var Value: LongBool; var IsNull: LongBool); override; procedure GetUInt8(DbxValue: TDBXUInt8Value; var Value: Byte; var IsNull: LongBool); override; procedure GetInt8(DbxValue: TDBXInt8Value; var Value: ShortInt; var IsNull: LongBool); override; procedure GetUInt16(DbxValue: TDBXUInt16Value; var Value: Word; var IsNull: LongBool); override; procedure GetInt16(DbxValue: TDBXInt16Value; var Value: SmallInt; var IsNull: LongBool); override; procedure GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32; var IsNull: LongBool); override; procedure GetInt64(DbxValue: TDBXInt64Value; var Value: Int64; var IsNull: LongBool); override; private FRow: TDBXTableRow; end; function TDBXMetaDataCommandFactory.GetProductName: string; begin Result := ''; end; class procedure TDBXMetaDataCommandFactory.RegisterMetaDataCommandFactory(const ObjectClass: TClass); var ClassRegistry: TClassRegistry; ClassName: string; begin ClassRegistry := TClassRegistry.GetClassRegistry; ClassName := ObjectClass.ClassName; if not ClassRegistry.HasClass(ClassName) then ClassRegistry.RegisterClass(ClassName, ObjectClass); { Do not resource } end; class procedure TDBXMetaDataCommandFactory.UnRegisterMetaDataCommandFactory( const ObjectClass: TClass); var ClassName: string; begin ClassName := ObjectClass.ClassName; TClassRegistry.GetClassRegistry.UnRegisterClass(ClassName); end; function TDBXMetaDataCommandFactory.CreateCommand(DbxContext: TDBXContext; Connection: TDBXConnection; MorphicCommand: TDBXCommand): TDBXCommand; var Reader: TDBXMetaDataReader; ProviderContext: TDBXDataExpressProviderContext; ProductName: string; begin ProductName := GetProductName; if (ProductName = '') or (ProductName = Connection.ProductName) then begin Reader := TDBXMetaDataReader(TDBXDriverHelp.GetMetaDataReader(Connection)); if Reader = nil then begin Reader := CreateMetaDataReader; ProviderContext := TDBXDataExpressProviderContext.Create; ProviderContext.Connection := Connection; ProviderContext.UseAnsiStrings := TDBXProviderContext.UseAnsiString(Reader.ProductName); ProviderContext.RemoveIsNull := True; Reader.Context := ProviderContext; Reader.Version := TDBXConnection(Connection).ProductVersion; TDBXDriverHelp.SetMetaDataReader(Connection, Reader); end; Result := TDBXMetaDataCommand.Create(DBXContext, MorphicCommand, Reader); end else Result := nil; end; constructor TDBXDataExpressProviderContext.Create; begin inherited Create; end; destructor TDBXDataExpressProviderContext.Destroy; begin FreeAndNil(FScanner); inherited Destroy; end; function TDBXDataExpressProviderContext.GetPlatformTypeName(const DataType: Integer; const IsUnsigned: Boolean): string; begin case DataType of TDBXDataTypes.Uint8Type: Result := 'Byte'; TDBXDataTypes.Int8Type: Result := 'ShortInt'; TDBXDataTypes.UInt16Type: Result := 'Word'; TDBXDataTypes.Int16Type: Result := 'SmallInt'; TDBXDataTypes.UInt32Type, TDBXDataTypes.Int32Type: Result := 'TInt32'; TDBXDataTypes.UInt64Type, TDBXDataTypes.Int64Type: Result := 'Int64'; TDBXDataTypes.BooleanType: Result := 'Boolean'; TDBXDataTypes.DateType: Result := 'TDBXDate'; TDBXDataTypes.TimeType: Result := 'TDBXTime'; TDBXDataTypes.TimeStampType: Result := 'TSQLTimeStamp'; TDBXDataTypes.IntervalType: Result := 'TSQLTimeStamp'; TDBXDataTypes.TimeStampOffsetType: Result := 'TSQLTimeStampOffset'; TDBXDataTypes.WideStringType: Result := 'String'; TDBXDataTypes.AnsiStringType: Result := 'AnsiString'; TDBXDataTypes.BcdType: Result := 'TBcd'; TDBXDataTypes.SingleType: Result := 'Single'; TDBXDataTypes.DoubleType: Result := 'Double'; TDBXDataTypes.BlobType, TDBXDataTypes.BytesType, TDBXDataTypes.VarBytesType: Result := 'TBytes'; TDBXDataTypes.ObjectType: Result := 'TObject'; else raise Exception.Create(SUnknownDataType); end; end; function TDBXDataExpressProviderContext.GetSqlParameterMarker: string; begin Result := FParameterMarker; end; function TDBXDataExpressProviderContext.GetMarkerIncludedInParameterName: Boolean; begin Result := FMarkerIncludedInParameterName; end; function TDBXDataExpressProviderContext.ExecuteQuery(const Sql: string; const ParameterNames: TDBXStringArray; const ParameterValues: TDBXStringArray): TDBXTable; var Reader: TDBXReader; Command: TDBXCommand; begin Command := FConnection.CreateCommand; Command.Text := Sql; try if ParameterValues <> nil then begin BindParametersByOrdinal(Command, ParameterNames, ParameterValues); end; Reader := Command.ExecuteQuery; if Reader = nil then Result := nil else begin Result := TDBXStringTrimTable.CreateTrimTableIfNeeded(TDBXReaderTableStorage.Create(Command,Reader)); // When the Result is freed, this Command will be freed. // Command := nil; end; finally FreeAndNil(Command); end; end; function TDBXDataExpressProviderContext.CreateTableStorage(const CollectionName: string; const Columns: TDBXValueTypeArray): TDBXTable; begin Result := nil; end; function TDBXDataExpressProviderContext.CreateRowStorage(const CollectionName: string; const Columns: TDBXValueTypeArray): TDBXTableRow; begin Result := nil; end; procedure TDBXDataExpressProviderContext.StartTransaction; begin end; procedure TDBXDataExpressProviderContext.StartSerializedTransaction; begin end; procedure TDBXDataExpressProviderContext.Commit; begin end; procedure TDBXDataExpressProviderContext.Rollback; begin end; function TDBXDataExpressProviderContext.GetVendorProperty(const name: string): string; begin Result := FConnection.GetVendorProperty(name); end; { procedure TDBXDataExpressProviderContext.BindParametersByName(Command: TDBXCommand; ParameterNames: TDBXStringArray; ParameterValues: TDBXStringArray); var Parameters: TDBXParameterList; Parameter: TDBXParameter; Index: Integer; begin Parameters := Command.Parameters; for Index := Low(ParameterValues) to High(ParameterValues) do begin Parameter := Command.CreateParameter; Parameter.DataType := TDBXDataTypes.WideStringType; Parameter.Name := ParameterNames[Index]; if ParameterValues[Index] = NullString then Parameter.Value.SetNull else Parameter.Value.SetWideString(ParameterValues[Index]); Parameters.AddParameter(Parameter); end; end; } procedure TDBXDataExpressProviderContext.BindParametersByOrdinal(Command: TDBXCommand; ParameterNames: TDBXStringArray; ParameterValues: TDBXStringArray); const KeywordIS = 'IS'; { Do not localize } KeywordNULL = 'NULL'; { Do not localize } SqlTrueValue = '1=1'; { Do not localize } SqlFalseValue = '1=2'; { Do not localize } DummyValue = 'A'; { Do not localize } TokenIS = 1; TokenNULL = 2; var Count, EndPos, Index, ParameterIndex, StartPos, Token: Integer; Parameters: TDBXParameterList; Parameter: TDBXParameter; Buffer: TStringBuilder; Params: array of Integer; NullWasRemoved: Boolean; begin Count := 0; StartPos := 1; Buffer := nil; if FScanner = nil then begin FScanner := TDBXSqlScanner.Create('','',''); FScanner.RegisterId(KeywordIS, TokenIS); FScanner.RegisterId(KeywordNULL, TokenNULL); end; FScanner.Init(Command.Text); Token := FScanner.NextToken; while Token <> TDBXSqlScanner.TokenEos do begin if (Token <> TDBXSqlScanner.TokenSymbol) or (FScanner.Symbol <> ':') then Token := FScanner.NextToken else begin EndPos := FScanner.NextIndex; Token := FScanner.NextToken; if Token = TDBXSqlScanner.TokenId then begin if Buffer = nil then begin Buffer := TStringBuilder.Create(Command.Text.Length); SetLength(Params,Length(ParameterNames)*3); end; Buffer.Append(Command.Text.Substring(StartPos - 1, EndPos - StartPos)); StartPos := FScanner.NextIndex+1; ParameterIndex := FindParameterByName(FScanner.Id, ParameterNames); NullWasRemoved := False; if RemoveIsNull then begin if (FScanner.LookAtNextToken = TokenIS) then begin FScanner.NextToken; if FScanner.LookAtNextToken = TokenNull then begin FScanner.NextToken; StartPos := FScanner.NextIndex+1; NullWasRemoved := True; if ParameterValues[ParameterIndex] = NullString then Buffer.Append(SqlTrueValue) else Buffer.Append(SqlFalseValue) end; end; end; if not NullWasRemoved then begin Buffer.Append('?'); if Length(Params) <= Count then SetLength(Params, Count+2); Params[Count] := ParameterIndex; Inc(Count); end; end; end; end; if Buffer <> nil then begin Buffer.Append(Command.Text.Substring(StartPos - 1, Command.Text.Length - StartPos + 1)); Command.Text := Buffer.ToString; Parameters := Command.Parameters; Parameters.ClearParameters; for Index := 0 to Count - 1 do begin ParameterIndex := Params[Index]; Parameter := Command.CreateParameter; if UseAnsiStrings then Parameter.DataType := TDBXDataTypes.AnsiStringType else Parameter.DataType := TDBXDataTypes.WideStringType; if RemoveIsNull and (ParameterValues[ParameterIndex] = NullString) then ParameterValues[ParameterIndex] := DummyValue; if (ParameterValues[ParameterIndex] = NullString) then Parameter.Value.SetNull {$IFNDEF NEXTGEN} else if UseAnsiStrings then Parameter.Value.SetAnsiString(AnsiString(ParameterValues[ParameterIndex])) {$ENDIF !NEXTGEN} else Parameter.Value.SetString(ParameterValues[ParameterIndex]); Parameters.AddParameter(Parameter); end; Buffer.Free; Params := nil; end; end; function TDBXDataExpressProviderContext.FindParameterByName(const ParameterName: string; ParameterNames: TDBXStringArray): Integer; var Index: Integer; Found: Boolean; begin Index := High(ParameterNames); Found := False; while not Found and (Index >= Low(ParameterNames)) do begin if ParameterNames[Index] = ParameterName then Found := True else Dec(Index); end; if not Found then raise Exception.Create('ParameterName not found: '+ParameterName); Result := Index; end; constructor TDBXMetaDataCommand.Create(DBXContext: TDBXContext; MorphicCommand: TDBXCommand; Provider: TDBXMetaDataReader); begin inherited Create(DBXContext); FQueryCommand := nil; FReader := Provider; end; destructor TDBXMetaDataCommand.Destroy; begin FQueryCommand.DisposeOf; inherited Destroy; end; procedure TDBXMetaDataCommand.SetRowSetSize(const RowSetSize: Int64); begin end; procedure TDBXMetaDataCommand.SetMaxBlobSize(const MaxBlobSize: Int64); begin end; function TDBXMetaDataCommand.GetRowsAffected: Int64; begin Result := 0; end; function TDBXMetaDataCommand.DerivedGetNextReader: TDBXReader; begin Result := nil; end; procedure TDBXMetaDataCommand.DerivedOpen; begin end; function TDBXMetaDataCommand.CreateValueType(Name: string; DataType, Size: Integer): TDBXValueType; begin Result := TDBXValueType.Create; Result.Name := Name; Result.DataType := DataType; Result.Size := Size; end; procedure TDBXMetaDataCommand.DerivedClose; begin end; procedure TDBXMetaDataCommand.DerivedPrepare; begin end; function TDBXMetaDataCommand.DerivedExecuteQuery: TDBXReader; var Table: TDBXTable; Row: TDBXMetaDataRow; begin Table := FReader.FetchCollection(Text); if Table = nil then Table := FetchDatabaseColumns else begin if FQueryCommand <> nil then FreeAndNil(FQueryCommand); FQueryCommand := TDBXCommand(Table.Command); end; Row := TDBXMetaDataRow.Create(FDBXContext,Table); Result := TDBXMetaDataDbxReader.Create(FDBXContext,Row,Table); end; procedure TDBXMetaDataCommand.DerivedExecuteUpdate; begin end; function TDBXMetaDataCommand.FetchDatabaseColumns: TDBXTable; var Columns: TDBXValueTypeArray; begin SetLength(Columns, DatabaseColumnCount); Columns[QuoteCharOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.QuoteChar, TDBXDataTypes.WideStringType, 2); Columns[ProcedureQuoteCharOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.ProcedureQuoteChar, TDBXDataTypes.WideStringType, 2); Columns[SupportsTransactionsOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.SupportsTransactions, TDBXDataTypes.BooleanType, 1); Columns[SupportsNestedTransactionsOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.SupportsNestedTransactions, TDBXDataTypes.BooleanType, 1); Columns[MaxCommandsOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.MaxCommands, TDBXDataTypes.Int32Type, 4); Columns[SupportsRowSetSizeOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.SupportsRowSetSize, TDBXDataTypes.BooleanType, 1); // Sybase ASE/ASA, and Informix return values much larger than 20. // Columns[ProductVersionOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.ProductVersion, TDBXDataTypes.WideStringType, 128); Columns[ProductNameOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.ProductName, TDBXDataTypes.WideStringType, 128); Columns[QuotePrefixOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.QuotePrefix, TDBXDataTypes.WideStringType, 2); Columns[QuoteSuffixOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.QuoteSuffix, TDBXDataTypes.WideStringType, 2); Columns[SupportsLowerCaseIdentifiersOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.SupportsLowerCaseIdentifiers, TDBXDataTypes.BooleanType, 1); Columns[SupportsUpperCaseIdentifiersOrdinal] := CreateValueType(TDBXMetaDatabaseColumnNames.SupportsUpperCaseIdentifiers, TDBXDataTypes.BooleanType, 1); Columns[SupportsSPReturnCode] := CreateValueType(TDBXMetaDatabaseColumnNames.SupportsSPReturnCode, TDBXDataTypes.BooleanType, 1); Columns[SupportsParameterMetadata] := CreateValueType(TDBXMetaDatabaseColumnNames.SupportsParameterMetadata, TDBXDataTypes.BooleanType, 1); Columns[SupportsCatalogFunctions] := CreateValueType(TDBXMetaDatabaseColumnNames.SupportsCatalogFunctions, TDBXDataTypes.BooleanType, 1); Columns[SupportsCatalogs] := CreateValueType(TDBXMetaDatabaseColumnNames.SupportsCatalogs, TDBXDataTypes.BooleanType, 1); Columns[SupportsSchemas] := CreateValueType(TDBXMetaDatabaseColumnNames.SupportsSchemas, TDBXDataTypes.BooleanType, 1); Result := TDatabaseCursor.Create(Columns,FReader,FReader.Context); end; { TDatabaseCursor } constructor TDatabaseCursor.Create(Columns: TDBXValueTypeArray; Provider: TDBXMetaDataReader; TypeNames: TDBXPlatformTypeNames); begin inherited Create(TypeNames, DatabaseCollectionName, Columns, nil); FReader := Provider; FDatabaseRow := TDBXSingleValueRow.Create; FDatabaseRow.Columns := CopyColumns(); end; destructor TDatabaseCursor.Destroy; begin FreeAndNil(FDatabaseRow); inherited; end; function TDatabaseCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue; begin Result := FDatabaseRow.Value[Ordinal]; end; function TDatabaseCursor.Next: Boolean; begin if FRow < 2 then Inc(FRow); Result := (FRow = 1); FDatabaseRow.Value[QuoteCharOrdinal].SetWideString(FReader.SqlIdentifierQuoteChar); FDatabaseRow.Value[ProcedureQuoteCharOrdinal].SetWideString(FReader.SqlProcedureQuoteChar); FDatabaseRow.Value[ProductVersionOrdinal].SetWideString(FReader.Version); FDatabaseRow.Value[ProductNameOrdinal].SetWideString(FReader.ProductName); FDatabaseRow.Value[QuotePrefixOrdinal].SetWideString(FReader.SqlIdentifierQuotePrefix); FDatabaseRow.Value[QuoteSuffixOrdinal].SetWideString(FReader.SqlIdentifierQuoteSuffix); FDatabaseRow.Value[SupportsTransactionsOrdinal].SetBoolean(FReader.TransactionsSupported); FDatabaseRow.Value[SupportsNestedTransactionsOrdinal].SetBoolean(FReader.NestedTransactionsSupported); FDatabaseRow.Value[SupportsRowSetSizeOrdinal].SetBoolean(FReader.SetRowSizeSupported); FDatabaseRow.Value[SupportsLowerCaseIdentifiersOrdinal].SetBoolean(FReader.LowerCaseIdentifiersSupported); FDatabaseRow.Value[SupportsUpperCaseIdentifiersOrdinal].SetBoolean(FReader.UpperCaseIdentifiersSupported); FDatabaseRow.Value[SupportsSPReturnCode].SetBoolean(FReader.SPReturnCodeSupported); FDatabaseRow.Value[SupportsParameterMetadata].SetBoolean(FReader.ParameterMetadataSupported); FDatabaseRow.Value[SupportsCatalogFunctions].SetBoolean(FReader.CatalogFunctionsSupported); FDatabaseRow.Value[SupportsCatalogs].SetBoolean(FReader.CatalogsSupported); FDatabaseRow.Value[SupportsSchemas].SetBoolean(FReader.SchemasSupported); if FReader.MultipleCommandsSupported then FDatabaseRow.Value[MaxCommandsOrdinal].SetInt32(0) else FDatabaseRow.Value[MaxCommandsOrdinal].SetInt32(1); end; { TDBXMetaDataDbxReader } constructor TDBXMetaDataDbxReader.Create(DBXContext: TDBXContext; Row: TDBXMetaDataRow; Cursor: TDBXTable); var Ordinal: Integer; Column, ValueType: TDBXValueType; Values: TDBXValueArray; begin inherited Create(DBXContext, Row, nil); FCursor := Cursor; SetLength(Values, Length(Cursor.Columns)); for Ordinal := Low(Values) to High(Values) do begin Column := Cursor.Columns[Ordinal]; ValueType := TDBXDriverHelp.CreateTDBXValueType(DBXContext,Row); ValueType.DataType := MapToDBXType(Column.DataType); ValueType.SubType := TDBXDataTypes.UnknownType; ValueType.Ordinal := Ordinal; ValueType.Scale := 0; ValueType.Size := Column.Size; ValueType.Name := Column.Name; if (ValueType.DataType = TDBXDataTypes.WideStringType) then begin if ValueType.Size = 0 then ValueType.Size := 256; if ValueType.Precision = 0 then ValueType.Precision := ValueType.Size; ValueType.Size := ValueType.Size + 2; // Allow space for the zero terminator. end; ValueType.ValueTypeFlags := TDBXValueTypeFlags.Nullable or TDBXValueTypeFlags.ReadOnly; Values[Ordinal] := TDBXValue.CreateValue(FDBXContext, ValueType, FDbxRow, true); end; SetValues(Values); end; destructor TDBXMetaDataDbxReader.Destroy; begin FreeAndNil(FByteReader); FreeAndNil(FCursor); inherited Destroy; end; function TDBXMetaDataDbxReader.MapToDBXType(ColumnType: Integer): Integer; begin Result := ColumnType; end; function TDBXMetaDataDbxReader.DerivedNext: Boolean; begin if FCursor = nil then Result := False else begin Result := FCursor.Next; if not Result then begin FCursor.Close; FreeAndNil(FCursor); end; end; end; function TDBXMetaDataDbxReader.GetByteReader: TDBXByteReader; begin if FByteReader = nil then FByteReader := TDBXReaderByteReader.Create(FDbxContext, Self); Result := FByteReader; end; procedure TDBXMetaDataDbxReader.DerivedClose; begin if FCursor <> nil then begin FCursor.Close; FreeAndNil(FCursor); end; end; { TDBXMetaDataRow } constructor TDBXMetaDataRow.Create(DBXContext: TDBXContext; Row: TDBXTableRow); begin inherited Create(DBXContext); FRow := Row; end; procedure TDBXMetaDataRow.GetWideString(DbxValue: TDBXWideStringValue; var WideStringBuilder: TDBXWideStringBuilder; var IsNull: LongBool); var Ordinal, SourceSize: Integer; Source: string; begin Ordinal := DbxValue.ValueType.Ordinal; IsNull := FRow.Value[Ordinal].IsNull; if not IsNull then begin Source := FRow.Value[Ordinal].AsString; SourceSize := Source.Length; if SourceSize >= DbxValue.ValueType.Size then TDBXPlatform.ResizeWideStringBuilder(WideStringBuilder, SourceSize + 2); TDBXPlatform.CopyWideStringToBuilder(Source, SourceSize + 2, WideStringBuilder); end; end; procedure TDBXMetaDataRow.GetBoolean(DbxValue: TDBXBooleanValue; var Value: LongBool; var IsNull: LongBool); var Ordinal: Integer; begin Ordinal := DbxValue.ValueType.Ordinal; IsNull := FRow.Value[Ordinal].IsNull; if not IsNull then Value := FRow.Value[Ordinal].AsBoolean else Value := False; end; procedure TDBXMetaDataRow.GetInt16(DbxValue: TDBXInt16Value; var Value: SmallInt; var IsNull: LongBool); var Ordinal: Integer; begin Ordinal := DbxValue.ValueType.Ordinal; IsNull := FRow.Value[Ordinal].IsNull; if not IsNull then Value := FRow.Value[Ordinal].AsInt16 else Value := 0; end; procedure TDBXMetaDataRow.GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32; var IsNull: LongBool); var Ordinal: Integer; begin Ordinal := DbxValue.ValueType.Ordinal; IsNull := FRow.Value[Ordinal].IsNull; if not IsNull then Value := FRow.Value[Ordinal].AsInt32 else Value := 0; end; procedure TDBXMetaDataRow.GetInt64(DbxValue: TDBXInt64Value; var Value: Int64; var IsNull: LongBool); var Ordinal: Integer; begin Ordinal := DbxValue.ValueType.Ordinal; IsNull := FRow.Value[Ordinal].IsNull; if not IsNull then Value := FRow.Value[Ordinal].AsInt64 else Value := 0; end; procedure TDBXMetaDataRow.GetInt8(DbxValue: TDBXInt8Value; var Value: ShortInt; var IsNull: LongBool); var Ordinal: Integer; begin Ordinal := DbxValue.ValueType.Ordinal; IsNull := FRow.Value[Ordinal].IsNull; if not IsNull then Value := FRow.Value[Ordinal].AsInt8 else Value := 0; end; procedure TDBXMetaDataRow.GetUInt16(DbxValue: TDBXUInt16Value; var Value: Word; var IsNull: LongBool); var Ordinal: Integer; begin Ordinal := DbxValue.ValueType.Ordinal; IsNull := FRow.Value[Ordinal].IsNull; if not IsNull then Value := FRow.Value[Ordinal].AsUInt16 else Value := 0; end; procedure TDBXMetaDataRow.GetUInt8(DbxValue: TDBXUInt8Value; var Value: Byte; var IsNull: LongBool); var Ordinal: Integer; begin Ordinal := DbxValue.ValueType.Ordinal; IsNull := FRow.Value[Ordinal].IsNull; if not IsNull then Value := FRow.Value[Ordinal].AsUInt8 else Value := 0; end; constructor TDBXReaderTableStorage.Create(Command: TDBXCommand; Reader: TDBXReader); begin inherited Create(nil, nil); FCommand := Command; FReader := Reader; end; destructor TDBXReaderTableStorage.Destroy; begin Close; FreeObjectArray(TDBXFreeArray(FColumns)); inherited Destroy; end; function TDBXReaderTableStorage.GetCommand: TObject; begin Result := FCommand; FCommand := nil; end; function TDBXReaderTableStorage.GetOrdinal( const ColumnName: string): Integer; begin Result := FReader.GetOrdinal(ColumnName); end; function TDBXReaderTableStorage.First: Boolean; begin if FNextCalled then raise Exception.Create(SUnsupportedOperation); Result := True; end; function TDBXReaderTableStorage.Next: Boolean; begin FNextCalled := True; Result := FReader.Next; FLastNext := Result; end; function TDBXReaderTableStorage.InBounds: Boolean; begin if not FNextCalled then Next; Result := FLastNext; end; procedure TDBXReaderTableStorage.Close; begin FreeAndNil(FReader); FreeAndNil(FCommand); end; function TDBXReaderTableStorage.GetColumns: TDBXValueTypeArray; var Ordinal: Integer; ValueType: TDBXValueType; begin if FColumns = nil then begin SetLength(FColumns, FReader.ColumnCount); for Ordinal := Low(FColumns) to High(FColumns) do begin ValueType := FReader.ValueType[Ordinal]; FColumns[Ordinal] := TDBXValueType.Create; FColumns[Ordinal].Name := ValueType.Name; FColumns[Ordinal].DisplayName := ValueType.DisplayName; FColumns[Ordinal].DataType := ValueType.DataType; FColumns[Ordinal].SubType := ValueType.SubType; FColumns[Ordinal].Size := ValueType.Size; FColumns[Ordinal].Precision := ValueType.Precision; end; end; Result := FColumns; end; function TDBXReaderTableStorage.GetStorage: TObject; begin Result := FReader; end; function TDBXReaderTableStorage.GetWritableValue(const Ordinal: Integer): TDBXWritableValue; begin Result := TDBXWritableValue(FReader.Value[Ordinal]); end; end.
//****************************************************************************** //*** COMMON DELPHI FUNCTIONS *** //*** *** //*** (c) Massimo Magnano 24-10-2006. *** //*** *** //*** *** //****************************************************************************** // File : ScriptableObject.pas REV. 0.3 (01-12-2006) // // Description : Delphi scripting support // // Rev. 0.3 // MaxM Adds : // LexicalOrder Call for a Method // Infos About a Method // // Rev. 0.2 // MaxM Adds : // Reorganization of the Unit // // //The Original Code is: JvOle2Auto.PAS, released on 2002-07-04. // //The Initial Developers of the Original Code are: // Fedor Koshevnikov, Igor Pavluk and Serge Korolev // Copyright (c) 1997, 1998 Fedor Koshevnikov, Igor Pavluk and Serge Korolev // Copyright (c) 2001,2002 SGB Software //All Rights Reserved. unit ScriptableObject; interface {$J+} {$O-} uses Windows, ActiveX, ObjComAuto, SysUtils, TypInfo, ObjAuto; type TParamInfos= array of PParamInfo; {$METHODINFO ON} //{$TYPEINFO ON} use this if you want only published methods TScriptableObject = class(TObjectDispatch) private FRetValue : Variant; FInstanceObj : TObject; public constructor Create(Instance: TObject; Owned: Boolean = True); function NameToDispID(const AName: string): TDispID; function Invoke2(dispidMember: TDispID; wFlags: Word; var pdispparams: TDispParams; Res: PVariant): PVariant; function GetPropertyByID(ID: TDispID): PVariant; function GetProperty(PropName :String): PVariant; function GetPropertyTypeInfoByID(ID: TDispID): PTypeInfo; function GetPropertyTypeInfo(PropName :String): PTypeInfo; procedure SetPropertyByID(ID: TDispID; const Prop: array of const); procedure SetProperty(PropName :String; const Prop: array of const); function CallMethod(ID: TDispID; const Args : array of variant; NeedResult: Boolean): PVariant; overload; function CallMethod(MethodName :String; const Args : array of variant; NeedResult: Boolean; ResultTypeInfo :PReturnInfo): PVariant; overload; function CallMethodLexicalOrder(ID: TDispID; const Args : array of variant; NeedResult: Boolean): PVariant; overload; function CallMethodLexicalOrder(MethodName :String; const Args : array of variant; NeedResult: Boolean; ResultTypeInfo :PReturnInfo): PVariant; overload; function GetMethodInfos(MethodName :String; var MethodInfo: PMethodInfoHeader; var ReturnInfo: PReturnInfo; var ParamInfos: TParamInfos):Boolean; property InstanceObj : TObject read FInstanceObj write FInstanceObj; end; //{$TYPEINFO OFF} {$METHODINFO OFF} implementation type PPParamInfo = ^PParamInfo; constructor TScriptableObject.Create(Instance: TObject; Owned: Boolean = True); begin if (Instance=nil) then inherited Create(Self, false) else inherited Create(Instance, Owned); InstanceObj :=Instance; end; function TScriptableObject.NameToDispID(const AName: string): TDispID; var CharBuf: array [0..255] of WideChar; P: array [0..0] of PWideChar; begin StringToWideChar(AName, @CharBuf[0], 256); P[0] := @CharBuf[0]; GetIDsOfNames(GUID_NULL, @P, 1, GetThreadLocale, @Result); end; function TScriptableObject.Invoke2(dispidMember: TDispID; wFlags: Word; var pdispparams: TDispParams; Res: PVariant): PVariant; var pexcepinfo: TExcepInfo; puArgErr: Integer; begin if Res <> nil then VarClear(Res^); try Invoke(dispidMember, GUID_NULL, GetThreadLocale, wFlags, pdispparams, Res, @pexcepinfo, @puArgErr); except if Res <> nil then VarClear(Res^); Result := Res; raise; end; end; function TScriptableObject.GetPropertyByID(ID: TDispID): PVariant; const Disp: TDispParams = (rgvarg: nil; rgdispidNamedArgs: nil; cArgs: 0; cNamedArgs: 0); begin Result := Invoke2(ID, DISPATCH_PROPERTYGET, Disp, @FRetValue); end; function TScriptableObject.GetProperty(PropName :String): PVariant; begin Result :=GetPropertyByID(NameToDispID(PropName)); end; procedure AssignVariant(var Dest: TVariantArg; const Value: TVarRec); begin with Value do case VType of vtInteger: begin Dest.vt := VT_I4; Dest.lVal := VInteger; end; vtBoolean: begin Dest.vt := VT_BOOL; Dest.vbool := VBoolean; end; vtChar: begin Dest.vt := VT_BSTR; Dest.bstrVal := StringToOleStr(VChar); end; vtExtended: begin Dest.vt := VT_R8; Dest.dblVal := VExtended^; end; vtString: begin Dest.vt := VT_BSTR; Dest.bstrVal := StringToOleStr(VString^); end; vtPointer: if VPointer = nil then begin Dest.vt := VT_NULL; Dest.byRef := nil; end else begin Dest.vt := VT_BYREF; Dest.byRef := VPointer; end; vtPChar: begin Dest.vt := VT_BSTR; Dest.bstrVal := StringToOleStr(StrPas(VPChar)); end; vtObject: begin Dest.vt := VT_BYREF; Dest.byRef := VObject; end; vtClass: begin Dest.vt := VT_BYREF; Dest.byRef := VClass; end; vtWideChar: begin Dest.vt := VT_BSTR; Dest.bstrVal := @VWideChar; end; vtPWideChar: begin Dest.vt := VT_BSTR; Dest.bstrVal := VPWideChar; end; vtAnsiString: begin Dest.vt := VT_BSTR; Dest.bstrVal := StringToOleStr(string(VAnsiString)); end; vtCurrency: begin Dest.vt := VT_CY; Dest.cyVal := VCurrency^; end; vtVariant: begin Dest.vt := VT_BYREF or VT_VARIANT; Dest.pvarVal := VVariant; end; vtInterface: begin Dest.vt := VT_UNKNOWN or VT_BYREF; Dest.byRef := VInterface; end; vtInt64: begin Dest.vt := VT_I8 or VT_BYREF; Dest.byRef := VInt64; end; end; end; procedure TScriptableObject.SetPropertyByID(ID: TDispID; const Prop: array of const); const NameArg: TDispID = DISPID_PROPERTYPUT; var Disp: TDispParams; ArgCnt, I: Integer; Args: array[0..63] of TVariantArg; begin ArgCnt := 0; try for I := 0 to High(Prop) do begin AssignVariant(Args[I], Prop[I]); Inc(ArgCnt); if ArgCnt >= 64 then Break; end; with Disp do begin rgvarg := @Args; rgdispidNamedArgs := @NameArg; cArgs := ArgCnt; cNamedArgs := 1; end; Invoke2(ID, DISPATCH_PROPERTYPUT, Disp, nil); finally end; end; procedure TScriptableObject.SetProperty(PropName :String; const Prop: array of const); begin SetPropertyByID(NameToDispID(PropName), Prop); end; function WashVariant(const Value: Variant): OleVariant; begin if TVarData(Value).VType = (varString or varByRef) then Result := PString(TVarData(VAlue).VString)^ + '' else Result := Value; end; function TScriptableObject.CallMethod(ID: TDispID; const Args : array of variant; NeedResult: Boolean): PVariant; var DispParams: TDispParams; I: Integer; OleArgs: array of OleVariant; begin if ID=-1 then raise Exception.Create('Method not found'); SetLength(OleArgs, High(Args) + 1); for I := Low(Args) to High(Args) do OleArgs[I] := WashVariant(Args[I]); DispParams.rgvarg := @OleArgs[0]; DispParams.cArgs := High(Args) + 1; DispParams.rgdispidNamedArgs := nil; DispParams.cNamedArgs := 0; if NeedResult then Result := Invoke2(ID, DISPATCH_METHOD or DISPATCH_PROPERTYGET, DispParams, @FRetValue) else begin Result :=nil; Invoke2(ID, DISPATCH_METHOD or DISPATCH_PROPERTYGET, DispParams, nil); end; end; function TScriptableObject.CallMethod(MethodName :String; const Args : array of variant; NeedResult: Boolean; ResultTypeInfo: PReturnInfo): PVariant; Var MethodInfo: PMethodInfoHeader; begin if NeedResult then begin MethodInfo := ObjAuto.GetMethodInfo(InstanceObj, MethodName); ResultTypeInfo := PReturnInfo(MethodInfo); Inc(Integer(ResultTypeInfo), SizeOf(TMethodInfoHeader) - SizeOf(ShortString) + 1 + Length(MethodName)); end else ResultTypeInfo :=nil; Result :=CallMethod(NameToDispID(MethodName), Args, NeedResult); end; function TScriptableObject.GetPropertyTypeInfo(PropName: String): PTypeInfo; begin Result :=GetPropertyTypeInfoByID(NameToDispID(PropName)); end; function TScriptableObject.GetPropertyTypeInfoByID(ID: TDispID): PTypeInfo; begin Result :=nil; GetTypeInfo(ID, GetThreadLocale, Result); end; function TScriptableObject.GetMethodInfos(MethodName: String; var MethodInfo: PMethodInfoHeader; var ReturnInfo: PReturnInfo; var ParamInfos: TParamInfos): Boolean; var Name: ShortString; InfoEnd: Pointer; Params, Param: PParamInfo; I: Integer; ID: Cardinal; CompIndex: Integer; Instance: TObject; pt :Pointer; (* CharBuf: array [0..255] of WideChar; P: array [0..0] of PWideChar; *) begin (* StringToWideChar(MethodName, @CharBuf[0], 256); P[0] := @CharBuf[0]; GetIDsOfNames(GUID_NULL, @P, 1, GetThreadLocale, @Result); AllocDispID(dkMethod, Info, Instance); *) SetLength(ParamInfos, 0); ReturnInfo := nil; MethodInfo := ObjAuto.GetMethodInfo(InstanceObj, MethodName); if (MethodInfo<>nil) then begin pt := MethodInfo; MethodName := PMethodInfoHeader(pt)^.Name; Inc(Integer(pt), SizeOf(TMethodInfoHeader) - SizeOf(ShortString) + 1 + Length(MethodName)); ReturnInfo := pt; Inc(Integer(pt), SizeOf(TReturnInfo)); Param := PParamInfo(pt); InfoEnd := Pointer(Integer(MethodInfo) + MethodInfo^.Len); ID := 0; while Integer(Param) < Integer(InfoEnd) do begin // ignore Self if not((Param^.ParamType^.Kind = tkClass) and SameText(Param^.Name, 'SELF')) then begin SetLength(ParamInfos, ID+1); ParamInfos[ID] := Param; Inc(ID); end; Inc(Integer(Param), SizeOf(TParamInfo) - SizeOf(ShortString) + 1 + Length(PParamInfo(Param)^.Name)); end; end; end; function TScriptableObject.CallMethodLexicalOrder(MethodName: String; const Args: array of variant; NeedResult: Boolean; ResultTypeInfo: PReturnInfo): PVariant; begin Result :=CallMethodLexicalOrder(NameToDispID(MethodName), Args, NeedResult); end; function TScriptableObject.CallMethodLexicalOrder(ID: TDispID; const Args: array of variant; NeedResult: Boolean): PVariant; begin end; initialization OleInitialize(nil); finalization OleUninitialize; end.
unit BD.Adresse; interface uses System.Classes, System.SysUtils, BD.Postnr, BD.Land; type IAdresse = interface(IPostnr) ['{88446A75-3C46-4F83-8B03-FFC7F238839C}'] function GetAdresse: TStrings; function GetFullAdresse: TStrings; function LineCount: Integer; function GetLine(Index: Integer): String; procedure SetLine(Index: Integer; const Value: string); property Line[Index: Integer]: String read GetLine write SetLine; end; TAdresse = class(TInterfacedObject, IAdresse, IPostnr, ILand) private FAdresse: TStrings; FLine: array [0..1] of String; FPostnr: String; FPoststed: String; FLandkode: String; FLand: String; protected function GetLand: String; function GetLandkode: String; procedure SetLand(const Value: String); procedure SetLandkode(const Value: String); function GetPostnr: String; procedure SetPostnr(const Value: String); function GetPoststed: String; procedure SetPoststed(const Value: String); function GetLine(Index: Integer): String; procedure SetLine(Index: Integer; const Value: string); public constructor Create; destructor Destroy; override; function GetAdresse: TStrings; function GetFullAdresse: TStrings; function LineCount: Integer; property Line[Index: Integer]: String read GetLine write SetLine; property Postnr: String read GetPostnr write SetPostnr; property Poststed: String read GetPoststed write SetPoststed; property Landkode: String read GetLandkode write SetLandkode; property Land: String read GetLand write SetLand; end; implementation { TAdresse } constructor TAdresse.Create; begin FAdresse := TStringList.Create; end; destructor TAdresse.Destroy; begin FAdresse.Free; inherited; end; function TAdresse.GetAdresse: TStrings; var I: Integer; begin FAdresse.Clear; //Generer full adresse for I := Low(FLine) to High(FLine) do FAdresse.Add(FLine[I]); FAdresse.Add(FPostnr + ' ' + FPostSted); Result := FAdresse; end; function TAdresse.GetFullAdresse: TStrings; begin GetAdresse; FAdresse.Add(FLand); Result := FAdresse; end; function TAdresse.GetLand: String; begin Result := FLand; end; function TAdresse.GetLandkode: String; begin Result := FLandkode; end; function TAdresse.GetLine(Index: Integer): String; begin if (Index > High(FLine)) or (Index < Low(FLine)) then Exit; Result := FLine[Index]; end; function TAdresse.GetPostnr: String; begin Result := FPostnr; end; function TAdresse.GetPoststed: String; begin Result := FPoststed; end; function TAdresse.LineCount: Integer; begin Result := High(FLine); end; procedure TAdresse.SetLand(const Value: String); begin FLand := Value; end; procedure TAdresse.SetLandkode(const Value: String); begin FLandkode := Value; end; procedure TAdresse.SetLine(Index: Integer; const Value: string); begin if (Index > High(FLine)) or (Index < Low(FLine)) then Exit; FLine[Index] := Value; end; procedure TAdresse.SetPostnr(const Value: String); begin FPostnr := Value; end; procedure TAdresse.SetPoststed(const Value: String); begin FPoststed := Value; end; end.
unit uToolLazVersion; {$mode objfpc}{$H+} interface uses Classes, uBuildFile, sysutils; type TBuildToolLazVersion = class(TBuildTool) function Execute(const aOrder: TStringList): Integer; override; end; implementation uses Laz2_XMLCfg, fileinfo, strutils, FileUtil; function TryStrToVersionQuadOpt(S: String; out Quad: TVersionQuad): Boolean; var i, k: integer; p: string; begin Result:= false; FillChar({%H-}Quad[1], sizeof(TVersionQuad), 0); for i:= 1 to 4 do begin p:= Copy2SymbDel(S, '.'); if TryStrToInt(p, k) then Quad[i]:= k else Exit; if S = '' then break; end; Result:= (S = ''); end; Operator + (a, b : TVersionQuad) : TVersionQuad; begin Result[1]:= a[1] + b[1]; Result[2]:= a[2] + b[2]; Result[3]:= a[3] + b[3]; Result[4]:= a[4] + b[4]; end; function VersionQuadToStrNoBuild(const Quad: TVersionQuad): String; begin Result:=Format('%d.%d.%d',[Quad[1],Quad[2],Quad[3]]); end; function BackupFile(const fn: TFilename): boolean; begin Result:= CopyFile(fn, fn + '.bak', [cffOverwriteFile, cffPreserveTime], true); end; { TBuildToolLazVersion } const VPATH = 'ProjectOptions/VersionInfo/'; function TBuildToolLazVersion.Execute(const aOrder: TStringList): Integer; function CopyVersionInfo(From: TXMLConfig; Target: TFilename): boolean; var trg: TXMLConfig; begin Result:= false; trg:= TXMLConfig.Create(Target); try trg.SetDeleteValue(VPATH+'UseVersionInfo/Value', From.GetValue(VPATH+'UseVersionInfo/Value', False), False); trg.SetDeleteValue(VPATH+'MajorVersionNr/Value', From.GetValue(VPATH+'MajorVersionNr/Value', 0), 0); trg.SetDeleteValue(VPATH+'MinorVersionNr/Value', From.GetValue(VPATH+'MinorVersionNr/Value', 0), 0); trg.SetDeleteValue(VPATH+'RevisionNr/Value', From.GetValue(VPATH+'RevisionNr/Value', 0), 0); trg.SetDeleteValue(VPATH+'BuildNr/Value', From.GetValue(VPATH+'BuildNr/Value', 0), 0); trg.SetDeleteValue(VPATH+'Attributes/pvaDebug', From.GetValue(VPATH+'Attributes/pvaDebug', false), false); trg.SetDeleteValue(VPATH+'Attributes/pvaPreRelease', From.GetValue(VPATH+'Attributes/pvaPreRelease', false), false); trg.SetDeleteValue(VPATH+'Attributes/pvaPatched', From.GetValue(VPATH+'Attributes/pvaPatched', false), false); trg.SetDeleteValue(VPATH+'Attributes/pvaPrivateBuild', From.GetValue(VPATH+'Attributes/pvaPrivateBuild', false), false); trg.SetDeleteValue(VPATH+'Attributes/pvaSpecialBuild', From.GetValue(VPATH+'Attributes/pvaSpecialBuild', false), false); BackupFile(trg.Filename); trg.Flush; WriteLn('Copied version info to LPI file ', Target); finally FreeAndNil(trg); end; end; var proj, f, cf: string; lpi: TXMLConfig; currentver, vi: TVersionQuad; begin Result := 0; proj := ExpandFileName(aOrder.Values['PROJECT']); if proj = '' then begin WriteLn(ErrOutput, 'Task ', Owner.CurrentTask, ': Project specifier missing.'); Exit(ERROR_TASK_PARAMETER); end; lpi:= TXMLConfig.Create(proj); try WriteLn('Loaded LPI file ', proj); if lpi.GetValue(VPATH+'UseVersionInfo/Value', '') = '' then begin WriteLn(ErrOutput, 'Task ', Owner.CurrentTask, ': Project file does not contain version information (or it is disabled).'); Exit(ERROR_TASK_PROCESS); end; currentver[1]:= lpi.GetValue(VPATH+'MajorVersionNr/Value', 0); currentver[2]:= lpi.GetValue(VPATH+'MinorVersionNr/Value', 0); currentver[3]:= lpi.GetValue(VPATH+'RevisionNr/Value', 0); currentver[4]:= lpi.GetValue(VPATH+'BuildNr/Value', 0); if aOrder.Values['INCREMENT'] > '' then begin if not TryStrToVersionQuadOpt(aOrder.Values['INCREMENT'], vi) then begin WriteLn(ErrOutput, 'Task ', Owner.CurrentTask, ': Increment definition is not of the form "u.v.w.x".'); Exit(ERROR_TASK_PARAMETER); end; currentver:= currentver + vi; lpi.SetDeleteValue(VPATH+'MajorVersionNr/Value', currentver[1], 0); lpi.SetDeleteValue(VPATH+'MinorVersionNr/Value', currentver[2], 0); lpi.SetDeleteValue(VPATH+'RevisionNr/Value', currentver[3], 0); lpi.SetDeleteValue(VPATH+'BuildNr/Value', currentver[4], 0); end; WriteLn('Version number ', VersionQuadToStr(currentver)); f:= aOrder.Values['SETENV']; if f > '' then begin if Owner.SetGlobal(f, VersionQuadToStrNoBuild(currentver)) then WriteLn('Exported version number to ', f) else begin WriteLn(ErrOutput, 'Task ', Owner.CurrentTask, ': Cannot set env var ', f, '.'); Exit(ERROR_TASK_PROCESS); end; end; f:= aOrder.Values['ADDFLAG']; while f > '' do begin f:= TrimSet(f, [' ', ',']); cf:= Copy2SymbDel(f, ','); lpi.SetDeleteValue(VPATH+'Attributes/'+cf, True, False); end; f:= aOrder.Values['REMOVEFLAG']; while f > '' do begin f:= TrimSet(f, [' ', ',']); cf:= Copy2SymbDel(f, ','); lpi.SetDeleteValue(VPATH+'Attributes/'+cf, False, False); end; f:= aOrder.Values['COPYTO']; while f > '' do begin f:= TrimSet(f, [' ', ',']); cf:= Copy2SymbDel(f, ','); CopyVersionInfo(lpi, cf); end; BackupFile(lpi.Filename); lpi.Flush; finally FreeAndNil(lpi); end; end; end.
unit DataSet.Serialize.UpdatedStatus; interface uses Data.DB; type TUpdateStatusHelper = record helper for TUpdateStatus function ToString: string; end; implementation { TUpdateStatusHelper } function TUpdateStatusHelper.ToString: string; begin case Self of usModified: Result := 'MODIFIED'; usInserted: Result := 'INSERTED'; usDeleted: Result := 'DELETED'; else Result := 'UNOMODIFIED'; end; end; end.
unit uCompo_Adic; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, frxDsgnIntf, frxDCtrl, frxClass, frxDesgn,cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxCurrencyEdit, cxEdit; type //criar a classe TfrxcxDateEditControl = class(TfrxDialogControl) private FcxDateEdit: TcxDateEdit; function GetDate: TDate; procedure SetDate(const Value: TDate); public constructor Create(AOwner: TComponent); override; property DateEdit: TcxDateEdit read FcxDateEdit; published property Date: TDate read GetDate write SetDate; property TabStop; property OnClick; property OnDblClick; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; end; TfrxcxCurrencyEdit = class(TfrxDialogControl) private FcxCurrencyEdit : TcxCurrencyEdit; FOnChange: TfrxNotifyEvent; function GetValue: Double; function GetDisplayFormat: string; procedure SetValue(Value: Double); procedure SetDisplayFormat(Value: string); function GetDecimalPlaces: integer; procedure SetDecimalPlaces(Value: integer); public constructor Create(AOwner: TComponent); override; property cxCurrencyEdit: TcxCurrencyEdit read FcxCurrencyEdit; published property Value: Double read GetValue write SetValue; property DisplayFormat: String read GetDisplayFormat write SetDisplayFormat; property QtdDecimais: Integer read GetDecimalPlaces write SetDecimalPlaces; end; implementation { TfrxcxDateEditControl } constructor TfrxcxDateEditControl.Create(AOwner: TComponent); begin inherited; FcxDateEdit := TcxDateEdit.Create(nil); InitControl(FcxDateEdit); Date := now; FcxDateEdit.Properties.SaveTime := False; FcxDateEdit.Properties.ShowTime := False; width := 97; height := 21; end; function TfrxcxDateEditControl.GetDate: TDate; begin Result := FcxDateEdit.Date end; procedure TfrxcxDateEditControl.SetDate(const Value: TDate); begin FcxDateEdit.Date := Value; end; { TfrxcxCurrencyEdit } constructor TfrxcxCurrencyEdit.Create(AOwner: TComponent); begin inherited; FcxCurrencyEdit := TcxCurrencyEdit.Create(nil); InitControl(FcxCurrencyEdit); FcxCurrencyEdit.Properties.Alignment.Horz := taRightJustify; Value := 0; width := 97; height := 21; end; function TfrxcxCurrencyEdit.GetDecimalPlaces: integer; begin Result := FcxCurrencyEdit.Properties.DecimalPlaces; end; function TfrxcxCurrencyEdit.GetDisplayFormat: string; begin Result := FcxCurrencyEdit.Properties.DisplayFormat; end; function TfrxcxCurrencyEdit.GetValue: Double; begin Result := FcxCurrencyEdit.Value; end; procedure TfrxcxCurrencyEdit.SetDecimalPlaces(Value: integer); begin FcxCurrencyEdit.Properties.DecimalPlaces := Value; end; procedure TfrxcxCurrencyEdit.SetDisplayFormat(Value: string); begin FcxCurrencyEdit.Properties.DisplayFormat := Value; end; procedure TfrxcxCurrencyEdit.SetValue(Value: Double); begin FcxCurrencyEdit.Value := Value; end; initialization frxObjects.RegisterObject1(TfrxcxDateEditControl, nil, 'frxcxDateEdit', '', 0, 20); frxObjects.RegisterObject1(TfrxcxCurrencyEdit, nil, 'frxcxCurrencyEdit', '', 0, 13); end.
unit CopyHk; interface uses Windows, ActiveX, ComObj, ShlObj; type TCopyHook = class(TComObject, ICopyHook) public function CopyCallback(Wnd: HWND; wFunc, wFlags: UINT; pszSrcFile: PAnsiChar; dwSrcAttribs: DWORD; pszDestFile: PAnsiChar; dwDestAttribs: DWORD): UINT; stdcall; end; const Class_CopyHook: TGUID = '{29F97553-FBD6-11D1-AFC1-00A024D1875C}'; implementation uses ComServ, ShellAPI, SysUtils, Registry; function TCopyHook.CopyCallBack(Wnd: HWND; wFunc, wFlags: UINT; pszSrcFile: PAnsiChar; dwSrcAttribs: DWORD; pszDestFile: PAnsiChar; dwDestAttribs: DWORD): UINT; // This is the method which is called by the shell for folder operations const ConfirmMessage = 'Are you sure you want to %s ''%s''?'; var Operation: string; begin case wFunc of FO_COPY: Operation := 'copy'; FO_DELETE: Operation := 'delete'; FO_MOVE: Operation := 'move'; FO_RENAME: Operation := 'rename'; else Operation := 'continue this operation on' end; // confirm operation Result := MessageBox(Wnd, PChar(Format(ConfirmMessage, [Operation, pszSrcFile])), 'Delphi 4.0 CopyHook Shell Extension...' , MB_YESNOCANCEL); end; type TCopyHookFactory = class(TComObjectFactory) public procedure UpdateRegistry(Register: Boolean); override; end; procedure TCopyHookFactory.UpdateRegistry(Register: Boolean); var ClassID: string; begin if Register then begin inherited UpdateRegistry(Register); ClassID := GUIDToString(Class_CopyHook); CreateRegKey('Directory\shellex\CopyHookHandlers\Delphi4CopyHook', '', ClassID); if (Win32Platform = VER_PLATFORM_WIN32_NT) then with TRegistry.Create do try RootKey := HKEY_LOCAL_MACHINE; OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions', True); OpenKey('Approved', True); WriteString(ClassID, 'Delphi 4.0 CopyHook Shell Extension Example'); finally Free; end; end else begin DeleteRegKey('Directory\shellex\CopyHookHandlers\Delphi4CopyHook'); inherited UpdateRegistry(Register); end; end; initialization TCopyHookFactory.Create(ComServer, TCopyHook, Class_CopyHook, '', 'Delphi 4.0 CopyHook Shell Extension Example', ciMultiInstance, tmApartment); end.
{ "Balanced Binary search List" - Copyright (c) Danijel Tkalcec @exclude } unit memStrObjList; {$INCLUDE rtcDefs.inc} interface uses SysUtils, memPtrPool; type itemType=ansistring; infoType=TObject; type pnode=^tnode; tnode=record key:itemType; info:infoType; b:boolean; l,r:pnode; end; pnodearr=^tnodearr; tnodearr=array[0..(MaxLongInt div SizeOf(tnode))-1] of tnode; pParentList=^tParentList; tParentList=record NodeCount:byte; Nodes:array[0..100] of pnode; end; tStrObjList=class(tObject) private myPoolSize:longint; myPools:array of pointer; pool:tPtrPool; cnt:cardinal; head,z:pnode; Parents:pParentList; procedure del_node(node:pnode); function new_node(const k:itemType; const i:infoType; const bi:boolean; const ll,rr:pnode):pnode; public constructor Create(size:integer); destructor Destroy; override; function Empty:boolean; function Count:cardinal; procedure PoolSize(size:integer); function search(const v:itemType):infoType; // Search for exact "v" function search_min(var i:infoType):itemType; function search_max(var i:infoType):itemType; function search_l(const v:itemType; var i:infoType):itemType; // Search index lower than "v" function search_g(const v:itemType; var i:infoType):itemType; // Search index higher than "v" function search_le(const v:itemType; var i:infoType):itemType; // Search index for lower or equel to "v" function search_ge(const v:itemType; var i:infoType):itemType; // Search index for higher or equal to "v" procedure change(const v:itemType;const info:infoType); procedure insert(const v:itemType;const info:infoType); procedure remove(const v:itemType); procedure removeall; public property RootNode:pnode read head; property NilNode:pnode read z; end; implementation const itemMin=''; infoNil=NIL; function tStrObjList.Empty:boolean; begin Result:=head^.r=z; end; function tStrObjList.New_Node(const k:itemType; const i:infoType; const bi:boolean; const ll,rr:pnode):pnode; var a:longint; p:pnodearr; begin if myPoolSize>0 then begin Result:=pool.Get; if Result=nil then // Pool empty, need to resize pool and create a new list begin SetLength(myPools,Length(myPools)+1); // Resize myPools list GetMem(p,SizeOf(tnode)*myPoolSize); // Create new list myPools[length(myPools)-1]:=p; // store list pool.Size:=pool.Size+myPoolSize; // resize Pool for a:=0 to myPoolSize-1 do pool.Put(@p^[a]); Result:=pool.Get; end; end else GetMem(Result,SizeOf(tnode)); FillChar(Result^,SizeOf(tnode),0); with Result^ do begin key:=k; info:=i; l:=ll; r:=rr; b:=bi; end; end; procedure tStrObjList.PoolSize(size:integer); // PoolSize; begin if (pool.Size=0) or (myPoolSize>0) then myPoolSize:=size; end; procedure tStrObjList.Del_Node(node:pnode); // del_node begin if myPoolSize>0 then pool.Put(node) else FreeMem(node); end; constructor tStrObjList.Create(size:integer); // Create begin inherited Create; cnt:=0; myPoolSize:=size; pool:=tPtrPool.Create; z:=new_node(itemMin,infoNil,false,nil,nil); z^.l:=z; z^.r:=z; head:=new_node(itemMin,infoNil,false,z,z); New(Parents); end; procedure tStrObjList.Change(const v:itemType;const info:infoType); // Change var x:pnode; begin x:=head^.r; while (x<>z) and (v<>x^.key) do if (v<x^.key) then x:=x^.l else x:=x^.r; x^.info:=info; end; procedure tStrObjList.RemoveAll; // RemoveAll procedure RemoveThis(var t:pnode); begin if t^.l<>z then RemoveThis(t^.l); if t^.r<>z then RemoveThis(t^.r); t^.info:=infoNil; t^.key:=itemMin; del_node(t); t:=z; end; begin if head^.r<>z then RemoveThis(head^.r); head^.info:=infoNil; head^.key:=itemMin; cnt:=0; end; destructor tStrObjList.Destroy; // Destroy; var a:longint; begin RemoveAll; Dispose(Parents); if assigned(head) then begin head^.info:=infoNil; head^.key:=itemMin; del_node(head); end; if assigned(z) then begin z^.info:=infoNil; z^.key:=itemMin; del_node(z); end; for a:=0 to Length(myPools)-1 do FreeMem(myPools[a]); SetLength(myPools,0); pool.destroy; inherited; end; function tStrObjList.Search(const v:itemType):infoType; // Search var x:pnode; begin x:=head^.r; while (x<>z) and (v<>x^.key) do if (v<x^.key) then x:=x^.l else x:=x^.r; Result:=x^.info; end; function tStrObjList.Search_Min(var i:infoType):itemType; // Search_Min var x:pnode; begin x:=head^.r; if x<>z then begin while x^.l<>z do x:=x^.l; i:=x^.info; Result:=x^.key; end else begin i:=infoNil; Result:=itemMin; end; end; function tStrObjList.Search_Max(var i:infoType):itemType; // Search_Max var x:pnode; begin x:=head^.r; if x<>z then begin while x^.r<>z do x:=x^.r; i:=x^.info; Result:=x^.key; end else begin i:=infoNil; Result:=itemMin; end; end; function tStrObjList.Search_L(const v:itemType; var i:infoType):itemType; // Search_L var x,y:pnode; begin x:=head^.r; y:=head; while x<>z do begin if (x^.key<v) then begin y:=x; x:=x^.r; end else begin if (x^.key=v) and (x^.l<>z) then y:=x^.l; x:=x^.l; end; end; Result:=y^.key; i:=y^.info; end; function tStrObjList.Search_G(const v:itemType; var i:infoType):itemType; // Search_G var x,y:pnode; begin x:=head^.r; y:=head; while x<>z do begin if (x^.key>v) then begin y:=x; x:=x^.l; end else begin if (x^.key=v) and (x^.r<>z) then y:=x^.r; x:=x^.r; end; end; Result:=y^.key; i:=y^.info; end; function tStrObjList.Search_LE(const v:itemType; var i:infoType):itemType; // Search_LE var x,y:pnode; begin x:=head^.r; y:=head; while (x<>z) and (v<>x^.key) do begin if (x^.key<v) then begin y:=x; x:=x^.r; end else x:=x^.l; end; if x<>z then begin Result:=x^.key; i:=x^.info; end else begin Result:=y^.key; i:=y^.info; end; end; function tStrObjList.Search_GE(const v:itemType; var i:infoType):itemType; // Search_GE var x,y:pnode; begin x:=head^.r; y:=head; while (x<>z) and (v<>x^.key) do begin if (x^.key>v) then begin y:=x; x:=x^.l; end else x:=x^.r; end; if x<>z then begin Result:=x^.key; i:=x^.info; end else begin Result:=y^.key; i:=y^.info; end; end; procedure tStrObjList.Insert(const v:itemType;const info:infoType); // Insert var nx,x,p,g,gg,c:pnode; procedure split; procedure p_rotate_g; begin c:=p; if (v<c^.key) then begin p:=c^.l; c^.l:=p^.r; p^.r:=c; end else begin p:=c^.r; c^.r:=p^.l; p^.l:=c; end; if (v<g^.key) then g^.l:=p else g^.r:=p; end; procedure x_rotate_gg; begin c:=g; if (v<c^.key) then begin x:=c^.l; c^.l:=x^.r; x^.r:=c; end else begin x:=c^.r; c^.r:=x^.l; x^.l:=c; end; if (v<gg^.key) then gg^.l:=x else gg^.r:=x; end; begin x^.b:=true; x^.l^.b:=false; x^.r^.b:=false; if (p^.b) then begin g^.b:=true; if (v<g^.key)<>(v<p^.key) then p_rotate_g; x_rotate_gg; x^.b:=false; end; head^.r^.b:=false; end; begin nx:=new_node(v,info,True,z,z); // Key Sort x:=head; p:=head; g:=head; while (x<>z) do begin gg:=g; g:=p; p:=x; if (v<x^.key) then x:=x^.l else x:=x^.r; if (x^.l^.b and x^.r^.b) then split; end; x:=nx; if (v<p^.key) then p^.l:=x else p^.r:=x; split; Inc(cnt); end; procedure tStrObjList.Remove(const v:itemType); // Remove var cb:boolean; c,p,g,y,p2,x,t:pnode; procedure AddParentNode(node:pnode); begin if node<>nil then with Parents^ do begin Nodes[NodeCount]:=node; Inc(NodeCount); end; end; function GetParentNode:pnode; begin with Parents^ do if NodeCount=0 then Result:=z else begin Dec(NodeCount); Result:=Nodes[NodeCount]; end; end; procedure InitParentNodes; begin Parents^.NodeCount:=0; end; procedure SwapParentNode; var a:byte; begin with Parents^ do for a:=0 to NodeCount-1 do if Nodes[a]=t then begin Nodes[a]:=c; Break; end; end; procedure deleteFixup; procedure p_rotateLeft_g; begin AddParentNode(g); p^.r := y^.l; if (p = g^.r) then g^.r := y else g^.l := y; y^.l := p; g:=y; y:=p^.r; end; procedure p_rotateRight_g; begin AddParentNode(g); p^.l := y^.r; if (p = g^.l) then g^.l := y else g^.r := y; y^.r := p; g:=y; y:=p^.l; end; procedure y_rotateRight_p; begin c := y^.l; y^.l := c^.r; if (p^.r = y) then p^.r := c else p^.l := c; c^.r := y; y := p^.r; end; procedure y_rotateLeft_p; begin c := y^.r; y^.r := c^.l; if (p^.l = y) then p^.l := c else p^.r := c; c^.l := y; y := p^.l; end; begin p:=GetParentNode; g:=GetParentNode; while (x <> head^.r) and (x^.b = false) do begin if (x = p^.l) then begin y:=p^.r; if (y^.b = true) then begin y^.b := false; p^.b := true; p_rotateLeft_g; end; if (y^.l^.b = false) and (y^.r^.b = false) then begin y^.b := true; x := p; p := g; g := GetParentNode; end else if (p<>head) then begin if (y^.r^.b = false) then begin y^.l^.b := false; y^.b := true; y_rotateRight_p; end; y^.b := p^.b; p^.b := false; y^.r^.b := false; p_rotateLeft_g; x:=head^.r; break; end; end else begin y:=p^.l; if (y^.b = true) then begin y^.b := false; p^.b := true; p_rotateRight_g; end; if (y^.r^.b = false) and (y^.l^.b = false) then begin y^.b := true; x := p; p := g; g := GetParentNode; end else begin if (y^.l^.b = false) then begin y^.r^.b := false; y^.b := true; y_rotateLeft_p; end; y^.b := p^.b; p^.b := false; y^.l^.b := false; p_rotateRight_g; x:=head^.r; break; end; end; end; if (x<>z) then x^.b := false; end; begin InitParentNodes; p:=head; t:=head^.r; AddParentNode(p); while (t<>z) and (v<>t^.key) do begin p:=t; AddParentNode(p); if (v<t^.key) then t:=t^.l else t:=t^.r; end; if t=z then raise Exception.Create('Key not found !'); if (t^.r=z) then begin cb:=t^.b; x:=t^.l; if (p^.l=t) then p^.l:=x else p^.r:=x; end else if (t^.l=z) then begin cb:=t^.b; x:=t^.r; if (p^.l=t) then p^.l:=x else p^.r:=x; end else begin p2:=p; c:=t^.r; if c^.l=z then begin AddParentNode(c); x:=c^.r; cb:=c^.b; c^.b:=t^.b; c^.l:=t^.l; if p2^.l=t then p2^.l:=c else p2^.r:=c; end else begin AddParentNode(t); repeat AddParentNode(c); p:=c; c:=c^.l; until c^.l=z; SwapParentNode; x:=c^.r; p^.l:=x; cb:=c^.b; c^.b:=t^.b; c^.l:=t^.l; c^.r:=t^.r; if p2^.l=t then p2^.l:=c else p2^.r:=c; end; end; if cb=false then deleteFixup; t^.info:=infoNil; t^.key:=itemMin; del_node(t); Dec(cnt); end; function tStrObjList.Count: cardinal; begin Result:=cnt; end; end.
unit NtUtils.Access.Expected; interface uses Ntapi.ntpsapi, Ntapi.ntseapi, Winapi.ntlsa, Ntapi.ntsam, Winapi.Svc, NtUtils.Exceptions; { Process } procedure RtlxComputeProcessQueryAccess(var LastCall: TLastCallInfo; InfoClass: TProcessInfoClass); procedure RtlxComputeProcessSetAccess(var LastCall: TLastCallInfo; InfoClass: TProcessInfoClass); { Thread } procedure RtlxComputeThreadQueryAccess(var LastCall: TLastCallInfo; InfoClass: TThreadInfoClass); procedure RtlxComputeThreadSetAccess(var LastCall: TLastCallInfo; InfoClass: TThreadInfoClass); { Token } procedure RtlxComputeTokenQueryAccess(var LastCall: TLastCallInfo; InfoClass: TTokenInformationClass); procedure RtlxComputeTokenSetAccess(var LastCall: TLastCallInfo; InfoClass: TTokenInformationClass); { LSA policy } procedure RtlxComputePolicyQueryAccess(var LastCall: TLastCallInfo; InfoClass: TPolicyInformationClass); procedure RtlxComputePolicySetAccess(var LastCall: TLastCallInfo; InfoClass: TPolicyInformationClass); { SAM domain } procedure RtlxComputeDomainQueryAccess(var LastCall: TLastCallInfo; InfoClass: TDomainInformationClass); procedure RtlxComputeDomainSetAccess(var LastCall: TLastCallInfo; InfoClass: TDomainInformationClass); { SAM user } procedure RtlxComputeUserQueryAccess(var LastCall: TLastCallInfo; InfoClass: TUserInformationClass); procedure RtlxComputeUserSetAccess(var LastCall: TLastCallInfo; InfoClass: TUserInformationClass); { Service } procedure RtlxComputeServiceControlAccess(var LastCall: TLastCallInfo; Control: TServiceControl); { Section } procedure RtlxComputeSectionFileAccess(var LastCall: TLastCallInfo; Win32Protect: Cardinal); procedure RtlxComputeSectionMapAccess(var LastCall: TLastCallInfo; Win32Protect: Cardinal); implementation uses Ntapi.ntmmapi, Ntapi.ntioapi; { Process } procedure RtlxComputeProcessQueryAccess(var LastCall: TLastCallInfo; InfoClass: TProcessInfoClass); begin case InfoClass of ProcessBasicInformation, ProcessQuotaLimits, ProcessIoCounters, ProcessVmCounters, ProcessTimes, ProcessDefaultHardErrorMode, ProcessPooledUsageAndLimits, ProcessPriorityClass, ProcessHandleCount, ProcessPriorityBoost, ProcessSessionInformation, ProcessWow64Information, ProcessImageFileName, ProcessLUIDDeviceMapsEnabled, ProcessIoPriority, ProcessImageInformation, ProcessCycleTime, ProcessPagePriority, ProcessImageFileNameWin32, ProcessAffinityUpdateMode, ProcessMemoryAllocationMode, ProcessGroupInformation, ProcessConsoleHostProcess, ProcessWindowInformation: LastCall.Expects(PROCESS_QUERY_LIMITED_INFORMATION, @ProcessAccessType); ProcessDebugPort, ProcessWorkingSetWatch, ProcessWx86Information, ProcessDeviceMap, ProcessBreakOnTermination, ProcessDebugObjectHandle, ProcessDebugFlags, ProcessHandleTracing, ProcessExecuteFlags, ProcessWorkingSetWatchEx, ProcessImageFileMapping, ProcessHandleInformation: LastCall.Expects(PROCESS_QUERY_INFORMATION, @ProcessAccessType); ProcessCookie: LastCall.Expects(PROCESS_VM_WRITE, @ProcessAccessType); ProcessLdtInformation: LastCall.Expects(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, @ProcessAccessType); end; end; procedure RtlxComputeProcessSetAccess(var LastCall: TLastCallInfo; InfoClass: TProcessInfoClass); begin // Privileges case InfoClass of ProcessQuotaLimits: LastCall.ExpectedPrivilege := SE_INCREASE_QUOTA_PRIVILEGE; ProcessBasePriority, ProcessIoPriority: LastCall.ExpectedPrivilege := SE_INCREASE_BASE_PRIORITY_PRIVILEGE; ProcessExceptionPort, ProcessUserModeIOPL, ProcessWx86Information, ProcessSessionInformation: LastCall.ExpectedPrivilege := SE_TCB_PRIVILEGE; ProcessAccessToken: LastCall.ExpectedPrivilege := SE_ASSIGN_PRIMARY_TOKEN_PRIVILEGE; ProcessBreakOnTermination: LastCall.ExpectedPrivilege := SE_DEBUG_PRIVILEGE; end; // Access case InfoClass of ProcessBasePriority, ProcessRaisePriority, ProcessDefaultHardErrorMode, ProcessIoPortHandlers, ProcessWorkingSetWatch, ProcessUserModeIOPL, ProcessEnableAlignmentFaultFixup, ProcessPriorityClass, ProcessWx86Information, ProcessAffinityMask, ProcessPriorityBoost, ProcessDeviceMap, ProcessForegroundInformation, ProcessBreakOnTermination, ProcessDebugFlags, ProcessHandleTracing, ProcessIoPriority, ProcessPagePriority, ProcessWorkingSetWatchEx, ProcessMemoryAllocationMode, ProcessTokenVirtualizationEnabled: LastCall.Expects(PROCESS_SET_INFORMATION, @ProcessAccessType); ProcessSessionInformation: LastCall.Expects(PROCESS_SET_INFORMATION or PROCESS_SET_SESSIONID, @ProcessAccessType); ProcessExceptionPort: LastCall.Expects(PROCESS_SUSPEND_RESUME, @ProcessAccessType); ProcessQuotaLimits: LastCall.Expects(PROCESS_SET_QUOTA, @ProcessAccessType); ProcessAccessToken: begin LastCall.Expects(PROCESS_SET_INFORMATION, @ProcessAccessType); LastCall.Expects(TOKEN_ASSIGN_PRIMARY, @TokenAccessType); end; ProcessLdtInformation, ProcessLdtSize: LastCall.Expects(PROCESS_SET_INFORMATION or PROCESS_VM_WRITE, @ProcessAccessType); end; end; { Thread } procedure RtlxComputeThreadQueryAccess(var LastCall: TLastCallInfo; InfoClass: TThreadInfoClass); begin case InfoClass of ThreadBasicInformation, ThreadTimes, ThreadAmILastThread, ThreadPriorityBoost, ThreadIsTerminated, ThreadIoPriority, ThreadCycleTime, ThreadPagePriority, ThreadGroupInformation, ThreadIdealProcessorEx: LastCall.Expects(THREAD_QUERY_LIMITED_INFORMATION, @ThreadAccessType); ThreadDescriptorTableEntry, ThreadQuerySetWin32StartAddress, ThreadPerformanceCount, ThreadIsIoPending, ThreadHideFromDebugger, ThreadBreakOnTermination, ThreadUmsInformation, ThreadCounterProfiling: LastCall.Expects(THREAD_QUERY_INFORMATION, @ThreadAccessType); ThreadLastSystemCall, ThreadWow64Context: LastCall.Expects(THREAD_GET_CONTEXT, @ThreadAccessType); ThreadTebInformation: LastCall.Expects(THREAD_GET_CONTEXT or THREAD_SET_CONTEXT, @ThreadAccessType); end; end; procedure RtlxComputeThreadSetAccess(var LastCall: TLastCallInfo; InfoClass: TThreadInfoClass); begin // Privileges case InfoClass of ThreadBreakOnTermination: LastCall.ExpectedPrivilege := SE_DEBUG_PRIVILEGE; ThreadPriority, ThreadIoPriority: LastCall.ExpectedPrivilege := SE_INCREASE_BASE_PRIORITY_PRIVILEGE; end; // Access case InfoClass of ThreadPriority, ThreadBasePriority, ThreadAffinityMask, ThreadPriorityBoost, ThreadActualBasePriority: LastCall.Expects(THREAD_SET_LIMITED_INFORMATION, @ThreadAccessType); ThreadEnableAlignmentFaultFixup, ThreadZeroTlsCell, ThreadIdealProcessor, ThreadHideFromDebugger, ThreadBreakOnTermination, ThreadIoPriority, ThreadPagePriority, ThreadGroupInformation, ThreadCounterProfiling, ThreadIdealProcessorEx: LastCall.Expects(THREAD_SET_INFORMATION, @ThreadAccessType); ThreadWow64Context: LastCall.Expects(THREAD_SET_CONTEXT, @ThreadAccessType); ThreadImpersonationToken: begin LastCall.Expects(THREAD_SET_THREAD_TOKEN, @ThreadAccessType); LastCall.Expects(TOKEN_IMPERSONATE, @TokenAccessType); end; end; end; { Token } procedure RtlxComputeTokenQueryAccess(var LastCall: TLastCallInfo; InfoClass: TTokenInformationClass); begin // Privileges case InfoClass of TokenAuditPolicy: LastCall.ExpectedPrivilege := SE_SECURITY_PRIVILEGE; end; // Access case InfoClass of TokenSource: LastCall.Expects(TOKEN_QUERY_SOURCE, @TokenAccessType); else LastCall.Expects(TOKEN_QUERY, @TokenAccessType); end; end; procedure RtlxComputeTokenSetAccess(var LastCall: TLastCallInfo; InfoClass: TTokenInformationClass); begin // Privileges case InfoClass of TokenSessionId, TokenSessionReference, TokenAuditPolicy, TokenOrigin, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy: LastCall.ExpectedPrivilege := SE_TCB_PRIVILEGE; TokenLinkedToken, TokenVirtualizationAllowed: LastCall.ExpectedPrivilege := SE_CREATE_TOKEN_PRIVILEGE; end; // Access case InfoClass of TokenSessionId: LastCall.Expects(TOKEN_ADJUST_DEFAULT or TOKEN_ADJUST_SESSIONID, @TokenAccessType); TokenLinkedToken: LastCall.Expects(TOKEN_ADJUST_DEFAULT or TOKEN_QUERY, @TokenAccessType); else LastCall.Expects(TOKEN_ADJUST_DEFAULT, @TokenAccessType); end; end; { Policy } procedure RtlxComputePolicyQueryAccess(var LastCall: TLastCallInfo; InfoClass: TPolicyInformationClass); begin // See [MS-LSAD] & LsapDbRequiredAccessQueryPolicy case InfoClass of PolicyAuditLogInformation, PolicyAuditEventsInformation, PolicyAuditFullQueryInformation: LastCall.Expects(POLICY_VIEW_AUDIT_INFORMATION, @PolicyAccessType); PolicyPrimaryDomainInformation, PolicyAccountDomainInformation, PolicyLsaServerRoleInformation, PolicyReplicaSourceInformation, PolicyDefaultQuotaInformation, PolicyDnsDomainInformation, PolicyDnsDomainInformationInt, PolicyLocalAccountDomainInformation: LastCall.Expects(POLICY_VIEW_LOCAL_INFORMATION, @PolicyAccessType); PolicyPdAccountInformation: LastCall.Expects(POLICY_GET_PRIVATE_INFORMATION, @PolicyAccessType); end; end; procedure RtlxComputePolicySetAccess(var LastCall: TLastCallInfo; InfoClass: TPolicyInformationClass); begin // See [MS-LSAD] & LsapDbRequiredAccessSetPolicy case InfoClass of PolicyPrimaryDomainInformation, PolicyAccountDomainInformation, PolicyDnsDomainInformation, PolicyDnsDomainInformationInt, PolicyLocalAccountDomainInformation: LastCall.Expects(POLICY_TRUST_ADMIN, @PolicyAccessType); PolicyAuditLogInformation, PolicyAuditFullSetInformation: LastCall.Expects(POLICY_AUDIT_LOG_ADMIN, @PolicyAccessType); PolicyAuditEventsInformation: LastCall.Expects(POLICY_SET_AUDIT_REQUIREMENTS, @PolicyAccessType); PolicyLsaServerRoleInformation, PolicyReplicaSourceInformation: LastCall.Expects(POLICY_SERVER_ADMIN, @PolicyAccessType); PolicyDefaultQuotaInformation: LastCall.Expects(POLICY_SET_DEFAULT_QUOTA_LIMITS, @PolicyAccessType); end; end; { Domain } procedure RtlxComputeDomainQueryAccess(var LastCall: TLastCallInfo; InfoClass: TDomainInformationClass); begin // See [MS-SAMR] case InfoClass of DomainGeneralInformation, DomainLogoffInformation, DomainOemInformation, DomainNameInformation, DomainReplicationInformation, DomainServerRoleInformation, DomainModifiedInformation, DomainStateInformation, DomainUasInformation, DomainModifiedInformation2: LastCall.Expects(DOMAIN_READ_OTHER_PARAMETERS, @DomainAccessType); DomainPasswordInformation, DomainLockoutInformation: LastCall.Expects(DOMAIN_READ_PASSWORD_PARAMETERS, @DomainAccessType); DomainGeneralInformation2: LastCall.Expects(DOMAIN_READ_PASSWORD_PARAMETERS or DOMAIN_READ_OTHER_PARAMETERS, @DomainAccessType); end; end; procedure RtlxComputeDomainSetAccess(var LastCall: TLastCallInfo; InfoClass: TDomainInformationClass); begin // See [MS-SAMR] case InfoClass of DomainPasswordInformation, DomainLockoutInformation: LastCall.Expects(DOMAIN_WRITE_PASSWORD_PARAMS, @DomainAccessType); DomainLogoffInformation, DomainOemInformation, DomainUasInformation: LastCall.Expects(DOMAIN_WRITE_OTHER_PARAMETERS, @DomainAccessType); DomainReplicationInformation, DomainServerRoleInformation, DomainStateInformation: LastCall.Expects(DOMAIN_ADMINISTER_SERVER, @DomainAccessType); end; end; { User } procedure RtlxComputeUserQueryAccess(var LastCall: TLastCallInfo; InfoClass: TUserInformationClass); begin // See [MS-SAMR] case InfoClass of UserGeneralInformation, UserNameInformation, UserAccountNameInformation, UserFullNameInformation, UserPrimaryGroupInformation, UserAdminCommentInformation: LastCall.Expects(USER_READ_GENERAL, @UserAccessType); UserLogonHoursInformation, UserHomeInformation, UserScriptInformation, UserProfileInformation, UserWorkStationsInformation: LastCall.Expects(USER_READ_LOGON, @UserAccessType); UserControlInformation, UserExpiresInformation, UserInternal1Information, UserParametersInformation: LastCall.Expects(USER_READ_ACCOUNT, @UserAccessType); UserPreferencesInformation: LastCall.Expects(USER_READ_PREFERENCES or USER_READ_GENERAL, @UserAccessType); UserLogonInformation, UserAccountInformation: LastCall.Expects(USER_READ_GENERAL or USER_READ_PREFERENCES or USER_READ_LOGON or USER_READ_ACCOUNT, @UserAccessType); UserLogonUIInformation: ; // requires administrator and whatever access end; end; procedure RtlxComputeUserSetAccess(var LastCall: TLastCallInfo; InfoClass: TUserInformationClass); begin // See [MS-SAMR] case InfoClass of UserLogonHoursInformation, UserNameInformation, UserAccountNameInformation, UserFullNameInformation, UserPrimaryGroupInformation, UserHomeInformation, UserScriptInformation, UserProfileInformation, UserAdminCommentInformation, UserWorkStationsInformation, UserControlInformation, UserExpiresInformation, UserParametersInformation: LastCall.Expects(USER_WRITE_ACCOUNT, @UserAccessType); UserPreferencesInformation: LastCall.Expects(USER_WRITE_PREFERENCES, @UserAccessType); UserSetPasswordInformation: LastCall.Expects(USER_FORCE_PASSWORD_CHANGE, @UserAccessType); end; end; procedure RtlxComputeServiceControlAccess(var LastCall: TLastCallInfo; Control: TServiceControl); begin // MSDN case Control of ServiceControlPause, ServiceControlContinue, ServiceControlParamChange, ServiceControlNetbindAdd, ServiceControlNetbindRemove, ServiceControlNetbindEnable, ServiceControlNetbindDisable: LastCall.Expects(SERVICE_PAUSE_CONTINUE, @ScmAccessType); ServiceControlStop: LastCall.Expects(SERVICE_STOP, @ScmAccessType); ServiceControlInterrogate: LastCall.Expects(SERVICE_INTERROGATE, @ScmAccessType); else if (Cardinal(Control) >= 128) and (Cardinal(Control) < 255) then LastCall.Expects(SERVICE_USER_DEFINED_CONTROL, @ScmAccessType); end; end; procedure RtlxComputeSectionFileAccess(var LastCall: TLastCallInfo; Win32Protect: Cardinal); begin case Win32Protect and $FF of PAGE_NOACCESS, PAGE_READONLY, PAGE_WRITECOPY: LastCall.Expects(FILE_READ_DATA, @FileAccessType); PAGE_READWRITE: LastCall.Expects(FILE_WRITE_DATA or FILE_READ_DATA, @FileAccessType); PAGE_EXECUTE: LastCall.Expects(FILE_EXECUTE, @FileAccessType); PAGE_EXECUTE_READ, PAGE_EXECUTE_WRITECOPY: LastCall.Expects(FILE_EXECUTE or FILE_READ_DATA, @FileAccessType); PAGE_EXECUTE_READWRITE: LastCall.Expects(FILE_EXECUTE or FILE_WRITE_DATA or FILE_READ_DATA, @FileAccessType); end; end; procedure RtlxComputeSectionMapAccess(var LastCall: TLastCallInfo; Win32Protect: Cardinal); begin case Win32Protect and $FF of PAGE_NOACCESS, PAGE_READONLY, PAGE_WRITECOPY: LastCall.Expects(SECTION_MAP_READ, @SectionAccessType); PAGE_READWRITE: LastCall.Expects(SECTION_MAP_WRITE, @SectionAccessType); PAGE_EXECUTE: LastCall.Expects(SECTION_MAP_EXECUTE, @SectionAccessType); PAGE_EXECUTE_READ, PAGE_EXECUTE_WRITECOPY: LastCall.Expects(SECTION_MAP_EXECUTE or SECTION_MAP_READ, @SectionAccessType); PAGE_EXECUTE_READWRITE: LastCall.Expects(SECTION_MAP_EXECUTE or SECTION_MAP_WRITE, @SectionAccessType); end; end; end.
Program main; { DESKRIPSI : Program Manajemen Perpustakaan untuk Membantu Wan Shi Tong! } { ASUMSI : Beberapa contoh di spesifikasi tidak perlu dilakukan validasi, namun kita menambahkan validasi opsional untuk beberapa contoh tersebut } uses csv_parser, buku_handler, user_handler, peminjaman_Handler, pengembalian_Handler, kehilangan_handler, crt, intro, f01_registrasi, f02_Login, f03_findCategory, f04_findYear, f05_peminjaman, f06_KembalikanBuku, f07_laporhilang, f08_lihatlaporan, f09_tambahbaru, f10_tambahjumlah, f11_riwayatPeminjaman, f12_statistik, f13_load, f14_save, f15_carianggota, f16_exitprogram, // b01_simpanpw digunakan di f01_registrasi dan f02_login // b02_denda digunakan di f06_kembalikanbuku utilitas, tipe_data; { KAMUS GLOBAL } var data_buku : tabel_buku; data_user : tabel_user; data_peminjaman : tabel_peminjaman; data_pengembalian : tabel_pengembalian; data_kehilangan : tabel_kehilangan; who_login : user; have_login : Boolean; inp : string; c : char; { ALGORITMA } begin welcome(); { LOAD DATA KE ARRAY } writeln('Load file by writing "load"'); write('$ '); repeat begin readln(inp); if (inp <> 'load') then write('$ '); end; until(inp = 'load'); load(data_buku, data_user, data_peminjaman, data_pengembalian, data_kehilangan); end_of_submenu(c); clrscr(); loading(); end_of_submenu(c); { LOGIN PENGGUNA ATAU EXIT PROGRAM } writeln('Silahkan Login dengan mengetik "login" terlebih atau keluar program dengan mengetik "exit"'); write('$ '); repeat begin readln(inp); if ((inp <> 'login') and (inp <> 'exit')) then write('$ '); end; until((inp = 'login') or (inp = 'exit')); if(inp='exit') then writeln('Terima kasih telah berkunjung ke Wan Shi Tong''s Library!') else // inp = 'login' begin repeat begin who_login := login(data_user); have_login := isLogin(who_login); if (have_login = False) then begin repeat who_login := login(data_user); have_login := isLogin(who_login); until(have_login = true); end; end; until (have_login = True); writeln; writeln('Press Any Key to Proceed'); inp := readkey; clrscr1(); { MENU DAN I/O } if (who_login.Role = 'Admin') then load_menu_admin() else load_menu_pengunjung(); write('$ '); readln(inp); if(inp='exit') then begin exitprogram(data_buku,data_user,data_peminjaman,data_pengembalian,data_kehilangan); end else begin while(inp <> 'exit') do begin { MENU ADMIN } if (who_login.Role = 'Admin') then begin case inp of 'register' : registrasi(data_user); 'cari' : cari_kategori(data_buku); 'caritahunterbit' : cari_tahun(data_buku); 'lihat_laporan' : lihat_hilang(data_buku,data_kehilangan); 'tambah_buku' : tambah_baru(data_buku); 'tambah_jumlah_buku' : tambah_jumlah(data_buku); 'statistik' : getStatistik(data_user, data_buku); 'save' : save(data_buku, data_user, data_peminjaman, data_pengembalian, data_kehilangan); 'cari_anggota' : lihatUser(data_user); 'riwayat' : lihathistory(data_buku,data_peminjaman); else writeln('Masukan ', inp, ' tidak valid!'); end; end_of_submenu(c); load_menu_admin(); write('$ '); readln(inp); if(inp='exit') then exitprogram(data_buku,data_user,data_peminjaman,data_pengembalian,data_kehilangan); end else { MENU PENGUNJUNG } if (who_login.Role = 'Pengunjung') then begin case inp of 'cari' : cari_kategori(data_buku); 'save' : save(data_buku, data_user, data_peminjaman, data_pengembalian, data_kehilangan); 'caritahunterbit' : cari_tahun(data_buku); 'pinjam_buku' : pinjam(data_peminjaman,data_buku,who_login.username); 'lapor_hilang' : lapor(data_kehilangan, data_peminjaman, data_buku, who_login.Username); 'kembalikan_buku' : kembalikan_buku(who_login,data_peminjaman,data_buku,data_pengembalian); else writeln('Masukan ', inp, ' tidak valid!'); end; end_of_submenu(c); load_menu_pengunjung(); write('$ '); readln(inp); if(inp='exit') then exitprogram(data_buku,data_user,data_peminjaman,data_pengembalian,data_kehilangan); end; end; end; end; end.
unit U_MatrixFunctions; interface uses U_Typeset,U_ListFunctions,U_Association; procedure InitializeMatrix(var mat : matrix_array; w,l : longint); // What : Initializes the matrix, sets it's length, all it's elements sets to zero procedure PrintMatrix(const mat : matrix_array; w,l : longint); // What : Prints the matrix. procedure FillCol(var mat : matrix_array; w,l : longint; var StackL : PStack; col_num : longint;ReactOrProduct : integer); // What : Fills one column (which means one variable = reactant) of the matrix // with appropriate numbers. // How : Goes through the stack popping, if it finds a positive or a negative number // (positive are elements, negative are "numbers") and makes the appropriate // changes to the matrix. For more see documentation on tokenizing. // ReactOrProduct determines if the string is on the left or on the right // side of the equation. procedure FillMatrix(var mat : matrix_array; var assoc_field : dynamic_array_str; e_elem,e_react : longint; StackL : PStack; ListS : PItem; ReactOnLeft : longint ); // What : Fills the whole matrix with numbers coresponging to the equation. // How : Goes through the list of reactatns, calls for tokenization then immediately // calls for FillCol. Repeats for the whole list. implementation procedure InitializeMatrix(var mat : matrix_array; w,l : longint); var m,n : longint; begin setlength(mat,w,l); m := 0; n := 0; for m := 0 to (w-1) do begin for n := 0 to (l-1) do begin mat[m][n] := 0; end; end; writeln('OK _ Matrix intialized') end; procedure PrintMatrix(const mat : matrix_array; w,l : longint); var m,n : longint; begin m := 0; n := 0; WriteLn; for m := 0 to (w-1) do begin for n := 0 to (l-1) do begin Write(mat[m][n],' '); end; Writeln; end; end; procedure FillCol(var mat : matrix_array; w,l : longint; var StackL : PStack; col_num : longint; ReactOrProduct : integer); var tmp, mul, next, current : longint; TmpStackL : PStack; begin mul := 1; { multiplying by one, not zero! } next := 1; current := 0; new(TmpStackL); TmpStackL^.val := -31000; TmpStackL^.last := nil; TmpStackL^.next := nil; current := PopEnd(StackL); while(current <> -31000) do begin if(current < 0) then begin if current = -32000 then begin tmp := PopEnd(TmpStackL); mul := mul div tmp; tmp := 0; end else next := (-1)*current; end else if(current >= 0) then begin if current = 32000 then begin tmp := PopEnd(StackL); mul := mul*(-1)*tmp; PushEnd((-1*tmp),TmpStackL); tmp := 0; end else begin mat[current][col_num] := mat[current][col_num] + mul*next*ReactOrProduct; next := 1; end; end; current := PopEnd(StackL); end; dispose(TmpStackL); end; procedure FillMatrix(var mat : matrix_array; var assoc_field : dynamic_array_str; e_elem,e_react : longint; StackL : PStack; ListS : PItem; ReactOnLeft : longint); var react : PItem; i,LeftOrRight : longint; begin react := ListS^.next; i := 0; while react <> nil do begin TokenizeString(react^.val, assoc_field, e_elem, StackL); if(i < ReactOnLeft) then LeftOrRight := 1 else LeftOrRight := -1; FillCol(mat,e_elem, e_react, StackL, i,LeftOrRight); react := react^.next; i := i+1; end; WriteLn('OK _ Matrix fill completed'); end; end.
unit TestBowlingGame; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, Generics.Collections, BowlingGame; type // Test methods for class TFrameRollsCtrl TestTBowlingGame = class(TTestCase) strict private FBowlingGame: TBowlingGame; public procedure SetUp; override; procedure TearDown; override; published procedure TestStart; procedure TestRoll; procedure TestPerfectGame(); procedure TestAllGutterGame(); procedure TestStrikeSpare(); procedure TestAllSpareAndStrike(); procedure TestGame1(); procedure TestGame2(); procedure TestScoreByFrame; procedure TestScoreByFrame2; procedure TestNewGame(); end; implementation procedure TestTBowlingGame.SetUp; begin FBowlingGame := TBowlingGame.Create; FBowlingGame.Start; Assert(FBowlingGame.TotalScore = 0); Assert(not FBowlingGame.GameOver); end; procedure TestTBowlingGame.TearDown; begin FBowlingGame.Free; FBowlingGame := nil; end; procedure TestTBowlingGame.TestStart; begin // TODO: Validate method results end; procedure TestTBowlingGame.TestStrikeSpare; begin Assert(not FBowlingGame.GameOver); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 200); Assert(FBowlingGame.GameOver); ////////////////////////////////////////////////////////// FBowlingGame.Start(); Assert(not FBowlingGame.GameOver); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); Assert(FBowlingGame.TotalScore = 200); Assert(FBowlingGame.GameOver); ////////////////////////////////////////////////////////////// FBowlingGame.Start(); Assert(not FBowlingGame.GameOver); FBowlingGame.Roll(5); FBowlingGame.Roll(3); //1 FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(6); FBowlingGame.Roll(3); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(0); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); FBowlingGame.Roll(7); FBowlingGame.Roll(3); Assert(FBowlingGame.TotalScore = 173); Assert(FBowlingGame.GameOver); end; procedure TestTBowlingGame.TestAllGutterGame; begin FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(0); Assert(FBowlingGame.TotalScore = 0); end; procedure TestTBowlingGame.TestAllSpareAndStrike; begin FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(8); FBowlingGame.Roll(2); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(5); FBowlingGame.Roll(5); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(9); FBowlingGame.Roll(1); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(8); FBowlingGame.Roll(2); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 175); Assert(FBowlingGame.GameOver); end; procedure TestTBowlingGame.TestGame1; begin FBowlingGame.Roll(9); Assert(FBowlingGame.FramesCtrl.GetCurrent().Number = 1); FBowlingGame.Roll(0); Assert(FBowlingGame.FramesCtrl.GetCurrent().Number = 2); FBowlingGame.Roll(2); FBowlingGame.Roll(7); FBowlingGame.Roll(10); FBowlingGame.Roll(3); FBowlingGame.Roll(6); FBowlingGame.Roll(8); FBowlingGame.Roll(1); FBowlingGame.Roll(7); FBowlingGame.Roll(3); FBowlingGame.Roll(5); FBowlingGame.Roll(3); FBowlingGame.Roll(6); FBowlingGame.Roll(2); FBowlingGame.Roll(7); Assert(FBowlingGame.FramesCtrl.GetCurrent().Number = 9); FBowlingGame.Roll(3); Assert(FBowlingGame.FramesCtrl.GetCurrent().Number = 10); FBowlingGame.Roll(6); Assert(FBowlingGame.FramesCtrl.GetCurrent().Number = 10); FBowlingGame.Roll(3); Assert(FBowlingGame.FramesCtrl.GetCurrent().Number = 10); Assert(FBowlingGame.TotalScore = 111); Assert(FBowlingGame.GameOver); end; procedure TestTBowlingGame.TestGame2; begin FBowlingGame.Roll(9); FBowlingGame.Roll(0); FBowlingGame.Roll(10); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(3); FBowlingGame.Roll(6); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(10); FBowlingGame.Roll(0); FBowlingGame.Roll(10); FBowlingGame.Roll(6); FBowlingGame.Roll(4); FBowlingGame.Roll(0); FBowlingGame.Roll(0); FBowlingGame.Roll(6); FBowlingGame.Roll(3); Assert(FBowlingGame.TotalScore = 83); Assert(FBowlingGame.GameOver); end; procedure TestTBowlingGame.TestNewGame; var sbfl: TList<TScoreByFrame>; sbf: TScoreByFrame; begin sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 0); FBowlingGame.Roll(10); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 1); sbfl := FBowlingGame.ScoreByFrame(); sbf := sbfl[0]; Assert(sbf.Status = 'Pending'); Assert(sbf.Number = 1); Assert(sbf.FrameScore = 'X'); Assert(sbf.FrameScoreInPoints = 0); Assert(sbf.GameScore = 0); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 300); Assert(FBowlingGame.GameOver); FBowlingGame.Start(); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 0); FBowlingGame.Roll(10); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 1); sbf := sbfl[0]; Assert(sbf.Status = 'Pending'); Assert(sbf.Number = 1); Assert(sbf.FrameScore = 'X'); Assert(sbf.FrameScoreInPoints = 0); Assert(sbf.GameScore = 0); FBowlingGame.Roll(10); FBowlingGame.Roll(10); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 3); sbf := sbfl[0]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 1); Assert(sbf.FrameScore = 'X'); Assert(sbf.FrameScoreInPoints = 30); Assert(sbf.GameScore = 30); sbf := sbfl[2]; Assert(sbf.Status = 'Pending'); sbf := sbfl[2]; Assert(sbf.Status = 'Pending'); Assert(sbf.Number = 3); Assert(sbf.FrameScore = 'X'); Assert(sbf.FrameScoreInPoints = 0); Assert(sbf.GameScore = 30); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 300); Assert(FBowlingGame.GameOver); end; procedure TestTBowlingGame.TestPerfectGame; begin FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 300); Assert(FBowlingGame.GameOver); end; procedure TestTBowlingGame.TestRoll; begin // TODO: Setup method call parameters FBowlingGame.Roll(4); Assert(FBowlingGame.TotalScore = 0); FBowlingGame.Roll(3); Assert(FBowlingGame.TotalScore = 7); FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 7); FBowlingGame.Roll(7); FBowlingGame.Roll(2); Assert(FBowlingGame.TotalScore = 35); // TODO: Validate method results end; procedure TestTBowlingGame.TestScoreByFrame; var sbfl: TList<TScoreByFrame>; sbf: TScoreByFrame; begin sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 0); FBowlingGame.Roll(4); Assert(FBowlingGame.TotalScore = 0); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 1); Assert(sbfl[0].Status = 'In Play'); Assert(sbfl[0].Number = 1); FBowlingGame.Roll(5); Assert(FBowlingGame.TotalScore = 9); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 1); sbf := sbfl[0]; Assert(sbf.Status = 'Scored'); Assert(sbfl[0].Number = 1); // 1 FBowlingGame.Roll(2); Assert(FBowlingGame.TotalScore = 9); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 2); sbf := sbfl[1]; Assert(sbf.Status = 'In Play'); Assert(sbf.Number = 2); FBowlingGame.Roll(3); Assert(FBowlingGame.TotalScore = 14); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 2); sbf := sbfl[1]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 2); // 2 FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 14); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 3); sbf := sbfl[2]; Assert(sbf.Status = 'Pending'); Assert(sbf.Number = 3); // 3 FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 14); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 4); sbf := sbfl[3]; Assert(sbf.Status = 'Pending'); Assert(sbf.Number = 4); // 4 FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 44); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 5); sbf := sbfl[4]; Assert(sbf.Status = 'Pending'); Assert(sbf.Number = 5); // 5 FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 74); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 6); sbf := sbfl[5]; Assert(sbf.Status = 'Pending'); Assert(sbf.Number = 6); // 6 FBowlingGame.Roll(9); Assert(FBowlingGame.TotalScore = 103); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 7); sbf := sbfl[6]; Assert(sbf.Status = 'In Play'); Assert(sbf.Number = 7); FBowlingGame.Roll(1); Assert(FBowlingGame.TotalScore = 123); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 7); sbf := sbfl[6]; Assert(sbf.Status = 'Pending'); Assert(sbf.Number = 7); // 7 FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 143); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 8); sbf := sbfl[7]; Assert(sbf.Status = 'Pending'); Assert(sbf.Number = 8); // 8 FBowlingGame.Roll(10); Assert(FBowlingGame.TotalScore = 143); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 9); sbf := sbfl[8]; Assert(sbf.Status = 'Pending'); Assert(sbf.Number = 9); // 9 FBowlingGame.Roll(4); Assert(FBowlingGame.TotalScore = 167); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 10); sbf := sbfl[9]; Assert(sbf.Status = 'In Play'); Assert(sbf.Number = 10); FBowlingGame.Roll(3); Assert(FBowlingGame.TotalScore = 191); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 10); sbf := sbfl[9]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 10); // 10 sbfl := FBowlingGame.ScoreByFrame(); sbf := sbfl[0]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 1); Assert(sbf.FrameScore = '4 5'); Assert(sbf.FrameScoreInPoints = 9); Assert(sbf.GameScore = 9); sbf := sbfl[1]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 2); Assert(sbf.FrameScore = '2 3'); Assert(sbf.FrameScoreInPoints = 5); Assert(sbf.GameScore = 14); sbf := sbfl[2]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 3); Assert(sbf.FrameScore = 'X'); Assert(sbf.FrameScoreInPoints = 30); Assert(sbf.GameScore = 44); sbf := sbfl[3]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 4); Assert(sbf.FrameScore = 'X'); Assert(sbf.FrameScoreInPoints = 30); Assert(sbf.GameScore = 74); sbf := sbfl[4]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 5); Assert(sbf.FrameScore = 'X'); Assert(sbf.FrameScoreInPoints = 29); Assert(sbf.GameScore = 103); sbf := sbfl[5]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 6); Assert(sbf.FrameScore = 'X'); Assert(sbf.FrameScoreInPoints = 20); Assert(sbf.GameScore = 123); sbf := sbfl[6]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 7); Assert(sbf.FrameScore = '9 /'); Assert(sbf.FrameScoreInPoints = 20); Assert(sbf.GameScore = 143); sbf := sbfl[7]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 8); Assert(sbf.FrameScore = 'X'); Assert(sbf.FrameScoreInPoints = 24); Assert(sbf.GameScore = 167); sbf := sbfl[8]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 9); Assert(sbf.FrameScore = 'X'); Assert(sbf.FrameScoreInPoints = 17); Assert(sbf.GameScore = 184); sbf := sbfl[9]; Assert(sbf.Status = 'Scored'); Assert(sbf.Number = 10); Assert(sbf.FrameScore = '4 3'); Assert(sbf.FrameScoreInPoints = 7); Assert(sbf.GameScore = 191); end; procedure TestTBowlingGame.TestScoreByFrame2; var sbfl: TList<TScoreByFrame>; sbf: TScoreByFrame; begin sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 0); FBowlingGame.Roll(9); Assert(FBowlingGame.TotalScore = 0); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 1); Assert(sbfl[0].Status = 'In Play'); Assert(sbfl[0].Number = 1); FBowlingGame.Roll(1); Assert(FBowlingGame.TotalScore = 0); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 1); sbf := sbfl[0]; Assert(sbf.Status = 'Pending'); Assert(sbfl[0].Number = 1); // 1 FBowlingGame.Roll(2); Assert(FBowlingGame.TotalScore = 12); sbfl := FBowlingGame.ScoreByFrame(); Assert(sbfl.Count = 2); sbf := sbfl[1]; Assert(sbf.Status = 'In Play'); Assert(sbf.Number = 2); end; initialization // Register any test cases with the test runner RegisterTest(TestTBowlingGame.Suite); end.
(* Name: UpgradeMnemonicLayout Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 31 Dec 2014 Modified Date: 2 Jun 2015 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 31 Dec 2014 - mcdurdin - I4553 - V9.0 - Upgrade to 476 or later requires recompile of all mnemonic layouts 06 Feb 2015 - mcdurdin - I4552 - V9.0 - Add mnemonic recompile option to ignore deadkeys 08 Apr 2015 - mcdurdin - I4651 - V9.0 - Mnemonic layout recompiler maps AltGr+VK_BKSLASH rather than VK_OEM_102 02 Jun 2015 - mcdurdin - I4657 - CrashID:kmshell.exe_9.0.492.0_2C46973C_ERegistryException *) unit UpgradeMnemonicLayout; // I4553 interface uses keymanapi_TLB; type TUpgradeMnemonicLayout = class class procedure UpgradeLayout(Keyboard: IKeymanKeyboardInstalled); class procedure Run; private class procedure UpgradeLayoutLanguage(Keyboard: IKeymanKeyboardInstalled; const OutputFileName: string); static; end; implementation uses System.SysUtils, System.Win.Registry, Winapi.Windows, ErrorControlledRegistry, KeymanPaths, kmint, RegistryKeys, utilexecute, utilkmshell; const { CurrentMnemonicLayoutVersion = 476; // First 9.0 build with fixes for mnemonic layouts } { CurrentMnemonicLayoutVersion = 480; // Adds support for deadkey conversion // I4552 } CurrentMnemonicLayoutVersion = 492; // Fixes bkslash order // I4651 { TUpgradeMnemonicLayout } class procedure TUpgradeMnemonicLayout.Run; var i: Integer; begin with TRegistry.Create do try RootKey := HKEY_LOCAL_MACHINE; if OpenKeyReadOnly(SRegKey_KeymanEngine) and ValueExists(SRegValue_MnemonicLayoutVersion) then if ReadInteger(SRegValue_MnemonicLayoutVersion) >= CurrentMnemonicLayoutVersion then Exit; finally Free; end; if not kmcom.SystemInfo.IsAdministrator then begin WaitForElevatedConfiguration(0, '-upgrademnemoniclayout'); Exit; end; // // Iterate through all installed layouts and rewrite any // mnemonic layout files in the folders. We need to rewrite // all of them, not just the ones used by the current user, // in case other users have different base layouts. // for i := 0 to kmcom.Keyboards.Count - 1 do UpgradeLayout(kmcom.Keyboards[i]); with TRegistryErrorControlled.Create do // I4657 try RootKey := HKEY_LOCAL_MACHINE; try OpenKey(SRegKey_KeymanEngine, True); WriteInteger(SRegValue_MnemonicLayoutVersion, CurrentMnemonicLayoutVersion); except on E:ERegistryException do RaiseLastRegistryError(E.Message); end; finally Free; end; end; class procedure TUpgradeMnemonicLayout.UpgradeLayout( Keyboard: IKeymanKeyboardInstalled); var FBaseName: string; f: TSearchRec; begin FBaseName := ChangeFileExt(Keyboard.Filename, ''); if FindFirst(FBaseName + '-????????.kmx', 0, f) = 0 then // I4552 begin repeat UpgradeLayoutLanguage(Keyboard, f.Name); until FindNext(f) <> 0; System.SysUtils.FindClose(f); end; end; function GetKeyboardLayoutFileName(id: Integer): string; begin with TRegistry.Create do try RootKey := HKEY_LOCAL_MACHINE; if OpenKeyReadOnly(SRegKey_KeyboardLayouts+'\'+IntToHex(id,8)) and ValueExists(SRegValue_KeyboardLayoutFile) then begin Exit(ReadString(SRegValue_KeyboardLayoutFile)); end; finally Free; end; Result := ''; end; { Extracted from utilkeyman } // I4552 function GetShortKeyboardName(const FileName: string): string; begin if (LowerCase(ExtractFileExt(FileName)) = '.kmx') or (LowerCase(ExtractFileExt(FileName)) = '.kxx') or (LowerCase(ExtractFileExt(FileName)) = '.kmp') then Result := ChangeFileExt(ExtractFileName(FileName), '') else Result := FileName; end; function GetRegistryKeyboardInstallKey(const FileName: string): string; begin Result := SRegKey_InstalledKeyboards+'\'+GetShortKeyboardName(FileName); end; class procedure TUpgradeMnemonicLayout.UpgradeLayoutLanguage( Keyboard: IKeymanKeyboardInstalled; const OutputFileName: string); var FMCompilePath: string; BaseKeyboardID: Integer; FBaseKeyboardIDHex: string; FBaseFileName: string; FDestFileName: string; FBaseKeyboardFileName: string; FDestPath: string; FLogText: string; FExitCode: Integer; FDestDeadkeyFileName: string; begin // OutputFileName format is C:\ProgramData\Keyman Engine <ver>\...\package\keyboard-########.kmx if not TryStrToInt('$'+Copy(OutputFileName, Length(OutputFileName)-11, 8), BaseKeyboardID) then Exit; FBaseKeyboardIDHex := IntToHex(BaseKeyboardID, 8); FBaseFileName := Keyboard.Filename; FDestFileName := OutputFileName; FDestDeadkeyFileName := ChangeFileExt(FDestFileName, '') + '-d.kmx'; // I4552 FMCompilePath := TKeymanPaths.KeymanEngineInstallPath(TKeymanPaths.S_MCompileExe); FDestPath := ExtractFileDir(Keyboard.Filename); FBaseKeyboardFileName := GetKeyboardLayoutFileName(BaseKeyboardID); if FBaseKeyboardFileName = '' then Exit; // Run mcompile to rebuild the mnemonic layout TUtilExecute.Console(Format('"%s" "%s" "%s" %s "%s"', [ FMCompilePath, FBaseFileName, FBaseKeyboardFileName, FBaseKeyboardIDHex, FDestFileName]), FDestPath, FLogText, FExitCode); // Run mcompile to rebuild the mnemonic layout with deadkey conversion // I4552 TUtilExecute.Console(Format('"%s" -d "%s" "%s" %s "%s"', [ FMCompilePath, FBaseFileName, FBaseKeyboardFileName, FBaseKeyboardIDHex, FDestDeadkeyFileName]), FDestPath, FLogText, FExitCode); with TRegistry.Create do // I4552 try RootKey := HKEY_LOCAL_MACHINE; if OpenKey('\'+GetRegistryKeyboardInstallKey(Keyboard.Filename), True) then begin WriteString(SRegValue_KeymanFile_MnemonicOverride, IncludeTrailingPathDelimiter(FDestPath)+FDestFileName); WriteString(SRegValue_KeymanFile_MnemonicOverride_Deadkey, IncludeTrailingPathDelimiter(FDestPath)+FDestDeadkeyFileName); end; finally Free; end; end; end.
unit ASDTexture; {<|Модуль библиотеки ASDEngine|>} {<|Дата создания 31.05.07|>} {<|Автор Adler3D|>} {<|e-mail : Adler3D@Mail.ru|>} {<|Дата последнего изменения 6.07.07|>} interface uses Windows, OpenGL, ASDUtils, ASDInterface, ASDType, ASDClasses; const TEX_MAX = 16; type TTexData = record ID: Cardinal; Width: Integer; Height: Integer; Ref: Integer; Group: Integer; Flag: Boolean; MipMap: Boolean; Name: string; end; TTexImage = class(TASDObject, ITexImage) private FID: Cardinal; FWidth: Integer; FHeight: Integer; FGroup: Integer; FMipMap: Boolean; FName: string; public constructor CreateEx; override; destructor Destroy; override; procedure Enable(Channel: Integer); procedure Disable(Channel: Integer); procedure RenderCopy(X, Y, W, H, Format: Integer; Level: Integer); procedure RenderBegin(Mode: TTexMode); procedure RenderEnd; procedure Filter(FilterType: Integer); procedure UnLoad; override; public function ID: Cardinal; function Width: Integer; function Height: Integer; function Group: Integer; function MipMap: Boolean; function Name: string; end; TTexture = class(TASDObject, ITexture) private FFrame: DWORD; FDepth: DWORD; FCurmode: Byte; FList: TList; FTexCur: array[0..TEX_MAX] of HTexture; FDefTex: TTexImage; // Текстура по умолчанию public constructor CreateEx; override; destructor Destroy; override; function Make(Name: PChar; c, f, W, H: Integer; Data: Pointer; Clamp, MipMap: Boolean; Group: Integer): ITexImage; function LoadFromFile(FileName: PChar; Clamp: Boolean = False; MipMap: Boolean = True; Group: Integer = 0): ITexImage; function LoadFromMem(Name: PChar; Mem: Pointer; Size: Integer; Clamp: Boolean = False; MipMap: Boolean = True; Group: Integer = 0): ITexImage; function LoadDataFromFile(FileName: PChar; var W, H, BPP: Integer; var Data: Pointer): Boolean; function LoadDataFromMem(Name: PChar; Mem: Pointer; Size: Integer; var W, H, BPP: Integer; var Data: Pointer): Boolean; procedure Free(var Data: Pointer); overload; procedure Delete(Tex:ITexImage); procedure Enable(ID: HTexture; Channel: Integer); procedure Disable(Channel: Integer); procedure Filter(FilterType: Integer; Group: Integer); function RenderInit(TexSize: Integer): Boolean; procedure UnLoad; override; procedure Clear; public procedure AddLog(Text: string); function Init: Boolean; function GetTex(const Name: string): ITexImage; function NewTex(const Name: string; Data: Pointer; C, F, W, H, Group: Integer; Clamp, MipMap: Boolean): ITexImage; end; implementation uses ASDEng, ASDOpenGL, ASDTGA, ASDBJG; { TTexImage } constructor TTexImage.CreateEx; begin inherited CreateEx; end; destructor TTexImage.Destroy; begin inherited Destroy; end; procedure TTexImage.Disable(Channel: Integer); begin Texture.Disable(Channel); end; procedure TTexImage.Enable(Channel: Integer); begin Texture.Enable(FID, Channel); end; procedure TTexImage.Filter(FilterType: Integer); begin Enable(0); if FMipMap then case FilterType of FT_NONE: begin glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1); end; FT_BILINEAR: begin glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1); end; FT_TRILINEAR: begin glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1); end; FT_ANISOTROPY: begin glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, GL_max_aniso); end; end else case FilterType of FT_NONE: begin glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); end; FT_BILINEAR, FT_TRILINEAR, FT_ANISOTROPY: // без мипмапов - никакой нормальной фильтрации ;) begin glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); end; end; end; function TTexImage.Group: Integer; begin Result := FGroup; end; function TTexImage.Height: Integer; begin Result := FHeight; end; function TTexImage.ID: Cardinal; begin Result := FID; end; function TTexImage.MipMap: Boolean; begin Result := FMipMap; end; function TTexImage.Name: string; begin Result := FName; end; procedure TTexImage.RenderBegin(Mode: TTexMode); begin glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, Texture.FFrame); case Mode of TM_COLOR: glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, ID, 0); TM_DEPTH: glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, ID, 0); end; Texture.FCurmode := Texture.FCurmode or Byte(Mode); if glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) <> GL_FRAMEBUFFER_COMPLETE_EXT then begin Texture.FCurmode := 0; glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); end; end; procedure TTexImage.RenderCopy(X, Y, W, H, Format, Level: Integer); begin Enable(0); glCopyTexImage2D(GL_TEXTURE_2D, Level, Format, X, Y, W, H, 0); with Texture do if (FTexCur[0] = FDefTex.ID) or (FTexCur[0] = 0) then Disable(0) else Enable(FTexCur[0], 0); end; procedure TTexImage.RenderEnd; begin if Texture.FCurmode and Byte(TM_COLOR) > 0 then glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, 0, 0); if Texture.FCurmode and Byte(TM_DEPTH) > 0 then glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0); if Texture.FCurmode > 0 then glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); Texture.FCurmode := 0; end; procedure TTexImage.UnLoad; begin Texture.AddLog('Unload ID: ' + IntToStr(FID) + #9 + FName); glDeleteTextures(1, @FID); //Texture.Delete(Self); inherited; end; function TTexImage.Width: Integer; begin Result := FWidth; end; { TTexture } destructor TTexture.Destroy; begin inherited; end; //== Создание текстуры по битовом массиву и другим параметрам function TTexture.Make(Name: PChar; c, f, W, H: Integer; Data: Pointer; Clamp, MipMap: Boolean; Group: Integer): ITexImage; begin Result := GetTex(Name); if Result = nil then begin Result := NewTex(Name, Data, c, f, W, H, group, Clamp, MipMap); AddLog('Create ID: ' + IntToStr(Result.ID) + #9 + Name); end; end; //== Загрузка текстуры из TGA, BMP, JPG, GIF (без анимации) файлов function TTexture.LoadFromFile(FileName: PChar; Clamp, MipMap: Boolean; Group: Integer): ITexImage; var W, H, b: Integer; Data: Pointer; c, f: Integer; begin Result := GetTex(FileName); if Result = nil then try // Если текстура не загружена - грузим Result := FDefTex; if not LoadDataFromFile(FileName, W, H, b, Data) then Exit; if b = 24 then // Любые текстуры на выходе преобразуются 24 или 32 битные begin c := GL_RGB8; f := GL_BGR; end else begin c := GL_RGBA8; f := GL_BGRA; end; Result := NewTex(FileName, Data, c, f, W, H, group, Clamp, MipMap); Free(Data); AddLog('Loaded ID: ' + IntToStr(Result.ID) + #9 + Result.Name); except AddLog('Error Loading "' + Result.Name + '"'); Result := nil; end; end; //== Загрузка текстуры из памяти (потока) function TTexture.LoadFromMem(Name: PChar; Mem: Pointer; Size: Integer; Clamp, MipMap: Boolean; Group: Integer): ITexImage; var W, H, b: Integer; Data: Pointer; c, f: Integer; begin Result := GetTex(Name); if Result = nil then try // Если текстура не загружена - грузим Result := FDefTex; if not LoadDataFromMem(Name, Mem, Size, W, H, b, Data) then Exit; if b = 24 then // Любые текстуры на выходе преобразуются 24 или 32 битные begin c := GL_RGB8; f := GL_BGR; end else begin c := GL_RGBA8; f := GL_BGRA; end; Result := NewTex(Name, Data, c, f, W, H, group, Clamp, MipMap); Free(Data); AddLog('Loaded ID: ' + IntToStr(Result.ID) + #9 + Name); except AddLog('Error Loading "' + Name + '"'); Result := nil; end; end; // Загрузка данных текстуры function TTexture.LoadDataFromFile(FileName: PChar; var W, H, BPP: Integer; var Data: Pointer): Boolean; begin if LowerCase(ExtractFileExt(FileName)) = 'tga' then Result := LoadTGA(FileName, W, H, BPP, PByteArray(Data)) else Result := LoadBJG(FileName, W, H, BPP, PByteArray(Data)); if not Result then AddLog('Error Loading "' + FileName + '"'); end; function TTexture.LoadDataFromMem(Name: PChar; Mem: Pointer; Size: Integer; var W, H, BPP: Integer; var Data: Pointer): Boolean; begin if LowerCase(ExtractFileExt(Name)) = 'tga' then Result := LoadTGAmem(Mem, Size, W, H, BPP, PByteArray(Data)) else Result := LoadBJGmem(Mem, Size, W, H, BPP, PByteArray(Data)); if not Result then AddLog('Error Loading "' + Name + '"'); end; procedure TTexture.Free(var Data: Pointer); begin try if Data <> nil then FreeMem(Data); Data := nil; except AddLog('error: free data'); end; end; //== Удаление текстуры (если она никем не занята) procedure TTexture.Enable(ID: HTexture; Channel: Integer); begin if not (Channel in [0..TEX_MAX]) then Exit; glActiveTextureARB(GL_TEXTURE0_ARB + Channel); glEnable(GL_TEXTURE_2D); if Texture.FTexCur[Channel] <> ID then begin glBindTexture(GL_TEXTURE_2D, ID); Texture.FTexCur[Channel] := ID; end; end; procedure TTexture.Disable(Channel: Integer); begin if not (Channel in [0..TEX_MAX]) then Exit; glActiveTextureARB(GL_TEXTURE0_ARB + Channel); glBindTexture(GL_TEXTURE_2D, FDefTex.FID); FTexCur[Channel] := FDefTex.FID; glDisable(GL_TEXTURE_2D); end; procedure TTexture.Filter(FilterType: Integer; Group: Integer); var i: Integer; begin for i := 0 to FList.Count - 1 do if (Group and TTexImage(FList[i]).FGroup > 0) or (Group = -1) then TTexImage(FList[I]).Filter(FilterType); if (FTexCur[0] = FDefTex.FID) or (FTexCur[0] = 0) then Disable(0) else Enable(FTexCur[0], 0); end; function TTexture.RenderInit(TexSize: Integer): Boolean; begin // инициализация Frame Buffer Result := False; if GL_EXT_framebuffer_object then if TexSize = 0 then begin if FFrame <> 0 then glDeleteRenderbuffersEXT(1, @FFrame); if FDepth <> 0 then glDeleteRenderbuffersEXT(1, @FDepth); FFrame := 0; FDepth := 0; end else begin RenderInit(0); FCurmode := 0; glGenFramebuffersEXT(1, @FFrame); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, FFrame); // depth glGenRenderbuffersEXT(1, @FDepth); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, FDepth); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24_ARB, TexSize, TexSize); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, FDepth); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); Result := True; end; end; procedure TTexture.AddLog(Text: string); begin Log.Print(Self,PChar(Text)); end; function TTexture.Init: Boolean; const Size = 32; var pix: array[0..Size - 1, 0..Size - 1] of Byte; i: Integer; begin Result := False; if not GL_ARB_multitexture then begin AddLog('Fatal Error "GL_ARB_multitexture"'); Exit; end; //== Создаёт Default текстуру ZeroMemory(@pix, Size * Size); for i := 0 to Size - 1 do begin pix[i, 0] := 255; pix[i, Size - 1] := 255; pix[0, i] := 255; pix[Size - 1, i] := 255; pix[i, i] := 255; pix[i, Size - 1 - i] := 255; end; FDefTex := TTexImage.CreateEx; with FDefTex do begin FWidth := Size; FHeight := Size; FGroup := 0; FMipMap := False; FName := 'DefTex'; end; glGenTextures(1, @FDefTex.FID); glBindTexture(GL_TEXTURE_2D, FDefTex.FID); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, 1, Size, Size, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, @pix); Result := True; end; function TTexture.GetTex(const Name: string): ITexImage; var I: Integer; begin Result := nil; for I := 0 to FList.Count - 1 do if Name = TTexImage(FList[I]).FName then begin Result := TTexImage(FList[I]); Exit; end; end; function TTexture.NewTex(const Name: string; Data: Pointer; c, f, W, H, Group: Integer; Clamp, MipMap: Boolean): ITexImage; var Last: TTexImage; begin Last := TTexImage.CreateEx; Last.FName := Name; Last.FMipMap := MipMap; Last.FGroup := Group; FList.Add(Last); with Last do begin FWidth := W; FHeight := H; FMipMap := MipMap; Result := ITexImage(Last); glGenTextures(1, @FID); glBindTexture(GL_TEXTURE_2D, ID); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); if Clamp then begin glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); end else begin glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); end; if MipMap then glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) else glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if MipMap then gluBuild2DMipmaps(GL_TEXTURE_2D, c, W, H, f, GL_UNSIGNED_BYTE, Data) else glTexImage2D(GL_TEXTURE_2D, 0, C, W, H, 0, f, GL_UNSIGNED_BYTE, Data); end; end; constructor TTexture.CreateEx; begin inherited CreateEx; FList := TQuickList.CreateEx; end; procedure TTexture.Clear; var I: Integer; Tex: TTexImage; begin for I := FList.Count - 1 downto 0 do begin Tex := TTexImage(FList[I]); Tex.UnLoad; FList.Delete(I); end; end; procedure TTexture.UnLoad; begin // Удаление всех текстур FDefTex.UnLoad; Clear; FList.UnLoad; RenderInit(0); inherited; end; procedure TTexture.Delete(Tex: ITexImage); var I:Integer; begin I:=FList.IndexOf(Pointer(Tex)); if I<>-1 then begin FList.Delete(I); end; end; end.
unit SettingsManager; interface uses Types, IOUtils, IniFiles, SysUtils; type TSettingsManager = class private type TFiles = class private const Settings = 'settings.ini'; end; TFolders = class private const Voices = 'voices'; end; TSections = class private const Delays = 'Delays'; Voice = 'Voice'; end; TKeys = class private const ShortDelay = 'ShortDelay'; NormalDelay = 'NormalDelay'; LongDelay = 'LongDelay'; HyphenDelay = NormalDelay; ExclamationMarkDelay = LongDelay; ComaDelay = NormalDelay; ColonDelay = NormalDelay; SemicolonDelay = LongDelay; DotDelay = LongDelay; QuestionMarkDelay = LongDelay; SpaceDelay = ShortDelay; SelectedVoice = 'SelectedVoice'; end; TDefaultSettings = class private const ShortDelay = 50; NormalDelay = 100; LongDelay = 500; Voice = 'voices\zahar'; end; private FIniFile: TIniFile; FShortDelay: Integer; FNormalDelay: Integer; FLongDelay: Integer; FSelectedVoice: String; private procedure LoadSettingsFromFile(); function GetListOfVoices(): TArray<String>; function GetHyphenDelay(): Integer; function GetExclamationMarkDelay(): Integer; function GetComaDelay(): Integer; function GetColonDelay(): Integer; function GetSemicolonDelay(): Integer; function GetDotDelay(): Integer; function GetQuestionMarkDelay(): Integer; function GetSpaceDelay(): Integer; procedure SetHyphenDelay(ADelay: Integer); procedure SetExclamationMarkDelay(ADelay: Integer); procedure SetComaDelay(ADelay: Integer); procedure SetColonDelay(ADelay: Integer); procedure SetSemicolonDelay(ADelay: Integer); procedure SetDotDelay(ADelay: Integer); procedure SetQuestionMarkDelay(ADelay: Integer); procedure SetSpaceDelay(ADelay: Integer); function GetSelectedVoice(): String; procedure SetSelectedVoice(AVoice: String); function GetSettingsFilename(): String; public constructor Create(); destructor Destroy(); override; published property ListOfVoices: TArray<String> read GetListOfVoices; property HyphenDelay: Integer read GetHyphenDelay write SetHyphenDelay; property ExclamationMarkDelay: Integer read GetExclamationMarkDelay write SetExclamationMarkDelay; property ComaDelay: Integer read GetComaDelay write SetComaDelay; property ColonDelay: Integer read GetColonDelay write SetColonDelay; property SemicolonDelay: Integer read GetSemicolonDelay write SetSemicolonDelay; property DotDelay: Integer read GetDotDelay write SetDotDelay; property QuestionMarkDelay: Integer read GetQuestionMarkDelay write SetQuestionMarkDelay; property SpaceDelay: Integer read GetSpaceDelay write SetSpaceDelay; property SelectedVoice: String read GetSelectedVoice write SetSelectedVoice; property SettingsFilename: String read GetSettingsFilename; end; implementation constructor TSettingsManager.Create; begin FIniFile := TIniFile.Create(TFiles.Settings); LoadSettingsFromFile; end; destructor TSettingsManager.Destroy; begin inherited; FreeAndNil(FIniFile); end; function TSettingsManager.GetColonDelay: Integer; begin Result := FNormalDelay; end; function TSettingsManager.GetComaDelay: Integer; begin Result := FNormalDelay; end; function TSettingsManager.GetDotDelay: Integer; begin Result := FLongDelay; end; function TSettingsManager.GetExclamationMarkDelay: Integer; begin Result := FLongDelay; end; function TSettingsManager.GetHyphenDelay: Integer; begin Result := FNormalDelay; end; function TSettingsManager.GetListOfVoices: TArray<String>; begin Result := TArray<String>(TDirectory.GetDirectories(TFolders.Voices)); end; function TSettingsManager.GetQuestionMarkDelay: Integer; begin Result := FLongDelay; end; function TSettingsManager.GetSelectedVoice: String; begin Result := FSelectedVoice; end; function TSettingsManager.GetSemicolonDelay: Integer; begin Result := FLongDelay; end; function TSettingsManager.GetSettingsFilename: String; begin Result := TFiles.Settings; end; function TSettingsManager.GetSpaceDelay: Integer; begin Result := FShortDelay; end; procedure TSettingsManager.LoadSettingsFromFile; begin FShortDelay := FIniFile.ReadInteger(TSections.Delays, TKeys.ShortDelay, TDefaultSettings.ShortDelay); FNormalDelay := FIniFile.ReadInteger(TSections.Delays, TKeys.NormalDelay, TDefaultSettings.NormalDelay); FLongDelay := FIniFile.ReadInteger(TSections.Delays, TKeys.LongDelay, TDefaultSettings.LongDelay); FSelectedVoice := FIniFile.ReadString(TSections.Delays, TKeys.SelectedVoice, TDefaultSettings.Voice); end; procedure TSettingsManager.SetColonDelay(ADelay: Integer); begin FNormalDelay := ADelay; FIniFile.WriteInteger(TSections.Delays, TKeys.ColonDelay, ADelay); end; procedure TSettingsManager.SetComaDelay(ADelay: Integer); begin FNormalDelay := ADelay; FIniFile.WriteInteger(TSections.Delays, TKeys.ComaDelay, ADelay); end; procedure TSettingsManager.SetDotDelay(ADelay: Integer); begin FLongDelay := ADelay; FIniFile.WriteInteger(TSections.Delays, TKeys.DotDelay, ADelay); end; procedure TSettingsManager.SetExclamationMarkDelay(ADelay: Integer); begin FLongDelay := ADelay; FIniFile.WriteInteger(TSections.Delays, TKeys.ExclamationMarkDelay, ADelay); end; procedure TSettingsManager.SetHyphenDelay(ADelay: Integer); begin FNormalDelay := ADelay; FIniFile.WriteInteger(TSections.Delays, TKeys.HyphenDelay, ADelay); end; procedure TSettingsManager.SetQuestionMarkDelay(ADelay: Integer); begin FLongDelay := ADelay; FIniFile.WriteInteger(TSections.Delays, TKeys.QuestionMarkDelay, ADelay); end; procedure TSettingsManager.SetSelectedVoice(AVoice: String); begin FSelectedVoice := AVoice; FIniFile.WriteString(TSections.Voice, TKeys.SelectedVoice, AVoice); end; procedure TSettingsManager.SetSemicolonDelay(ADelay: Integer); begin FLongDelay := ADelay; FIniFile.WriteInteger(TSections.Delays, TKeys.SemicolonDelay, ADelay); end; procedure TSettingsManager.SetSpaceDelay(ADelay: Integer); begin FShortDelay := ADelay; FIniFile.WriteInteger(TSections.Delays, TKeys.SpaceDelay, ADelay); end; end.
unit TabbedNotebookImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB, Tabnotbk, ComCtrls; type TTabbedNotebookX = class(TActiveXControl, ITabbedNotebookX) private { Private declarations } FDelphiControl: TTabbedNotebook; FEvents: ITabbedNotebookXEvents; procedure ChangeEvent(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); procedure ClickEvent(Sender: TObject); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_ActivePage: WideString; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_Cursor: Smallint; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_Enabled: WordBool; safecall; function Get_Font: IFontDisp; safecall; function Get_PageIndex: Integer; safecall; function Get_Pages: IStrings; safecall; function Get_TabFont: IFontDisp; safecall; function Get_TabsPerRow: Integer; safecall; function Get_TopFont: IFontDisp; safecall; function Get_Visible: WordBool; safecall; function GetControlsAlignment: TxAlignment; safecall; function GetIndexForPage(const PageName: WideString): Integer; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure _Set_Font(const Value: IFontDisp); safecall; procedure AboutBox; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure Set_ActivePage(const Value: WideString); safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_Font(const Value: IFontDisp); safecall; procedure Set_PageIndex(Value: Integer); safecall; procedure Set_Pages(const Value: IStrings); safecall; procedure Set_TabFont(const Value: IFontDisp); safecall; procedure Set_TabsPerRow(Value: Integer); safecall; procedure Set_Visible(Value: WordBool); safecall; end; implementation uses ComObj, About33; { TTabbedNotebookX } procedure TTabbedNotebookX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_TabbedNotebookXPage); } end; procedure TTabbedNotebookX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as ITabbedNotebookXEvents; end; procedure TTabbedNotebookX.InitializeControl; begin FDelphiControl := Control as TTabbedNotebook; FDelphiControl.OnChange := ChangeEvent; FDelphiControl.OnClick := ClickEvent; end; function TTabbedNotebookX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TTabbedNotebookX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TTabbedNotebookX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TTabbedNotebookX.Get_ActivePage: WideString; begin Result := WideString(FDelphiControl.ActivePage); end; function TTabbedNotebookX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TTabbedNotebookX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TTabbedNotebookX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TTabbedNotebookX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TTabbedNotebookX.Get_Font: IFontDisp; begin GetOleFont(FDelphiControl.Font, Result); end; function TTabbedNotebookX.Get_PageIndex: Integer; begin Result := FDelphiControl.PageIndex; end; function TTabbedNotebookX.Get_Pages: IStrings; begin GetOleStrings(FDelphiControl.Pages, Result); end; function TTabbedNotebookX.Get_TabFont: IFontDisp; begin GetOleFont(FDelphiControl.TabFont, Result); end; function TTabbedNotebookX.Get_TabsPerRow: Integer; begin Result := FDelphiControl.TabsPerRow; end; function TTabbedNotebookX.Get_TopFont: IFontDisp; begin GetOleFont(FDelphiControl.TopFont, Result); end; function TTabbedNotebookX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TTabbedNotebookX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TTabbedNotebookX.GetIndexForPage( const PageName: WideString): Integer; begin Result := FDelphiControl.GetIndexForPage(PageName); end; function TTabbedNotebookX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TTabbedNotebookX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TTabbedNotebookX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TTabbedNotebookX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TTabbedNotebookX._Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TTabbedNotebookX.AboutBox; begin ShowTabbedNotebookXAbout; end; procedure TTabbedNotebookX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TTabbedNotebookX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TTabbedNotebookX.Set_ActivePage(const Value: WideString); begin FDelphiControl.ActivePage := String(Value); end; procedure TTabbedNotebookX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TTabbedNotebookX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TTabbedNotebookX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TTabbedNotebookX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TTabbedNotebookX.Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TTabbedNotebookX.Set_PageIndex(Value: Integer); begin FDelphiControl.PageIndex := Value; end; procedure TTabbedNotebookX.Set_Pages(const Value: IStrings); begin SetOleStrings(FDelphiControl.Pages, Value); end; procedure TTabbedNotebookX.Set_TabFont(const Value: IFontDisp); begin SetOleFont(FDelphiControl.TabFont, Value); end; procedure TTabbedNotebookX.Set_TabsPerRow(Value: Integer); begin FDelphiControl.TabsPerRow := Value; end; procedure TTabbedNotebookX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TTabbedNotebookX.ChangeEvent(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); var TempAllowChange: WordBool; begin TempAllowChange := WordBool(AllowChange); if FEvents <> nil then FEvents.OnChange(NewTab, TempAllowChange); AllowChange := Boolean(TempAllowChange); end; procedure TTabbedNotebookX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; initialization TActiveXControlFactory.Create( ComServer, TTabbedNotebookX, TTabbedNotebook, Class_TabbedNotebookX, 33, '{695CDBD3-02E5-11D2-B20D-00C04FA368D4}', 0, tmApartment); end.
unit UnContasReceberListaRegistrosView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, JvExControls, JvButton, JvTransparentButton, ExtCtrls, DB, { helsonsant } Util, DataUtil, UnModelo, UnAplicacao, UnContasReceberListaRegistrosModelo, Grids, DBGrids, StdCtrls, JvExDBGrids, JvDBGrid, JvDBUltimGrid; type TContasReceberListaRegistrosView = class(TForm, ITela) pnlTitulo: TPanel; btnIncluir: TJvTransparentButton; btnMenu: TJvTransparentButton; pnlFiltro: TPanel; EdtContaReceber: TEdit; gContasReceber: TJvDBUltimGrid; procedure btnIncluirClick(Sender: TObject); procedure gContasReceberDblClick(Sender: TObject); procedure EdtContaReceberChange(Sender: TObject); private FControlador: IResposta; FContasReceberListaRegistrosModelo: TContasReceberListaRegistrosModelo; public function Controlador(const Controlador: IResposta): ITela; function Descarregar: ITela; function Modelo(const Modelo: TModelo): ITela; function Preparar: ITela; function ExibirTela: Integer; end; implementation {$R *.dfm} { TContasReceberListaRegistrosView } function TContasReceberListaRegistrosView.Controlador( const Controlador: IResposta): ITela; begin Self.FControlador := Controlador; Result := Self; end; function TContasReceberListaRegistrosView.Descarregar: ITela; begin Self.FControlador := nil; Self.FContasReceberListaRegistrosModelo := nil; Result := Self; end; function TContasReceberListaRegistrosView.ExibirTela: Integer; begin Result := Self.ShowModal; end; function TContasReceberListaRegistrosView.Modelo( const Modelo: TModelo): ITela; begin Self.FContasReceberListaRegistrosModelo := (Modelo as TContasReceberListaRegistrosModelo); Result := Self; end; function TContasReceberListaRegistrosView.Preparar: ITela; begin Self.gContasReceber.DataSource := Self.FContasReceberListaRegistrosModelo.DataSource; Result := Self; end; procedure TContasReceberListaRegistrosView.btnIncluirClick( Sender: TObject); var _chamada: TChamada; _parametros: TMap; begin _parametros := Self.FContasReceberListaRegistrosModelo.Parametros; _parametros .Gravar('acao', Ord(adrIncluir)); _chamada := TChamada.Create .Chamador(Self) .Parametros(_parametros); Self.FControlador.Responder(_chamada); end; procedure TContasReceberListaRegistrosView.gContasReceberDblClick( Sender: TObject); var _chamada: TChamada; _dataSet: TDataSet; begin _dataSet := Self.FContasReceberListaRegistrosModelo.DataSet; _chamada := TChamada.Create .Chamador(Self) .Parametros(TMap.Create .Gravar('acao', Ord(adrCarregar)) .Gravar('oid', _dataSet.FieldByName('titr_oid').AsString) ); Self.FControlador.Responder(_chamada) end; procedure TContasReceberListaRegistrosView.EdtContaReceberChange( Sender: TObject); begin if Self.EdtContaReceber.Text = '' then Self.FContasReceberListaRegistrosModelo.Carregar else Self.FContasReceberListaRegistrosModelo.CarregarPor( Criterio.Campo('CL_NOME').como(Self.EdtContaReceber.Text).obter()); end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} {$HPPEMIT '#pragma link "Data.DbxMySql"'} {Do not Localize} unit Data.DbxMySql; interface uses Data.DBXDynalink, Data.DBXDynalinkNative, Data.DBXCommon, Data.DbxMySqlReadOnlyMetaData, Data.DbxMysqlMetaData; type TDBXMySQLProperties = class(TDBXProperties) private const StrServerCharSet = 'ServerCharSet'; function GetHostName: string; function GetPassword: string; function GetUserName: string; function GetBlobSize: Integer; function GetDatabase: string; function GetCompressed: Boolean; function GetEncrypted: Boolean; function GetServerCharSet: string; procedure SetServerCharSet(const Value: string); procedure SetCompressed(const Value: Boolean); procedure SetEncrypted(const Value: Boolean); procedure SetDatabase(const Value: string); procedure SetHostName(const Value: string); procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); procedure SetBlobSize(const Value: Integer); public constructor Create(DBXContext: TDBXContext); override; published property HostName: string read GetHostName write SetHostName; property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword write SetPassword; property Database: string read GetDatabase write SetDatabase; property BlobSize: Integer read GetBlobSize write SetBlobSize; property Compressed: Boolean read GetCompressed write SetCompressed; property Encrypted: Boolean read GetEncrypted write SetEncrypted; property ServerCharSet: string read GetServerCharSet write SetServerCharSet; end; TDBXMySQLDriver = class(TDBXDynalinkDriverNative) public constructor Create(DBXDriverDef: TDBXDriverDef); override; end; implementation uses Data.DBXPlatform, System.SysUtils; const sDriverName = 'MySQL'; { TDBXMySQLDriver } constructor TDBXMySQLDriver.Create(DBXDriverDef: TDBXDriverDef); var Props: TDBXMySQLProperties; I, Index: Integer; begin Props := TDBXMySQLProperties.Create(DBXDriverDef.FDBXContext); if DBXDriverDef.FDriverProperties <> nil then begin for I := 0 to DBXDriverDef.FDriverProperties.Count - 1 do begin Index := Props.Properties.IndexOfName(DBXDriverDef.FDriverProperties.Properties.Names[I]); if Index > -1 then Props.Properties.Strings[Index] := DBXDriverDef.FDriverProperties.Properties.Strings[I]; end; Props.AddUniqueProperties(DBXDriverDef.FDriverProperties.Properties); DBXDriverDef.FDriverProperties.AddUniqueProperties(Props.Properties); end; inherited Create(DBXDriverDef, TDBXDynalinkDriverLoader, Props); rpr; end; constructor TDBXMySQLProperties.Create(DBXContext: TDBXContext); begin inherited Create(DBXContext); Values[TDBXPropertyNames.DriverUnit] := 'Data.DBXMySql'; Values[TDBXPropertyNames.DriverPackageLoader] := 'TDBXDynalinkDriverLoader,DBXMySQLDriver160.bpl'; Values[TDBXPropertyNames.DriverAssemblyLoader] := 'Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken; Values[TDBXPropertyNames.MetaDataPackageLoader] := 'TDBXMySqlMetaDataCommandFactory,DbxMySQLDriver160.bpl'; Values[TDBXPropertyNames.MetaDataAssemblyLoader] := 'Borland.Data.TDBXMySqlMetaDataCommandFactory,Borland.Data.DbxMySQLDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken; Values[TDBXPropertyNames.GetDriverFunc] := 'getSQLDriverMYSQL'; Values[TDBXPropertyNames.LibraryName] := 'dbxmys.dll'; Values[TDBXPropertyNames.LibraryNameOsx] := 'libsqlmys.dylib'; Values[TDBXPropertyNames.VendorLib] := 'libmysql.dll'; Values[TDBXPropertyNames.VendorLibWin64] := 'libmysql.dll'; Values[TDBXPropertyNames.VendorLibOsx] := 'libmysqlclient.dylib'; Values[TDBXPropertyNames.HostName] := 'ServerName'; Values[TDBXPropertyNames.Database] := 'DBNAME'; Values[TDBXPropertyNames.UserName] := 'user'; Values[TDBXPropertyNames.Password] := 'password'; Values[TDBXPropertyNames.MaxBlobSize] := '-1'; Values[TDBXPropertyNames.ErrorResourceFile] := ''; // Do we really us all of these? Should they be moved to TDBXPropertyNames? // Values['ServerCharSet'] := ''; Values[TDBXDynalinkPropertyNames.LocaleCode] := '0000'; Values[TDBXDynalinkPropertyNames.Compressed] := 'False'; Values[TDBXDynalinkPropertyNames.Encrypted] := 'False'; end; function TDBXMySqlProperties.GetBlobSize: Integer; begin Result := StrToIntDef(Values[TDBXPropertyNames.MaxBlobSize], -1); end; function TDBXMySqlProperties.GetCompressed: Boolean; begin Result := StrToBoolDef(Values[TDBXDynalinkPropertyNames.Compressed], False); end; function TDBXMySqlProperties.GetDatabase: string; begin Result := Values[TDBXPropertyNames.Database]; end; function TDBXMySqlProperties.GetEncrypted: Boolean; begin Result := StrToBoolDef(Values[TDBXDynalinkPropertyNames.Encrypted], False); end; function TDBXMySqlProperties.GetHostName: string; begin Result := Values[TDBXPropertyNames.HostName]; end; function TDBXMySqlProperties.GetPassword: string; begin Result := Values[TDBXPropertyNames.Password]; end; function TDBXMySQLProperties.GetServerCharSet: string; begin Result := Values[StrServerCharSet]; end; function TDBXMySqlProperties.GetUserName: string; begin Result := Values[TDBXPropertyNames.UserName]; end; procedure TDBXMySqlProperties.SetBlobSize(const Value: Integer); begin Values[TDBXPropertyNames.MaxBlobSize] := IntToStr(Value); end; procedure TDBXMySqlProperties.SetCompressed(const Value: Boolean); begin Values[TDBXDynalinkPropertyNames.Compressed] := BoolToStr(Value, True); end; procedure TDBXMySqlProperties.SetDatabase(const Value: string); begin Values[TDBXPropertyNames.Database] := Value; end; procedure TDBXMySqlProperties.SetEncrypted(const Value: Boolean); begin Values[TDBXDynalinkPropertyNames.Encrypted] := BoolToStr(Value, True); end; procedure TDBXMySqlProperties.SetHostName(const Value: string); begin Values[TDBXPropertyNames.HostName] := Value; end; procedure TDBXMySqlProperties.SetPassword(const Value: string); begin Values[TDBXPropertyNames.Password] := Value; end; procedure TDBXMySQLProperties.SetServerCharSet(const Value: string); begin Values[StrServerCharSet] := Value; end; procedure TDBXMySqlProperties.SetUserName(const Value: string); begin Values[TDBXPropertyNames.UserName] := Value; end; initialization TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXMySQLDriver); end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2013-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Permissions; {$SCOPEDENUMS ON} interface uses System.Classes, System.Generics.Collections, System.SysUtils, System.Types; type EPermissionException = class(Exception); TPermissionStatus = (Granted, Denied, PermanentlyDenied); /// <summary>Callback type for when the system has processed our permission requests</summary> /// <remarks>For each requested permission in APermissions, there is /// a Boolean in AGrantResults indicating if the permission was granted. /// <para>This type is compatible with an event handler method.</para></remarks> TRequestPermissionsResultEvent = procedure(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>) of object; /// <summary>Callback type for when the system has processed our permission requests</summary> /// <remarks>For each requested permission in APermissions, there is /// a Boolean in AGrantResults indicating if the permission was granted. /// <para>This type is compatible with an anonymous procedure.</para></remarks> TRequestPermissionsResultProc = reference to procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); /// <summary>Callback type for providing an explanation to the user for the need for a permission</summary> /// <remarks>For previously denied permissions that we pre-loaded a rationale string for, /// this callback provides the opportunity to display it, but it *must* be done asynchronously. /// When the rationale display is over, be sure to call the APostRationalProc routine, /// which will then request the permissions that need requesting. /// <para>This type is compatible with an event handler method.</para></remarks> TDisplayRationaleEvent = procedure(Sender: TObject; const APermissions: TArray<string>; const APostRationaleProc: TProc) of object; /// <summary>Callback type for providing an explanation to the user for the need for a permission</summary> /// <remarks>For previously denied permissions that we pre-loaded a rationale string for, /// this callback provides the opportunity to display it, but it *must* be done asynchronously. /// When the rationale display is over, be sure to call the APostRationalProc routine, /// which will then request the permissions that need requesting. /// <para>This type is compatible with an anonymous procedure.</para></remarks> TDisplayRationaleProc = reference to procedure(const APermissions: TArray<string>; const APostRationaleProc: TProc); /// <summary>Base permissions service abstract class</summary> TPermissionsService = class abstract private class function GetDefaultService: TPermissionsService; static; protected class var FDefaultService: TPermissionsService; constructor Create; virtual; public class destructor UnInitialize; /// <summary>Find out if a permission is currently granted to the app</summary> /// <remarks>If there is no platform permissions service implemented to actually do any checking, /// then we default to responding that all permissions are granted</remarks> function IsPermissionGranted(const APermission: string): Boolean; virtual; /// <summary>Find out if a permissions are all currently granted to the app</summary> function IsEveryPermissionGranted(const APermissions: TArray<string>): Boolean; virtual; /// <summary>Request one or more permissions</summary> /// <remarks>Any permissions that are not currently granted will be requested. /// Beforehand, a rationale may be displayed to the user if: /// <para> i) a rationale string has been set for the permission in question</para> /// <para> ii) the OS deems it appropriate (we're requesting a permission again that was previously denied)</para> /// <para>iii) a rationale display routine is passed in</para> /// The rationale handler must display the passed in rationale string asynchronously and not block the thread. /// <para>This overload takes an event handler method.</para></remarks> procedure RequestPermissions(const APermissions: TArray<string>; const AOnRequestPermissionsResult: TRequestPermissionsResultEvent; AOnDisplayRationale: TDisplayRationaleEvent = nil); overload; virtual; /// <summary>Request one or more permissions</summary> /// <remarks>Any permissions that are not currently granted will be requested. /// Beforehand, a rationale may be displayed to the user if: /// <para> i) a rationale string has been set for the permission in question</para> /// <para> ii) the OS deems it appropriate (we're requesting a permission again that was previously denied)</para> /// <para>iii) a rationale display routine is passed in</para> /// The rationale handler must display the passed in rationale string asynchronously and not block the thread. /// <para>This overload takes an event handler method.</para></remarks> procedure RequestPermissions(const APermissions: TArray<string>; const AOnRequestPermissionsResult: TRequestPermissionsResultProc; AOnDisplayRationale: TDisplayRationaleProc = nil); overload; virtual; /// <summary>Factory property to retrieve an appropriate permissions implementation, if available on the current platform</summary> class property DefaultService: TPermissionsService read GetDefaultService; end; TPermissionsServiceClass = class of TPermissionsService; var PermissionsServiceClass: TPermissionsServiceClass = TPermissionsService; /// <summary>Helper to call TPermissionsService.DefaultService</summary> function PermissionsService: TPermissionsService; inline; implementation {$IFDEF ANDROID} uses System.Android.Permissions; {$ENDIF} { TPermissionsService } constructor TPermissionsService.Create; begin inherited Create; end; class function TPermissionsService.GetDefaultService: TPermissionsService; begin if (FDefaultService = nil) and (PermissionsServiceClass <> nil) then FDefaultService := PermissionsServiceClass.Create; Result := FDefaultService; end; function TPermissionsService.IsPermissionGranted(const APermission: string): Boolean; begin Result := True end; function TPermissionsService.IsEveryPermissionGranted(const APermissions: TArray<string>): Boolean; begin Result := True end; procedure TPermissionsService.RequestPermissions(const APermissions: TArray<string>; const AOnRequestPermissionsResult: TRequestPermissionsResultEvent; AOnDisplayRationale: TDisplayRationaleEvent); var GrantResults: TArray<TPermissionStatus>; I: Integer; begin SetLength(GrantResults, Length(APermissions)); for I := Low(GrantResults) to High(GrantResults) do GrantResults[I] := TPermissionStatus.Granted; AOnRequestPermissionsResult(Self, APermissions, GrantResults) end; procedure TPermissionsService.RequestPermissions(const APermissions: TArray<string>; const AOnRequestPermissionsResult: TRequestPermissionsResultProc; AOnDisplayRationale: TDisplayRationaleProc); var GrantResults: TArray<TPermissionStatus>; I: Integer; begin SetLength(GrantResults, Length(APermissions)); for I := Low(GrantResults) to High(GrantResults) do GrantResults[I] := TPermissionStatus.Granted; AOnRequestPermissionsResult(APermissions, GrantResults) end; class destructor TPermissionsService.UnInitialize; begin FreeAndNil(FDefaultService); end; function PermissionsService: TPermissionsService; begin Exit(TPermissionsService.DefaultService) end; end.
unit DX.Messages.Dialog; interface uses System.Classes, System.SysUtils, System.Messaging, DX.Messages.Dialog.Types; type {$SCOPEDENUMS ON} TMessageDialogRequest = class(TMessage) strict private FMessage: string; FResult: TDialogOption; FOptions: TDialogOptions; FOnResultCallback: TProc<TDialogOption>; FDefault: TDialogOption; procedure SetResult(const Value: TDialogOption); procedure SetDefault(const Value: TDialogOption); public constructor Create(const AMessage: string; const AOptions: TDialogOptions); overload; constructor Create(const AMessage: string; const AOptions: TDialogOptions; const ADefault: TDialogOption); overload; class function CreateAndSend(const AMessage: string; const AOptions: TDialogOptions = []; const ADefault: TDialogOption = TDialogOption.Close; AResultCallback: TProc < TDialogOption >= nil) : TMessageDialogRequest; property Message: string read FMessage write FMessage; property Default: TDialogOption read FDefault write SetDefault; property Response: TDialogOption read FResult write SetResult; property Options: TDialogOptions read FOptions; function OnResult(ACallback: TProc<TDialogOption>): TMessageDialogRequest; end; implementation { TMessageDialogRequest } constructor TMessageDialogRequest.Create(const AMessage: string; const AOptions: TDialogOptions; const ADefault: TDialogOption); begin inherited Create; FMessage := AMessage; if AOptions = [] then begin //No option selected, it's gona be a simple OK-Dialog FOptions := [TDialogOption.OK]; FDefault := TDialogOption.OK; end else begin FOptions := AOptions; FDefault := ADefault; end; // Result is initialized with Default FResult := FDefault; end; class function TMessageDialogRequest.CreateAndSend(const AMessage: string; const AOptions: TDialogOptions = []; const ADefault: TDialogOption = TDialogOption.Close; AResultCallback: TProc < TDialogOption >= nil) : TMessageDialogRequest; begin result := Create(AMessage, AOptions, ADefault); result.OnResult(AResultCallback); TMessageManager.DefaultManager.SendMessage(nil, result, false); end; function TMessageDialogRequest.OnResult(ACallback: TProc<TDialogOption>): TMessageDialogRequest; begin FOnResultCallback := ACallback; result := self; end; constructor TMessageDialogRequest.Create(const AMessage: string; const AOptions: TDialogOptions); begin Create(AMessage, AOptions, TDialogOption.Close); end; procedure TMessageDialogRequest.SetDefault(const Value: TDialogOption); begin FDefault := Value; FResult := FDefault; end; procedure TMessageDialogRequest.SetResult(const Value: TDialogOption); begin FResult := Value; if Assigned(FOnResultCallback) then begin FOnResultCallback(FResult); end; end; end.
{ Double Commander ------------------------------------------------------------------------- Form allowing user to sort a list of element via drag and drop Copyright (C) 2020 Alexander Koblov (alexx2000@mail.ru) 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit fSortAnything; {$mode objfpc}{$H+} interface uses //Lazarus, Free-Pascal, etc. Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, Buttons, ButtonPanel, //DC uOSForms, uClassesEx; type { TfrmSortAnything } TfrmSortAnything = class(TModalForm) ButtonPanel: TButtonPanel; btnSort: TBitBtn; lblSortAnything: TLabel; lbSortAnything: TListBox; procedure FormCreate(Sender: TObject); procedure btnSortClick(Sender: TObject); procedure lbSortAnythingDragDrop(Sender, {%H-}Source: TObject; X, Y: integer); procedure lbSortAnythingDragOver(Sender, {%H-}Source: TObject; {%H-}X, {%H-}Y: integer; {%H-}State: TDragState; var Accept: boolean); private IniPropStorage: TIniPropStorageEx; end; var frmSortAnything: TfrmSortAnything; function HaveUserSortThisList(TheOwner: TCustomForm; const ACaption: string; const slListToSort: TStringList): integer; implementation {$R *.lfm} uses //Lazarus, Free-Pascal, etc. //DC uGlobs; { TfrmSortAnything } { TfrmSortAnything.FormCreate } procedure TfrmSortAnything.FormCreate(Sender: TObject); begin IniPropStorage := InitPropStorage(Self); end; { TfrmSortAnything.btnSortClick } // Simply "lbSortAnything.Sorted" was working fine in Windows. // When tested under Ubuntu 64 with "LAZ 2.0.6/FPC 3.0.4 x86_64-linux-gtk2", it was not working correctly. // For example, if our list was like "D,A,C,B", it was sorted correctly. // But if list was like sorted in reverse, like "D,C,B,A", it did nothing. // If we set "D,C,A,B", or "C,D,B,A" or "D,B,C,A", it was working. // So it seems when it was pre-sorted reversed, it does not sort. // For the moment let's use a TStringList on-the-side for the job. procedure TfrmSortAnything.btnSortClick(Sender: TObject); var slJustForSort: TStringList; iIndex: integer; begin slJustForSort := TStringList.Create; try slJustForSort.Sorted := True; slJustForSort.Duplicates := dupAccept; slJustForSort.CaseSensitive := False; for iIndex := 0 to pred(lbSortAnything.items.Count) do slJustForSort.Add(lbSortAnything.Items.Strings[iIndex]); lbSortAnything.Items.BeginUpdate; try lbSortAnything.Items.Clear; for iIndex := 0 to pred(slJustForSort.Count) do lbSortAnything.Items.Add(slJustForSort.Strings[iIndex]); lbSortAnything.ItemIndex := 0; finally lbSortAnything.Items.EndUpdate; end; finally slJustForSort.Free; end; end; { TfrmSortAnything.lbSortAnythingDragOver } procedure TfrmSortAnything.lbSortAnythingDragOver(Sender, Source: TObject; X, Y: integer; State: TDragState; var Accept: boolean); begin Accept := True; end; { TfrmSortAnything.lbSortAnythingDragDrop } // Key prodecure here that will let user do the drag and drop in the list to move item in the order he wants. // Basically we first remove from the list the elements to be moved... // ... and then we place them back to the correct destination. // The key thing is to determine where will be this destination location based on current selection and target position. procedure TfrmSortAnything.lbSortAnythingDragDrop(Sender, Source: TObject; X, Y: integer); var iFirstSelection, iBeforeTarget, iSeeker, iDestIndex: integer; bMoveSelectionUp: boolean; slBuffer: TStringList; begin iDestIndex := lbSortAnything.GetIndexAtXY(X, Y); if (iDestIndex >= 0) and (iDestIndex < lbSortAnything.Items.Count) then //Don't laught, apparently it's possible to get a iDestIndex=-1 if we move totally on top. begin //1o) Let's determine in which direction the move is taken place with hint about down move. iFirstSelection := -1; iBeforeTarget := 0; iSeeker := 0; while (iSeeker < lbSortAnything.Count) do begin if lbSortAnything.Selected[iSeeker] then begin if iFirstSelection = -1 then iFirstSelection := iSeeker; if iSeeker < iDestIndex then Inc(iBeforeTarget); end; Inc(iSeeker); end; bMoveSelectionUp := (iDestIndex <= iFirstSelection); if (iFirstSelection >= 0) then begin lbSortAnything.Items.BeginUpdate; try slBuffer := TStringList.Create; try //2o) Let's remove from the list the element that will be relocated. for iSeeker := pred(lbSortAnything.Items.Count) downto 0 do begin if lbSortAnything.Selected[iSeeker] then begin slBuffer.Insert(0, lbSortAnything.Items[iSeeker]); lbSortAnything.Items.Delete(iSeeker); end; end; //3o) If we're moving down, we need to readjust destination based on elements seen prior the destination. if not bMoveSelectionUp then iDestIndex := iDestIndex - pred(iBeforeTarget); //4o) Putting back elements in the list after move. It could be "inserted" or "added at the end" based on the result of move. if iDestIndex < lbSortAnything.Items.Count then begin for iSeeker := pred(slBuffer.Count) downto 0 do begin lbSortAnything.Items.Insert(iDestIndex, slBuffer.Strings[iSeeker]); lbSortAnything.Selected[iDestIndex] := True; end; end else begin for iSeeker := 0 to pred(slBuffer.Count) do begin lbSortAnything.Items.Add(slBuffer.Strings[iSeeker]); lbSortAnything.Selected[pred(lbSortAnything.Items.Count)] := True; end; end; finally lbSortAnything.Items.EndUpdate; end; finally slBuffer.Free; end; end; end; end; { HaveUserSortThisList } function HaveUserSortThisList(TheOwner: TCustomForm; const ACaption: string; const slListToSort: TStringList): integer; begin Result := mrCancel; with TfrmSortAnything.Create(TheOwner) do begin try Caption := ACaption; lbSortAnything.Items.Assign(slListToSort); Result := ShowModal; if Result = mrOk then slListToSort.Assign(lbSortAnything.Items); finally Free; end; end; end; end.
(** This module defines a class which represents a form for entering a path and wildcards for additional files to be included in the zipping process. @Version 1.0 @Date 05 Jan 2018 @Author David Hoyle **) Unit ITHelper.AdditionalZipFilesForm; Interface Uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, ToolsAPI; Type (** This is a class to represents the form interface. **) TfrmITHAdditionalZipFiles = Class(TForm) lblWildcard: TLabel; edtWildcard: TEdit; btnBrowse: TButton; btnOK: TBitBtn; btnCancel: TBitBtn; Procedure btnBrowseClick(Sender: TObject); Procedure btnOKClick(Sender: TObject); Private { Private declarations } FProject: IOTAProject; Public { Public declarations } Class Function Execute(Const Project: IOTAProject; Var strWildcard: String): Boolean; End; Implementation {$R *.dfm} Uses FileCtrl, ITHelper.TestingHelperUtils; (** This is an on click event handler for the Browse button. @precon None. @postcon Allows the users to browse for a directory. @param Sender as a TObject **) Procedure TfrmITHAdditionalZipFiles.btnBrowseClick(Sender: TObject); ResourceString strZipFilePath = 'Zip File Path'; Var strDir: String; Begin strDir := ExtractFilePath(edtWildcard.Text); If SelectDirectory(strZipFilePath, '', strDir{$IFDEF D2005}, [sdNewFolder, sdShowShares, sdNewUI, sdValidateDir] {$ENDIF} ) Then edtWildcard.Text := strDir + '\' + ExtractFileName(edtWildcard.Text); End; (** This is an on click event handler for the OK button. @precon None. @postcon Ebsures that the directory exists. @param Sender as a TObject **) Procedure TfrmITHAdditionalZipFiles.btnOKClick(Sender: TObject); ResourceString strDirectoryDoesNotExists = 'The directory "%s" does not exists.'; Var strDir: String; Begin strDir := ExtractFilePath(edtWildcard.Text); If Not SysUtils.DirectoryExists(ExpandMacro(strDir, FProject.FileName)) Then Begin ModalResult := mrNone; MessageDlg(Format(strDirectoryDoesNotExists, [strDir]), mtError, [mbOK], 0); End; End; (** This is the classes main interface method for invoking the dialogue. @precon None. @postcon Displays the dialogue. On confirmation the wildcard is passed back via the var parameter. @param Project as an IOTAProject as a constant @param strWildcard as a String as a reference @return a Boolean **) Class Function TfrmITHAdditionalZipFiles.Execute(Const Project: IOTAProject; Var strWildcard: String): Boolean; Var frm: TfrmITHAdditionalZipFiles; Begin Result := False; frm := TfrmITHAdditionalZipFiles.Create(Nil); Try frm.FProject := Project; frm.edtWildcard.Text := strWildcard; If frm.ShowModal = mrOK Then Begin strWildcard := frm.edtWildcard.Text; Result := True; End; Finally frm.Free; End; End; End.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 16384,0,0} { by Behdad Esfahbod Algorithmic Problems Book April '2000 Problem 73 O(N2) 2Sat Alg. Dfs Method } program SatisfiabilityGame;{QBF2} const MaxN = 100; var N, M : Integer; G : array [-MaxN .. MaxN, -MaxN .. MaxN] of Boolean; X : array [-MaxN .. MaxN] of Boolean; Mark, MarkBak : array [1 .. MaxN] of Boolean; I, J, K, T : Integer; procedure ReadInput; begin Assign(Input, 'input.txt'); Reset(Input); Readln(N, M); for I := 1 to M do begin Read(J, K); G[J, K] := True; G[K, J] := True; end; Close(Input); Assign(Input, ''); Reset(Input); end; function Force (V : Integer) : Boolean; var I : Integer; begin if Mark[Abs(V)] then begin Force := X[V]; Exit; end; if not Odd(V) and (Abs(V) <> K) then begin Force := False; Exit; end; Mark[Abs(V)] := True; X[V] := True; for I := -N to N do if G[-V, I] then begin if not Force(I) then begin Force := False; Exit; end; end; Force := True; end; function RestoreMark : Boolean; begin Mark := MarkBak; RestoreMark := True; end; function QBFSatisfy : Boolean; begin for K := 1 to N do begin MarkBak := Mark; if (Odd(K) and (not Force(K) and (RestoreMark and not Force(-K)))) or (not Odd(K) and (not Force(K) or (RestoreMark and not Force(-K)))) then begin QBFSatisfy := False; Exit; end; end; QBFSatisfy := True; end; procedure Play; begin FillChar(Mark, SizeOf(Mark), 0); I := 1; while I <= N do begin if I mod 2 = J then begin K := J; MarkBak := Mark; if Force(I) xor Odd(J) then begin Mark := MarkBak; Force(-I); T := 0; end else T := 1; Writeln('X[', I, '] = ', T); end else begin Write('X[', I, '] = ? '); Readln(T); if (T <> 0) and (T <> 1) then begin Writeln('Error'); Halt; end; K := 0; if T = 1 then Force(I) else Force(-I); end; Inc(I); end; end; procedure Solve; begin if QBFSatisfy then begin Writeln('The first player has a winning strategy.'); J := 1; end else begin Writeln('The second player has a winning strategy.'); J := 0; end; Play; Writeln('I won!'); end; begin ReadInput; Solve; end.
unit obj; {$IFDEF FPC}{$mode objfpc}{$H+}{$ENDIF} interface //load and save meshes in WaveFront OBJ format uses Classes, sysutils, meshify_simplify_quadric; procedure LoadObj(const FileName: string; var faces: TFaces; var vertices: TVertices); procedure SaveObj(const FileName: string; var faces: TFaces; var vertices: TVertices); implementation function FSize (lFName: String): longint; var F : File Of byte; begin result := 0; if not fileexists(lFName) then exit; Assign (F, lFName); Reset (F); result := FileSize(F); Close (F); end; procedure LoadObj(const FileName: string; var faces: TFaces; var vertices: TVertices); //WaveFront Obj file used by Blender // https://en.wikipedia.org/wiki/Wavefront_.obj_file const kBlockSize = 8192; var f: TextFile; fsz : int64; s : string; strlst : TStringList; i,j, num_v, num_f, new_f: integer; begin fsz := FSize (FileName); if fsz < 32 then exit; //init values num_v := 0; num_f := 0; strlst:=TStringList.Create; setlength(vertices, (fsz div 70)+kBlockSize); //guess number of faces based on filesize to reduce reallocation frequencey setlength(faces, (fsz div 35)+kBlockSize); //guess number of vertices based on filesize to reduce reallocation frequencey //load faces and vertices AssignFile(f, FileName); Reset(f); {$IFDEF FPC}DefaultFormatSettings.DecimalSeparator := '.';{$ELSE}DecimalSeparator := '.';{$ENDIF} while not EOF(f) do begin readln(f,s); if length(s) < 7 then continue; if (s[1] <> 'v') and (s[1] <> 'f') then continue; //only read 'f'ace and 'v'ertex lines if (s[2] = 'p') or (s[2] = 'n') or (s[2] = 't') then continue; //ignore vp/vn/vt data: avoid delimiting text yields 20% faster loads strlst.DelimitedText := s; if (strlst.count > 3) and ( (strlst[0]) = 'f') then begin //warning: need to handle "f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3" //warning: face could be triangle, quad, or more vertices! new_f := strlst.count - 3; if ((num_f+new_f) >= length(faces)) then setlength(faces, length(faces)+new_f+kBlockSize); for i := 1 to (strlst.count-1) do if (pos('/', strlst[i]) > 1) then // "f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3" -> f v1 v2 v3 strlst[i] := Copy(strlst[i], 1, pos('/', strlst[i])-1); for j := 1 to (new_f) do begin faces[num_f].X := strtointDef(strlst[1], 0) - 1; //-1 since "A valid vertex index starts from 1" faces[num_f].Y := strtointDef(strlst[j+1], 0) - 1; //-1 since "A valid vertex index starts from 1" faces[num_f].Z := strtointDef(strlst[j+2], 0) - 1; //-1 since "A valid vertex index starts from 1" inc(num_f); end; end; if (strlst.count > 3) and ( (strlst[0]) = 'v') then begin if ((num_v+1) >= length(vertices)) then setlength(vertices, length(vertices)+kBlockSize); vertices[num_v].X := strtofloatDef(strlst[1], 0); vertices[num_v].Y := strtofloatDef(strlst[2], 0); vertices[num_v].Z := strtofloatDef(strlst[3], 0); inc(num_v); end; end; CloseFile(f); strlst.free; setlength(faces, num_f); setlength(vertices, num_v); end; // LoadObj() procedure SaveObj(const FileName: string; var faces: TFaces; var vertices: TVertices); //create WaveFront object file // https://en.wikipedia.org/wiki/Wavefront_.obj_file var f : TextFile; FileNameObj: string; i : integer; begin if (length(faces) < 1) or (length(vertices) < 3) then begin writeln('You need to open a mesh before you can save it'); exit; end; FileNameObj := changeFileExt(FileName, '.obj'); AssignFile(f, FileNameObj); ReWrite(f); WriteLn(f, '# WaveFront Object format image created with Surf Ice'); for i := 0 to (length(vertices)-1) do WriteLn(f, 'v ' + floattostr(vertices[i].X)+' '+floattostr(vertices[i].Y)+' '+ floattostr(vertices[i].Z)); for i := 0 to (length(faces)-1) do WriteLn(f, 'f ' + inttostr(faces[i].X+1)+' '+inttostr(faces[i].Y+1)+' '+ inttostr(faces[i].Z+1)); //+1 since "A valid vertex index starts from 1 " CloseFile(f); end; end.
// Copyright 2021 Darian Miller, Licensed under Apache-2.0 // SPDX-License-Identifier: Apache-2.0 // More info: www.radprogrammer.com unit radRTL.HOTP.Tests; interface uses TestFramework, System.SysUtils; type THOTPTest = class(TTestCase) published procedure TestRFCVectors; end; implementation uses radRTL.HOTP; (* https://datatracker.ietf.org/doc/html/rfc4226 Appendix D The following test data uses the ASCII string "12345678901234567890" for the secret: Secret = 0x3132333435363738393031323334353637383930 Table 1 details for each count, the intermediate HMAC value. Count Hexadecimal HMAC-SHA-1(secret, count) 0 cc93cf18508d94934c64b65d8ba7667fb7cde4b0 1 75a48a19d4cbe100644e8ac1397eea747a2d33ab 2 0bacb7fa082fef30782211938bc1c5e70416ff44 3 66c28227d03a2d5529262ff016a1e6ef76557ece 4 a904c900a64b35909874b33e61c5938a8e15ed1c 5 a37e783d7b7233c083d4f62926c7a25f238d0316 6 bc9cd28561042c83f219324d3c607256c03272ae 7 a4fb960c0bc06e1eabb804e5b397cdc4b45596fa 8 1b3c89f65e6c9e883012052823443f048b4332db 9 1637409809a679dc698207310c8c7fc07290d9e5 Table 2 details for each count the truncated values (both in hexadecimal and decimal) and then the HOTP value. Truncated Count Hexadecimal Decimal HOTP 0 4c93cf18 1284755224 755224 1 41397eea 1094287082 287082 2 82fef30 137359152 359152 3 66ef7655 1726969429 969429 4 61c5938a 1640338314 338314 5 33c083d4 868254676 254676 6 7256c032 1918287922 287922 7 4e5b397 82162583 162583 8 2823443f 673399871 399871 9 2679dc69 645520489 520489 *) procedure THOTPTest.TestRFCVectors; const SECRET_PLAINTEXT_BYTES:TBytes = [49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48]; //'12345678901234567890' SECRET_BASE32_STRING = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'; // TBase32.Encode('12345678901234567890'); EXPECTED_VALUES: array [0 .. 9] of string = ('755224', '287082', '359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489'); var i:integer; begin for i := low(EXPECTED_VALUES) to high(EXPECTED_VALUES) do begin CheckEquals(EXPECTED_VALUES[i], THOTP.GeneratePassword(SECRET_PLAINTEXT_BYTES, i)); CheckEquals(EXPECTED_VALUES[i], THOTP.GeneratePassword(SECRET_BASE32_STRING, i)); end; end; initialization RegisterTest(THOTPTest.Suite); end.
unit untEasyBaseConst; interface uses DB, DBClient; const EasyErrorHint_NRight = '无相应的操作权限!'; EasyHint_ConfirmDelete = '是否执行删除操作?'; EasyEditHint_Edit = '编辑操作出错!'; EasySaveHint_Success = '保存成功!'; EasySaveHint_Error = '保存失败,原因:'; EasyFindHint_Save = '是否保存当前更改,再进行查找操作?'; EasyRefreshHint_Save = '是否保存当前更改,再进行刷新操作?'; EasyNotNullField_Hint = '字段不能为空!'; EasyErrorHint_DirCreate = '目录创建出错,原因:'; EasyErrorHint_NotFile = ' 文件不存在!'; EasyErrorHint_RDMDispNIL = '中间服务器获取异常,原因:接口返回为空值!'; ActionStr: array[TReconcileAction] of string = ('忽略', '中断', '合并', '正确', '取消', '刷新'); UpdateKindStr: array[TUpdateKind] of string = ('修改', '插入', '删除'); SCaption = '更新出错 - %s'; SUnchanged = '<未发生改变>'; SBinary = '(Binary)'; SAdt = '(ADT)'; SArray = '(Array)'; SFieldName = '字段名'; SOriginal = '原始值'; //Original Value SConflict = '冲突值'; //Conflicting Value SValue = '值'; //Value SNoData = '<无记录>'; //No Records SNew = 'New'; //New implementation end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, OpenGL; type TfrmGL = class(TForm) Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Timer1Timer(Sender: TObject); procedure FormResize(Sender: TObject); private DC : HDC; hrc: HGLRC; {позиция курсора} xpos : GLfloat; ypos : GLfloat; end; var frmGL: TfrmGL; implementation {$R *.DFM} {======================================================================= Перерисовка окна} procedure TfrmGL.FormPaint(Sender: TObject); var i : 1..100; begin glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета For i := 1 to 100 do begin glColor3f (random, random, random); glLineStipple (random (5), random ($FFFF)); glBegin (GL_LINES); glVertex2f (xpos, ypos); glVertex2f (xpos + 0.5 * random * sin (random (360)), ypos + 0.5 * random * cos (random (360))); glEnd; end; 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); glEnable (GL_LINE_STIPPLE); end; {======================================================================= Конец работы приложения} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC (Handle, DC); DeleteDC (DC); end; {======================================================================= Обрабока движения курсора} procedure TfrmGL.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin xpos := 2 * X / ClientWidth - 1; ypos := 2 * (ClientHeight - Y) / ClientHeight - 1; end; procedure TfrmGL.Timer1Timer(Sender: TObject); begin InvalidateRect(Handle, nil, False); end; procedure TfrmGL.FormResize(Sender: TObject); begin glViewPort (0, 0, ClientWidth, ClientHeight); end; end.
unit UFrmExample; interface uses Vcl.Forms, Vcl.ImgList, Vcl.Controls, System.Classes, Vcl.DzHTMLText, {$IF CompilerVersion >= 29}System.ImageList,{$ENDIF} // Vcl.Graphics; type TForm1 = class(TForm) Lb: TDzHTMLText; MyImages: TImageList; Lb2: TDzHTMLText; Lb3: TDzHTMLText; procedure FormCreate(Sender: TObject); procedure LbRetrieveImgRes(Sender: TObject; const ResourceName: string; Picture: TPicture; var Handled: Boolean); procedure LbLinkClick(Sender: TObject; Link: TDHBaseLink; var Handled: Boolean); end; var Form1: TForm1; implementation {$R *.dfm} uses Vcl.Dialogs; procedure TForm1.FormCreate(Sender: TObject); begin ReportMemoryLeaksOnShutdown := True; end; procedure TForm1.LbLinkClick(Sender: TObject; Link: TDHBaseLink; var Handled: Boolean); begin if Link.LinkRef.Target='INFO_ABOUT' then begin ShowMessage('This is the example app.'); Handled := True; end; end; procedure TForm1.LbRetrieveImgRes(Sender: TObject; const ResourceName: string; Picture: TPicture; var Handled: Boolean); begin if ResourceName='LOGO' then begin //Load image by myself Picture.Assign(Application.Icon); Handled := True; //tell the component to NOT load resource automatically end; end; end.
unit UEndereco; interface uses UCidade; type Endereco = class protected Logradouro : string[100]; Numero : string[10]; CEP : string[9]; Bairro : string[50]; Complemento : string[100]; umaCidade : Cidade; Public Constructor CrieObjeto; Destructor Destrua_Se; Procedure setLogradouro (vLogradouro : string); Procedure setNumero (vNumero : string); Procedure setCEP (vCEP : string); Procedure setBairro (vBairro : string); Procedure setComplemento (vComplemento : string); Procedure setumaCidade (vCidade : Cidade); Function getLogradouro : string; Function getNumero :string; Function getCEP : string; Function getBairro : string; Function getComplemento : string; Function getumaCidade : Cidade; End; implementation { Endereco } constructor Endereco.CrieObjeto; begin Logradouro := ' '; Numero := ' '; CEP := ' '; Bairro := ' '; Complemento := ' '; umaCidade := Cidade.CrieObjeto; end; destructor Endereco.Destrua_Se; begin end; function Endereco.getBairro: string; begin Result := Bairro; end; function Endereco.getCEP: string; begin Result := CEP; end; function Endereco.getComplemento: string; begin Result := Complemento; end; function Endereco.getLogradouro: string; begin Result := Logradouro; end; function Endereco.getNumero: string; begin Result := Numero; end; function Endereco.getumaCidade: Cidade; begin Result := umaCidade; end; procedure Endereco.setBairro(vBairro: string); begin Bairro := vBairro; end; procedure Endereco.setCEP(vCEP: string); begin CEP := vCEP; end; procedure Endereco.setComplemento(vComplemento: string); begin Complemento := vComplemento; end; procedure Endereco.setLogradouro(vLogradouro: string); begin Logradouro := vLogradouro; end; procedure Endereco.setNumero(vNumero: string); begin Numero := vNumero; end; procedure Endereco.setumaCidade(vCidade: Cidade); begin umaCidade := vCidade; end; end.
{ Double Commander ------------------------------------------------------------------------- Quick search/filter options page Copyright (C) 2006-2011 Koblov Alexander (Alexx2000@mail.ru) 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } unit fOptionsQuickSearchFilter; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StdCtrls, ExtCtrls, fOptionsFrame; type { TfrmOptionsQuickSearchFilter } TfrmOptionsQuickSearchFilter = class(TOptionsEditor) cbExactBeginning: TCheckBox; cbExactEnding: TCheckBox; cgpOptions: TCheckGroup; gbExactNameMatch: TGroupBox; rgpSearchCase: TRadioGroup; rgpSearchItems: TRadioGroup; protected procedure Init; override; procedure Load; override; function Save: TOptionsEditorSaveFlags; override; public class function GetIconIndex: Integer; override; class function GetTitle: String; override; end; implementation {$R *.lfm} uses DCStrUtils, uGlobs, uLng, fQuickSearch; const OPTION_AUTOHIDE_POSITION = 0; OPTION_SAVE_SESSION_MODIFICATIONS = 1; { TfrmOptionsQuickSearchFilter } class function TfrmOptionsQuickSearchFilter.GetIconIndex: Integer; begin Result := 12; end; class function TfrmOptionsQuickSearchFilter.GetTitle: String; begin Result := rsOptionsEditorQuickSearch; end; procedure TfrmOptionsQuickSearchFilter.Init; begin // Copy localized strings to each combo box. ParseLineToList(rsOptSearchItems, rgpSearchItems.Items); ParseLineToList(rsOptSearchCase, rgpSearchCase.Items); ParseLineToList(rsOptSearchOpt, cgpOptions.Items); end; procedure TfrmOptionsQuickSearchFilter.Load; begin cbExactBeginning.Checked := qsmBeginning in gQuickSearchOptions.Match; cbExactEnding.Checked := qsmEnding in gQuickSearchOptions.Match; rgpSearchItems.ItemIndex := Integer(gQuickSearchOptions.Items); rgpSearchCase.ItemIndex := Integer(gQuickSearchOptions.SearchCase); cgpOptions.Checked[OPTION_AUTOHIDE_POSITION] := gQuickFilterAutoHide; cgpOptions.Checked[OPTION_SAVE_SESSION_MODIFICATIONS] := gQuickFilterSaveSessionModifications; end; function TfrmOptionsQuickSearchFilter.Save: TOptionsEditorSaveFlags; begin Result := []; if cbExactBeginning.Checked then Include(gQuickSearchOptions.Match, qsmBeginning) else Exclude(gQuickSearchOptions.Match, qsmBeginning); if cbExactEnding.Checked then Include(gQuickSearchOptions.Match, qsmEnding) else Exclude(gQuickSearchOptions.Match, qsmEnding); gQuickSearchOptions.Items := TQuickSearchItems(rgpSearchItems.ItemIndex); gQuickSearchOptions.SearchCase := TQuickSearchCase(rgpSearchCase.ItemIndex); gQuickFilterAutoHide := cgpOptions.Checked[OPTION_AUTOHIDE_POSITION]; gQuickFilterSaveSessionModifications := cgpOptions.Checked[OPTION_SAVE_SESSION_MODIFICATIONS]; end; end.
unit UnComandaPrint; interface uses Classes, Printers, { Fluente } UnComandaModelo; type TUnidadeDeMedidaDaImpressao = (umiMilimetros, umiCaracteres); TAlinhamentoDaImpressao = (adiEsquerda, adiDireira, adiCentralizado); TDispositivoDeImpressao = (ddiTela, ddiImpressora); TComandaPrint = class private FAlinhamento: TAlinhamentoDaImpressao; FComandaModelo: TComandaModelo; FDispositivo: TDispositivoDeImpressao; FLarguraImpressao: Integer; FImprimirDiretamente: Boolean; FImpressaoExpandida: Boolean; FSpool: TStringList; FUnidadeDeMedidaDaLarguraDeImpressao: TUnidadeDeMedidaDaImpressao; protected procedure ImprimirArquivoTexto; public function AlinharADireita: TComandaPrint; function AlinharAEsquerda: TComandaPrint; function AtivarExpandido: TComandaPrint; function ComandaModelo(const ComandaModelo: TComandaModelo): TComandaPrint; function DefinirLarguraDaImpressaoEmCaracteres( const LarguraEmCaracteres: Integer): TComandaPrint; function DefinirLarguraDaImpressaoEmMilimetros( const LarguraEmMilimetros: Integer): TComandaPrint; function DesativarExpandido: TComandaPrint; function Descarregar: TComandaPrint; function DesligarImpressaoDireta: TComandaPrint; function DispositivoParaImpressao( const Dispositivo: TDispositivoDeImpressao): TComandaPrint; function FinalizarImpressao: TComandaPrint; function Imprimir(const Texto: string): TComandaPrint; function ImprimirLinha(const Texto: string): TComandaPrint; function IniciarImpressao: TComandaPrint; function LigarImpressaoDireta: TComandaPrint; function Preparar: TComandaPrint; end; implementation uses { Fluente } UnImpressao, SysUtils; { TComandaPrint } function TComandaPrint.AlinharADireita: TComandaPrint; begin Self.FAlinhamento := adiDireira; Result := Self; end; function TComandaPrint.AlinharAEsquerda: TComandaPrint; begin Self.FAlinhamento := adiEsquerda; Result := Self; end; function TComandaPrint.AtivarExpandido: TComandaPrint; begin Self.FImpressaoExpandida := True; Result := Self; end; function TComandaPrint.ComandaModelo( const ComandaModelo: TComandaModelo): TComandaPrint; begin Self.FComandaModelo := ComandaModelo; Result := Self; end; function TComandaPrint.DefinirLarguraDaImpressaoEmCaracteres( const LarguraEmCaracteres: Integer): TComandaPrint; begin Self.FLarguraImpressao := LarguraEmCaracteres; Self.FUnidadeDeMedidaDaLarguraDeImpressao := umiCaracteres; Result := Self; end; function TComandaPrint.DefinirLarguraDaImpressaoEmMilimetros( const LarguraEmMilimetros: Integer): TComandaPrint; begin Self.FLarguraImpressao := LarguraEmMilimetros; Self.FUnidadeDeMedidaDaLarguraDeImpressao := umiMilimetros; Result := Self; end; function TComandaPrint.DesativarExpandido: TComandaPrint; begin Self.FImpressaoExpandida := False; Result := Self; end; function TComandaPrint.Descarregar: TComandaPrint; begin Result := Self; end; function TComandaPrint.DesligarImpressaoDireta: TComandaPrint; begin Self.FImprimirDiretamente := False; Result := Self; end; function TComandaPrint.DispositivoParaImpressao( const Dispositivo: TDispositivoDeImpressao): TComandaPrint; begin Self.FDispositivo := Dispositivo; Result := Self; end; function TComandaPrint.FinalizarImpressao: TComandaPrint; var _i: Integer; _saida: TImpressaoView; begin if FileExists('.\system\virtualprinter.sys') then begin _saida := TImpressaoView.Create(nil); try for _i := 0 to Self.FSpool.Count-1 do _saida.Impressao.Lines.Add(Self.FSpool[_i]); _saida.ShowModal; finally _saida.descarregar; FreeAndNil(_saida); end; end else Self.ImprimirArquivoTexto; Result := Self; end; function TComandaPrint.Imprimir(const Texto: string): TComandaPrint; begin Self.FSpool[Self.FSpool.Count-1] := Self.FSpool[Self.FSpool.Count-1] + Texto; Result := Self; end; procedure TComandaPrint.ImprimirArquivoTexto; var _arquivoTexto : TextFile; _i: Integer; begin AssignPrn(_arquivoTexto); Rewrite(_arquivoTexto); for _i := 0 to Self.FSpool.Count-1 do Writeln(_arquivoTexto, Self.FSpool[_i]); CloseFile(_arquivoTexto); end; function TComandaPrint.ImprimirLinha(const Texto: string): TComandaPrint; begin Self.FSpool.Add(Texto); Result := Self; end; function TComandaPrint.IniciarImpressao: TComandaPrint; begin Result := Self; end; function TComandaPrint.LigarImpressaoDireta: TComandaPrint; begin Self.FImprimirDiretamente := True; Result := Self; end; function TComandaPrint.Preparar: TComandaPrint; begin Self.FSpool := TStringList.Create; Result := Self; end; end.
unit ncMsgCli; interface uses SysUtils, Classes, Windows, ncClassesBase; type TncMsgCli = class private FID : Cardinal; FCliente : Cardinal; FTitulo : String; FTexto : String; function GetString: String; procedure SetString(Value: String); public constructor Create; property ID: Cardinal read FID write FID; property Cliente: Cardinal read FCliente write FCliente; property Titulo: String read FTitulo write FTitulo; property Texto: String read FTexto write FTexto; property AsString: String read GetString write SetString; end; TncMsgCliList = class private FList : TList; function GetString: String; procedure SetString(Value: String); function GetItem(I: Integer): TncMsgCli; public constructor Create; destructor Destroy; override; function Add: TncMsgCli; function Remove(M: TncMsgCli): Integer; procedure Clear; function Count: Integer; property Itens[I: Integer]: TncMsgCli read GetItem; default; property AsString: String read GetString write SetString; end; implementation { TncMsgCli } constructor TncMsgCli.Create; begin FID := 0; FCliente := 0; FTitulo := ''; FTexto := ''; end; function TncMsgCli.GetString: String; begin Result := IntToStr(FID) + sFldDelim(classid_TncMsgCli) + IntToStr(FCliente) + sFldDelim(classid_TncMsgCli) + FTitulo + sFldDelim(classid_TncMsgCli) + FTexto + sFldDelim(classid_TncMsgCli); end; procedure TncMsgCli.SetString(Value: String); function _NextField: String; begin Result := GetNextStrDelim(Value, classid_TncMsgCli); end; begin FID := StrToIntDef(_NextField, 0); FCliente := StrToIntDef(_NextField, 0); FTitulo := _NextField; FTexto := _NextField; end; { TncMsgCliList } function TncMsgCliList.Add: TncMsgCli; begin Result := TncMsgCli.Create; FList.Add(Result); end; procedure TncMsgCliList.Clear; begin while Count>0 do begin TObject(FList[0]).Free; FList.Delete(0); end; end; function TncMsgCliList.Count: Integer; begin Result := FList.Count; end; constructor TncMsgCliList.Create; begin FList := TList.Create; end; destructor TncMsgCliList.Destroy; begin Clear; FList.Free; inherited; end; function TncMsgCliList.GetItem(I: Integer): TncMsgCli; begin Result := TncMsgCli(FList[I]); end; function TncMsgCliList.GetString: String; var I : Integer; begin Result := ''; for I := 0 to Count-1 do Result := Result + Itens[I].AsString + sListaDelim(classid_TncMsgCliList); end; function TncMsgCliList.Remove(M: TncMsgCli): Integer; begin Result := FList.Remove(M); end; procedure TncMsgCliList.SetString(Value: String); var S: String; begin Clear; while GetNextListItem(Value, S, classid_TncmsgCliList) do Add.AsString := S; end; end.
unit WinAPI.WindowsStore; {$SCOPEDENUMS ON} interface uses System.Generics.Collections, System.SysUtils, System.Classes, System.TimeSpan, System.Win.WinRT, WinAPI.WinRT, WinAPI.Windows, WinAPI.CommonTypes, WinAPI.WinRT.Utils; type TAppLicense = class private FIsActive: boolean; FIsTrial: boolean; FIsTrialOwnedByThisUser: boolean; FExtendedJsonData: string; FExpirationDate: TDateTime; FSkuStoreId: string; FTrialTimeRemaining: TTimeSpan; FTrialUniqueId: string; FStoreLicense: IStoreAppLicense; FInfo: TStringList; public constructor Create(const AStoreLicense: IStoreAppLicense); destructor Destroy; override; function ToString: string; override; function GetInfo: TStringList; property IsActive: boolean read FIsActive; property IsTrial: boolean read FIsTrial; property IsTrialOwnedByThisUser: boolean read FIsTrialOwnedByThisUser; property ExtendedJsonData: string read FExtendedJsonData; property ExpirationDate: TDateTime read FExpirationDate; property SkuStoreId: string read FSkuStoreId; property TrialTimeRemaining: TTimeSpan read FTrialTimeRemaining; property TrialUniqueId: string read FTrialUniqueId; property StoreLicense: IStoreAppLicense read FStoreLicense; end; TAppProducts = class private FProducts: TList<IStoreProduct>; function GetProducts(const Index: Integer): IStoreProduct; protected procedure Clear; procedure Add(AStoreProduct: IStoreProduct); public constructor Create; virtual; destructor Destroy; override; function Count: Integer; function UserHasBought(const AInAppOfferToken: String): boolean; function IndexOf(const AInAppOfferToken: String): Integer; overload; function IndexOf(const AStoreProduct: IStoreProduct): Integer; overload; property Products[const Index: Integer]: IStoreProduct read GetProducts; default; end; TStoreProductKind = (Application, Game, Consumable, UnmanagedConsumable, Durable); TStoreProductKinds = set of TStoreProductKind; TStoreProductKindNames = class sealed public const Application = 'Application'; // Do not localize Game = 'Game'; // Do not localize Consumable = 'Consumable'; // Do not localize UnmanagedConsumable = 'UnmanagedConsumable'; // Do not localize Durable = 'Durable'; // Do not localize end; /// <summary> /// The Windows.Services.Store namespace was introduced in Windows 10, version 1607, and it can only /// be used in projects that target Windows 10 Anniversary Edition (10.0; Build 14393) or a later release. /// </summary> TWindowsStoreCore = class private FStoreContext: IStoreContext; FAppLicense: TAppLicense; FAppProducts: TAppProducts; FUserCollection: TAppProducts; FApplicationProcessMessages: TApplicationProcessMessagesProc; procedure InitStoreContext; function GetAppLicense: TAppLicense; function GetAppProducts: TAppProducts; function GetUserCollection: TAppProducts; procedure ResetAppProducts(var AAppProducts: TAppProducts); function GetProductsFilter(const ProductKinds: TStoreProductKinds): IIterable_1__HSTRING; function GetStoreProductForCurrentApp: IStoreProduct; public constructor Create(const AApplicationProcessMessages: TApplicationProcessMessagesProc); virtual; destructor Destroy; override; /// <summary> /// Requests the purchase for the specified app or add-on and displays the UI that is used to complete the transaction via the Microsoft Store. /// Important: This method must be called on the UI thread. /// </summary> function PurchaseProduct(AStoreProduct: IStoreProduct): StorePurchaseStatus; /// <summary> /// Reports a consumable add-on for the current app as fulfilled in the Microsoft Store. /// </summary> function ReportConsumableFulfillment(const AProductStoreId: String; const AQuantity: UInt32; const ATrackingId: TGUID): IStoreConsumableResult; /// <summary> /// Reports an unmanaged-consumable add-on for the current app as fulfilled in the Microsoft Store. /// </summary> function ReportUnmanagedConsumableFulfillment(const AProductStoreId: String; const ATrackingId: TGUID) : IStoreConsumableResult; /// <summary> /// Gets the remaining balance for the specified consumable add-on for the current app. /// Use consumable add-ons for items that can be purchased, used, and purchased again. /// This is especially useful for things like in-game currency (gold, coins, etc.) /// that can be purchased and then used to purchase specific power-ups. /// </summary> function GetConsumableBalanceRemaining(const AStoreProduct: IStoreProduct): IStoreConsumableResult; /// <summary> /// Refreshed informations about products and user collection /// </summary> procedure RefreshInfo; /// <summary> /// Return true id the current user has bought the specified InAppOfferToken. /// </summary> function UserHasBought(const AInAppOfferToken: String): boolean; /// <summary> /// Gets license info for the current app, including licenses for add-ons for the current app. /// </summary> property AppLicense: TAppLicense read GetAppLicense; /// <summary> /// Gets Microsoft Store listing info for the products that can be purchased from within the current app. /// </summary> property AppProducts: TAppProducts read GetAppProducts; /// <summary> /// Gets Microsoft Store info for the add-ons of the current app for which the user has purchased. /// </summary> property UserCollection: TAppProducts read GetUserCollection; property StoreProductForCurrentApp: IStoreProduct read GetStoreProductForCurrentApp; end; IInitializeWithWindow = interface(IUnknown) ['{3E68D4BD-7135-4D10-8018-9FB6D9F33FA1}'] procedure Initialize(hwnd: HANDLE_PTR); end; implementation uses WinAPI.ServicesRT.Store, WinAPI.HSTRINGIterables; resourcestring StrProductsNotIterable = 'Products list is not iterable'; Str_IAP_E_UNEXPECTED = 'Cannot initialize Store interface (IAP_E_UNEXPECTED)'; StrCannotGetCurrAppStoreProduct = 'Cannot get store product for current app'; const IAP_E_UNEXPECTED: Int64 = $803F6107; AllProductsKinds: TStoreProductKinds = [TStoreProductKind.Application, TStoreProductKind.Game, TStoreProductKind.Consumable, TStoreProductKind.UnmanagedConsumable, TStoreProductKind.Durable]; StrInfoNamesIsActive = 'IsActive'; StrInfoNamesIsTrial = 'IsTrial'; StrInfoNamesIsTrialOwnedByThisUser = 'IsTrialOwnedByThisUser'; StrInfoNamesExtendedJsonData = 'ExtendedJsonData'; StrInfoNamesExpirationDate = 'ExpirationDate'; StrInfoNamesSkuStoreId = 'SkuStoreId'; StrInfoNamesTrialTimeRemaining = 'TrialTimeRemaining'; StrInfoNamesTrialUniqueId = 'TrialUniqueId'; { TWindowsStoreCore } constructor TWindowsStoreCore.Create(const AApplicationProcessMessages: TApplicationProcessMessagesProc); begin inherited Create; Assert(Assigned(AApplicationProcessMessages), 'AApplicationProcessMessages cannot be nil'); FApplicationProcessMessages := AApplicationProcessMessages; InitStoreContext; end; destructor TWindowsStoreCore.Destroy; begin FAppLicense.Free; FAppProducts.Free; FUserCollection.Free; inherited; end; function TWindowsStoreCore.GetAppProducts: TAppProducts; var LProducts: IMapView_2__HSTRING__IStoreProduct; LProductsIterable: IIterable_1__IKeyValuePair_2__HSTRING__IStoreProduct; LProductsIterator: IIterator_1__IKeyValuePair_2__HSTRING__IStoreProduct; LFilterList: IIterable_1__HSTRING; lAddOns: IAsyncOperation_1__IStoreProductQueryResult; begin if Assigned(FAppProducts) then begin Exit(FAppProducts); end; LFilterList := GetProductsFilter(AllProductsKinds); { Gets Microsoft Store listing info for the products that can be purchased from within the current app. } lAddOns := FStoreContext.GetAssociatedStoreProductsAsync(LFilterList); Await(lAddOns, FApplicationProcessMessages); if lAddOns.GetResults.ExtendedError = IAP_E_UNEXPECTED then raise Exception.Create(Str_IAP_E_UNEXPECTED); LProducts := lAddOns.GetResults.Products; if not Supports(LProducts, IIterable_1__IKeyValuePair_2__HSTRING__IStoreProduct_Base, LProductsIterable) then raise Exception.Create(StrProductsNotIterable); ResetAppProducts(FAppProducts); LProductsIterator := LProductsIterable.First(); while LProductsIterator.HasCurrent do begin FAppProducts.Add(LProductsIterator.Current.Value); LProductsIterator.MoveNext; end; Result := FAppProducts; end; function TWindowsStoreCore.GetConsumableBalanceRemaining(const AStoreProduct: IStoreProduct): IStoreConsumableResult; var LStoreConsumableResult: IAsyncOperation_1__IStoreConsumableResult; begin LStoreConsumableResult := FStoreContext.GetConsumableBalanceRemainingAsync(AStoreProduct.StoreId); Await(LStoreConsumableResult, FApplicationProcessMessages); Result := LStoreConsumableResult.GetResults; end; function TWindowsStoreCore.GetProductsFilter(const ProductKinds: TStoreProductKinds): IIterable_1__HSTRING; begin Result := TIterableHSTRING.Create; if TStoreProductKind.Consumable in ProductKinds then TIterableHSTRING(Result).Add(CreateHSTRING(TStoreProductKindNames.Consumable)); if TStoreProductKind.Durable in ProductKinds then TIterableHSTRING(Result).Add(CreateHSTRING(TStoreProductKindNames.Durable)); if TStoreProductKind.UnmanagedConsumable in ProductKinds then TIterableHSTRING(Result).Add(CreateHSTRING(TStoreProductKindNames.UnmanagedConsumable)); if TStoreProductKind.Application in ProductKinds then TIterableHSTRING(Result).Add(CreateHSTRING(TStoreProductKindNames.Application)); if TStoreProductKind.Game in ProductKinds then TIterableHSTRING(Result).Add(CreateHSTRING(TStoreProductKindNames.Game)); end; function TWindowsStoreCore.GetStoreProductForCurrentApp: IStoreProduct; var LRes: IAsyncOperation_1__IStoreProductResult; begin LRes := FStoreContext.GetStoreProductForCurrentAppAsync(); Await(LRes, FApplicationProcessMessages); if not Succeeded(LRes.GetResults.ExtendedError) then begin raise Exception.Create(StrCannotGetCurrAppStoreProduct); end; Result := LRes.GetResults.Product; end; function TWindowsStoreCore.GetUserCollection: TAppProducts; var lPrdcts: IMapView_2__HSTRING__IStoreProduct; lOut: IIterable_1__IKeyValuePair_2__HSTRING__IStoreProduct; lIterator: IIterator_1__IKeyValuePair_2__HSTRING__IStoreProduct; LFilterList: IIterable_1__HSTRING; LUserProducts: IAsyncOperation_1__IStoreProductQueryResult; begin if Assigned(FUserCollection) then begin Exit(FUserCollection); end; LFilterList := GetProductsFilter(AllProductsKinds); LUserProducts := FStoreContext.GetUserCollectionAsync(LFilterList); Await(LUserProducts, FApplicationProcessMessages); if LUserProducts.GetResults.ExtendedError = IAP_E_UNEXPECTED then raise Exception.Create(Str_IAP_E_UNEXPECTED); lPrdcts := LUserProducts.GetResults.Products; if not Supports(lPrdcts, IIterable_1__IKeyValuePair_2__HSTRING__IStoreProduct_Base, lOut) then raise Exception.Create(StrProductsNotIterable); ResetAppProducts(FUserCollection); lIterator := lOut.First(); while lIterator.HasCurrent do begin FUserCollection.Add(lIterator.Current.Value); lIterator.MoveNext; end; Result := FUserCollection; end; function TWindowsStoreCore.GetAppLicense: TAppLicense; var LAppLicense: IAsyncOperation_1__IStoreAppLicense; begin if not Assigned(FAppLicense) then begin LAppLicense := FStoreContext.GetAppLicenseAsync(); Await(LAppLicense, FApplicationProcessMessages); FAppLicense := TAppLicense.Create(LAppLicense.GetResults); end; Result := FAppLicense; end; procedure TWindowsStoreCore.InitStoreContext; begin if not Assigned(FStoreContext) then begin FStoreContext := TStoreContext.Statics.GetDefault(); end; end; function TWindowsStoreCore.PurchaseProduct(AStoreProduct: IStoreProduct): StorePurchaseStatus; var LPurchaseRequest: IAsyncOperation_1__IStorePurchaseResult; LInitWindow: IInitializeWithWindow; begin // https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/Store/cs/Scenario2_InAppPurchase.xaml.cs // This method *must* be called on the Main thread TThread.Synchronize(nil, procedure begin LInitWindow := FStoreContext as IInitializeWithWindow; LInitWindow.Initialize(GetForegroundWindow()); LPurchaseRequest := FStoreContext.RequestPurchaseAsync(AStoreProduct.StoreId); Await(LPurchaseRequest, FApplicationProcessMessages); end); Result := LPurchaseRequest.GetResults.Status; end; procedure TWindowsStoreCore.RefreshInfo; begin FreeAndNil(FAppLicense); AppLicense; FreeAndNil(FAppProducts); FreeAndNil(FUserCollection); AppProducts.Count; // just to refresh UserCollection.Count; // just to refresh end; function TWindowsStoreCore.ReportConsumableFulfillment(const AProductStoreId: String; const AQuantity: UInt32; const ATrackingId: TGUID): IStoreConsumableResult; var LStoreConsumableResult: IAsyncOperation_1__IStoreConsumableResult; begin LStoreConsumableResult := FStoreContext.ReportConsumableFulfillmentAsync(CreateHSTRING(AProductStoreId), AQuantity, ATrackingId); Await(LStoreConsumableResult, FApplicationProcessMessages); Result := LStoreConsumableResult.GetResults; end; function TWindowsStoreCore.ReportUnmanagedConsumableFulfillment(const AProductStoreId: String; const ATrackingId: TGUID) : IStoreConsumableResult; begin { Quantity: For a developer-managed consumable (that is, a consumable where the developer keeps track of the balance), specify 1. } Result := ReportConsumableFulfillment(AProductStoreId, 1, ATrackingId); end; procedure TWindowsStoreCore.ResetAppProducts(var AAppProducts: TAppProducts); begin if not Assigned(AAppProducts) then begin AAppProducts := TAppProducts.Create; end else begin AAppProducts.Clear; end; end; function TWindowsStoreCore.UserHasBought(const AInAppOfferToken: String): boolean; begin Result := UserCollection.UserHasBought(AInAppOfferToken); end; constructor TAppLicense.Create(const AStoreLicense: IStoreAppLicense); begin inherited Create; FIsActive := AStoreLicense.IsActive; FIsTrial := AStoreLicense.IsTrial; FIsTrialOwnedByThisUser := AStoreLicense.IsTrialOwnedByThisUser; FExtendedJsonData := AStoreLicense.ExtendedJsonData.ToString; FExpirationDate := DateTimeToTDateTime(AStoreLicense.ExpirationDate); FSkuStoreId := AStoreLicense.SkuStoreId.ToString; FTrialTimeRemaining := TTimeSpan.Create(AStoreLicense.TrialTimeRemaining.Duration); FTrialUniqueId := AStoreLicense.TrialUniqueId.ToString; FStoreLicense := AStoreLicense; end; destructor TAppLicense.Destroy; begin FInfo.Free; inherited; end; function TAppLicense.GetInfo: TStringList; begin if not Assigned(FInfo) then begin FInfo := TStringList.Create; try FInfo.Values[StrInfoNamesIsActive] := IsActive.ToString(TUseBoolStrs.True); FInfo.Values[StrInfoNamesIsTrial] := IsTrial.ToString(TUseBoolStrs.True); FInfo.Values[StrInfoNamesIsTrialOwnedByThisUser] := IsTrialOwnedByThisUser.ToString(TUseBoolStrs.True); FInfo.Values[StrInfoNamesExtendedJsonData] := ExtendedJsonData; FInfo.Values[StrInfoNamesExpirationDate] := DateTimeToStr(FExpirationDate); FInfo.Values[StrInfoNamesSkuStoreId] := FSkuStoreId; FInfo.Values[StrInfoNamesTrialTimeRemaining] := FTrialTimeRemaining; FInfo.Values[StrInfoNamesTrialUniqueId] := FTrialUniqueId; except FreeAndNil(FInfo); raise; end; end; Result := FInfo; end; function TAppLicense.ToString: string; begin Result := GetInfo.Text; end; procedure TAppProducts.Add(AStoreProduct: IStoreProduct); begin FProducts.Add(AStoreProduct); end; procedure TAppProducts.Clear; begin FProducts.Clear; end; function TAppProducts.Count: Integer; begin Result := FProducts.Count; end; constructor TAppProducts.Create; begin inherited; FProducts := TList<IStoreProduct>.Create; end; destructor TAppProducts.Destroy; begin FProducts.Free; inherited; end; function TAppProducts.GetProducts(const Index: Integer): IStoreProduct; begin Result := FProducts[Index]; end; function TAppProducts.IndexOf(const AInAppOfferToken: String): Integer; var I: Integer; begin Result := -1; for I := 0 to FProducts.Count - 1 do begin if TWindowsString.HStringToString(FProducts[I].InAppOfferToken) = AInAppOfferToken then begin Exit(I); end; end; end; function TAppProducts.IndexOf(const AStoreProduct: IStoreProduct): Integer; var I: Integer; begin Result := -1; for I := 0 to FProducts.Count - 1 do begin if FProducts[I] = AStoreProduct then begin Exit(I); end; end; end; function TAppProducts.UserHasBought(const AInAppOfferToken: String): boolean; begin Result := IndexOf(AInAppOfferToken) > -1; end; end.
{ Affichage de texte en mode texte pour Mister Patate } unit MrpText; interface { Passe en mode texte } procedure InitTexte; { Renvoie le mode courant } function GetMode: Byte; { Ecrit un texte … la position du curseur, avec la couleur 'color' } procedure Print (Txt: String; Color: Byte); { Idem que 'Print' mais passe … la ligne } procedure PrintR (Txt: String; Color: Byte); { Retourne … la ligne si la colonne du curseur est sup‚rieur … 0 } procedure Retour; { Efface l'‚cran } procedure ClsTexte; implementation procedure InitTexte; assembler; asm MOV AX,0003h { INT 10h, fonction 00h: Change de mode vid‚o } INT 10h end; function GetMode; assembler; asm MOV AH,0Fh { INT 10h, fonctions 0Fh: renvoie le mode vid‚o } INT 10h end; procedure Print; assembler; asm PUSH DS LDS SI,[Txt] LODSB MOV DL,AL XOR BH,BH MOV BL,[Color] MOV CX,1 @LoopChar: MOV AX,$0900 INT $10 MOV AH,$0E LODSB INT $10 DEC DL JNZ @LoopChar POP DS end; procedure PrintR; begin Print (Txt, Color); Retour; end; procedure Retour; assembler; asm MOV AX,$0E0A INT $10 MOV AX,$0E0D INT $10 end; procedure ClsTexte; assembler; asm MOV AX,$B800 MOV ES,AX DB 66h XOR AX,AX MOV CX,80*25*2/4 DB 66h REP STOSW PUSH BP MOV AH,$02 XOR DX,DX INT 10h POP BP end; end.
{$i deltics.unicode.inc} unit Deltics.Unicode.Bom; interface uses Deltics.Unicode.Types; type Utf8Bom = class class function AsBytes: TBom; class function AsString: Utf8String; end; Utf16Bom = class class function AsBytes: TBom; class function AsString: UnicodeString; end; Utf16LEBom = class class function AsBytes: TBom; class function AsString: UnicodeString; end; Utf32Bom = class class function AsBytes: TBom; end; Utf32LEBom = class class function AsBytes: TBom; end; implementation const bomUtf8 : array[0..2] of Byte = ($ef, $bb, $bf); bomUtf16 : array[0..1] of Byte = ($fe, $ff); bomUtf32 : array[0..3] of Byte = ($00, $00, $fe, $ff); { Utf8Bom } class function Utf8Bom.AsBytes: TBom; begin SetLength(result, 3); result[0] := bomUtf8[0]; result[1] := bomUtf8[1]; result[2] := bomUtf8[2]; end; class function Utf8Bom.AsString: Utf8String; begin result := Utf8Char(bomUtf8[0]) + Utf8Char(bomUtf8[1]) + Utf8Char(bomUtf8[2]); end; { Utf16Bom } class function Utf16Bom.AsBytes: TBom; begin SetLength(result, 2); result[0] := bomUtf16[0]; result[1] := bomUtf16[1]; end; class function Utf16Bom.AsString: UnicodeString; begin result := WideChar((bomUtf16[0] shl 8) or bomUtf16[1]); end; { Utf16LEBom } class function Utf16LEBom.AsBytes: TBom; begin SetLength(result, 2); result[0] := bomUtf16[1]; result[1] := bomUtf16[0]; end; class function Utf16LEBom.AsString: UnicodeString; begin result := WideChar(Word((bomUtf16[1] shl 8) or bomUtf16[0])) end; { Utf32Bom } class function Utf32Bom.AsBytes: TBom; begin SetLength(result, 4); result[0] := bomUtf32[0]; result[1] := bomUtf32[1]; result[2] := bomUtf32[2]; result[3] := bomUtf32[3]; end; { Utf32LEBom } class function Utf32LEBom.AsBytes: TBom; begin SetLength(result, 4); result[0] := bomUtf32[3]; result[1] := bomUtf32[2]; result[2] := bomUtf32[1]; result[3] := bomUtf32[0]; end; end.
//****************************************************************************** //*** SCRIPT VCL FUNCTIONS *** //*** *** //*** (c) Massimo Magnano 2006 *** //*** *** //*** *** //****************************************************************************** // File : Script_DBTables.pas (rev. 2.0) // // Description : Access from scripts to Classes declared in "DBTables.pas" // //****************************************************************************** // // TDataset <- TBDEDataSet <- TDBDataSet <- TTable // <- TQuery // ------------------------------------------------------------- // TScriptDataset <- TScriptBDEDataSet <- TScriptDBDataSet <- TScriptTable // <- TScriptQuery //============================================================================== unit Script_DBTables; interface uses TypInfo, Classes, DB, BDE, DBTables, Script_DB; type //============================================================================== TScriptBDEDataSet = class (TScriptDataset) protected class function GetPublicPropertyAccessClass :TClass; override; public (* function GetArrayPropType(Name :String; index :Variant) :PTypeInfo; override; function GetArrayProp(Name :String; index :Variant) :Variant; override; function GetElementType(Name :String) :PTypeInfo; override; function GetElement(Name :String) :Variant; override; *) procedure ApplyUpdates; procedure CancelUpdates; procedure CommitUpdates; function ConstraintCallBack(Req: DsInfoReq; var ADataSources: DataSources): DBIResult; function ConstraintsDisabled: Boolean; procedure DisableConstraints; procedure EnableConstraints; procedure FetchAll; procedure FlushBuffers; procedure GetIndexInfo; procedure RevertRecord; end; //============================================================================== TScriptDBDataSet = class (TScriptBDEDataSet) protected class function GetPublicPropertyAccessClass :TClass; override; public (* function GetArrayPropType(Name :String; index :Variant) :PTypeInfo; override; function GetArrayProp(Name :String; index :Variant) :Variant; override; function GetElementType(Name :String) :PTypeInfo; override; function GetElement(Name :String) :Variant; override; *) function CheckOpen(Status: DBIResult): Boolean; procedure CloseDatabase(Database: TDatabase); function OpenDatabase: TDatabase; end; //============================================================================== TScriptTable = class (TScriptDBDataSet) protected class function GetPublicPropertyAccessClass :TClass; override; public function GetArrayPropType(Name :String; index :Variant) :PTypeInfo; override; function GetArrayProp(Name :String; index :Variant) :Variant; override; function BatchMove(ASource: TBDEDataSet; AMode: TBatchMode): Longint; procedure AddIndex(const Name, Fields: string; Options: TIndexOptions; const DescFields: string = ''); procedure ApplyRange; procedure CancelRange; procedure CloseIndexFile(const IndexFileName: string); procedure CreateTable; procedure DeleteIndex(const Name: string); procedure DeleteTable; procedure EditKey; procedure EditRangeEnd; procedure EditRangeStart; procedure EmptyTable; function FindKey(const KeyValues: array of const): Boolean; procedure FindNearest(const KeyValues: array of const); procedure GetIndexNames(List: TStrings); procedure GotoCurrent(Table: TTable); function GotoKey: Boolean; procedure GotoNearest; procedure LockTable(LockType: TLockType); procedure OpenIndexFile(const IndexName: string); procedure RenameTable(const NewTableName: string); procedure SetKey; procedure SetRange(const StartValues, EndValues: array of const); procedure SetRangeEnd; procedure SetRangeStart; procedure UnlockTable(LockType: TLockType); end; //============================================================================== TScriptQuery = class (TScriptDBDataSet) protected class function GetPublicPropertyAccessClass :TClass; override; public (* function GetArrayPropType(Name :String; index :Variant) :PTypeInfo; override; function GetArrayProp(Name :String; index :Variant) :Variant; override; function GetElementType(Name :String) :PTypeInfo; override; function GetElement(Name :String) :Variant; override; *) procedure ExecSQL; function ParamByName(const Value: string): TParam; procedure Prepare; procedure UnPrepare; end; implementation uses Variants, SysUtils, Script_System; type //============================================================================== TBDEDataSetAccess = class(TBDEDataSet) published property CacheBlobs; property ExpIndex; //property Handle; Pointer property KeySize; //property Locale; Pointer property UpdateObject; property UpdatesPending; property UpdateRecordTypes; end; //============================================================================== TDBDataSetAccess = class(TDBDataSet) published property Database; //property DBHandle; Pointer //property DBLocale; Pointer property DBSession; //property Handle; Pointer end; //============================================================================== TTableAccess = class(TTable) published property Exists; property IndexFieldCount; //property IndexFields[Index: Integer]: TField; property KeyExclusive; property KeyFieldCount; property TableLevel; end; //============================================================================== TQueryAccess = class(TQuery) published property Prepared; property ParamCount; property Local; //property StmtHandle; Pointer property Text; property RowsAffected; //property SQLBinary; Pointer end; { TScriptBDEDataSet } class function TScriptBDEDataSet.GetPublicPropertyAccessClass: TClass; begin Result :=TBDEDataSetAccess; end; procedure TScriptBDEDataSet.CancelUpdates; begin TBDEDataset(InstanceObj).CancelUpdates; end; procedure TScriptBDEDataSet.ApplyUpdates; begin TBDEDataset(InstanceObj).ApplyUpdates; end; procedure TScriptBDEDataSet.CommitUpdates; begin TBDEDataset(InstanceObj).CommitUpdates; end; procedure TScriptBDEDataSet.DisableConstraints; begin TBDEDataset(InstanceObj).DisableConstraints; end; procedure TScriptBDEDataSet.FetchAll; begin TBDEDataset(InstanceObj).FetchAll; end; procedure TScriptBDEDataSet.EnableConstraints; begin TBDEDataset(InstanceObj).EnableConstraints; end; function TScriptBDEDataSet.ConstraintsDisabled: Boolean; begin Result :=TBDEDataset(InstanceObj).ConstraintsDisabled; end; procedure TScriptBDEDataSet.GetIndexInfo; begin TBDEDataset(InstanceObj).GetIndexInfo; end; function TScriptBDEDataSet.ConstraintCallBack(Req: DsInfoReq; var ADataSources: DataSources): DBIResult; begin Result :=TBDEDataset(InstanceObj).ConstraintCallBack(Req, ADataSources); end; procedure TScriptBDEDataSet.FlushBuffers; begin TBDEDataset(InstanceObj).FlushBuffers; end; procedure TScriptBDEDataSet.RevertRecord; begin TBDEDataset(InstanceObj).RevertRecord; end; { TScriptDBDataSet } class function TScriptDBDataSet.GetPublicPropertyAccessClass: TClass; begin Result :=TDBDataSetAccess; end; procedure TScriptDBDataSet.CloseDatabase(Database: TDatabase); begin TDBDataSet(InstanceObj).CloseDatabase(Database); end; function TScriptDBDataSet.CheckOpen(Status: DBIResult): Boolean; begin Result :=TDBDataSet(InstanceObj).CheckOpen(Status); end; function TScriptDBDataSet.OpenDatabase: TDatabase; begin Result :=TDBDataSet(InstanceObj).OpenDatabase; end; { TScriptTable } function TScriptTable.GetArrayPropType(Name: String; index: Variant): PTypeInfo; begin Name :=Uppercase(Name); Result :=nil; if (Name='INDEXFIELDS') then begin if (TTable(InstanceObj).IndexFields[index]<>nil) then Result :=TypeInfo(TField); end else Result :=inherited GetArrayPropType(Name, index); end; function TScriptTable.GetArrayProp(Name: String; index: Variant): Variant; begin if (Name='INDEXFIELDS') then begin if (TTable(InstanceObj).IndexFields[index]<>nil) then Result :=Integer(TTable(InstanceObj).IndexFields[index]) else Result :=NULL; end else Result := inherited GetArrayProp(name, index) end; class function TScriptTable.GetPublicPropertyAccessClass: TClass; begin Result :=TTableAccess; end; procedure TScriptTable.SetRange(const StartValues, EndValues: array of const); begin TTable(InstanceObj).SetRange(StartValues, EndValues); end; procedure TScriptTable.GetIndexNames(List: TStrings); begin TTable(InstanceObj).GetIndexNames(List); end; procedure TScriptTable.SetKey; begin TTable(InstanceObj).SetKey; end; procedure TScriptTable.CreateTable; begin TTable(InstanceObj).CreateTable; end; procedure TScriptTable.GotoNearest; begin TTable(InstanceObj).GotoNearest; end; procedure TScriptTable.RenameTable(const NewTableName: string); begin TTable(InstanceObj).RenameTable(NewTableName); end; procedure TScriptTable.CloseIndexFile(const IndexFileName: string); begin TTable(InstanceObj).CloseIndexFile(IndexFileName); end; procedure TScriptTable.DeleteIndex(const Name: string); begin TTable(InstanceObj).DeleteIndex(Name); end; function TScriptTable.BatchMove(ASource: TBDEDataSet; AMode: TBatchMode): Longint; begin Result :=TTable(InstanceObj).BatchMove(ASource, AMode); end; procedure TScriptTable.EditRangeStart; begin TTable(InstanceObj).EditRangeStart; end; procedure TScriptTable.CancelRange; begin TTable(InstanceObj).CancelRange; end; function TScriptTable.GotoKey: Boolean; begin Result :=TTable(InstanceObj).GotoKey; end; procedure TScriptTable.ApplyRange; begin TTable(InstanceObj).ApplyRange; end; procedure TScriptTable.LockTable(LockType: TLockType); begin TTable(InstanceObj).LockTable(LockType); end; procedure TScriptTable.FindNearest(const KeyValues: array of const); begin TTable(InstanceObj).FindNearest(KeyValues); end; procedure TScriptTable.UnlockTable(LockType: TLockType); begin TTable(InstanceObj).UnlockTable(LockType); end; procedure TScriptTable.GotoCurrent(Table: TTable); begin TTable(InstanceObj).GotoCurrent(Table); end; procedure TScriptTable.SetRangeStart; begin TTable(InstanceObj).SetRangeStart; end; procedure TScriptTable.AddIndex(const Name, Fields: string; Options: TIndexOptions; const DescFields: string); begin TTable(InstanceObj).AddIndex(Name, Fields, Options, DescFields); end; procedure TScriptTable.EditRangeEnd; begin TTable(InstanceObj).EditRangeEnd; end; procedure TScriptTable.EditKey; begin TTable(InstanceObj).EditKey; end; procedure TScriptTable.DeleteTable; begin TTable(InstanceObj).DeleteTable; end; function TScriptTable.FindKey(const KeyValues: array of const): Boolean; begin Result :=TTable(InstanceObj).FindKey(KeyValues); end; procedure TScriptTable.EmptyTable; begin TTable(InstanceObj).EmptyTable; end; procedure TScriptTable.SetRangeEnd; begin TTable(InstanceObj).SetRangeEnd; end; procedure TScriptTable.OpenIndexFile(const IndexName: string); begin TTable(InstanceObj).OpenIndexFile(IndexName); end; { TScriptQuery } class function TScriptQuery.GetPublicPropertyAccessClass: TClass; begin Result :=TQueryAccess; end; procedure TScriptQuery.ExecSQL; begin TQuery(InstanceObj).ExecSQL; end; function TScriptQuery.ParamByName(const Value: string): TParam; begin Result :=TQuery(InstanceObj).ParamByName(Value); end; procedure TScriptQuery.Prepare; begin TQuery(InstanceObj).Prepare; end; procedure TScriptQuery.UnPrepare; begin TQuery(InstanceObj).UnPrepare; end; initialization Script_System.RegisterClass(TBDEDataSet, TScriptBDEDataSet); Script_System.RegisterClass(TDBDataSet, TScriptDBDataSet); Script_System.RegisterClass(TTable, TScriptTable); Script_System.RegisterClass(TQuery, TScriptQuery); end.
{ ******************************************************** } { } { dbClipImport unit } { Copyright (c) 1997,1998,1999,2000,2001 } { by Joselito G. Real } { } { You can use this unit as freely as you wish, } { compile it with your code, distribute the source but } { you should include my copyright notice in full. } { If you use in part, please credit it as such. } { } { ******************************************************** } unit dbClipImport; interface uses SysUtils, Classes, db, ClipBrd, DBGrids; { Simply use this unit to add the capability to import TEXT data from ClipBoard, StringLists, Text Files, and CSV (comma- separated variable length ASCII file) to any TDataSet descendants, including but not limited to DBISAM Tables, dBASE & Paradox, tables, Advantage Tables, etc. This unit will not import blobs, graphics nor import memo fields containing CR-LF and non-ASCII characters. This unit will work with Datasets having blob or graphics fields as long as you don't include the fieldnames of these fields in the header of the import file or clipboard. This unit can also import memo fields as long as the memo fields are composed of a properly delimited string. The first row should be the fieldname header, subsequent rows are data to import. This will only import data for the matching fieldnames, it will skip blank column names, and any data under the column names not found in the destination dataset are also skipped. If you have more datafields than your header on the subsequent lines, those extra datafields will be ignored. This will import data regardless of column position. This uses direct index location of data fields, and this saves some CPU time especially if you have many data fields. Included in this unit are four methods and two functions: a) ImportFromClipBoard(const ADataSet:TDataSet); Simply type something like ImportFromClipBoard(MyTable); and this will "paste" the data from a clipboard to your table. b) ImportFromFile(const AFileName:String; ADelimiter:Char; const ADataSet:TDataSet); Simply type something like ImportFromFile('C:\Temp\MyImportFile.TXT',#9, MyTable); and this will import the data from a tab-delimited file to your dataset. You don't care the position of the fields as long as the first row is the header field names. Although my implementation can be faster than a direct file reading, files greater than 4 MB to import, my implementation can become memory resource intensive, a direct file reading line by line coupled with read-ahead buffering at 32KB at a time may be more efficient and a lot faster than my current implementation. c) ImportFromStrings(const AStrings:TStrings; ADelimiter:Char; const ADataSet:TDataSet); you can use this method to import data from a stringlist, as long as element 0 of the list is your header, and you can use any delimiter. In fact my ImportFromClipboard and ImportFromFile methods uses this procedure. There are other numerous applications aside from these. d) ImportFromCSVFile(const AFileName:String; const ADataSet:TDataSet); If your file is CSV (comma separated variable length), simply type something like ImportFromFile('C:\Temp\MyImportFile.CSV', MyTable); and this will import the data from a CSV file to your Dataset. CSV files are commonly produced by Excel. My implementation of CSV import uses two parser functions: GetLeftWord and GetLeftWordCSV. The File is directly opened for read-only and this procedure reads the file line by line and will therefore have no memory constraints compared to the other ImportFromFile method mentioned earlier. e) GetLeftWord(var ASentence:string; ADelimiter:char):string; as the name implies, it gets and removes the left most word from sentence string. This is the parser that I use to break down a line string into individual columns one at a time. f) GetLeftWordCSV(var ASentence:string):string; this is a special parser designed for CSV strings. This is the parser that I use to break down a CSV line string into individual columns one at a time. } procedure ImportFromClipBoard(const ADataSet:TDataSet); procedure ImportFromFile(const AFileName:String; ADelimiter:Char; const ADataSet:TDataSet); procedure ImportFromStrings(const AStrings:TStrings; ADelimiter:Char; const ADataSet:TDataSet); procedure ImportFromCSVFile(const AFileName:String; const ADataSet:TDataSet); function GetLeftWordCSV(var ASentence:string):string; function GetLeftWord(var ASentence:string; ADelimiter:char):string; procedure ExportToClipBoard(G:TDBGrid); function ExportToString(G:TDBGrid):String; implementation function GetLeftWordCSV(var ASentence:string):string; begin Result:=''; ASentence:=Trim(ASentence);// needed to remove spaces and strange chars for CSV if Length(ASentence)=0 then exit; if ASentence[1]='"' then begin Delete(ASentence,1,1); Result:=GetLeftWord(ASentence,'"'); GetLeftWord(ASentence,',');//get rid of comma exit; end; Result:=GetLeftWord(ASentence,','); end; function GetLeftWord(var ASentence:string; ADelimiter:char):string; var i:integer; begin Result := ''; i := Pos(ADelimiter,ASentence); if i = 0 then begin Result := Trim(ASentence); ASentence := ''; exit; end; Result:=trim(Copy(ASentence,1,i-1)); Delete(ASentence,1,i); end; procedure ImportFromStrings(const AStrings:TStrings; ADelimiter:Char; const ADataSet:TDataSet); var i,j,HeaderCount:integer; FldPtr:array[0..255] of TField; aColValue,aLineString:string; HasCommonField:boolean; F:TField; begin {first row must be headers, string list columns should be delimited by a common char } if AStrings.Count < 2 then exit; // nothing to import ALineString:=AStrings[0]; // parse the header HasCommonField:=False; HeaderCount:=0; while (length(ALineString) > 0) and (HeaderCount < 255) do begin aColValue := GetLeftWord(ALineString,ADelimiter); F:=ADataSet.FindField(aColValue); FldPtr[HeaderCount] := F; if F <> nil then HasCommonField:=True; inc(HeaderCount); end; if not HasCommonField then exit; // not a single field found on list for i := 1 to AStrings.Count-1 do begin ALineString := AStrings[i]; j := -1; ADataSet.Append; while (length(ALineString) > 0) and (j < HeaderCount-1) do begin aColValue := GetLeftWord(ALineString,ADelimiter); inc(j); if FldPtr[j] = nil then continue; // skip unmatched columns try FldPtr[j].Text := aColValue; except // simply ignore all data conversion errors // or handle it here as you wish end; end; // while ADataSet.Post; end; // for end; // procedure procedure ImportFromClipBoard(const ADataSet:TDataSet); var AStringList:TStringList; begin AStringList:=TStringList.Create; try AStringList.Text:=ClipBoard.AsText; // Excel's clipboard is tab delimited (#9) ImportFromStrings(AStringList,#9,ADataSet); finally AStringList.Free; end; end; procedure ImportFromFile(const AFileName:String; ADelimiter:Char; const ADataSet:TDataSet); var AStringList:TStringList; begin if not FileExists(AFileName) then exit; AStringList:=TStringList.Create; try AStringList.LoadFromFile(AFileName); ImportFromStrings(AStringList,ADelimiter,ADataSet); finally AStringList.Free; end; end; procedure ImportFromCSVFile(const AFileName:String; const ADataSet:TDataSet); var aTextFile:TextFile; j,HeaderCount:integer; FldPtr:array[0..255] of integer; aColValue,aLineString:string; HasCommonField:boolean; begin if not FileExists(AFileName) then exit; AssignFile(aTextFile,AFileName); Reset(aTextFile); try { first row must be headers } Readln(aTextFile, ALineString); HasCommonField:=False; HeaderCount:=0; while (length(ALineString) > 0) and (HeaderCount < 255) do begin aColValue := GetLeftWordCSV(ALineString); j := ADataSet.FieldDefs.IndexOf(aColValue); FldPtr[HeaderCount] := j; if j > -1 then HasCommonField:=True; inc(HeaderCount); end; if not HasCommonField then exit; // not a single field found on list while not EOF(aTextFile) do begin Readln(aTextFile,ALineString); j := -1; ADataSet.Append; while (length(ALineString) > 0) and (j < HeaderCount-1) do begin aColValue := GetLeftWordCSV(ALineString); inc(j); if FldPtr[j] = -1 then continue; // skip unmatched columns try ADataSet.Fields[FldPtr[j]].AsString := aColValue; except // simply ignore all data conversion errors // or handle it here as you wish end; end; // while ADataSet.Post; end; // for finally CloseFile(aTextFile); end; end; // procedure procedure ExportToClipBoard(G:TDBGrid); begin ClipBoard.Clear; Clipboard.AsText:=ExportToString(G); end; function ExportToString(G:TDBGrid):String; var S:String; J: Integer; F:Array of TField; I,Cnt:Integer; B:String; begin Result:=''; Cnt:=G.Columns.Count; SetLength(F,Cnt); S:=''; for I:=0 to Cnt-1 do begin F[I]:=G.Columns[I].Field; S:=S+F[I].FieldName+#9; end; if S='' then Exit; Delete(S,Length(S),1); S:=S+#13#10; B:=G.DataSource.DataSet.Bookmark; try G.DataSource.DataSet.DisableControls; try G.DataSource.DataSet.First; if G.SelectedRows.Count>0 then begin for J := 0 to G.SelectedRows.Count - 1 do begin G.DataSource.DataSet.BookMark:=G.SelectedRows[J]; for i:=0 to Cnt-1 do S:=S+F[I].Text+#9; Delete(S,Length(S),1); S:=S+#13#10; end; end else while not G.DataSource.DataSet.Eof do begin for i:=0 to Cnt-1 do S:=S+F[I].Text+#9; Delete(S,Length(S),1); S:=S+#13#10; G.DataSource.DataSet.Next; end finally G.DataSource.DataSet.EnableControls; end; finally G.DataSource.DataSet.Bookmark:=B; end; Result:=S; end; end.
unit SaveDocFunc; interface uses Forms, Registry, INIFiles, SysUtils, Variants, Windows, Ora, OracleUniProvider, Uni, DBAccess, MemDS; const C_MACRO_USERHOME = '[USERHOME]'; C_MACRO_NMATTER = '[NMATTER]'; C_MACRO_FILEID = '[FILEID]'; C_MACRO_TEMPDIR = '[TEMPDIR]'; C_MACRO_TEMPFILE = '[TEMPFILE]'; C_MACRO_DATE = '[DATE]'; C_MACRO_TIME = '[TIME]'; C_MACRO_DATETIME = '[DATETIME]'; C_MACRO_CLIENTID = '[CLIENTID]'; C_MACRO_AUTHOR = '[AUTHOR]'; C_MACRO_USERINITIALS = '[USERINITIALS]'; C_MACRO_DOCSEQUENCE = '[DOCSEQUENCE]'; C_MACRO_DOCID = '[DOCID]'; procedure GetUserID; function GetSeqNumber(sSequence: string): Integer; function TableString(Table, LookupField, LookupValue, ReturnField: string): string; overload; function TableInteger(Table, LookupField, LookupValue, ReturnField: string): integer; overload; function ParseMacros(AFileName: String; ANMatter: Integer): String; function SystemString(sField: string): string; function SystemInteger(sField: string): integer; function ProcString(Proc: string; LookupValue: integer): string; function ReportVersion: string; function FormExists(frmInput: TForm): boolean; function TokenizePath(var s,w:string): boolean; function IndexPath(PathText, PathLoc: string): string; implementation uses SaveDoc; var // for macros.. GTempPath, GHomePath: String; procedure GetUserID; var regAxiom: TRegistry; sRegistryRoot: string; LoginUser: string; begin // Find out what registry key we are using { try iniAxiom := TINIFile.Create(ExtractFilePath(Application.EXEName) + '..\Axiom.INI'); except // do nothing end; sRegistryRoot := iniAxiom.ReadString('Main', 'RegistryRoot', 'Software\Colateral\Axiom'); iniAxiom.Free; } sRegistryRoot := 'Software\Colateral\Axiom'; regAxiom := TRegistry.Create; try regAxiom.RootKey := HKEY_CURRENT_USER; if regAxiom.OpenKey(sRegistryRoot+'\InsightDocSave', False) then begin if regAxiom.ReadString('Password') <> '' then begin try if dmSaveDoc.uniInsight.Connected then dmSaveDoc.uniInsight.Disconnect; if regAxiom.ReadString('Net') = 'Y' then dmSaveDoc.uniInsight.SpecificOptions.Values['Direct'] := 'true' else dmSaveDoc.uniInsight.SpecificOptions.Values['Direct'] := 'false'; dmSaveDoc.uniInsight.Server := regAxiom.ReadString('Server Name'); dmSaveDoc.uniInsight.Username := regAxiom.ReadString('User Name'); dmSaveDoc.uniInsight.Password := regAxiom.ReadString('Password'); dmSaveDoc.uniInsight.Connect; except Application.MessageBox('Could not connect to Insight database','DragON'); Application.Terminate; end; end else begin Application.MessageBox('Could not connect to Insight database','DragON'); Application.Terminate; end; regAxiom.CloseKey; regAxiom.RootKey := HKEY_CURRENT_USER; if regAxiom.OpenKey(sRegistryRoot+'\InsightDocSave', False) then begin LoginUser := regAxiom.ReadString('User Name'); with dmSaveDoc.qryEmps do begin Close; SQL.Text := 'SELECT CODE FROM EMPLOYEE WHERE UPPER(USER_NAME) = upper(''' + LoginUser + ''') AND ACTIVE = ''Y'''; Prepare; Open; // Make sure that the UserID is valid if IsEmpty then begin Application.MessageBox('User not valid.','DragON'); Application.Terminate; end else dmSaveDoc.UserID := FieldByName('CODE').AsString; Close; end; dmSaveDoc.qryGetEntity.Close(); dmSaveDoc.qryGetEntity.ParamByName('Emp').AsString := uppercase(dmSaveDoc.UserID); dmSaveDoc.qryGetEntity.ParamByName('Owner').AsString := 'Desktop'; dmSaveDoc.qryGetEntity.ParamByName('Item').AsString := 'Entity'; dmSaveDoc.qryGetEntity.Open(); dmSaveDoc.Entity := dmSaveDoc.qryGetEntity.FieldByName('value').AsString; end; end else begin Application.MessageBox('Could not connect to Insight database','DragON'); Application.Terminate; end; finally regAxiom.Free; end; end; function GetSeqNumber(sSequence: string): Integer; begin with dmSaveDoc.qryTmp do begin Close; SQL.Clear; SQL.Add('SELECT ' + sSequence + '.currval'); SQL.Add('FROM DUAL'); ExecSQL; Result := Fields[0].AsInteger; Close; end; end; function ParseMacros(AFileName: String; ANMatter: Integer): String; var LBfr: Array[0..MAX_PATH] of Char; begin if(GHomePath = '') then GHomePath := GetEnvironmentVariable('HOMEDRIVE') + GetEnvironmentVariable('HOMEPATH'); if(GTempPath = '') then begin GetTempPath(MAX_PATH,Lbfr); GTempPath := String(LBfr); end; Result := AFileName; Result := StringReplace(Result,C_MACRO_USERHOME,GHomePath,[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_TEMPDIR,GTempPath,[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_NMATTER,IntToStr(ANMatter),[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_FILEID, TableString('MATTER','NMATTER',IntToStr(ANMatter),'FILEID'),[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_CLIENTID, TableString('MATTER','NMATTER',IntToStr(ANMatter),'CLIENTID'),[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_DATE,FormatDateTime('dd-mm-yyyy',Now()) ,[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_TIME,FormatDateTime('hh-nn-ss',Now()),[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_DATETIME,FormatDateTime('dd-mm-yyyy-hh-nn-ss',Now()),[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_AUTHOR, TableString('MATTER','NMATTER',IntToStr(ANMatter),'AUTHOR'),[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_DOCSEQUENCE, ProcString('getDocSequence',ANMatter),[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_USERINITIALS, dmSaveDoc.UserID ,[rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result,C_MACRO_DOCID, dmSaveDoc.DocID,[rfReplaceAll, rfIgnoreCase]); if(Pos(C_MACRO_TEMPFILE,Result) > 0) then begin GetTempFileName(PChar(GTempPath),'axm',0,LBfr); Result := StringReplace(Result,C_MACRO_TEMPFILE,String(LBfr),[rfReplaceAll, rfIgnoreCase]); end; end; function TableString(Table, LookupField, LookupValue, ReturnField: string): string; overload; var qryLookup: TUniQuery; begin qryLookup := TUniQuery.Create(nil); qryLookup.Connection := dmSaveDoc.uniInsight; with qryLookup do begin SQL.Text := 'SELECT ' + ReturnField + ' FROM ' + Table + ' WHERE ' + LookupField + ' = :' + LookupField; Params[0].AsString := LookupValue; Open; Result := Fields[0].AsString; Close; end; qryLookup.Free; end; function TableInteger(Table, LookupField, LookupValue, ReturnField: string): integer; overload; var qryLookup: TUniQuery; begin qryLookup := TUniQuery.Create(nil); qryLookup.Connection := dmSaveDoc.uniInsight; with qryLookup do begin SQL.Text := 'SELECT ' + ReturnField + ' FROM ' + Table + ' WHERE ' + LookupField + ' = :' + LookupField; Params[0].AsString := LookupValue; Open; Result := Fields[0].AsInteger; Close; end; qryLookup.Free; end; function SystemString(sField: string): string; begin with dmSaveDoc.qrySysfile do begin SQL.Text := 'SELECT ' + sField + ' FROM SYSTEMFILE'; try Open; SystemString := FieldByName(sField).AsString; Close; except // end; end; end; function SystemInteger(sField: string): integer; begin SystemInteger := 0; with dmSaveDoc.qrySysfile do begin SQL.Text := 'SELECT ' + sField + ' FROM SYSTEMFILE'; try Open; SystemInteger := FieldByName(sField).AsInteger; Close; except // end; end; end; function ProcString(Proc: string; LookupValue: integer): string; begin Result := IntToStr(dmSaveDoc.uniInsight.ExecProc('getDocSequence',[lookupValue])); { with dmSaveDoc.procTemp do begin storedProcName := Proc; Params.Add.DisplayName := 'matterNo'; ParamByName('matterNo').AsInteger := LookupValue; ExecProc; Result := ParamByName('tmpVar').AsString; end; } end; function ReportVersion: string; var wVersionMajor, wVersionMinor, wVersionRelease, wVersionBuild : Word; VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; begin VerInfoSize := GetFileVersionInfoSize(PChar(ParamStr(0)), Dummy); GetMem(VerInfo, VerInfoSize); GetFileVersionInfo(PChar(ParamStr(0)), 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); with VerValue^ do begin wVersionMajor := dwFileVersionMS shr 16; wVersionMinor := dwFileVersionMS and $FFFF; wVersionRelease := dwFileVersionLS shr 16; wVersionBuild := dwFileVersionLS and $FFFF; end; FreeMem(VerInfo, VerInfoSize); ReportVersion := IntToStr(wVersionMajor) + '.' + IntToStr(wVersionMinor) + '.' + IntToStr(wVersionRelease) + '.' + IntToStr(wVersionBuild); end; function FormExists(frmInput : TForm):boolean; var iCount : integer; bResult : boolean; begin bResult := false; for iCount := 0 to (Application.ComponentCount - 1) do if Application.Components[iCount] is TForm then if Application.Components[iCount] = frmInput then bResult:=true; FormExists := bResult; end; function IndexPath(PathText, PathLoc: string): string; var iWords, i: integer; NewPath, sWord, sNewline, AUNCPath: string; LImportFile: array of string; begin AUNCPath := ExpandUNCFileName(PathText); NewPath := SystemString(PathLoc); if NewPath <> '' then begin iWords := 0; SetLength(LImportFile,length(PathText)); sNewline := copy(PathText,3,length(PathText)); while TokenizePath(sNewline ,sWord) do begin LImportFile[iWords] := sWord; inc(iWords); end; for i := 0 to (length(LImportFile) - 1) do begin if LImportFile[i] <> '' then NewPath := NewPath + '/' + LImportFile[i]; end; Result := NewPath; end else Result := AUNCPath; //PathText; end; function TokenizePath(var s,w:string):boolean; {Note that this a "destructive" getword. The first word of the input string s is returned in w and the word is deleted from the input string} const delims:set of char = ['/','\']; var i:integer; begin w:=''; if length(s)>0 then begin i:=1; while (i<length(s)) and (s[i] in delims) do inc(i); delete(s,1,i-1); i:=1; while (i<=length(s)) and (not (s[i] in delims)) do inc(i); w:=copy(s,1,i-1); delete(s,1,i); end; result := (length(w) >0); end; end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUIRadioGroup.pas // Creator : Shen Min // Date : 2002-09-22 V1-V3 // 2003-06-24 V4 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUIRadioGroup; interface {$I SUIPack.inc} uses Windows, Messages, SysUtils, Classes, Controls, ExtCtrls, Forms, Graphics, SUIImagePanel, SUIGroupBox, SUIButton, SUIThemes, SUIMgr; type TsuiCheckGroup = class(TsuiCustomGroupBox) private m_Items : TStrings; m_Buttons : TList; m_Columns : Integer; m_TopMargin : Integer; m_Cursor : TCursor; m_OnClick : TNotifyEvent; procedure ItemChanged(Sender : TObject); procedure SetItems(const Value: TStrings); function UpdateButtons() : Boolean; procedure ArrangeButtons(); procedure SetColumns(const Value: Integer); procedure SetTopMargin(const Value: Integer); function GetChecked(Index: Integer): Boolean; procedure SetChecked(Index: Integer; const Value: Boolean); function GetItemEnabled(Index: Integer): Boolean; procedure SetItemEnabled(Index: Integer; const Value: Boolean); function GetFontColor: TColor; procedure SetFontColor(const Value: TColor); procedure SetCursor2(const Value : TCursor); procedure CMFONTCHANGED(var Msg : TMessage); message CM_FONTCHANGED; procedure WMSetFocus (var Msg: TWMSetFocus); message WM_SETFOCUS; procedure DoClick(Sender : TObject); protected procedure NewClick; virtual; function CreateAButton() : TsuiCheckBox; virtual; procedure ReSize(); override; procedure SetTransparent(const Value: Boolean); override; procedure FocusUpdate(); virtual; public constructor Create(AOwner : TComponent); override; destructor Destroy(); override; procedure UpdateUIStyle(UIStyle : TsuiUIStyle; FileTheme : TsuiFileTheme); override; property Checked[Index: Integer]: Boolean read GetChecked write SetChecked; property ItemEnabled[Index : Integer]: Boolean read GetItemEnabled write SetItemEnabled; published property Items : TStrings read m_Items write SetItems; property Columns : Integer read m_Columns write SetColumns; property TopMargin : Integer read m_TopMargin write SetTopMargin; property FontColor : TColor read GetFontColor write SetFontColor; property BorderColor; property Cursor read m_Cursor write SetCursor2; property OnClick : TNotifyEvent read m_OnClick write m_OnClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnStartDock; property OnStartDrag; end; TsuiRadioGroup = class(TsuiCheckGroup) private procedure SetItemIndex(const Value: Integer); function GetItemIndex: Integer; protected function CreateAButton() : TsuiCheckBox; override; procedure FocusUpdate(); override; function CanModify: Boolean; virtual; published property ItemIndex : Integer read GetItemIndex write SetItemIndex; end; TsuiCheckGroupButton = class(TsuiCheckBox) private m_CheckGroup : TsuiCheckGroup; protected function NeedDrawFocus() : Boolean; override; public constructor Create(AOwner : TComponent; CheckGroup : TsuiCheckGroup); reintroduce; end; TsuiRadioGroupButton = class(TsuiRadioButton) private m_RadioGroup : TsuiRadioGroup; protected function NeedDrawFocus() : Boolean; override; procedure DoClick(); override; public constructor Create(AOwner : TComponent; RadioGroup : TsuiRadioGroup); reintroduce; end; implementation uses SUIPublic; { TsuiCheckGroup } procedure TsuiCheckGroup.ArrangeButtons; var R : TRect; nHeight : Integer; i : Integer; ButtonsPerCol : Integer; ButtonWidth : Integer; ButtonHeight : Integer; TopMargin : Integer; begin if m_Buttons.Count = 0 then Exit; R := GetClient(); R.Top := R.Top + m_TopMargin; nHeight := R.Bottom - R.Top; ButtonsPerCol := (m_Buttons.Count + m_Columns - 1) div m_Columns; ButtonWidth := (Width - 10) div m_Columns; ButtonHeight := nHeight div ButtonsPerCol; TopMargin := R.Top + (nHeight mod ButtonsPerCol) div 2; for i := 0 to m_Buttons.Count - 1 do begin if BidiMode <> bdRightToLeft then TsuiCheckBox(m_Buttons[i]).Left := (i div ButtonsPerCol) * ButtonWidth + 8 else TsuiCheckBox(m_Buttons[i]).Left := Width - (i div ButtonsPerCol) * ButtonWidth - 8 - TsuiCheckBox(m_Buttons[i]).Width; TsuiCheckBox(m_Buttons[i]).Top := (I mod ButtonsPerCol) * ButtonHeight + TopMargin; end; end; constructor TsuiCheckGroup.Create(AOwner: TComponent); begin inherited; m_Items := TStringList.Create(); (m_Items as TStringList).OnChange := ItemChanged; m_Buttons := TList.Create(); m_Columns := 1; m_TopMargin := 8; UIStyle := GetSUIFormStyle(AOwner); Transparent := false; ParentColor := true; TabStop := true; inherited OnClick := DoClick; end; function TsuiCheckGroup.CreateAButton: TsuiCheckBox; begin Result := TsuiCheckGroupButton.Create(self, self); end; destructor TsuiCheckGroup.Destroy; begin m_Buttons.Free(); m_Buttons := nil; m_Items.Free(); m_Items := nil; inherited; end; procedure TsuiCheckGroup.ItemChanged(Sender: TObject); var bRepaint : Boolean; begin bRepaint := UpdateButtons(); ArrangeButtons(); if bRepaint then begin Transparent := not Transparent; Transparent := not Transparent; end; end; procedure TsuiCheckGroup.SetItems(const Value: TStrings); begin m_Items.Assign(Value); end; procedure TsuiCheckGroup.ReSize; begin inherited; ArrangeButtons(); end; function TsuiCheckGroup.UpdateButtons() : Boolean; var i : Integer; nItems : Integer; AButton : TsuiCheckBox; begin Result := false; nItems := m_Items.Count - m_Buttons.Count; if nItems > 0 then begin for i := 1 to nItems do begin AButton := CreateAButton(); AButton.Parent := self; AButton.Font := Font; AButton.AutoSize := true; AButton.FileTheme := FileTheme; AButton.UIStyle := UIStyle; AButton.Transparent := Transparent; AButton.ParentColor := true; AButton.TabStop := false; AButton.OnClick := DoClick; AButton.Cursor := m_Cursor; m_Buttons.Add(AButton); Result := true; end; end else if nItems < 0 then begin for i := 1 to Abs(nItems) do begin TsuiCheckBox(m_Buttons[m_Buttons.Count - 1]).Free(); m_Buttons.Delete(m_Buttons.Count - 1); end; end; for i := 0 to m_Buttons.Count - 1 do begin TsuiCheckBox(m_Buttons[i]).Caption := m_Items[i]; TsuiCheckBox(m_Buttons[i]).AutoSize := true; end; end; procedure TsuiCheckGroup.SetColumns(const Value: Integer); begin if Value < 0 then Exit; m_Columns := Value; ArrangeButtons(); end; function TsuiCheckGroup.GetChecked(Index: Integer): Boolean; begin Result := false; if ( (Index > m_Buttons.Count - 1) or (Index < 0) ) then Exit; Result := TsuiCheckBox(m_Buttons[Index]).Checked; end; procedure TsuiCheckGroup.SetChecked(Index: Integer; const Value: Boolean); begin TsuiCheckBox(m_Buttons[Index]).Checked := Value; end; procedure TsuiCheckGroup.UpdateUIStyle(UIStyle: TsuiUIStyle; FileTheme : TsuiFileTheme); var i : Integer; begin inherited; if m_Buttons = nil then Exit; for i := 0 to m_Buttons.Count - 1 do begin TsuiCheckBox(m_Buttons[i]).FileTheme := FileTheme; TsuiCheckBox(m_Buttons[i]).UIStyle := UIStyle; TsuiCheckBox(m_Buttons[i]).Color := Color; end; end; procedure TsuiCheckGroup.SetTransparent(const Value: Boolean); var i : Integer; begin inherited; if m_Buttons = nil then Exit; for i := 0 to m_Buttons.Count - 1 do TsuiCheckBox(m_Buttons[i]).Transparent := Value; end; procedure TsuiCheckGroup.DoClick(Sender: TObject); begin NewClick(); if csLoading in ComponentState then Exit; if Assigned(m_OnClick) then m_OnClick(self); end; procedure TsuiCheckGroup.SetTopMargin(const Value: Integer); begin if Value < 0 then Exit; m_TopMargin := Value; ArrangeButtons(); end; procedure TsuiCheckGroup.NewClick; begin end; procedure TsuiCheckGroup.CMFONTCHANGED(var Msg: TMessage); var i : Integer; begin inherited; if m_Buttons = nil then Exit; for i := 0 to m_Buttons.Count - 1 do TsuiCheckBox(m_Buttons[i]).Font.Assign(Font); end; function TsuiCheckGroup.GetFontColor: TColor; begin Result := Font.Color; end; procedure TsuiCheckGroup.SetFontColor(const Value: TColor); begin Font.Color := Value; end; function TsuiCheckGroup.GetItemEnabled(Index: Integer): Boolean; begin Result := false; if ( (Index > m_Buttons.Count - 1) or (Index < 0) ) then Exit; Result := TsuiCheckBox(m_Buttons[Index]).Enabled; end; procedure TsuiCheckGroup.SetItemEnabled(Index: Integer; const Value: Boolean); begin TsuiCheckBox(m_Buttons[Index]).Enabled := Value; end; procedure TsuiCheckGroup.WMSetFocus(var Msg: TWMSetFocus); begin inherited; FocusUpdate(); end; procedure TsuiCheckGroup.FocusUpdate; begin if Items.Count = 0 then Exit; if TsuiCheckBox(m_Buttons[0]).CanFocus() then TsuiCheckBox(m_Buttons[0]).SetFocus(); end; procedure TsuiCheckGroup.SetCursor2(const Value: TCursor); var i : Integer; begin for i := 0 to m_Buttons.Count - 1 do TsuiCheckBox(m_Buttons[i]).Cursor := Value; m_Cursor := Value; end; { TsuiRadioGroup } function TsuiRadioGroup.CanModify: Boolean; begin Result := true; end; function TsuiRadioGroup.CreateAButton: TsuiCheckBox; begin Result := TsuiRadioGroupButton.Create(self, self); end; procedure TsuiRadioGroup.FocusUpdate; begin if (ItemIndex < 0) or (ItemIndex >= Items.Count) then Exit; TsuiCheckBox(m_Buttons[ItemIndex]).SetFocus; end; function TsuiRadioGroup.GetItemIndex: Integer; var i : Integer; begin Result := -1; for i := 0 to m_Buttons.Count - 1 do begin if TsuiRadioButton(m_Buttons[i]).Checked then begin Result := i; break; end; end; end; procedure TsuiRadioGroup.SetItemIndex(const Value: Integer); var i : Integer; begin if Value > m_Items.Count - 1 then Exit; if Value < -1 then Exit; if Value >= 0 then TsuiRadioButton(m_Buttons[Value]).Checked := true else // -1 begin for i := 0 to m_Buttons.Count - 1 do TsuiRadioButton(m_Buttons[i]).Checked := false; end; end; { TsuiRadioGroupButton } constructor TsuiRadioGroupButton.Create(AOwner : TComponent; RadioGroup: TsuiRadioGroup); begin inherited Create(AOwner); m_RadioGroup := RadioGroup; end; procedure TsuiRadioGroupButton.DoClick; begin if (Parent as TsuiRadioGroup).CanModify then inherited; end; function TsuiRadioGroupButton.NeedDrawFocus: Boolean; begin Result := (m_RadioGroup.Focused or Focused) and Checked; end; { TsuiCheckGroupButton } constructor TsuiCheckGroupButton.Create(AOwner: TComponent; CheckGroup: TsuiCheckGroup); begin inherited Create(AOwner); m_CheckGroup := CheckGroup; end; function TsuiCheckGroupButton.NeedDrawFocus: Boolean; begin Result := Focused; end; end.
unit oData.GenScript.Typescript; interface uses System.Classes, System.SysUtils; implementation uses oData.GenScript, oData.ServiceModel, System.Json; function GerarNg5Script: string; var str: TStringList; serv: TJsonArray; it: TJsonValue; AResource: string; AMethod: string; begin str := TStringList.create; with str do try add('/// <summary> '); add('/// ODataBr - Generate NG5 Script '); add('/// Date: ' + DateTimeToStr(now) + ' '); add('/// Auth: amarildo lacerda - tireideletra.com.br '); add('/// gerado pelo Servidor ODataBr: .../OData/hello/ng '); add('/// </summary> '); add(''); add('import { Injectable, Inject } from ''@angular/core'';'); add('import { HttpClient, HttpHeaders } from ''@angular/common/http'';'); add('import { ODataProviderService,ODataFactory,ODataService } from ''./odata-provider.service'';'); add('import { Observable } from ''rxjs/Rx'';'); add(''); add('export interface ODataBrQuery extends ODataService{} '); add(''); add('@Injectable()'); add('export class ODataBrProvider {'); add(' token:string=""; '); add(' urlBase:string=""; '); add(' urlPort:number = 8080; '); add(' headers: HttpHeaders;'); add(''); add(' port(aPort:number):ODataBrProvider{'); add(' this.urlPort = aPort;'); add(' return this;'); add(' } '); add(' url(aUrl:string):ODataBrProvider{'); add(' this.urlBase = aUrl;'); add(' return this;'); add(' }'); add(''); add(' getJson(url:string):Observable<any>{'); add(' this.configOptions();'); add(' return this._odata.getJson(url);'); add(' }'); add(' getOData(query:ODataService):ODataProviderService{'); add(' this.configOptions();'); add(' return this._odata.getValue(query);'); add(' }'); add(' private configOptions(){ '); add(' if (this.token!="") { this._odata.token = this.token; }; '); add(' this._odata.createUrlBase(this.urlBase,this.urlPort); '); add(' if (this.headers.keys().length>0) {'); add(' //this._odata.headers.clear;'); add(' for(let item of this.headers.keys() ){ '); add(' this._odata.headers.set(item,this.headers.get(item));'); add(' }'); add(' }'); add(' }'); add(''); add('constructor(private _odata:ODataProviderService ) {'); add(' this.headers = new HttpHeaders(); '); add('}'); add('getItem(query: ODataBrQuery): ODataProviderService {'); add(' this.configOptions();'); add(' return this._odata.getValue(query);'); add('}'); add('postItem(resource: string, item: any, erroProc: any = null): Observable<any> {'); add(' this.configOptions();'); add(' return this._odata.postItem(resource, item, erroProc);'); add('}'); add(''); add('putItem(resource: string, item: any, erroProc: any = null): Observable<any> {'); add(' this.configOptions();'); add(' return this._odata.putItem(resource, item, erroProc);'); add('}'); add(''); add('deleteItem(resource: string, item: any, erroProc: any = null): Observable<any> {'); add(' this.configOptions();'); add(' return this._odata.deleteItem(resource, item, erroProc);'); add('}'); add(''); add('patchItem(resource: string, item: any, erroProc: any = null): Observable<any> {'); add(' this.configOptions();'); add(' return this._odata.patchItem(resource, item, erroProc);'); add('}'); if TODataServices.TryGetODataService(ODataServices.LockJson, serv) then try for it in serv do if it.TryGetValue<string>('resource', AResource) then if it.TryGetValue<string>('method', AMethod) then begin if AMethod.Contains('GET') then begin add(' get_' + AResource + '( query:ODataBrQuery ):ODataProviderService { '); add(' this.configOptions(); '); add(' query.resource = "' + AResource + '"+(query.join?query.join:"");'); add(' return this._odata.getValue( query ); '); add(' }'); add(''); end; if AMethod.Contains('PUT') then begin add(' put_' + AResource + '( item: any, erroProc:any=null): Observable<any> { '); add(' this.configOptions(); '); add(' return this._odata.putItem("' + AResource + '", item, erroProc ); '); add(' }'); add(''); end; if AMethod.Contains('POST') then begin add(' post_' + AResource + '( item: any, erroProc:any=null): Observable<any> { '); add(' this.configOptions(); '); add(' return this._odata.postItem("' + AResource + '", item, erroProc ); '); add(' }'); add(''); end; if AMethod.Contains('PATCH') then begin add(' patch_' + AResource + '( item: any, erroProc:any=null): Observable<any> { '); add(' this.configOptions(); '); add(' return this._odata.patchItem("' + AResource + '", item, erroProc ); '); add(' }'); add(''); end; if AMethod.Contains('DELETE') then begin add(' delete_' + AResource + '( item: any, erroProc:any=null): Observable<any> { '); add(' this.configOptions(); '); add(' return this._odata.deleteItem("' + AResource + '", item, erroProc ); '); add(' }'); add(''); end; end; finally ODataServices.UnlockJson; end; add('}'); result := str.text; finally str.free; end; end; initialization TODataGenScript.register('ng', GerarNg5Script); end.
unit PascalCoin.FMX.Frame.Keys; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FMX.Controls.Presentation, PascalCoin.Wallet.Interfaces, FMX.ScrollBox, FMX.Memo, PascalCoin.FMX.Frame.Base, System.ImageList, FMX.ImgList, FrameStand, PascalCoin.Frame.NewKey; type TKeysFrame = class(TBaseFrame) Layout1: TLayout; StateLabel: TLabel; KeyListBox: TListBox; KeyListLayout: TLayout; KeyNameLabel: TLabel; KeyTypeLabel: TLabel; PublicKeyLabel: TLabel; KeyNameValue: TLabel; KeyTypeValue: TLabel; PublicKeyValue: TMemo; NameLayout: TLayout; KeyTypeLayout: TLayout; PublicKeyLayout: TLayout; ButtonsLayout: TLayout; KeyImages: TImageList; PasswordButton: TButton; NewKeyButton: TButton; ImportWalletButton: TButton; BackupWalletButton: TButton; KeyDeleteButton: TButton; ChangeKeyNameButton: TButton; CopyPublicKeyBtn: TButton; FrameStandKeys: TFrameStand; Button1: TButton; procedure Button1Click(Sender: TObject); procedure ChangeKeyNameButtonClick(Sender: TObject); procedure CopyPublicKeyBtnClick(Sender: TObject); procedure KeyListBoxItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); procedure NewKeyButtonClick(Sender: TObject); procedure PasswordButtonClick(Sender: TObject); private FCanCopy: Boolean; FSelectedIndex: Integer; FSelectedKey: IWalletKey; FNewKeyInfo: TFrameInfo<TNewKeyFrame>; procedure CheckCopyFunction; procedure ChangeKeyName(const NewName: string); procedure SetPasswordButtonText; procedure SetSelectedIndex(const Value: Integer); procedure SetSelectedKey(const Value: IWalletKey); procedure UpdateSelectKeyDisplay; procedure OnLockChange(const ALockState: Boolean); protected property SelectedIndex: Integer read FSelectedIndex write SetSelectedIndex; property SelectedKey: IWalletKey read FSelectedKey write SetSelectedKey; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure InitialiseFrame; override; end; implementation {$R *.fmx} uses FMX.Platform, PascalCoin.FMX.DataModule, PascalCoin.ResourceStrings, PascalCoin.FMX.Wallet.Shared, PascalCoin.FMX.Strings, FMX.DialogService; procedure TKeysFrame.ChangeKeyName(const NewName: string); begin if NewName = '' then begin TDialogService.ShowMessage(SYouHavenTEneteredAName); Exit; end; if NewName = FSelectedKey.Name then begin TDialogService.ShowMessage(SThisIsTheSameAsTheExistingName); Exit; end; SelectedKey.Name := NewName; MainDataModule.Wallet.SaveToStream; UpdateSelectKeyDisplay; KeyListBox.BeginUpdate; KeyListBox.ListItems[FSelectedIndex].Text := FSelectedKey.Name + ' (' + cStateText[FSelectedKey.State] + ')'; KeyListBox.EndUpdate; end; procedure TKeysFrame.ChangeKeyNameButtonClick(Sender: TObject); var lNewName: string; begin TDialogService.InputQuery('Rename Key', ['New Name'], [lNewName], procedure(const AResult: TModalResult; const AValues: array of string) var aName: string; begin if (AResult <> mrOK) or (Length(AValues) = 0) then Exit; aName := AValues[0].Trim; ChangeKeyName(aName); end); end; procedure TKeysFrame.CheckCopyFunction; var Svc: IFMXClipboardService; begin FCanCopy := TPlatformServices.Current.SupportsPlatformService (IFMXClipboardService, Svc); end; procedure TKeysFrame.CopyPublicKeyBtnClick(Sender: TObject); var Svc: IFMXClipboardService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, Svc) then begin Svc.SetClipboard(PublicKeyValue.Text); WriteToStatusBar(SPublicKeyCopiedToClipboard); end; end; constructor TKeysFrame.Create(AOwner: TComponent); begin inherited; MainDataModule.Wallet.OnLockChange.Add(OnLockChange); CheckCopyFunction; ChangeKeyNameButton.Enabled := False; SetPasswordButtonText; end; destructor TKeysFrame.Destroy; begin MainDataModule.Wallet.OnLockChange.Remove(OnLockChange); inherited; end; procedure TKeysFrame.Button1Click(Sender: TObject); begin ShowMessage(SelectedKey.PublicKey.AsHexStr); end; { TFrame1 } procedure TKeysFrame.InitialiseFrame; var I: Integer; begin inherited; KeyListBox.Clear; StateLabel.Text := yourWalletIs + ' ' + cStateText [MainDataModule.Wallet.State]; for I := 0 to MainDataModule.Wallet.Count - 1 do begin KeyListBox.Items.Add(MainDataModule.Wallet[I].Name + ' (' + cStateText [MainDataModule.Wallet[1].State] + ')'); end; SelectedKey := nil; end; procedure TKeysFrame.KeyListBoxItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); begin SelectedIndex := Item.Index; end; procedure TKeysFrame.NewKeyButtonClick(Sender: TObject); begin FNewKeyInfo := FrameStandKeys.New<TNewKeyFrame>(KeyListLayout); FNewKeyInfo.Frame.OnCancel := procedure begin FNewKeyInfo.Hide(250, procedure begin FNewKeyInfo.Close; FNewKeyInfo := nil; end); end; FNewKeyInfo.Frame.OnCreateKey := procedure(Value: Integer) var lKey: IWalletKey; I: Integer; begin lKey := MainDataModule.Wallet[Value]; I := KeyListBox.Items.Add(lKey.Name + ' (' + cStateText [lKey.State] + ')'); Assert(I = Value, 'Key index doesn''t match'); KeyListBox.ItemIndex := I; FNewKeyInfo.Hide(250, procedure begin FNewKeyInfo.Close; FNewKeyInfo := nil; end); end; FNewKeyInfo.Show(); end; procedure TKeysFrame.OnLockChange(const ALockState: Boolean); begin end; procedure TKeysFrame.PasswordButtonClick(Sender: TObject); var lOk, lExit: Boolean; Password1, Password2: string; lInitialState: TEncryptionState; begin if not MainDataModule.TryUnlock then begin ShowMessage(SPleaseUnlockYourWalletFirst); Exit; end; lOk := False; lExit := False; repeat TDialogService.InputQuery('New Password', ['Password', 'Repeat Password'], [Password1, Password2], procedure(const AResult: TModalResult; const AValues: array of string) begin if AResult = mrOK then begin Password1 := AValues[0]; Password2 := AValues[1]; if Password1 <> Password2 then ShowMessage('Passwords do not match') else if Password1.StartsWith(' ') then ShowMessage('Passwords cannot start with a space') else if Password1.EndsWith(' ') then ShowMessage('Passwords cannot end with a space') else lOk := True; end else lExit := True; end); if lExit then Exit; until lOk; lInitialState := MainDataModule.Wallet.State; if MainDataModule.Wallet.ChangePassword(Password1) then begin if lInitialState = esPlainText then ShowMessage(SYourWalletHasBeenEncrypted) else ShowMessage(SYourPasswordHasBeenChanged) end else begin if lInitialState = esPlainText then ShowMessage(SItHasBeenNotPossibleToEncryptYou) else ShowMessage(SItHasNotBeenPossibleToChangeYour) end; end; procedure TKeysFrame.SetPasswordButtonText; begin case MainDataModule.Wallet.State of esPlainText: PasswordButton.Text := SSetAPassword; esEncrypted, esDecrypted: PasswordButton.Text := SChangeYourPassword; end; end; procedure TKeysFrame.SetSelectedIndex(const Value: Integer); begin FSelectedIndex := Value; if FSelectedIndex > -1 then SelectedKey := MainDataModule.Wallet[FSelectedIndex] else SelectedKey := nil; end; procedure TKeysFrame.SetSelectedKey(const Value: IWalletKey); begin FSelectedKey := Value; if FSelectedKey <> nil then begin UpdateSelectKeyDisplay; CopyPublicKeyBtn.Enabled := FCanCopy; ChangeKeyNameButton.Enabled := True; KeyDeleteButton.Enabled := True; end else begin KeyNameValue.Text := ''; KeyTypeValue.Text := ''; PublicKeyValue.ClearContent; CopyPublicKeyBtn.Enabled := False; ChangeKeyNameButton.Enabled := False; KeyDeleteButton.Enabled := False; end; end; procedure TKeysFrame.UpdateSelectKeyDisplay; begin KeyNameValue.Text := SelectedKey.Name; KeyTypeValue.Text := SelectedKey.PublicKey.KeyTypeAsStr; PublicKeyValue.ClearContent; PublicKeyValue.Text := SelectedKey.PublicKey.AsBase58; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC PostgreSQL API wrapping classes } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.PGWrapper; interface uses {$IFDEF MSWINDOWS} Winapi.Windows, {$ENDIF} System.Types, System.Classes, System.SysUtils, System.Math, Data.FmtBCD, FireDAC.Stan.Intf, FireDAC.Stan.Error, FireDAC.Stan.Option, FireDAC.Stan.Util, FireDAC.Phys.PGCli; type TPgLib = class; TPgObject = class; TFDPgError = class; EPgNativeException = class; TPgEnv = class; TPgMember = class; TPgType = class; TPgTypesManager = class; TPgConnection = class; TPgVariable = class; TPgVariableClass = class of TPgVariable; TPgVariables = class; TPgParam = class; TPgParams = class; TPgField = class; TPgFields = class; TPgStatement = class; TPgLargeObject = class; TPgLargeObjectStream = class; TPgBrand = (pbRegular, pbEnterprise); TPgLib = class(TFDLibrary) private FBrand: TPgBrand; protected procedure LoadEntries; override; public FPQconnectdb: TPQconnectdb; FPQfinish: TPQfinish; FPQreset: TPQreset; FPQserverVersion: TPQserverVersion; FPQprotocolVersion: TPQprotocolVersion; FPQstatus: TPQstatus; FPQerrorMessage: TPQerrorMessage; FPQparameterStatus: TPQparameterStatus; FPQtransactionStatus: TPQtransactionStatus; FPQsetClientEncoding: TPQsetClientEncoding; FPQclientEncoding: TPQclientEncoding; Fpg_encoding_to_char: Tpg_encoding_to_char; FPQexec: TPQexec; FPQexecParams: TPQexecParams; FPQprepare: TPQprepare; FPQexecPrepared: TPQexecPrepared; FPQresultStatus: TPQresultStatus; FPQresultErrorMessage: TPQresultErrorMessage; FPQresultErrorField: TPQresultErrorField; FPQclear: TPQresultStatus; FPQntuples: TPQntuples; FPQnfields: TPQnfields; FPQfname: TPQfname; FPQftable: TPQftable; FPQftablecol: TPQftablecol; FPQfformat: TPQfformat; FPQftype: TPQftype; FPQfmod: TPQfmod; FPQfsize: TPQfsize; FPQgetvalue: TPQgetvalue; FPQgetisnull: TPQgetisnull; FPQgetlength: TPQgetlength; FPQnparams: TPQnparams; FPQparamtype: TPQparamtype; FPQcmdStatus: TPQcmdStatus; FPQoidValue: TPQoidValue; FPQoidStatus: TPQoidStatus; FPQcmdTuples: TPQcmdTuples; FPQsetNoticeReceiver: TPQsetNoticeReceiver; FPQgetCancel: TPQgetCancel; FPQfreeCancel: TPQfreeCancel; FPQcancel: TPQcancel; FPQputCopyData: TPQputCopyData; FPQputCopyEnd: TPQputCopyEnd; //lo support Flo_creat: Tlo_creat; Flo_open: Tlo_open; Flo_write: Tlo_write; Flo_read: Tlo_read; Flo_lseek: Tlo_lseek; Flo_tell: Tlo_tell; Flo_close: Tlo_close; Flo_unlink: Tlo_unlink; Flo_truncate: Tlo_truncate; FPQgetResult: TPQgetResult; FPQnotifies: TPQnotifies; FPQfreemem: TPQfreemem; FPQconsumeInput: TPQconsumeInput; FPQsocket: TPQsocket; FPQexecBulkPrepared: TPQexecBulkPrepared; FPQencryptPassword: TPQencryptPassword; FPQencryptPasswordConn: TPQencryptPasswordConn; constructor Create(AOwningObj: TObject = nil); procedure Load(const AVendorHome, AVendorLib: String); property Brand: TPgBrand read FBrand; end; TPgObject = class(TObject) private FEnv: TPgEnv; [weak] FOwningObj: TObject; function GetLib: TPgLib; inline; protected procedure DoError(const AMessage: String; AStatus: Integer); public constructor Create(AEnv: TPgEnv; AOwningObj: TObject); property Env: TPgEnv read FEnv; property Lib: TPgLib read GetLib; property OwningObj: TObject read FOwningObj; end; TFDPgError = class(TFDDBError) private FSeverity: String; FErrorCode: String; FDetailedMessage: String; FHint: String; FPosition: Integer; FInternalPosition: Integer; FInternalQuery: String; FContext: String; FSchemaName: String; FTableName: String; FColumnName: String; FTypeName: String; FConstraintName: String; FSourceFile: String; FSourceLine: Integer; FSourceFunction: String; protected procedure Assign(ASrc: TFDDBError); override; procedure LoadFromStorage(const AStorage: IFDStanStorage); override; procedure SaveToStorage(const AStorage: IFDStanStorage); override; public property Severity: String read FSeverity; property ErrorCode: String read FErrorCode; property DetailedMessage: String read FDetailedMessage; property Hint: String read FHint; property Position: Integer read FPosition; property InternalPosition: Integer read FInternalPosition; property InternalQuery: String read FInternalQuery; property Context: String read FContext; property SchemaName: String read FSchemaName; property TableName: String read FTableName; property ColumnName: String read FColumnName; property TypeName: String read FTypeName; property ConstraintName: String read FConstraintName; property SourceFile: String read FSourceFile; property SourceLine: Integer read FSourceLine; property SourceFunction: String read FSourceFunction; end; EPgNativeException = class(EFDDBEngineException) private function GetErrors(AIndex: Integer): TFDPgError; protected function GetErrorClass: TFDDBErrorClass; override; public function AppendError(const ADetailedMessage: String): TFDDBError; overload; function AppendError(const ASeverity, AErrorCode, AMessage, ADetailedMessage, AHint: String; APosition, AInternalPosition: Integer; const AInternalQuery, AContext, ASchemaName, ATableName, AColumnName, ATypeName, AConstraintName, ASourceFile: String; ASourceLine: Integer; const ASourceFunction: String): TFDDBError; overload; /// <summary> Use the Errors property to get access to an error item from /// the collection of errors, associated with this exception object. </summary> property Errors[Index: Integer]: TFDPgError read GetErrors; default; end; TPgEnv = class(TObject) private FLib: TPgLib; [weak] FOwningObj: TObject; {$IFDEF FireDAC_MONITOR} FMonitor: IFDMoniClient; FTracing: Boolean; function GetTracing: Boolean; {$ENDIF} public constructor Create(ALib: TPgLib; AOwningObj: TObject); {$IFDEF FireDAC_MONITOR} procedure Trace(const AMsg: String; const AArgs: array of const); overload; procedure Trace(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep; const AMsg: String; const AArgs: array of const); overload; property Tracing: Boolean read FTracing write FTracing; property Monitor: IFDMoniClient read FMonitor write FMonitor; {$ENDIF} property Lib: TPgLib read FLib; property OwningObj: TObject read FOwningObj; end; TPgMember = class(TObject) private FName: String; FOid: Oid; FRef: TPgType; FLen: Integer; FPrec: Integer; FScale: Integer; FAttrs: TFDDataAttributes; public constructor Create; property Name: String read FName; property TypeOid: Oid read FOid; property TypeRef: TPgType read FRef; property Len: Integer read FLen; property Prec: Integer read FPrec; property Scale: Integer read FScale; property Attrs: TFDDataAttributes read FAttrs; end; TPgTypeAttrs = set of (paString, paFixed, paBlob, paOID, paArray, paRecord, paEnum, paRange, paCast); TPgMembers = array of TPgMember; TPgEnums = array of String; TPgType = class(TObject) private FId: Oid; FName: String; FFixedLen: Integer; FFDSize: Integer; FPgSize: Integer; FAttrs: TPgTypeAttrs; FMembers: TPgMembers; FEnums: TFDStringList; function GetIsFlatFixedArray: Boolean; function GetEnums: TFDStringList; public destructor Destroy; override; function DumpType: String; function GetEnumValue(AOid: Oid): String; property Id: Oid read FId; property Name: String read FName; property FixedLen: Integer read FFixedLen; // property PGSize: Integer read FPGSize; property FDSize: Integer read FFDSize; property Attrs: TPgTypeAttrs read FAttrs; property Members: TPgMembers read FMembers; property IsFlatFixedArray: Boolean read GetIsFlatFixedArray; property Enums: TFDStringList read GetEnums; end; TPgTypesManager = class(TObject) private [weak] FConnection: TPgConnection; FTypes: TFDObjList; FLastType: TPgType; procedure DescribeError(const AId, AReason: String); function AddBase(AId: OID; const AName: String; AFixedLen, APGSize, AFDSize: Integer; AAttrs: TPgTypeAttrs): TPgType; function AddArray(AId: OID; const AName: String; ABaseOid: OID; AFixedLen: Integer = 0): TPgType; function FindType(AId: OID; AExact: Boolean): Integer; procedure AddType(AType: TPgType); function Describe(AOid: OID): TPgType; procedure Connected; function GetTypes(AOid: OID): TPgType; function GetArrays(AMemberOid: OID): TPgType; public constructor Create(AConnection: TPgConnection); destructor Destroy; override; class procedure GetDefaults(AFormat: Integer; ATypeOid: Oid; out ALen, APrec, AScale: Integer); static; class procedure DecodeModifier(ATypeOid: Oid; AModifier: Integer; out ALen, APrec, AScale: Integer); static; function TypeByName(const AName: String): TPgType; property Types[AOid: OID]: TPgType read GetTypes; property Arrays[AMemberOid: OID]: TPgType read GetArrays; end; TPgConnectionNotifyEvent = procedure (const AName: String; AProcID: Integer; const AParameter: String) of object; TPgConnection = class(TPgObject) private FOwnHandle: Boolean; FBuffer: TFDBuffer; FEncoder: TFDEncoder; FNotices: EPgNativeException; FPStmtIDCounter: PInteger; FDefaultNoticeReceiver: TPQnoticeReceiver; FTypesManager: TPgTypesManager; FIntegerDateTimes: Integer; FServerVersion: TFDVersion; FLastInsertOid: Oid; FOnNotify: TPgConnectionNotifyEvent; FTimeZoneOffset: Integer; FUnknownFormat: OID; procedure Check; procedure ReadResultError(AHandle: PPGresult; AException: EPgNativeException); procedure CheckResult(AHandle: PPGresult; AOwningObj: TObject); procedure ClearNotices; procedure DoNoticeReceive(AHandle: PPGresult); function GetParameterStatus(const AParam: String): String; function GetTransactionStatus: Integer; function GetServerVersion: TFDVersion; function GetSERVER_VERSION: String; function GetClientEncoding: String; procedure SetClientEncoding(const AValue: String); function GenerateName: String; function GetSERVER_ENCODING: String; function GetCLIENT_ENCODING: String; function GetIS_SUPERUSER: String; function GetSESSION_AUTHORIZATION: String; function GetDATESTYLE: String; function GetINTEGER_DATETIMES: String; function GetTIMEZONE: String; function GetSTANDARD_CONFORMING_STRINGS: String; function GetIntegerDateTimes: Boolean; public FHandle: PPGconn; FStmtIDCounter: Integer; constructor Create(AEnv: TPgEnv; AOwningObj: TObject); constructor CreateUsingHandle(AEnv: TPgEnv; AHandle: PPGconn; APStmtIDCounter: PInteger; AOwningObj: TObject); destructor Destroy; override; procedure Connect(const AConnStr: String); procedure Disconnect; procedure ExecuteQuery(ASQL: String); procedure Abort; function CheckForInput: Boolean; function ReadNotifies(out AName: String; out AProcID: Integer; out AParameter: String): Boolean; function EncryptPassword(const APassword, AUser, AAlgorythm: String): String; // R/O property TypesManager: TPgTypesManager read FTypesManager; property Encoder: TFDEncoder read FEncoder; property Notices: EPgNativeException read FNotices; property LastInsertOid: Oid read FLastInsertOid; // server info property ServerVersion: TFDVersion read GetServerVersion; property TransactionStatus: Integer read GetTransactionStatus; property IntegerDateTimes: Boolean read GetIntegerDateTimes; // parameter status property SERVER_VERSION: String read GetSERVER_VERSION; property SERVER_ENCODING: String read GetSERVER_ENCODING; property CLIENT_ENCODING: String read GetCLIENT_ENCODING; property IS_SUPERUSER: String read GetIS_SUPERUSER; property SESSION_AUTHORIZATION: String read GetSESSION_AUTHORIZATION; property DATESTYLE: String read GetDATESTYLE; property INTEGER_DATETIMES: String read GetINTEGER_DATETIMES; property TIMEZONE: String read GetTIMEZONE; property STANDARD_CONFORMING_STRINGS: String read GetSTANDARD_CONFORMING_STRINGS; // R/W property ClientEncoding: String read GetClientEncoding write SetClientEncoding; property TimeZoneOffset: Integer read FTimeZoneOffset write FTimeZoneOffset default 0; property UnknownFormat: OID read FUnknownFormat write FUnknownFormat default 0; property OnNotify: TPgConnectionNotifyEvent read FOnNotify write FOnNotify; end; TPgVariable = class(TObject) private [weak] FOwner: TPgVariables; [weak] FStatement: TPgStatement; FIndex: Integer; FTypeOid: Oid; FTypeRef: TPgType; FFormat: Integer; FEncoding: TFDEncoding; FDumpLabel: String; function Pg2FDData(AType: TPgType; ASource: Pointer; ASourceLen: Integer; var ADest: Pointer; var ADestLen: LongWord; AByRef: Boolean): Boolean; function FD2PgData(AType: TPgType; ASource: Pointer; ASourceLen: Integer; var ADest: Pointer; var ADestLen: LongWord; var ADestFormat: Integer; AByRef: Boolean): Boolean; procedure CheckArrayBounds(AValue, ALBound, AHBound: Integer); {$IFDEF FireDAC_MONITOR} function DumpSQLDataType: String; function DumpFDValue(ABuffer: Pointer; ALen: Integer): String; {$ENDIF} protected procedure SetTypeOid(AValue: Oid); virtual; procedure AllocBuffer(ASize: LongWord); virtual; function GetDumpLabel: String; virtual; public constructor Create(AOwner: TPgVariables); virtual; property Statement: TPgStatement read FStatement; property Owner: TPgVariables read FOwner; property TypeRef: TPgType read FTypeRef; property TypeOid: Oid read FTypeOid write SetTypeOid; property DumpLabel: String read GetDumpLabel write FDumpLabel; property Encoding: TFDEncoding read FEncoding write FEncoding; end; TPgVariables = class(TObject) private FList: TFDObjList; [weak] FStatement: TPgStatement; function Add: TPgVariable; function GetCount: Integer; inline; protected function GetVariableClass: TPgVariableClass; virtual; abstract; procedure SetCount(AValue: Integer); virtual; public constructor Create(AOwner: TPgStatement); overload; destructor Destroy; override; property Count: Integer read GetCount write SetCount; property Statement: TPgStatement read FStatement; end; TPgParam = class(TPgVariable) private FSize: LongWord; // string size FBufferSize: LongWord; FDataSize: LongWord; // data size FValueSize: LongWord; // size of current value FBuffer: Pointer; FValueRef: Pointer; FIsNull: Boolean; FHBound, FLBound: Integer; FArrayIndex: Integer; procedure SetArrayIndex(AValue: Integer); procedure FreeBuffer; procedure CheckBuffer; procedure PackBuffer; {$IFDEF FireDAC_MONITOR} function DumpValue: String; {$ENDIF} protected procedure SetTypeOid(AValue: Oid); override; procedure AllocBuffer(ASize: LongWord); override; public constructor Create(AOwner: TPgVariables); override; destructor Destroy; override; procedure SetData(ApData: Pointer; ALen: LongWord; AByRef: Boolean = False); procedure SetArrayBounds(ALBound, AHBound: Integer); property Size: LongWord read FSize write FSize; property ArrayIndex: Integer read FArrayIndex write SetArrayIndex; end; TPgParams = class(TPgVariables) private FValueTypes: POid; FValueRefs: PPointer; FValueLengths: PInteger; FValueFormats: PInteger; function GetItems(AIndex: Integer): TPgParam; protected function GetVariableClass: TPgVariableClass; override; procedure SetCount(AValue: Integer); override; function GetValueTypes: Pointer; function GetValueRefs: Pointer; function GetValueLengths: Pointer; function GetValueFormats: Pointer; public property Items[Index: Integer]: TPgParam read GetItems; default; end; TPgField = class(TPgVariable) private FName: String; FTableOid: Oid; FTableCol: Integer; FLen: Integer; FPrec: Integer; FScale: Integer; FArrayIndex: Integer; FFields: TPgFields; function GetPgData(out APgData: Pointer; out APgDataLen: Integer): Boolean; procedure GetArrayInfo(ApData: Pointer; out ALBound, AHBound: Integer; out AClosed: Boolean; out ApFirstElem: Pointer); procedure SetArrayIndex(const AValue: Integer); function GetParentField: TPgField; inline; procedure SetDefaults; protected procedure SetTypeOid(AValue: Oid); override; function GetDumpLabel: String; override; {$IFDEF FireDAC_MONITOR} function DumpValue: String; {$ENDIF} public constructor Create(AOwner: TPgVariables); override; destructor Destroy; override; function GetData(var ApData: Pointer; var ALen: LongWord; AByRef: Boolean): Boolean; overload; function GetData(ApData: Pointer; var ALen: LongWord): Boolean; overload; inline; function GetData(ApData: Pointer): Boolean; overload; inline; function GetAsString: String; function GetArrayBounds(out ALBound, AHBound: Integer; out AClosed: Boolean): Boolean; // R/O property Name: String read FName; property TableCol: Integer read FTableCol; property TableOid: Oid read FTableOid; property Len: Integer read FLen; property Prec: Integer read FPrec; property Scale: Integer read FScale; property Fields: TPgFields read FFields; property ParentField: TPgField read GetParentField; // R/W property ArrayIndex: Integer read FArrayIndex write SetArrayIndex; end; TPgFields = class(TPgVariables) private [weak] FParentField: TPgField; FPgData: Pointer; FPgDataLen: Integer; function GetItems(AIndex: Integer): TPgField; protected function GetVariableClass: TPgVariableClass; override; public constructor Create(AOwner: TPgField); overload; property Items[Index: Integer]: TPgField read GetItems; default; property PgData: Pointer read FPgData; property PgDataLen: Integer read FPgDataLen; property ParentField: TPgField read FParentField; end; TPgStatement = class(TPgObject) private FConnection: TPgConnection; FCursorName: String; FStmtName: String; FRowsetStmtName: String; FParams: TPgParams; FFields: TPgFields; FRowsAffected: Int64; FLastInsertOid: Oid; FSQLStmtType: String; FRowsSelected: Int64; FRowsetOffset: Int64; FCurrentRow: Int64; FEOF: Boolean; FClosed: Boolean; FLastRowset: Boolean; FStrsTrim: Boolean; FStrsEmpty2Null: Boolean; FStrsTrim2Len: Boolean; FGUIDEndian: TEndian; FRowsetSize: Integer; FWithHold: Boolean; FResultFormat: Integer; procedure Check(AHandle: PPGresult); procedure GetResultInfo; procedure GetNextRowset; procedure Reset; procedure Clear; function InternalPrepare(const ASQL: String; AUseParams: Boolean): String; procedure InternalExecute(const AStmtName: String; AnParams: Integer; AParamValues: Pointer; AParamLengths, AParamFormats: PInteger; AResultFormat: Integer); overload; procedure InternalExecute(AResultFormat: Integer); overload; procedure InternalUnprepare(var AStmtName: String); procedure InternalExecuteDirect(const ASQL: String; AResultFormat: Integer); {$IFDEF FireDAC_MONITOR} procedure DumpInVars; procedure DumpOutVars; procedure GetStmtName(out AName, AValue: String); {$ENDIF} public FHandle: PPGresult; constructor Create(AConnection: TPgConnection; AOwningObj: TObject); destructor Destroy; override; procedure PrepareSQL(const ASQL: String); procedure PrepareCursor(const ACursorName: String); procedure DescribeFields; procedure Execute; procedure ExecuteDirect(const ASQL: String); function Fetch: Boolean; procedure Unprepare; procedure Close; // R/O property Connection: TPgConnection read FConnection; property Params: TPgParams read FParams; property Fields: TPgFields read FFields; property SQLStmtType: String read FSQLStmtType; property RowsAffected: Int64 read FRowsAffected; property RowsSelected: Int64 read FRowsSelected; property LastInsertOid: Oid read FLastInsertOid; property Eof: Boolean read FEOF; property Closed: Boolean read FClosed; property ResultFormat: Integer read FResultFormat; // R/W state property CurrentRow: Int64 read FCurrentRow write FCurrentRow; // R/W options property StrsTrim: Boolean read FStrsTrim write FStrsTrim; property StrsEmpty2Null: Boolean read FStrsEmpty2Null write FStrsEmpty2Null; property StrsTrim2Len: Boolean read FStrsTrim2Len write FStrsTrim2Len; property GUIDEndian: TEndian read FGUIDEndian write FGUIDEndian; property RowsetSize: Integer read FRowsetSize write FRowsetSize; property WithHold: Boolean read FWithHold write FWithHold; end; TPgLargeObject = class(TPgObject) private FConnection: TPgConnection; FPosition: Integer; FIsOpen: Boolean; FMode: TFDStreamMode; function GetLen: Integer; procedure SetLen(const AValue: Integer); procedure Error(const AOperation: String; AStatus: Integer); procedure CheckReadWrite; function Mode2PGMode: Integer; public FObjOid: Oid; FObjHandle: Integer; constructor Create(AConnection: TPgConnection; AMode: TFDStreamMode; AOwningObj: TObject); overload; constructor Create(AConnection: TPgConnection; AMode: TFDStreamMode; AOwningObj: TObject; AObjOid: Oid); overload; destructor Destroy; override; procedure CreateObj; procedure Open; procedure Close(AIgnoreErrors: Boolean); procedure UnLink; function Seek(AOffset: Integer; ASeekOrigin: Word): Integer; function Read(ABuff: PByte; ABuffLen: Integer): Integer; function Write(ABuff: PByte; ABuffLen: Integer): Integer; property IsOpen: Boolean read FIsOpen; property Mode: TFDStreamMode read FMode; property Connection: TPgConnection read FConnection; property Len: Integer read GetLen write SetLen; end; TPgLargeObjectStream = class(TStream) private FLargeObject: TPgLargeObject; protected procedure SetSize(const NewSize: Int64); override; public constructor Create(ALargeObject: TPgLargeObject); destructor Destroy; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; property LargeObject: TPgLargeObject read FLargeObject; end; procedure j2date(const AValue: Int64; out AYear, AMonth, ADay: Word); procedure dtInt2time(AValue: Int64; out AHour, AMin, ASec: Word; out AFsec: Cardinal); procedure dtDbl2time(AValue: Double; out AHour, AMin, ASec: Word; out AFsec: Cardinal); function date2j(AYear, AMonth, ADay: Word): Int64; function time2IntT(const AHour, AMin, ASec: Word; const AFsec: Cardinal): Int64; function time2DblT(const AHour, AMin, ASec: Word; const AFsec: Cardinal): Double; procedure GetPgNumeric(ASource: Pointer; out ADest: TBcd); procedure GetPgMoney(ASource: Pointer; ASourceLen: Integer; out ADest: Currency); procedure SetPgNumeric(const ASource: TBcd; ADest: Pointer; out ADestLen: LongWord); procedure SetPgMoney(const ASource: Currency; ADest: Pointer; ADestLen: LongWord); implementation uses {$IFDEF MSWINDOWS} Winapi.WinSock, {$ENDIF} {$IFDEF UNIX} sockets, netdb, {$ENDIF} System.SysConst, Data.SqlTimSt, FireDAC.Stan.SQLTimeInt, FireDAC.Stan.Consts; const sPQconnectdb: String = 'PQconnectdb'; sPQfinish: String = 'PQfinish'; sPQserverVersion: String = 'PQserverVersion'; sPQprotocolVersion: String = 'PQprotocolVersion'; sPQstatus: String = 'PQstatus'; sPQerrorMessage: String = 'PQerrorMessage'; sPQparameterStatus: String = 'PQparameterStatus'; sPQtransactionStatus: String = 'PQtransactionStatus'; sPQsetClientEncoding: String = 'PQsetClientEncoding'; sPQclientEncoding: String = 'PQclientEncoding'; spg_encoding_to_char: String = 'pg_encoding_to_char'; sPQexec: String = 'PQexec'; sPQexecParams: String = 'PQexecParams'; sPQprepare: String = 'PQprepare'; sPQexecPrepared: String = 'PQexecPrepared'; sPQresultStatus: String = 'PQresultStatus'; sPQresultErrorMessage: String = 'PQresultErrorMessage'; sPQresultErrorField: String = 'PQresultErrorField'; sPQclear: String = 'PQclear'; sPQntuples: String = 'PQntuples'; sPQnfields: String = 'PQnfields'; sPQfname: String = 'PQfname'; sPQftable: String = 'PQftable'; sPQftablecol: String = 'PQftablecol'; sPQfformat: String = 'PQfformat'; sPQftype: String = 'PQftype'; sPQfmod: String = 'PQfmod'; sPQfsize: String = 'PQfsize'; sPQgetisnull: String = 'PQgetisnull'; sPQgetlength: String = 'PQgetlength'; sPQgetvalue: String = 'PQgetvalue'; sPQnparams: String = 'PQnparams'; sPQparamtype: String = 'PQparamtype'; sPQcmdStatus: String = 'PQcmdStatus'; sPQoidValue: String = 'PQoidValue'; sPQoidStatus: String = 'PQoidStatus'; sPQcmdTuples: String = 'PQcmdTuples'; sPQsetNoticeReceiver: String = 'PQsetNoticeReceiver'; sPQgetCancel: String = 'PQgetCancel'; sPQfreeCancel: String = 'PQfreeCancel'; sPQcancel: String = 'PQcancel'; sPQputCopyData: String = 'PQputCopyData'; sPQputCopyEnd: String = 'PQputCopyEnd'; slo_creat: String = 'lo_creat'; slo_open: String = 'lo_open'; slo_write: String = 'lo_write'; slo_read: String = 'lo_read'; slo_lseek: String = 'lo_lseek'; slo_tell: String = 'lo_tell'; slo_close: String = 'lo_close'; slo_unlink: String = 'lo_unlink'; slo_truncate: String = 'lo_truncate'; sPQgetResult: String = 'PQgetResult'; sPQnotifies: String = 'PQnotifies'; sPQfreemem: String = 'PQfreemem'; sPQconsumeInput: String = 'PQconsumeInput'; sPQsocket: String = 'PQsocket'; sPQprepareOut: String = 'PQprepareOut'; sPQexecBulkPrepared: String = 'PQexecBulkPrepared'; sPQencryptPassword: String = 'PQencryptPassword'; sPQencryptPasswordConn: String = 'PQencryptPasswordConn'; max_string_size = 4000; cancel_buf_size = 255; pg_base_date = 36526; // 01.01.2000 MinDateTime = -657434; // 01/01/0100 12:00:00.000 AM MaxDateTime = 2958466; // 12/31/9999 11:59:59.999 PM McSecsPerSec = 1000000; McSecsPerDay = Int64(SecsPerDay) * McSecsPerSec; McSecsPerHour = Int64(SecsPerHour) * McSecsPerSec; McSecsPerMin = Int64(SecsPerMin) * McSecsPerSec; sClosePrefix: String = 'CLOSE "'; sDeallocatePrefix: String = 'DEALLOCATE "'; type TPgTimeStampBuf = array [0..7] of Byte; TPgTimeIntervalBuf = array [0..7 + 4 + 4] of Byte; {-------------------------------------------------------------------------------} { TPgLib } {-------------------------------------------------------------------------------} constructor TPgLib.Create(AOwningObj: TObject); begin inherited Create(S_FD_PGId, AOwningObj); end; {-------------------------------------------------------------------------------} procedure TPgLib.Load(const AVendorHome, AVendorLib: String); {$IFNDEF FireDAC_PGSQL_STATIC} const C_PgDll: String = 'libpq' + C_FD_DLLExt; C_PgDllFolder: String = 'lib'; var sDLLName: String; {$ENDIF} begin {$IFNDEF FireDAC_PGSQL_STATIC} sDLLName := AVendorHome; if sDLLName <> '' then sDLLName := FDNormPath(FDNormPath(sDLLName) + C_PgDllFolder); if AVendorLib <> '' then sDLLName := sDLLName + AVendorLib else sDLLName := sDLLName + C_PgDll; inherited Load([sDLLName], True); {$ELSE} LoadEntries; {$ENDIF} end; {-------------------------------------------------------------------------------} procedure TPgLib.LoadEntries; begin {$IFDEF FireDAC_PGSQL_STATIC} FBrand := pbRegular; FPQconnectdb := @PQconnectdb; FPQfinish := @PQfinish; FPQserverVersion := @PQserverVersion; FPQprotocolVersion := @PQprotocolVersion; // not used, not in 8.1 ? FPQstatus := @PQstatus; FPQerrorMessage := @PQerrorMessage; FPQparameterStatus := @PQparameterStatus; FPQtransactionStatus := @PQtransactionStatus; FPQsetClientEncoding := @PQsetClientEncoding; FPQclientEncoding := @PQclientEncoding; Fpg_encoding_to_char := @pg_encoding_to_char; FPQexec := @PQexec; FPQexecParams := @PQexecParams; FPQprepare := @PQprepare; // in 8.0 FPQexecPrepared := @PQexecPrepared; FPQresultStatus := @PQresultStatus; FPQresultErrorMessage := @PQresultErrorMessage; // not used FPQresultErrorField := @PQresultErrorField; FPQclear := @PQclear; FPQntuples := @PQntuples; FPQnfields := @PQnfields; FPQfname := @PQfname; FPQftable := @PQftable; FPQftablecol := @PQftablecol; FPQfformat := @PQfformat; FPQftype := @PQftype; FPQfmod := @PQfmod; FPQfsize := @PQfsize; // not used FPQgetvalue := @PQgetvalue; FPQgetisnull := @PQgetisnull; FPQgetlength := @PQgetlength; FPQnparams := @PQnparams; // not used, not in 8.1 ? FPQparamtype := @PQparamtype; // not used, not in 8.1 ? FPQcmdStatus := @PQcmdStatus; // FPQoidValue, FPQoidStatus, FPQcmdTuples since version 8.0 cas be used for // execute statements id () FPQoidValue := @PQoidValue; FPQoidStatus := @PQoidStatus; // not used FPQcmdTuples := @PQcmdTuples; FPQsetNoticeReceiver := @PQsetNoticeReceiver; FPQgetCancel := @PQgetCancel; FPQfreeCancel := @PQfreeCancel; FPQcancel := @PQcancel; FPQputCopyData := @PQputCopyData; // not used FPQputCopyEnd := @PQputCopyEnd; // not used Flo_creat := @lo_creat; Flo_open := @lo_open; Flo_write := @lo_write; Flo_read := @lo_read; Flo_lseek := @lo_lseek; Flo_tell := @lo_tell; // not used Flo_close := @lo_close; Flo_unlink := @lo_unlink; Flo_truncate = @lo_truncate; FPQgetResult := @PQgetResult; // not used FPQnotifies := @PQnotifies; FPQfreemem := @PQfreemem; FPQconsumeInput := @PQconsumeInput; FPQsocket := @PQsocket; FPQexecBulkPrepared := nil; FPQencryptPassword := @FPQencryptPassword; FPQencryptPasswordConn := @FPQencryptPasswordConn; {$ELSE} if GetProc(sPQprepareOut, False) = nil then FBrand := pbRegular else FBrand := pbEnterprise; FPQconnectdb := GetProc(sPQconnectdb); FPQfinish := GetProc(sPQfinish); FPQserverVersion := GetProc(sPQserverVersion, False); // not used, not in 7.4 FPQprotocolVersion := GetProc(sPQprotocolVersion, False); // not used, not in 8.1 FPQstatus := GetProc(sPQstatus); FPQerrorMessage := GetProc(sPQerrorMessage); FPQparameterStatus := GetProc(sPQparameterStatus); FPQtransactionStatus := GetProc(sPQtransactionStatus); FPQsetClientEncoding := GetProc(sPQsetClientEncoding); FPQclientEncoding := GetProc(sPQclientEncoding); Fpg_encoding_to_char := GetProc(spg_encoding_to_char); FPQexec := GetProc(sPQexec); FPQexecParams := GetProc(sPQexecParams, False); FPQprepare := GetProc(sPQprepare, False); // in 8.0 FPQexecPrepared := GetProc(sPQexecPrepared); FPQresultStatus := GetProc(sPQresultStatus); FPQresultErrorMessage := GetProc(sPQresultErrorMessage); // not used FPQresultErrorField := GetProc(sPQresultErrorField); FPQclear := GetProc(sPQclear); FPQntuples := GetProc(sPQntuples); FPQnfields := GetProc(sPQnfields); FPQfname := GetProc(sPQfname); FPQftable := GetProc(sPQftable); FPQftablecol := GetProc(sPQftablecol); FPQfformat := GetProc(sPQfformat); FPQftype := GetProc(sPQftype); FPQfmod := GetProc(sPQfmod); FPQfsize := GetProc(sPQfsize); // not used FPQgetvalue := GetProc(sPQgetvalue); FPQgetisnull := GetProc(sPQgetisnull); FPQgetlength := GetProc(sPQgetlength); FPQnparams := GetProc(sPQnparams, False); // not used, not in 8.1 ? FPQparamtype := GetProc(sPQparamtype, False); // not used, not in 8.1 ? FPQcmdStatus := GetProc(sPQcmdStatus); // FPQoidValue, FPQoidStatus, FPQcmdTuples since version 8.0 can be used // to execute statements id () FPQoidValue := GetProc(sPQoidValue); FPQoidStatus := GetProc(sPQoidStatus); // not used FPQcmdTuples := GetProc(sPQcmdTuples); FPQsetNoticeReceiver := GetProc(sPQsetNoticeReceiver); FPQgetCancel := GetProc(sPQgetCancel, False); FPQfreeCancel := GetProc(sPQfreeCancel, False); FPQcancel := GetProc(sPQcancel, False); FPQputCopyData := GetProc(sPQputCopyData); // not used FPQputCopyEnd := GetProc(sPQputCopyEnd); // not used Flo_creat := GetProc(slo_creat); Flo_open := GetProc(slo_open); Flo_write := GetProc(slo_write); Flo_read := GetProc(slo_read); Flo_lseek := GetProc(slo_lseek); Flo_tell := GetProc(slo_tell); // not used Flo_close := GetProc(slo_close); Flo_unlink := GetProc(slo_unlink); Flo_truncate := GetProc(slo_truncate, False); FPQgetResult := GetProc(sPQgetResult); // not used FPQnotifies := GetProc(sPQnotifies); FPQfreemem := GetProc(sPQfreemem); FPQconsumeInput := GetProc(sPQconsumeInput); FPQsocket := GetProc(sPQsocket); if FBrand = pbEnterprise then FPQexecBulkPrepared := GetProc(sPQexecBulkPrepared) else FPQexecBulkPrepared := nil; FPQencryptPassword := GetProc(sPQencryptPassword); FPQencryptPasswordConn := GetProc(sPQencryptPasswordConn, False); {$ENDIF} {$IFDEF POSIX} if Assigned(FPQprepare) then FVersion := svPGSQL080100 else FVersion := svPGSQL070300; {$ENDIF} end; {-------------------------------------------------------------------------------} { TFDPgError } {-------------------------------------------------------------------------------} procedure TFDPgError.Assign(ASrc: TFDDBError); begin inherited Assign(ASrc); if ASrc is TFDPgError then begin FSeverity := TFDPgError(ASrc).FSeverity; FErrorCode := TFDPgError(ASrc).FErrorCode; FDetailedMessage := TFDPgError(ASrc).FDetailedMessage; FHint := TFDPgError(ASrc).FHint; FPosition := TFDPgError(ASrc).FPosition; FInternalPosition := TFDPgError(ASrc).FInternalPosition; FInternalQuery := TFDPgError(ASrc).FSeverity; FContext := TFDPgError(ASrc).FSeverity; FSchemaName := TFDPgError(ASrc).FSchemaName; FTableName := TFDPgError(ASrc).FTableName; FColumnName := TFDPgError(ASrc).FColumnName; FTypeName := TFDPgError(ASrc).FTypeName; FConstraintName := TFDPgError(ASrc).FConstraintName; FSourceFile := TFDPgError(ASrc).FSeverity; FSourceLine := TFDPgError(ASrc).FSourceLine; FSourceFunction := TFDPgError(ASrc).FSeverity; end; end; {-------------------------------------------------------------------------------} procedure TFDPgError.LoadFromStorage(const AStorage: IFDStanStorage); begin inherited LoadFromStorage(AStorage); FSeverity := AStorage.ReadString('Severity', ''); FErrorCode := AStorage.ReadString('ErrorCode', ''); FDetailedMessage := AStorage.ReadString('DetailedMessage', ''); FHint := AStorage.ReadString('Hint', ''); FPosition := AStorage.ReadInteger('Position', 0); FInternalPosition := AStorage.ReadInteger('InternalPosition', 0); FInternalQuery := AStorage.ReadString('InternalQuery', ''); FContext := AStorage.ReadString('Context', ''); FSchemaName := AStorage.ReadString('SchemaName', ''); FTableName := AStorage.ReadString('TableName', ''); FColumnName := AStorage.ReadString('ColumnName', ''); FTypeName := AStorage.ReadString('TypeName', ''); FConstraintName := AStorage.ReadString('ConstraintName', ''); FSourceFile := AStorage.ReadString('SourceFile', ''); FSourceLine := AStorage.ReadInteger('SourceLine', 0); FSourceFunction := AStorage.ReadString('SourceFunction', ''); end; {-------------------------------------------------------------------------------} procedure TFDPgError.SaveToStorage(const AStorage: IFDStanStorage); begin inherited SaveToStorage(AStorage); AStorage.WriteString('Severity', FSeverity, ''); AStorage.WriteString('ErrorCode', FErrorCode, ''); AStorage.WriteString('DetailedMessage', FDetailedMessage, ''); AStorage.WriteString('Hint', FHint, ''); AStorage.WriteInteger('Position', FPosition, 0); AStorage.WriteInteger('InternalPosition', FInternalPosition, 0); AStorage.WriteString('InternalQuery', FInternalQuery, ''); AStorage.WriteString('Context', FContext, ''); AStorage.WriteString('SchemaName', FSchemaName, ''); AStorage.WriteString('TableName', FTableName, ''); AStorage.WriteString('ColumnName', FColumnName, ''); AStorage.WriteString('TypeName', FTypeName, ''); AStorage.WriteString('ConstraintName', FConstraintName, ''); AStorage.WriteString('SourceFile', FSourceFile, ''); AStorage.WriteInteger('SourceLine', FSourceLine, 0); AStorage.WriteString('SourceFunction', FSourceFunction, ''); end; {-------------------------------------------------------------------------------} { EPgNativeException } {-------------------------------------------------------------------------------} function EPgNativeException.AppendError(const ADetailedMessage: String): TFDDBError; var eKind: TFDCommandExceptionKind; sSeverity: String; sMessage, sLCMessage: String; iSep: Integer; begin iSep := Pos(':', ADetailedMessage); if iSep > 0 then sSeverity := Copy(ADetailedMessage, 1, iSep - 1) else sSeverity := ''; if (sSeverity = 'ERROR') or (sSeverity = 'FATAL') then sMessage := Trim(Copy(ADetailedMessage, iSep + 1, Length(ADetailedMessage) - iSep)) else sMessage := ADetailedMessage; sLCMessage := LowerCase(sMessage); if FDStrLike(sLCMessage, 'role "%" does not exist') or FDStrLike(sLCMessage, 'password authentication failed for user "%"') then eKind := ekUserPwdInvalid else if (Pos('connection refused', sLCMessage) <> 0) or (Pos('could not connect to server', sLCMessage) <> 0) or (Pos('server closed the connection unexpectedly', sLCMessage) <> 0) or (Pos('no connection to the server', sLCMessage) <> 0) then eKind := ekServerGone else eKind := ekOther; Result := inherited AppendError(1, 0, sMessage, '', eKind, -1, -1); TFDPgError(Result).FSeverity := sSeverity; Message := Message + ' ' + TFDPgError(Result).Message; end; {-------------------------------------------------------------------------------} function EPgNativeException.AppendError(const ASeverity, AErrorCode, AMessage, ADetailedMessage, AHint: String; APosition, AInternalPosition: Integer; const AInternalQuery, AContext, ASchemaName, ATableName, AColumnName, ATypeName, AConstraintName, ASourceFile: String; ASourceLine: Integer; const ASourceFunction: String): TFDDBError; var sErrorCodeClass: String; eKind: TFDCommandExceptionKind; sObj: String; oErr: TFDPgError; procedure ExtractObjName; var i1, i2: Integer; begin i2 := 0; while True do begin i1 := Pos('"', AMessage, i2 + 1); if i1 = 0 then Break; i2 := Pos('"', AMessage, i1 + 1); if i2 = 0 then Break; sObj := Copy(AMessage, i1 + 1, i2 - i1 - 1); end; end; begin sObj := ''; eKind := ekOther; sErrorCodeClass := Copy(AErrorCode, 1, 2); if sErrorCodeClass = '02' then // No Data Class eKind := ekNoDataFound else if AErrorCode = '40P01' then // DEADLOCK DETECTED eKind := ekRecordLocked else if sErrorCodeClass = '23' then begin ExtractObjName; if AErrorCode = '23505' then // UNIQUE VIOLATION eKind := ekUKViolated else if AErrorCode = '23503' then // FOREIGN KEY VIOLATION eKind := ekFKViolated; end else if sErrorCodeClass = '42' then begin ExtractObjName; if (aErrorCode = '42P01') or // UNDEFINED TABLE (aErrorCode = '42703') or // UNDEFINED COLUMN (aErrorCode = '42883') or // UNDEFINED FUNCTION (aErrorCode = '42704') then // UNDEFINED OBJECT eKind := ekObjNotExists else if aErrorCode = '42P02' then // UNDEFINED PARAMETER eKind := ekInvalidParams; end else if AErrorCode = '57014' then eKind := ekCmdAborted else if AErrorCode = '08P01' then eKind := ekInvalidParams else if (AErrorCode = '') or // at least, when service is terminated, // then error code is an empty string (aErrorCode = '08000') or // CONNECTION EXCEPTION (aErrorCode = '08003') or // CONNECTION DOES NOT EXIST (aErrorCode = '08006') or // CONNECTION FAILURE (aErrorCode = '57P01') or // ADMIN SHUTDOWN (aErrorCode = '57P02') or // CRASH SHUTDOWN (aErrorCode = '57P03') then // CANNOT CONNECT NOW eKind := ekServerGone; Result := inherited AppendError(1, 0, AMessage, sObj, eKind, APosition, -1); oErr := TFDPgError(Result); oErr.FSeverity := ASeverity; oErr.FErrorCode := AErrorCode; oErr.FDetailedMessage := ADetailedMessage; oErr.FHint := AHint; oErr.FPosition := APosition; oErr.FInternalPosition := AInternalPosition; oErr.FInternalQuery := AInternalQuery; oErr.FContext := AContext; oErr.FSchemaName := ASchemaName; oErr.FTableName := ATableName; oErr.FColumnName := AColumnName; oErr.FTypeName := ATypeName; oErr.FConstraintName := AConstraintName; oErr.FSourceFile := ASourceFile; oErr.FSourceLine := ASourceLine; oErr.FSourceFunction := ASourceFunction; if AConstraintName <> '' then Result.ObjName := AConstraintName else if ATypeName <> '' then Result.ObjName := ATypeName else if AColumnName <> '' then Result.ObjName := AColumnName else if ATableName <> '' then Result.ObjName := ATableName; if ASeverity <> 'NOTICE' then begin Message := Message + ' ' + ASeverity + ': ' + TFDPgError(Result).Message; if ADetailedMessage <> '' then Message := Message + '.' + C_FD_EOL + ADetailedMessage; if AHint <> '' then Message := Message + '.' + C_FD_EOL + AHint; end; end; {-------------------------------------------------------------------------------} function EPgNativeException.GetErrorClass: TFDDBErrorClass; begin Result := TFDPgError; end; {-------------------------------------------------------------------------------} function EPgNativeException.GetErrors(AIndex: Integer): TFDPgError; begin Result := TFDPgError(inherited Errors[AIndex]); end; {-------------------------------------------------------------------------------} { TPgEnv } {-------------------------------------------------------------------------------} constructor TPgEnv.Create(ALib: TPgLib; AOwningObj: TObject); begin inherited Create; FLib := ALib; FOwningObj := AOwningObj; end; {$IFDEF FireDAC_MONITOR} {-------------------------------------------------------------------------------} function TPgEnv.GetTracing: Boolean; begin Result := (FMonitor <> nil) and FMonitor.Tracing and FTracing; end; {-------------------------------------------------------------------------------} procedure TPgEnv.Trace(const AMsg: String; const AArgs: array of const); begin if GetTracing then FMonitor.Notify(ekVendor, esProgress, OwningObj, AMsg, AArgs); end; {-------------------------------------------------------------------------------} procedure TPgEnv.Trace(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep; const AMsg: String; const AArgs: array of const); begin if GetTracing then FMonitor.Notify(AKind, AStep, OwningObj, AMsg, AArgs); end; {$ENDIF} {-------------------------------------------------------------------------------} { TPgObject } {-------------------------------------------------------------------------------} constructor TPgObject.Create(AEnv: TPgEnv; AOwningObj: TObject); begin inherited Create; FEnv := AEnv; FOwningObj := AOwningObj; end; {-------------------------------------------------------------------------------} function TPgObject.GetLib: TPgLib; begin Result := FEnv.Lib; end; {-------------------------------------------------------------------------------} procedure TPgObject.DoError(const AMessage: String; AStatus: Integer); var oEx: EPgNativeException; begin oEx := EPgNativeException.Create(er_FD_PgGeneral, FDExceptionLayers([S_FD_LPhys, S_FD_PgId, 'libpq'])); oEx.AppendError(AMessage).ErrorCode := AStatus; {$IFDEF FireDAC_MONITOR} Env.Trace(ekError, esProgress, 'ERROR: ' + oEx[0].Message, ['Status', AStatus]); {$ENDIF} FDException(OwningObj, oEx {$IFDEF FireDAC_Monitor}, Env.Tracing {$ENDIF}); end; {-------------------------------------------------------------------------------} { TPgMember } {-------------------------------------------------------------------------------} constructor TPgMember.Create; begin inherited Create; FAttrs := [caAllowNull]; end; {-------------------------------------------------------------------------------} { TPgType } {-------------------------------------------------------------------------------} destructor TPgType.Destroy; var i: Integer; begin for i := 0 to Length(Members) - 1 do FDFree(Members[i]); FDFreeAndNil(FEnums); inherited Destroy; end; {-------------------------------------------------------------------------------} function TPgType.GetEnums: TFDStringList; begin if FEnums = nil then FEnums := TFDStringList.Create; Result := FEnums; end; {-------------------------------------------------------------------------------} function TPgType.DumpType: String; begin if paArray in Attrs then begin Result := Members[0].TypeRef.DumpType; if (paFixed in Attrs) and (FixedLen > 0) then Result := Result + '[' + IntToStr(FixedLen) + ']' else Result := Result + '[]'; end else Result := Name; end; {-------------------------------------------------------------------------------} function TPgType.GetIsFlatFixedArray: Boolean; begin Result := ([paArray, paFixed] * Attrs = [paArray, paFixed]) and (Length(Members) = 1) and ([paArray, paRecord, paRange] * Members[0].TypeRef.Attrs = []); end; {-------------------------------------------------------------------------------} function TPgType.GetEnumValue(AOid: Oid): String; var i: Integer; begin Result := ''; for i := 0 to FEnums.Count - 1 do if Oid(FEnums.Ints[i]) = AOid then begin Result := FEnums[i]; Break; end; end; {-------------------------------------------------------------------------------} { TPgTypesManager } {-------------------------------------------------------------------------------} constructor TPgTypesManager.Create(AConnection: TPgConnection); begin inherited Create; FConnection := AConnection; FTypes := TFDObjList.Create; // pg_* - records, query the dictionary // _cstring - pseudo type // record - pseudo types // cstring, any*, trigger, internal, opaque - pseudo types // txid_snapshot - ? // ts*, gts*, reg* - ? AddBase(SQL_BOOL, 'bool', 0, SizeOf(Byte), SizeOf(WordBool), []); AddBase(SQL_BYTEA, 'bytea', 0, 0, 0, [paBlob]); AddBase(SQL_CHAR, 'char', 0, 0, 0, [paString, paFixed]); AddBase(SQL_NAME, 'name', NAMEMAXLEN, 0, 0, [paString]); AddBase(SQL_INT8, 'int8', 0, SizeOf(Int64), SizeOf(Int64), []); AddBase(SQL_INT2, 'int2', 0, SizeOf(SmallInt), SizeOf(SmallInt), []); AddBase(SQL_INT4, 'int4', 0, SizeOf(Integer), SizeOf(Integer), []); AddBase(SQL_REGPROC, 'regproc', 0, SizeOf(Oid), SizeOf(Oid), [paOID]); AddBase(SQL_TEXT, 'text', 0, 0, 0, [paBlob]); AddBase(SQL_OID, 'oid', 0, SizeOf(Oid), SizeOf(Oid), [paOID]); AddBase(SQL_TID, 'tid', 0, 6, SizeOf(Int64), [paOID]); AddBase(SQL_XID, 'xid', 0, SizeOf(Oid), SizeOf(Oid), [paOID]); AddBase(SQL_CID, 'cid', 0, SizeOf(Oid), SizeOf(Oid), [paOID]); AddBase(SQL_JSON, 'json', 0, 0, 0, [paBlob, paCast]); AddBase(SQL_XML, 'xml', 0, 0, 0, [paBlob]); AddBase(SQL_NODE_TREE, 'pg_node_tree', 0, 0, 0, [paBlob]); AddBase(SQL_SMGR, 'smgr', 0, SizeOf(Word), SizeOf(Word), []); AddBase(SQL_CIDR, 'cidr', 0, 20, 20 {49}, [paString, paCast]); AddBase(SQL_FLOAT4, 'float4', 0, SizeOf(Single), SizeOf(Single), []); AddBase(SQL_FLOAT8, 'float8', 0, SizeOf(Double), SizeOf(Double), []); AddBase(SQL_ABSTIME, 'abstime', 0, SizeOf(Integer), SizeOf(TSQLTimeStamp), []); AddBase(SQL_RELTIME, 'reltime', 0, SizeOf(Integer), SizeOf(TSQLTimeStamp), []); AddBase(SQL_TINTERVAL, 'tinterval', 0, 0, 0, []); AddBase(SQL_UNKNOWN, 'unknown', 0, 0, 0, [paString]); AddBase(SQL_MACADDR8, 'macaddr8', 0, 8, 8 {23}, [paString, paFixed, paCast]); AddBase(SQL_CASH, 'money', 0, 0, SizeOf(Currency), []); AddBase(SQL_MACADDR, 'macaddr', 0, 6, 6 {17}, [paString, paFixed, paCast]); AddBase(SQL_INET, 'inet', 0, 20, 20 {49}, [paString, paCast]); AddBase(SQL_ACLITEM, 'aclitem', 0, 12, 12, []); AddBase(SQL_BPCHAR, 'bpchar', 0, 0, 0, [paString, paFixed]); AddBase(SQL_VARCHAR, 'varchar', 0, 0, 0, [paString]); AddBase(SQL_DATE, 'date', 0, SizeOf(Integer), SizeOf(Integer), []); AddBase(SQL_TIME, 'time', 0, SizeOf(TPgTimeStampBuf), SizeOf(Integer), []); AddBase(SQL_TIMESTAMP, 'timestamp', 0, SizeOf(TPgTimeStampBuf), SizeOf(TSQLTimeStamp), []); AddBase(SQL_TIMESTAMPTZ,'timestamptz', 0, SizeOf(TPgTimeStampBuf), SizeOf(TSQLTimeStamp), []); AddBase(SQL_INTERVAL, 'interval', 0, SizeOf(TPgTimeIntervalBuf),SizeOf(TFDSQLTimeInterval), []); AddBase(SQL_TIMETZ, 'timetz', 0, SizeOf(TPgTimeStampBuf), SizeOf(Integer), []); AddBase(SQL_BIT, 'bit', 0, 0, 0, [paString, paFixed]); AddBase(SQL_VARBIT, 'varbit', 0, 0, 0, [paString]); AddBase(SQL_NUMERIC, 'numeric', 0, 8 + (MaxFMTBcdFractionSize div 4) * SizeOf(Word), SizeOf(TBcd), []); AddBase(SQL_REFCURSOR, 'refcursor', 0, 0, 0, [paString]); AddBase(SQL_REGPROCEDURE,'regprocedure', 0, SizeOf(Oid), SizeOf(Oid), [paOID]); AddBase(SQL_REGOPER, 'regoper', 0, SizeOf(Oid), SizeOf(Oid), [paOID]); AddBase(SQL_REGOPERATOR,'regoperator', 0, SizeOf(Oid), SizeOf(Oid), [paOID]); AddBase(SQL_REGCLASS, 'regclass', 0, SizeOf(Oid), SizeOf(Oid), [paOID]); AddBase(SQL_REGTYPE, 'regtype', 0, SizeOf(Oid), SizeOf(Oid), [paOID]); AddBase(SQL_RECORD, 'record', 0, 0, 0, [paRecord]); AddBase(SQL_ANY, 'any', 0, 0, 0, [paString]); AddBase(SQL_VOID, 'void', 0, 0, 0, [paString]); AddBase(SQL_UUID, 'uuid', 0, SizeOf(TGUID), SizeOf(TGUID), []); AddBase(SQL_JSONB, 'jsonb', 0, 0, 0, [paBlob, paCast]); AddArray(SQL_INT2VECTOR, 'int2vector', SQL_INT2); AddArray(SQL_OIDVECTOR, 'oidvector', SQL_OID); AddArray(199, '_json', SQL_JSON); AddArray(SQL_XML + 1, '_xml', SQL_XML); AddArray(SQL_POINT, 'point', SQL_FLOAT8, 2); AddArray(SQL_LSEG, 'lseg', SQL_POINT, 2); AddArray(SQL_PATH, 'path', SQL_POINT); AddArray(SQL_BOX, 'box', SQL_POINT, 2); AddArray(SQL_POLYGON, 'polygon', SQL_POINT); AddArray(SQL_LINE, 'line', SQL_FLOAT8, 4); AddArray(SQL_LINE + 1, '_line', SQL_LINE); AddArray(SQL_CIDR + 1, '_cidr', SQL_CIDR); AddArray(SQL_CIRCLE, 'circle', SQL_FLOAT8, 3); AddArray(SQL_CIRCLE + 1, '_circle', SQL_CIRCLE); AddArray(SQL_MACADDR8 + 1,'_macaddr8', SQL_MACADDR8); AddArray(SQL_CASH + 1, '_money', SQL_CASH); AddArray(1000, '_bool', SQL_BOOL); AddArray(1001, '_bytea', SQL_BYTEA); AddArray(1002, '_char', SQL_CHAR); AddArray(1003, '_name', SQL_NAME); AddArray(1005, '_int2', SQL_INT2); AddArray(1006, '_int2vector', SQL_INT2VECTOR); AddArray(1007, '_int4', SQL_INT4); AddArray(1008, '_regproc', SQL_REGPROC); AddArray(1009, '_text', SQL_TEXT); AddArray(1010, '_tid', SQL_TID); AddArray(1011, '_xid', SQL_XID); AddArray(1012, '_cid', SQL_CID); AddArray(1013, '_oidvector', SQL_OIDVECTOR); AddArray(1014, '_bpchar', SQL_BPCHAR); AddArray(1015, '_varchar', SQL_VARCHAR); AddArray(1016, '_int8', SQL_INT8); AddArray(1017, '_point', SQL_POINT); AddArray(1018, '_lseg', SQL_LSEG); AddArray(1019, '_path', SQL_PATH); AddArray(1020, '_box', SQL_BOX); AddArray(1021, '_float4', SQL_FLOAT4); AddArray(1022, '_float8', SQL_FLOAT8); AddArray(1023, '_abstime', SQL_ABSTIME); AddArray(1024, '_reltime', SQL_RELTIME); AddArray(1025, '_tinterval', SQL_TINTERVAL); AddArray(1027, '_polygon', SQL_POLYGON); AddArray(1028, '_oid', SQL_OID); AddArray(1034, '_aclitem', 1033); AddArray(1040, '_macaddr', SQL_MACADDR); AddArray(1041, '_inet', SQL_INET); AddArray(SQL_TIMESTAMP+1,'_timestamp', SQL_TIMESTAMP); AddArray(1182, '_date', SQL_DATE); AddArray(1183, '_time', SQL_TIME); AddArray(SQL_TIMESTAMPTZ+1,'_timestamptz', SQL_TIMESTAMPTZ); AddArray(SQL_INTERVAL + 1,'_interval', SQL_INTERVAL); AddArray(1231, '_numeric', SQL_NUMERIC); AddArray(SQL_TIMETZ + 1, '_timetz', SQL_TIMETZ); AddArray(SQL_BIT + 1, '_bit', SQL_BIT); AddArray(SQL_VARBIT + 1, '_varbit', SQL_VARBIT); AddArray(2201, '_refcursor', SQL_REFCURSOR); AddArray(2207, '_regprocedure', SQL_REGPROCEDURE); AddArray(2208, '_regoper', SQL_REGOPER); AddArray(2209, '_regoperator', SQL_REGOPERATOR); AddArray(2210, '_regclass', SQL_REGCLASS); AddArray(2211, '_regtype', SQL_REGTYPE); AddArray(SQL_ANY + 1, 'anyarray', SQL_ANY); AddArray(2287, '_record', SQL_RECORD); AddArray(SQL_UUID + 1, '_uuid', SQL_UUID); AddArray(3807, '_jsonb', SQL_JSONB); end; {-------------------------------------------------------------------------------} destructor TPgTypesManager.Destroy; var i: Integer; begin for i := 0 to FTypes.Count - 1 do FDFree(TPgType(FTypes[i])); FDFreeAndNil(FTypes); FConnection := nil; FLastType := nil; inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TPgTypesManager.DescribeError(const AId, AReason: String); begin FDException(FConnection.OwningObj, [S_FD_LPhys, S_FD_PGId], er_FD_PgCannotDescribeType, [AId, AReason]); end; {-------------------------------------------------------------------------------} class procedure TPgTypesManager.GetDefaults(AFormat: Integer; ATypeOid: Oid; out ALen, APrec, AScale: Integer); begin ALen := 0; APrec := 0; AScale := 0; case ATypeOid of SQL_CHAR, SQL_BPCHAR: ALen := 1024; SQL_NAME: ALen := NAMEMAXLEN; SQL_VARCHAR, SQL_ACLITEM: ALen := 8190; SQL_TEXT, SQL_JSON, SQL_JSONB, SQL_XML, SQL_NODE_TREE, SQL_BYTEA, SQL_ANY: ALen := C_FD_DefMaxStrSize; SQL_MACADDR: if AFormat = 0 then ALen := 17 else ALen := 6; SQL_MACADDR8:if AFormat = 0 then ALen := 23 else ALen := 8; SQL_CIDR, SQL_INET: if AFormat = 0 then ALen := 49 else ALen := 20; SQL_NUMERIC: APrec := 64; SQL_BIT, SQL_VARBIT: ALen := 1024; SQL_TIME, SQL_TIMETZ, SQL_TIMESTAMP, SQL_TIMESTAMPTZ, SQL_INTERVAL: AScale := 0; end; end; {-------------------------------------------------------------------------------} class procedure TPgTypesManager.DecodeModifier(ATypeOid: Oid; AModifier: Integer; out ALen, APrec, AScale: Integer); begin case ATypeOid of SQL_CHAR, SQL_BPCHAR, SQL_NAME, SQL_VARCHAR, SQL_TEXT, SQL_JSON, SQL_JSONB, SQL_XML, SQL_NODE_TREE, SQL_BYTEA, SQL_ANY, SQL_ACLITEM, SQL_MACADDR, SQL_MACADDR8, SQL_CIDR, SQL_INET: if AModifier >= VARHDRSZ then ALen := AModifier - VARHDRSZ; SQL_NUMERIC: if AModifier <> -1 then begin APrec := (AModifier - VARHDRSZ) shr 16 and $FFFF; AScale := (AModifier - VARHDRSZ) and $FFFF; end; SQL_BIT, SQL_VARBIT: if AModifier <> -1 then ALen := (AModifier + 7) div 8; SQL_TIME, SQL_TIMETZ, SQL_TIMESTAMP, SQL_TIMESTAMPTZ, SQL_INTERVAL: if AModifier <> -1 then AScale := AModifier; end; end; {-------------------------------------------------------------------------------} function TPgTypesManager.FindType(AId: OID; AExact: Boolean): Integer; var iFirstNo, iLastNo: Integer; iOid: Oid; begin iFirstNo := 0; iLastNo := FTypes.Count - 1; while iFirstNo <= iLastNo do begin Result := (iFirstNo + iLastNo) div 2; iOid := TPgType(FTypes[Result]).Id; if AId < iOid then iLastNo := Result - 1 else if AId > iOid then iFirstNo := Result + 1 else Exit; end; if AExact then Result := -1 else if iFirstNo >= FTypes.Count then Result := FTypes.Count else if iLastNo < 0 then Result := -1 else begin Result := iLastNo; while (TPgType(FTypes[Result]).Id <= AId) and (Result < FTypes.Count) do Inc(Result); end; end; {-------------------------------------------------------------------------------} procedure TPgTypesManager.AddType(AType: TPgType); var i: Integer; begin i := FindType(AType.Id, False); FTypes.Insert(i, AType); end; {-------------------------------------------------------------------------------} function TPgTypesManager.AddArray(AId: OID; const AName: String; ABaseOid: OID; AFixedLen: Integer): TPgType; var oMbr: TPgMember; begin Result := TPgType.Create; Result.FId := AId; Result.FName := AName; Result.FFixedLen := AFixedLen; Result.FPGSize := 0; Result.FFDSize := 0; Result.FAttrs := [paArray]; if AFixedLen > 0 then Include(Result.FAttrs, paFixed); SetLength(Result.FMembers, 1); oMbr := TPgMember.Create; Result.FMembers[0] := oMbr; oMbr.FOid := ABaseOid; oMbr.FRef := Types[ABaseOid]; AddType(Result); end; {-------------------------------------------------------------------------------} function TPgTypesManager.AddBase(AId: OID; const AName: String; AFixedLen, APGSize, AFDSize: Integer; AAttrs: TPgTypeAttrs): TPgType; begin Result := TPgType.Create; Result.FId := AId; Result.FName := AName; Result.FFixedLen := AFixedLen; Result.FPGSize := APGSize; Result.FFDSize := AFDSize; Result.FAttrs := AAttrs; Result.FMembers := nil; AddType(Result); end; {-------------------------------------------------------------------------------} procedure TPgTypesManager.Connected; var iCashSz: Integer; begin if FConnection.ServerVersion >= svPGSQL080300 then iCashSz := SizeOf(Int64) else iCashSz := SizeOf(Integer); Types[SQL_CASH].FPgSize := iCashSz; end; {-------------------------------------------------------------------------------} function TPgTypesManager.Describe(AOid: OID): TPgType; var oStmt: TPgStatement; sId, sName, sType, sCat: String; iRelId, iElem, iArray, iBase: Oid; i, iMem, iNum, iTypeMod: Integer; lNotNull: WordBool; oMbr: TPgMember; begin Result := nil; oStmt := TPgStatement.Create(FConnection, FConnection.OwningObj); try sId := IntToStr(AOid); oStmt.PrepareSQL('SELECT TYPNAME, TYPRELID, TYPELEM, TYPARRAY, TYPBASETYPE, TYPTYPE, TYPCATEGORY ' + 'FROM PG_CATALOG.PG_TYPE ' + 'WHERE OID = ' + sId); oStmt.Execute; oStmt.DescribeFields; if not oStmt.Fetch then DescribeError('#' + sId, 'Type is not found'); sName := oStmt.Fields[0].GetAsString; iRelId := 0; oStmt.Fields[1].GetData(@iRelId); iElem := 0; oStmt.Fields[2].GetData(@iElem); iArray := 0; oStmt.Fields[3].GetData(@iArray); iBase := 0; oStmt.Fields[4].GetData(@iBase); sType := oStmt.Fields[5].GetAsString; sCat := oStmt.Fields[6].GetAsString; if iBase <> 0 then Result := Types[iBase] else if (iRelId = 0) and (iElem = 0) and (sType <> 'e') and (sType <> 'r') and (sType <> 'b') then if FConnection.UnknownFormat = 0 then DescribeError(sName, 'A type must be an array, composite, enum, range or base type') else Result := Types[FConnection.UnknownFormat]; if Result <> nil then Exit; // array type if iElem <> 0 then Result := AddArray(AOid, sName, iElem) // enum type else if sType = 'e' then begin oStmt.Unprepare; oStmt.PrepareSQL('SELECT OID, ENUMLABEL ' + 'FROM PG_CATALOG.PG_ENUM ' + 'WHERE ENUMTYPID = ' + sId + 'ORDER BY OID'); oStmt.Execute; oStmt.DescribeFields; Result := AddBase(AOid, sName, 0, 0, 0, [paString, paEnum]); while oStmt.Fetch do begin sName := oStmt.Fields[1].GetAsString; oStmt.Fields[0].GetData(@iElem); Result.Enums.AddInt(sName, iElem); end; end // range type else if sType = 'r' then begin oStmt.Unprepare; oStmt.PrepareSQL('SELECT RNGSUBTYPE ' + 'FROM PG_CATALOG.PG_RANGE ' + 'WHERE RNGTYPID = ' + sId); oStmt.Execute; oStmt.DescribeFields; oStmt.Fetch; oStmt.Fields[0].GetData(@iElem); Result := AddBase(AOid, sName, 0, 0, 0, [paRange]); SetLength(Result.FMembers, 3); oMbr := TPgMember.Create; Result.FMembers[0] := oMbr; oMbr.FName := 'lbound'; oMbr.FOid := iElem; oMbr := TPgMember.Create; Result.FMembers[1] := oMbr; oMbr.FName := 'hbound'; oMbr.FOid := iElem; oMbr := TPgMember.Create; Result.FMembers[2] := oMbr; oMbr.FName := 'flags'; oMbr.FOid := SQL_INT4; for i := 0 to 2 do begin oMbr := Result.FMembers[i]; GetDefaults(1, oMbr.FOid, oMbr.FLen, oMbr.FPrec, oMbr.FScale); oMbr.FRef := Types[oMbr.FOid]; Include(oMbr.FAttrs, caReadOnly); end; end // base type else if sType = 'b' then begin if sCat = 'B' then iBase := SQL_BOOL else if sCat = 'D' then iBase := SQL_TIMESTAMP else if sCat = 'N' then iBase := SQL_NUMERIC else if sCat = 'S' then iBase := SQL_TEXT else if sCat = 'T' then iBase := SQL_INTERVAL else if sCat = 'V' then iBase := SQL_BYTEA else if FConnection.UnknownFormat = 0 then DescribeError(sName, 'A type is not a simple base type') else iBase := FConnection.UnknownFormat; Result := Types[iBase]; end // composite type else begin oStmt.Unprepare; oStmt.PrepareSQL('SELECT ATTNAME, ATTTYPID, ATTNUM, ATTTYPMOD, ATTNOTNULL ' + 'FROM PG_CATALOG.PG_ATTRIBUTE ' + 'WHERE ATTRELID = ' + IntToStr(iRelId) + ' AND ATTNUM > 0 ' + 'ORDER BY ATTNUM'); oStmt.Execute; oStmt.DescribeFields; Result := AddBase(AOid, sName, 0, 0, 0, [paRecord]); SetLength(Result.FMembers, oStmt.RowsSelected); for i := 0 to oStmt.RowsSelected - 1 do Result.FMembers[i] := TPgMember.Create; iMem := 0; while oStmt.Fetch do begin oMbr := Result.FMembers[iMem]; oMbr.FName := oStmt.Fields[0].GetAsString; oStmt.Fields[1].GetData(@oMbr.FOid); oMbr.FRef := Types[oMbr.FOid]; oStmt.Fields[2].GetData(@iNum); oStmt.Fields[3].GetData(@iTypeMod); oStmt.Fields[4].GetData(@lNotNull); oMbr.FAttrs := []; if not lNotNull then Include(oMbr.FAttrs, caAllowNull); if iNum <= 0 then Include(oMbr.FAttrs, caReadOnly); FConnection.TypesManager.DecodeModifier(oMbr.FOid, iTypeMod, oMbr.FLen, oMbr.FPrec, oMbr.FScale); Inc(iMem); end; end; finally FDFree(oStmt); end; end; {-------------------------------------------------------------------------------} function TPgTypesManager.GetTypes(AOid: OID): TPgType; var i: Integer; begin if (FLastType = nil) or (FlastType.Id <> AOid) then begin i := FindType(AOid, True); if i <> -1 then FLastType := TPgType(FTypes[i]) else FLastType := Describe(AOid); end; Result := FLastType; end; {-------------------------------------------------------------------------------} function TPgTypesManager.TypeByName(const AName: String): TPgType; var i: Integer; oStmt: TPgStatement; iTypeId: Oid; begin for i := 0 to FTypes.Count - 1 do if CompareText(TPgType(FTypes[i]).Name, AName) = 0 then Exit(TPgType(FTypes[i])); oStmt := TPgStatement.Create(FConnection, FConnection.OwningObj); try oStmt.PrepareSQL('SELECT OID ' + 'FROM PG_CATALOG.PG_TYPE ' + 'WHERE LOWER(TYPNAME) = ''' + LowerCase(AName) + ''''); oStmt.Execute; oStmt.DescribeFields; if not oStmt.Fetch then DescribeError(AName, 'Type is not found'); iTypeId := 0; oStmt.Fields[0].GetData(@iTypeId); Result := Describe(iTypeId); finally FDFree(oStmt); end; end; {-------------------------------------------------------------------------------} function TPgTypesManager.GetArrays(AMemberOid: OID): TPgType; var i: Integer; oType: TPgType; begin GetTypes(AMemberOid); Result := nil; for i := 0 to FTypes.Count - 1 do begin oType := TPgType(FTypes[i]); if (paArray in oType.Attrs) and (oType.Members[0].TypeOid = AMemberOid) then begin Result := oType; Exit; end; end; if Result = nil then DescribeError('#' + IntToStr(AMemberOid), 'Array type of specified member is not found'); end; {-------------------------------------------------------------------------------} { TPgConnection } {-------------------------------------------------------------------------------} constructor TPgConnection.Create(AEnv: TPgEnv; AOwningObj: TObject); begin inherited Create(AEnv, AOwningObj); FOwnHandle := True; FBuffer := TFDBuffer.Create; FEncoder := TFDEncoder.Create(FBuffer); FTypesManager := TPgTypesManager.Create(Self); FPStmtIDCounter := @FStmtIDCounter; end; {-------------------------------------------------------------------------------} constructor TPgConnection.CreateUsingHandle(AEnv: TPgEnv; AHandle: PPGconn; APStmtIDCounter: PInteger; AOwningObj: TObject); begin inherited Create(AEnv, AOwningObj); FOwnHandle := False; FHandle := AHandle; FBuffer := TFDBuffer.Create; FEncoder := TFDEncoder.Create(FBuffer); FTypesManager := TPgTypesManager.Create(Self); FPStmtIDCounter := APStmtIDCounter; end; {-------------------------------------------------------------------------------} destructor TPgConnection.Destroy; begin if FHandle <> nil then Disconnect; FDFreeAndNil(FEncoder); FDFreeAndNil(FBuffer); FDFreeAndNil(FTypesManager); inherited Destroy; end; {-------------------------------------------------------------------------------} // this function checks connection state and retrieves connection error procedure TPgConnection.Check; procedure Error; var eSrcEnc: TFDEncoding; begin {$IFDEF MSWINDOWS} if Lib.FPQstatus(FHandle) = CONNECTION_BAD then eSrcEnc := ecANSI else {$ENDIF} eSrcEnc := ecDefault; DoError(Encoder.Decode(Lib.FPQerrorMessage(FHandle), -1, eSrcEnc), Lib.FPQstatus(FHandle)); end; begin if Lib.FPQstatus(FHandle) = CONNECTION_OK then Exit; Error; end; {-------------------------------------------------------------------------------} function TPgConnection.CheckForInput: Boolean; {$IFDEF MSWINDOWS} var iSock: Integer; rReadFD: TFDSet; rTime: TTimeVal; {$ENDIF} begin {$IFDEF MSWINDOWS} iSock := Lib.FPQsocket(FHandle); if iSock < 0 then begin Result := False; Exit; end; FD_ZERO(rReadFD); FD_SET(iSock, rReadFD); rTime.tv_sec := 0; rTime.tv_usec := 100000; Result := (select(iSock + 1, @rReadFD, nil, nil, @rTime) <> SOCKET_ERROR) and FD_ISSET(iSock, rReadFD); if Result then {$ENDIF} {$IFDEF POSIX} Sleep(5); Result := True; {$ENDIF} if Lib.FPQconsumeInput(FHandle) = 0 then Check; end; {-------------------------------------------------------------------------------} function TPgConnection.ReadNotifies(out AName: String; out AProcID: Integer; out AParameter: String): Boolean; var pEvent: PPGnotify; begin pEvent := Lib.FPQnotifies(FHandle); if pEvent <> nil then begin AName := Encoder.Decode(pEvent^.relname, -1, ecANSI); AProcID := pEvent^.be_pid; AParameter := Encoder.Decode(pEvent^.extra, -1, ecANSI); Lib.FPQfreemem(pEvent); Result := True; end else Result := False; end; {-------------------------------------------------------------------------------} procedure TPgConnection.ReadResultError(AHandle: PPGresult; AException: EPgNativeException); begin AException.AppendError( Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_SEVERITY), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_SQLSTATE), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_MESSAGE_PRIMARY), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_MESSAGE_DETAIL), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_MESSAGE_HINT), -1), StrToIntDef(Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_STATEMENT_POSITION), -1), 0), StrToIntDef(Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_INTERNAL_POSITION), -1), 0), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_INTERNAL_QUERY), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_CONTEXT), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_SCHEMA_NAME), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_TABLE_NAME), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_COLUMN_NAME), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_DATATYPE_NAME), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_CONSTRAINT_NAME), -1), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_SOURCE_FILE), -1), StrToIntDef(Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_SOURCE_LINE), -1), 0), Encoder.Decode(Lib.FPQresultErrorField(AHandle, PG_DIAG_SOURCE_FUNCTION), -1) ).ErrorCode := Lib.FPQresultStatus(AHandle); end; {-------------------------------------------------------------------------------} // call this function to check result state and get server info procedure TPgConnection.CheckResult(AHandle: PPGresult; AOwningObj: TObject); var iStatus: Integer; procedure Error; var oEx: EPgNativeException; begin oEx := EPgNativeException.Create(er_FD_PgGeneral, FDExceptionLayers([S_FD_LPhys, S_FD_PgId, 'libpq'])); ReadResultError(AHandle, oEx); {$IFDEF FireDAC_MONITOR} Env.Trace(ekError, esProgress, 'ERROR: ' + oEx[0].Message, ['Status', iStatus]); {$ENDIF} FDException(AOwningObj, oEx {$IFDEF FireDAC_Monitor}, Env.Tracing {$ENDIF}); end; begin if AHandle = nil then Check else begin iStatus := Lib.FPQresultStatus(AHandle); if iStatus in [PGRES_COMMAND_OK, PGRES_TUPLES_OK, PGRES_COPY_IN] then Exit; Error; end; end; {-------------------------------------------------------------------------------} procedure TPgConnection.ClearNotices; begin FDFreeAndNil(FNotices); end; {-------------------------------------------------------------------------------} procedure TPgConnection.DoNoticeReceive(AHandle: PPGresult); begin if FNotices = nil then FNotices := EPgNativeException.Create(er_FD_PgGeneral, FDExceptionLayers([S_FD_LPhys, S_FD_PgId, 'libpq'])); ReadResultError(AHandle, FNotices); end; {-------------------------------------------------------------------------------} procedure PQnoticeReciever(Aarg: Pointer; Ares: PPGresult); cdecl; begin TPgConnection(Aarg).DoNoticeReceive(Ares); end; {-------------------------------------------------------------------------------} procedure TPgConnection.Connect(const AConnStr: String); {$IFDEF FireDAC_MONITOR} procedure Trace1; var sConnStr: String; i1, i2: Integer; begin sConnStr := AConnStr; i1 := Pos('password=', LowerCase(sConnStr)); if i1 <> 0 then begin i2 := Pos(' ', sConnStr, i1); if i2 = 0 then i2 := Length(sConnStr) + 1; sConnStr := Copy(sConnStr, 1, i1 + 8) + '***' + Copy(sConnStr, i2, Length(sConnStr)); end; Env.Trace(sPQconnectdb, ['@ConnInfo', sConnStr, 'Result', FHandle]); end; {$ENDIF} var sConnBytes: TFDByteString; begin FIntegerDateTimes := MAXINT; FServerVersion := 0; try sConnBytes := Encoder.Encode(AConnStr, ecUTF8); FHandle := Lib.FPQconnectdb(PFDAnsiString(PByte(sConnBytes))); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} Check; // Register notice receiver if FOwnHandle then FDefaultNoticeReceiver := Lib.FPQsetNoticeReceiver(FHandle, PQnoticeReciever, Self); FTypesManager.Connected; except Disconnect; raise; end; end; {-------------------------------------------------------------------------------} procedure TPgConnection.Disconnect; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQfinish, ['ppgconn', FHandle]); end; {$ENDIF} begin {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} ClearNotices; if (FHandle = nil) or not FOwnHandle then Exit; Lib.FPQfinish(FHandle); FHandle := nil; end; {-------------------------------------------------------------------------------} function TPgConnection.GetParameterStatus(const AParam: String): String; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQparameterStatus, ['conn', FHandle, 'ParamName', AParam, 'Result', Result]); end; {$ENDIF} var sParam: TFDByteString; begin sParam := FEncoder.Encode(AParam, ecANSI); Result := FEncoder.Decode(Lib.FPQparameterStatus(FHandle, PFDAnsiString(PByte(sParam))), -1); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} end; {-------------------------------------------------------------------------------} function TPgConnection.GetTransactionStatus: Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQtransactionStatus, ['conn', FHandle, 'Result', Result]); end; {$ENDIF} begin Result := Lib.FPQtransactionStatus(FHandle); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} end; {-------------------------------------------------------------------------------} function TPgConnection.GetServerVersion: TFDVersion; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQserverVersion, ['conn', FHandle, 'Result', FServerVersion]); end; {$ENDIF} begin if FServerVersion = 0 then if Assigned(Lib.FPQserverVersion) then begin FServerVersion := TFDVersion(Lib.FPQserverVersion(FHandle)) * 10000; {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} Check; end else FServerVersion := FDVerStr2Int(SERVER_VERSION); Result := FServerVersion; end; {-------------------------------------------------------------------------------} function TPgConnection.GetSERVER_VERSION: String; begin Result := GetParameterStatus('server_version'); end; {-------------------------------------------------------------------------------} function TPgConnection.GetSERVER_ENCODING: String; begin Result := GetParameterStatus('server_encoding'); end; {-------------------------------------------------------------------------------} function TPgConnection.GetCLIENT_ENCODING: String; begin Result := GetParameterStatus('client_encoding'); end; {-------------------------------------------------------------------------------} function TPgConnection.GetIS_SUPERUSER: String; begin Result := GetParameterStatus('is_superuser'); end; {-------------------------------------------------------------------------------} function TPgConnection.GetSESSION_AUTHORIZATION: String; begin Result := GetParameterStatus('session_authorization'); end; {-------------------------------------------------------------------------------} function TPgConnection.GetDATESTYLE: String; begin Result := GetParameterStatus('DateStyle'); end; {-------------------------------------------------------------------------------} function TPgConnection.GetTIMEZONE: String; begin Result := GetParameterStatus('TimeZone'); end; {-------------------------------------------------------------------------------} function TPgConnection.GetINTEGER_DATETIMES: String; begin Result := GetParameterStatus('integer_datetimes'); end; {-------------------------------------------------------------------------------} function TPgConnection.GetIntegerDateTimes: Boolean; begin if FIntegerDateTimes = MAXINT then FIntegerDateTimes := CompareText(INTEGER_DATETIMES, 'on'); Result := FIntegerDateTimes = 0; end; {-------------------------------------------------------------------------------} function TPgConnection.GetSTANDARD_CONFORMING_STRINGS: String; begin Result := GetParameterStatus('standard_conforming_strings'); end; {-------------------------------------------------------------------------------} procedure TPgConnection.ExecuteQuery(ASQL: String); {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQexec, ['ppgconn', FHandle, 'sql', ASQL]); end; {$ENDIF} var hResult: PPGresult; begin {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} if (StrLComp(PChar(ASQL), PChar(sClosePrefix), Length(sClosePrefix)) <> 0) and (StrLComp(PChar(ASQL), PChar(sDeallocatePrefix), Length(sDeallocatePrefix)) <> 0) then ClearNotices; hResult := Lib.FPQexec(FHandle, PByte(Encoder.Encode(ASQL))); try CheckResult(hResult, OwningObj); finally Lib.FPQclear(hResult); end; end; {-------------------------------------------------------------------------------} procedure TPgConnection.Abort; var pCancel: PPGcancel; iCancelRes: Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQcancel, ['conn', FHandle, 'FPQcancel', pCancel]); end; {$ENDIF} begin if not Assigned(Lib.FPQgetCancel) then Exit; pCancel := Lib.FPQgetCancel(FHandle); try FBuffer.Check(cancel_buf_size); iCancelRes := Lib.FPQcancel(pCancel, FBuffer.FBuffer, cancel_buf_size); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} if iCancelRes = 0 then DoError(Encoder.Decode(PByte(FBuffer.FBuffer), -1), Lib.FPQstatus(FHandle)); finally Lib.FPQfreeCancel(pCancel); end; end; {-------------------------------------------------------------------------------} function TPgConnection.GetClientEncoding: String; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQClientEncoding, ['conn', FHandle, 'Result', Result]); end; {$ENDIF} begin Result := Encoder.Decode(PByte(Lib.Fpg_encoding_to_char( Lib.FPQclientEncoding(FHandle))), -1); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} end; {-------------------------------------------------------------------------------} procedure TPgConnection.SetClientEncoding(const AValue: String); {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQsetClientEncoding, ['conn', FHandle, 'encoding', AValue]); end; {$ENDIF} begin {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} Lib.FPQsetClientEncoding(FHandle, PFDAnsiString(PByte(Encoder.Encode(AValue)))); Check; end; {-------------------------------------------------------------------------------} function TPgConnection.GenerateName: String; begin Inc(FPStmtIDCounter^); Result := Format('%dSTM', [FPStmtIDCounter^]); end; {-------------------------------------------------------------------------------} function TPgConnection.EncryptPassword(const APassword, AUser, AAlgorythm: String): String; begin if Assigned(Lib.FPQencryptPasswordConn) then Result := Encoder.Decode(PByte(Lib.FPQencryptPasswordConn(FHandle, PFDAnsiString(PByte(Encoder.Encode(APassword))), PFDAnsiString(PByte(Encoder.Encode(AUser))), PFDAnsiString(PByte(Encoder.Encode(AAlgorythm))))), -1) else Result := Encoder.Decode(PByte(Lib.FPQencryptPassword( PFDAnsiString(PByte(Encoder.Encode(APassword))), PFDAnsiString(PByte(Encoder.Encode(AUser))))), -1); end; {-------------------------------------------------------------------------------} { Data conversion } {-------------------------------------------------------------------------------} procedure MoveRotate(ASrc, ADest: Pointer; ALen: Cardinal); var pSrc, pDest: PByte; begin pSrc := ASrc; pDest := PByte(ADest) + ALen - 1; while ALen > 0 do begin pDest^ := pSrc^; Inc(pSrc); Dec(pDest); Dec(ALen); end; end; {-------------------------------------------------------------------------------} function ReadWord(ABuffer: Pointer; AOffset: Cardinal = 0): Word; begin MoveRotate(Pointer(NativeUInt(ABuffer) + AOffset), @Result, SizeOf(Result)); end; {-------------------------------------------------------------------------------} procedure WriteWord(ABuffer: Pointer; AOffset: Cardinal; AValue: Word); begin MoveRotate(@AValue, Pointer(NativeUInt(ABuffer) + AOffset), SizeOf(AValue)); end; {-------------------------------------------------------------------------------} function ReadInteger(ABuffer: Pointer; AOffset: Cardinal = 0): Integer; begin MoveRotate(Pointer(NativeUInt(ABuffer) + AOffset), @Result, SizeOf(Result)); end; {-------------------------------------------------------------------------------} procedure WriteInteger(ABuffer: Pointer; AOffset: Cardinal; AValue: Integer); begin MoveRotate(@AValue, Pointer(NativeUInt(ABuffer) + AOffset), SizeOf(AValue)); end; {-------------------------------------------------------------------------------} procedure j2date(const AValue: Int64; out AYear, AMonth, ADay: Word); var julian, quad, extra: Cardinal; y: Integer; begin julian := AValue; julian := julian + 32044; quad := julian div 146097; extra := (julian - quad * 146097) * 4 + 3; julian := julian + 60 + quad * 3 + extra div 146097; quad := julian div 1461; julian := julian - quad * 1461; y := julian * 4 div 1461; if y <> 0 then julian := (julian + 305) mod 365 else julian := (julian + 306) mod 366; julian := julian + 123; y := y + Integer(quad * 4); AYear := y - 4800; quad := julian * 2141 div 65536; ADay := julian - 7834 * quad div 256; AMonth := (quad + 10) mod 12 + 1; end; {-------------------------------------------------------------------------------} procedure dtInt2time(AValue: Int64; out AHour, AMin, ASec: Word; out AFsec: Cardinal); begin AHour := AValue div McSecsPerHour; AValue := AValue - Int64(AHour) * Int64(McSecsPerHour); AMin := AValue div McSecsPerMin; AValue := AValue - Int64(AMin) * Int64(McSecsPerMin); ASec := AValue div McSecsPerSec; AFsec := (AValue - Int64(ASec) * Int64(McSecsPerSec)) div MSecsPerSec; end; {-------------------------------------------------------------------------------} procedure dtDbl2time(AValue: Double; out AHour, AMin, ASec: Word; out AFsec: Cardinal); begin AHour := Trunc(AValue / SecsPerHour); AValue := AValue - AHour * SecsPerHour; AMin := Trunc(AValue / SecsPerMin); AValue := AValue - AMin * SecsPerMin; ASec := Trunc(AValue); AFsec := Trunc((AValue - ASec) * MSecsPerSec); end; {-------------------------------------------------------------------------------} function date2j(AYear, AMonth, ADay: Word): Int64; var iCentury: Integer; begin if AMonth > 2 then begin AMonth := AMonth + 1; AYear := AYear + 4800; end else begin AMonth := AMonth + 13; AYear := AYear + 4799; end; iCentury := AYear div 100; Result := AYear * 365 - 32167; Result := Result + AYear div 4 - iCentury + iCentury div 4; Result := Result + 7834 * AMonth div 256 + ADay; end; {-------------------------------------------------------------------------------} function time2IntT(const AHour, AMin, ASec: Word; const AFsec: Cardinal): Int64; begin Result := ((AHour * MinsPerHour + AMin) * SecsPerMin + ASec) * MSecsPerSec + AFsec; end; {-------------------------------------------------------------------------------} function time2DblT(const AHour, AMin, ASec: Word; const AFsec: Cardinal): Double; begin Result := (AHour * MinsPerHour + AMin) * SecsPerMin + ASec + AFsec / MSecsPerSec; end; {-------------------------------------------------------------------------------} procedure GetPgNumeric(ASource: Pointer; out ADest: TBcd); var iWordCount: Integer; iOrder: Integer; iAbsOrder: Integer; iSign: Integer; iFOffset: Integer; i, j: Integer; iPrec: Integer; iScale: Integer; iDelta: Integer; wWord: Word; bHb, bLb: Byte; bDec: array[1..4] of Byte; begin FillChar(ADest, SizeOf(TBcd), 0); iWordCount := ReadWord(ASource); iOrder := SmallInt(ReadWord(ASource, 2)); iSign := ReadWord(ASource, 4); if (iWordCount = 0) and (iSign = 0) or // zero (iSign <> 0) and (iSign <> $4000) then begin // NaN ADest.Precision := 10; ADest.SignSpecialPlaces := 2; Exit; end; if iOrder < 0 then begin iAbsOrder := -iOrder; iFOffset := (-iOrder - 1) * 2; end else begin iAbsOrder := iOrder; iFOffset := 0; end; iPrec := 0; iScale := 0; if iWordCount <= iAbsOrder then begin iDelta := (iAbsOrder - iWordCount + 1) * 4; Inc(iPrec, iDelta); if iOrder < 0 then Inc(iScale, iDelta); end else if iOrder < -1 then begin iDelta := (iAbsOrder - 1) * 4; Inc(iPrec, iDelta); Inc(iScale, iDelta); end; for i := 0 to iWordCount - 1 do begin wWord := ReadWord(ASource, 8 + i * 2); bHb := wWord div 100; bLb := wWord mod 100; bDec[1] := bHb div 10; bDec[2] := bHb mod 10; bDec[3] := bLb div 10; bDec[4] := bLb mod 10; ADest.Fraction[i * 2 + iFOffset] := (bDec[1] shl 4) or bDec[2]; ADest.Fraction[i * 2 + 1 + iFOffset] := (bDec[3] shl 4) or bDec[4]; // fraction part if i > iOrder then begin Inc(iPrec, 4); Inc(iScale, 4); end else Inc(iPrec, 4); end; // trim trailing zeros if iScale <> 0 then for j := 4 downto 1 do if bDec[j] = 0 then begin Dec(iPrec); if iScale <> 0 then Dec(iScale); end else Break; // precision must be at least 1 if iPrec = 0 then iPrec := 1; ADest.Precision := iPrec; ADest.SignSpecialPlaces := iScale; if iSign = $4000 then ADest.SignSpecialPlaces := ADest.SignSpecialPlaces or $80; end; {-------------------------------------------------------------------------------} procedure GetPgMoney(ASource: Pointer; ASourceLen: Integer; out ADest: Currency); var aMoney: array[0..7] of Byte; begin MoveRotate(ASource, @aMoney[0], ASourceLen); if ASourceLen = SizeOf(Integer) then ADest := PInteger(@aMoney[0])^ / 100 else if ASourceLen = SizeOf(Int64) then ADest := PInt64(@aMoney[0])^ / 100 else ASSERT(False); end; {-------------------------------------------------------------------------------} procedure SetPgNumeric(const ASource: TBcd; ADest: Pointer; out ADestLen: LongWord); const MaxWords = MaxFMTBcdFractionSize div 4; MulTable: array[0..3] of Integer = (1000, 100, 10, 1); var i: Integer; iWordInd: Integer; iDigitInd: Integer; iDigit: Integer; iPrec: Integer; iScale: Integer; iLast: Integer; iOrder: Integer; lNegative: Boolean; HasDigit: Boolean; aWords: array[0..MaxWords - 1] of Word; begin FillChar(aWords[0], MaxWords * SizeOf(Word), 0); lNegative := ASource.SignSpecialPlaces and (1 shl 7) <> 0; iScale := ASource.SignSpecialPlaces and 63; iPrec := ASource.Precision - iScale; iLast := iPrec + iScale - 1; iWordInd := 0; iOrder := 0; HasDigit := False; iDigitInd := 4 - iPrec mod 4; if iDigitInd = 4 then iDigitInd := 0; for i := 0 to iLast do begin iDigit := ASource.Fraction[i div 2]; case i mod 2 of 0: iDigit := iDigit shr 4; 1: iDigit := iDigit and 15; end; if iDigit <> 0 then HasDigit := True; aWords[iWordInd] := aWords[iWordInd] + iDigit * MulTable[iDigitInd]; Inc(iDigitInd); if iDigitInd = 4 then begin iDigitInd := 0; if (aWords[iWordInd] <> 0) or HasDigit then begin if i < iLast then Inc(iWordInd); if i < iPrec then Inc(iOrder); end else if i >= iPrec - 1 then Dec(iOrder); end; end; if HasDigit then begin if (iOrder >= 0) or (iScale - iLast = 1) and (iOrder < 0) then Dec(iOrder); Inc(iWordInd); end else begin iWordInd := 0; iOrder := 0; lNegative := False; iScale := 0; end; WriteWord(ADest, 0, Word(iWordInd)); WriteWord(ADest, 2, Word(iOrder)); if lNegative then WriteWord(ADest, 4, $4000) else WriteWord(ADest, 4, 0); WriteWord(ADest, 6, Word(iScale)); for i := 0 to iWordInd - 1 do WriteWord(ADest, 8 + i * 2, aWords[i]); ADestLen := (4 + iWordInd) * SizeOf(Word); end; {-------------------------------------------------------------------------------} procedure SetPgMoney(const ASource: Currency; ADest: Pointer; ADestLen: LongWord); var aMoney: array[0..7] of Byte; begin if ADestLen = SizeOf(Integer) then PInteger(@aMoney[0])^ := Integer(Trunc(ASource * 100)) else if ADestLen = SizeOf(Int64) then PInt64(@aMoney[0])^ := Int64(Trunc(ASource * 100)) else ASSERT(False); MoveRotate(@aMoney[0], ADest, ADestLen); end; {-------------------------------------------------------------------------------} { TPgVariable } {-------------------------------------------------------------------------------} constructor TPgVariable.Create(AOwner: TPgVariables); begin inherited Create; FOwner := AOwner; FStatement := AOwner.FStatement; end; {-------------------------------------------------------------------------------} procedure TPgVariable.CheckArrayBounds(AValue, ALBound, AHBound: Integer); begin if AValue <> -1 then begin if (TypeRef = nil) or not (paArray in TypeRef.Attrs) then FDException(Statement.OwningObj, [S_FD_LPhys, S_FD_PGId], er_FD_PgIsNotArray, [DumpLabel]); if (AValue < ALBound) or (AValue > AHBound) then FDException(Statement.OwningObj, [S_FD_LPhys, S_FD_PGId], er_FD_PgArrIndexOutOfBound, [DumpLabel, AValue, ALBound, AHBound]); end; end; {-------------------------------------------------------------------------------} procedure TPgVariable.SetTypeOid(AValue: Oid); begin if FTypeOid <> AValue then begin FTypeRef := Statement.FConnection.TypesManager.Types[AValue]; FTypeOid := FTypeRef.Id; end; end; {-------------------------------------------------------------------------------} procedure TPgVariable.AllocBuffer(ASize: LongWord); begin ASSERT(False); end; {-------------------------------------------------------------------------------} function TPgVariable.Pg2FDData(AType: TPgType; ASource: Pointer; ASourceLen: Integer; var ADest: Pointer; var ADestLen: LongWord; AByRef: Boolean): Boolean; var iId: Oid; pWC: Pointer; procedure GetPgDate(ASource: Pointer; out ADest: Integer); var iDays: Integer; begin MoveRotate(ASource, @iDays, SizeOf(iDays)); iDays := pg_base_date + iDays; if iDays < MinDateTime then iDays := MinDateTime; if iDays > MaxDateTime then iDays := MaxDateTime; ADest := iDays + DateDelta; end; procedure GetPgTime(ASource: Pointer; out ADest: Integer); var aSeconds: TPgTimeStampBuf; begin MoveRotate(ASource, @aSeconds, SizeOf(aSeconds)); if Statement.FConnection.IntegerDateTimes then ADest := PInt64(@aSeconds)^ div MSecsPerSec else ADest := Trunc(PDouble(@aSeconds)^ * MSecsPerSec); end; procedure GetPgTimeStamp(ASource: Pointer; out ADest: TSQLTimeStamp; ATimeZoneOffset: Integer); var iDate, iTime: Int64; dDate, dTime: Double; begin if Statement.FConnection.IntegerDateTimes then begin ASSERT(SizeOf(TPgTimeStampBuf) = SizeOf(iTime)); MoveRotate(ASource, @iTime, SizeOf(TPgTimeStampBuf)); if iTime = C_FD_MaxInt64 then begin ADest.Year := 9999; ADest.Month := 12; ADest.Day := 31; ADest.Hour := 23; ADest.Minute := 59; ADest.Second := 59; ADest.Fractions := 999; end else if iTime = C_FD_MinInt64 then begin ADest.Year := 1; ADest.Month := 12; ADest.Day := 31; ADest.Hour := 23; ADest.Minute := 59; ADest.Second := 59; ADest.Fractions := 999; end else begin if ATimeZoneOffset <> 0 then iTime := iTime + ATimeZoneOffset * McSecsPerHour; iDate := iTime div McSecsPerDay; iTime := iTime mod McSecsPerDay; if iTime < 0 then begin iTime := iTime + McSecsPerDay; iDate := iDate - 1; end; iDate := iDate + POSTGRES_EPOCH_JDATE; j2date(iDate, Word(ADest.Year), ADest.Month, ADest.Day); dtInt2time(iTime, ADest.Hour, ADest.Minute, ADest.Second, ADest.Fractions); end; end else begin ASSERT(SizeOf(TPgTimeStampBuf) = SizeOf(dTime)); MoveRotate(ASource, @dTime, SizeOf(TPgTimeStampBuf)); if ATimeZoneOffset <> 0 then dTime := dTime + ATimeZoneOffset * SecsPerHour; if dTime < 0 then dDate := Ceil(dTime / SecsPerDay) else dDate := Floor(dTime / SecsPerDay); if dDate <> 0 then dTime := dTime - Round(dDate * SecsPerDay); if dTime < 0 then begin dTime := dTime + SecsPerDay; dDate := dDate - 1; end; dDate := dDate + POSTGRES_EPOCH_JDATE; j2date(Trunc(dDate), Word(ADest.Year), ADest.Month, ADest.Day); dtDbl2time(dTime, ADest.Hour, ADest.Minute, ADest.Second, ADest.Fractions); end; end; procedure GetPgRelTime(ASource: Pointer; out ADest: TSQLTimeStamp); procedure FMODULO(var t: Double; q: Word; const u: Double); begin if t < 0 then q := Ceil(t / u) else q := Floor(t / u); if q <> 0 then t := t - Round(q * u); end; var dTime: Double; begin dTime := PInteger(ASource)^; FMODULO(dTime, ADest.Year, SecsPerDay * 356.25); FMODULO(dTime, ADest.Month, SecsPerDay * 30); FMODULO(dTime, ADest.Day, SecsPerDay); FMODULO(dTime, ADest.Hour, SecsPerHour); FMODULO(dTime, ADest.Minute, SecsPerMin); FMODULO(dTime, ADest.Second, 1); ADest.Fractions := 0; end; procedure GetPgInterval(ASource: Pointer; out ADest: TFDSQLTimeInterval); var pBuff: TPgTimeStampBuf; dSeconds: Double; iDays: Integer; iMonths: Integer; iTmp: Integer; begin if Statement.FConnection.IntegerDateTimes then begin MoveRotate(ASource, @pBuff, SizeOf(dSeconds)); dSeconds := PInt64(@pBuff)^ / McSecsPerSec; end else MoveRotate(ASource, @dSeconds, SizeOf(dSeconds)); MoveRotate(Pointer(NativeUInt(ASource) + 8), @iDays, SizeOf(iDays)); MoveRotate(Pointer(NativeUInt(ASource) + 12), @iMonths, SizeOf(iMonths)); FillChar(ADest, SizeOf(ADest), 0); if iMonths <> 0 then begin ADest.Years := Abs(iMonths) div 12; ADest.Months := Abs(iMonths) mod 12; if iMonths >= 0 then ADest.Sign := 1 else ADest.Sign := -1; ADest.Kind := itYear2Month; end else begin if iDays <> 0 then begin ADest.Days := Abs(iDays); if iDays >= 0 then ADest.Sign := 1 else ADest.Sign := -1; ADest.Kind := itDay; end; if dSeconds <> 0 then begin iTmp := Abs(Trunc(dSeconds)); ADest.Hours := iTmp div SecsPerHour; iTmp := iTmp mod SecsPerHour; ADest.Minutes := iTmp div SecsPerMin; ADest.Seconds := iTmp mod SecsPerMin; ADest.Fractions := Abs(Trunc(Frac(dSeconds) * McSecsPerSec)); if ADest.Kind = itUnknown then begin if dSeconds >= 0 then ADest.Sign := 1 else ADest.Sign := -1; ADest.Kind := itHour2Second; end else ADest.Kind := itDay2Second; end; end; end; procedure Str2Guid(ASource: Pointer; ASourceLen: Integer; out ADest: TGUID); var s: String; begin SetString(s, PChar(ASource), ASourceLen); ADest := StringToGUID('{' + s + '}'); // Change GUID mixed-endian to UUID big-endian ADest.D1 := Cardinal(ReadInteger(@ADest.D1)); ADest.D2 := ReadWord(@ADest.D2); ADest.D3 := ReadWord(@ADest.D3); end; procedure Str2Curr(ASource: Pointer; ASourceLen: Integer; out ADest: Currency); var pSrc, pDest: PChar; lClear: Boolean; begin pSrc := PChar(ASource); (pSrc + ASourceLen)^ := #0; pDest := pSrc; lClear := False; while pSrc^ <> #0 do begin case pSrc^ of '0' .. '9', '+', '-': begin pDest^ := pSrc^; Inc(pDest); lClear := False; end; '.', ',': if not lClear then begin pDest^ := FormatSettings.DecimalSeparator; Inc(pDest); end; ' ', #160: ; else lClear := True; end; Inc(pSrc); end; pDest^ := #0; if not TextToFloat(PChar(ASource), ADest, fvCurrency) then raise EConvertError.CreateResFmt(@SInvalidFloat, [PChar(ASource)]); end; procedure Str2Bin(ASource: Pointer; ASourceLen: Integer; ADest: Pointer; out ADestLen: LongWord); var i: Integer; lOn: Boolean; B, M: Byte; begin ADestLen := (ASourceLen + 7) div 8; for i := 0 to ASourceLen - 1 do begin lOn := (PChar(ASource) + i)^ = '1'; if i mod 8 = 0 then B := 0 else B := (PByte(ASource) + (i div 8))^; M := 1 shl (i mod 8); if lOn then B := B or M else B := B and not M; (PByte(ASource) + (i div 8))^ := B; end; end; procedure Str2Interval(ASource: Pointer; ASourceLen: Integer; out ADest: TFDSQLTimeInterval); var s: String; begin SetString(s, PChar(ASource), ASourceLen); ADest := FDStr2SQLTimeInterval(s); end; procedure Hex2Bin(ASource: Pointer; ASourceLen: Integer; ADest: Pointer; out ADestLen: LongWord); {$IFDEF NEXTGEN} var aBuff: TBytes; {$ENDIF} begin if (PChar(ASource)^ = '\') and ((PChar(ASource) + 1)^ = 'x') then begin Inc(PChar(ASource), 2); Dec(ASourceLen, 2); end; ADestLen := (ASourceLen + 1) div 2; {$IFNDEF NEXTGEN} HexToBin(PChar(ASource), ADest^, ADestLen); {$ELSE} SetLength(aBuff, ADestLen); HexToBin(PChar(ASource), 0, aBuff, 0, ADestLen); Move(aBuff[0], ADest^, ADestLen); {$ENDIF} end; procedure Str2TimeStamp(ASource: Pointer; ASourceLen: Integer; out ADest: TSQLTimeStamp); var c: Char; begin c := (PChar(ASource) + ASourceLen - 3)^; if (c = '+') or (c = '-') then Dec(ASourceLen, 3); FDISOStr2TimeStamp(ASource, ASourceLen, ADest); end; begin Result := True; ADestLen := AType.FDSize; if ADestLen = 0 then ADestLen := ASourceLen; if (ADest = nil) and (AType.Attrs * [paString, paBlob] = []) then Exit; if paEnum in AType.Attrs then iId := SQL_VARCHAR else iId := AType.Id; if FFormat = 0 then case iId of SQL_NAME, SQL_CHAR, SQL_BPCHAR, SQL_VARCHAR, SQL_TEXT, SQL_JSON, SQL_JSONB, SQL_XML, SQL_NODE_TREE, SQL_REFCURSOR, SQL_UNKNOWN, SQL_ACLITEM, SQL_VOID: ; else begin pWC := nil; ASourceLen := Statement.FConnection.Encoder.Decode(ASource, ASourceLen, pWC, ecUTF16); ASource := pWC; end; end; case iId of SQL_INT2, SQL_INT4, SQL_INT8, SQL_OID, SQL_TID, SQL_XID, SQL_CID, SQL_REGPROC, SQL_REGPROCEDURE, SQL_REGOPER, SQL_REGOPERATOR, SQL_REGCLASS, SQL_REGTYPE, SQL_SMGR: if FFormat = 1 then MoveRotate(ASource, ADest, ADestLen) else FDStr2Int(ASource, ASourceLen, ADest, ADestLen, False, 0); SQL_FLOAT4, SQL_FLOAT8: if FFormat = 1 then MoveRotate(ASource, ADest, ADestLen) else FDStr2Float(ASource, ASourceLen, ADest, ADestLen, '.'); SQL_CASH: if FFormat = 1 then GetPgMoney(ASource, ADestLen, PCurrency(ADest)^) else Str2Curr(ASource, ASourceLen, PCurrency(ADest)^); SQL_NAME, SQL_CHAR, SQL_BPCHAR, SQL_VARCHAR, SQL_TEXT, SQL_JSON, SQL_JSONB, SQL_XML, SQL_NODE_TREE, SQL_REFCURSOR, SQL_UNKNOWN, SQL_ACLITEM, SQL_VOID: begin if (iId = SQL_JSONB) and (FFormat = 1) then begin if PByte(ASource)^ <> JSONB_VER then begin ADest := nil; ADestLen := 0; Exit(False); end; Inc(PByte(ASource)); Dec(ADestLen); Dec(ASourceLen); end; case Statement.FConnection.Encoder.Encoding of ecANSI: begin if (paFixed in AType.Attrs) and Statement.StrsTrim then while (ADestLen > 0) and (PFDAnsiString(ASource)[ADestLen - 1] = TFDAnsiChar(' ')) do Dec(ADestLen); if (ADestLen = 0) and Statement.StrsEmpty2Null then begin Result := False; ADest := nil; end else if AByRef then ADest := ASource else if ADest <> nil then Move(PFDAnsiString(ASource)^, PFDAnsiString(ADest)^, ADestLen * SizeOf(TFDAnsiChar)); end; ecUTF8: begin pWC := nil; ADestLen := Statement.FConnection.Encoder.Decode(ASource, ASourceLen, pWC, ecUTF16); ASource := pWC; if (paFixed in AType.Attrs) and Statement.StrsTrim then while (ADestLen > 0) and (PWideChar(ASource)[ADestLen - 1] = ' ') do Dec(ADestLen); if (ADestLen = 0) and Statement.StrsEmpty2Null then begin Result := False; ADest := nil; end else if AByRef then ADest := ASource else if ADest <> nil then Move(PWideChar(ASource)^, PWideChar(ADest)^, ADestLen * SizeOf(WideChar)); end; end; end; SQL_BYTEA, SQL_ANY, SQL_MACADDR, SQL_MACADDR8, SQL_CIDR, SQL_INET: if FFormat = 1 then if AByRef then ADest := ASource else Move(ASource^, ADest^, ADestLen) else begin if iId = SQL_BYTEA then Hex2Bin(ASource, ASourceLen, ASource, ADestLen) else ADestLen := ASourceLen; if AByRef then ADest := ASource else if ADest <> nil then Move(ASource^, ADest^, ADestLen); end; SQL_BIT, SQL_VARBIT: if FFormat = 1 then begin MoveRotate(ASource, @ADestLen, SizeOf(ADestLen)); ADestLen := (ADestLen + 7) div 8; if AByRef then ADest := Pointer(NativeUInt(ASource) + SizeOf(Integer)) else Move(Pointer(NativeUInt(ASource) + SizeOf(Integer))^, ADest^, ADestLen); end else begin Str2Bin(ASource, ASourceLen, ASource, ADestLen); if AByRef then ADest := ASource else if ADest <> nil then Move(ASource^, ADest^, ADestLen); end; SQL_DATE: if FFormat = 1 then GetPgDate(ASource, PInteger(ADest)^) else PInteger(ADest)^ := FDISOStr2Date(ASource, ASourceLen); SQL_TIME, SQL_TIMETZ: if FFormat = 1 then GetPgTime(ASource, PInteger(ADest)^) else PInteger(ADest)^ := FDISOStr2Time(ASource, ASourceLen); SQL_TIMESTAMP: if FFormat = 1 then GetPgTimeStamp(ASource, PSQLTimeStamp(ADest)^, 0) else FDISOStr2TimeStamp(ASource, ASourceLen, PSQLTimeStamp(ADest)^); SQL_TIMESTAMPTZ: if FFormat = 1 then GetPgTimeStamp(ASource, PSQLTimeStamp(ADest)^, Statement.Connection.TimeZoneOffset) else Str2TimeStamp(ASource, ASourceLen, PSQLTimeStamp(ADest)^); SQL_RELTIME: if FFormat = 1 then GetPgRelTime(ASource, PSQLTimeStamp(ADest)^) else PSQLTimeStamp(ADest)^ := FDTime2SQLTimeStamp(FDISOStr2Time(ASource, ASourceLen)); SQL_ABSTIME: begin Result := False; ADest := nil; end; SQL_INTERVAL: if FFormat = 1 then GetPgInterval(ASource, PFDSQLTimeInterval(ADest)^) else Str2Interval(ASource, ASourceLen, PFDSQLTimeInterval(ADest)^); SQL_NUMERIC: if FFormat = 1 then GetPgNumeric(ASource, PBcd(ADest)^) else FDStr2BCD(ASource, ASourceLen, PBcd(ADest)^, '.'); SQL_BOOL: if FFormat = 1 then PWordBool(ADest)^ := WordBool(PByte(ASource)^) else PWordBool(ADest)^ := (PChar(ASource)^ = 't') or (PChar(ASource)^ = 'T'); SQL_UUID: if FFormat = 1 then if Statement.GUIDEndian = Big then PGUID(ADest)^ := TGUID.Create(PByte(ASource)^, True) else PGUID(ADest)^ := PGUID(ASource)^ else begin Str2Guid(ASource, ASourceLen, PGUID(ADest)^); if Statement.GUIDEndian = Big then PGUID(ADest)^ := TGUID.Create(PGUID(ADest)^, True); end; else ASSERT(False); end; end; {-------------------------------------------------------------------------------} function TPgVariable.FD2PgData(AType: TPgType; ASource: Pointer; ASourceLen: Integer; var ADest: Pointer; var ADestLen: LongWord; var ADestFormat: Integer; AByRef: Boolean): Boolean; var iByteLen, iMaxChars: LongWord; pRes: Pointer; procedure ErrorDataTooLarge(AMax, AActual: LongWord); begin FDException(Statement.OwningObj, [S_FD_LPhys, S_FD_PGId], er_FD_AccDataToLarge, [DumpLabel, AMax, AActual]); end; procedure SetPgDate(const ASource: Integer; ADest: Pointer); var iDays: Integer; begin iDays := ASource - DateDelta - pg_base_date; MoveRotate(@iDays, ADest, SizeOf(Integer)); end; procedure SetPgTime(const ASource: Integer; ADest: Pointer); var pSeconds: TPgTimeStampBuf; begin if Statement.FConnection.IntegerDateTimes then PInt64(@pSeconds)^ := Int64(ASource) * MSecsPerSec else PDouble(@pSeconds)^ := ASource / MSecsPerSec; MoveRotate(@pSeconds, ADest, SizeOf(TPgTimeStampBuf)); end; procedure SetPgTimeStamp(const ASource: TSQLTimeStamp; ADest: Pointer); var iDate, iTime: Int64; dDate, dTime: Double; begin if Statement.FConnection.IntegerDateTimes then begin ASSERT(SizeOf(TPgTimeStampBuf) = SizeOf(iTime)); iDate := date2j(ASource.Year, ASource.Month, ASource.Day) - POSTGRES_EPOCH_JDATE; iTime := time2IntT(ASource.Hour, ASource.Minute, ASource.Second, ASource.Fractions); iTime := (iDate * MSecsPerDay + iTime) * MSecsPerSec; MoveRotate(@iTime, ADest, SizeOf(iTime)); end else begin ASSERT(SizeOf(TPgTimeStampBuf) = SizeOf(dTime)); dDate := date2j(ASource.Year, ASource.Month, ASource.Day) - POSTGRES_EPOCH_JDATE; dTime := time2DblT(ASource.Hour, ASource.Minute, ASource.Second, ASource.Fractions); dTime := dDate * SecsPerDay + dTime; MoveRotate(@dTime, ADest, SizeOf(dTime)); end; end; procedure SetPgInterval(const ASource: TFDSQLTimeInterval; ADest: Pointer); var dSeconds: Double; iDays: Integer; iMonths: Integer; iTime: Int64; begin iMonths := 0; iDays := 0; dSeconds := 0; if ASource.Kind in [itYear, itMonth, itYear2Month] then iMonths := ASource.Months + ASource.Years * 12; if ASource.Kind in [itDay, itDay2Hour, itDay2Minute, itDay2Second] then iDays := ASource.Days; if ASource.Kind in [itHour, itMinute, itSecond, itDay2Hour, itDay2Minute, itDay2Second, itHour2Minute, itHour2Second, itMinute2Second] then dSeconds := ASource.Hours * SecsPerHour + ASource.Minutes * SecsPerMin + ASource.Seconds + ASource.Fractions / McSecsPerSec; if ASource.Sign < 0 then if iMonths <> 0 then iMonths := -iMonths else if iDays <> 0 then iDays := -iDays else if dSeconds <> 0 then dSeconds := -dSeconds; if Statement.FConnection.IntegerDateTimes then begin iTime := Trunc(dSeconds * McSecsPerSec); MoveRotate(@iTime, ADest, SizeOf(iTime)); end else MoveRotate(@dSeconds, ADest, SizeOf(dSeconds)); MoveRotate(@iDays, Pointer(NativeUInt(ADest) + 8), SizeOf(iDays)); MoveRotate(@iMonths, Pointer(NativeUInt(ADest) + 12), SizeOf(iMonths)); end; begin Result := not ((ASource = nil) and (ASourceLen = 0)); if not Result then Exit; ADestFormat := 1; case AType.Id of SQL_INT2, SQL_INT4, SQL_INT8, SQL_OID, SQL_TID, SQL_XID, SQL_CID, SQL_REGPROC, SQL_REGPROCEDURE, SQL_REGOPER, SQL_REGOPERATOR, SQL_REGCLASS, SQL_REGTYPE, SQL_FLOAT4, SQL_FLOAT8, SQL_SMGR: begin ASSERT(ASourceLen = Integer(ADestLen)); MoveRotate(ASource, ADest, ADestLen); end; SQL_CASH: SetPgMoney(PCurrency(ASource)^, ADest, ASourceLen); SQL_NAME, SQL_CHAR, SQL_BPCHAR, SQL_VARCHAR, SQL_UNKNOWN, SQL_ACLITEM: begin if (paFixed in AType.Attrs) and Statement.StrsTrim then if FEncoding = ecUTF16 then while (ASourceLen > 0) and (PWideChar(ASource)[ASourceLen - 1] = ' ') do Dec(ASourceLen) else while (ASourceLen > 0) and (PFDAnsiString(ASource)[ASourceLen - 1] = TFDAnsiChar(' ')) do Dec(ASourceLen); if Statement.StrsEmpty2Null and (ASourceLen = 0) then Result := False; if Result then begin if (FEncoding = ecANSI) and (Statement.FConnection.Encoder.Encoding = ecANSI) then begin iByteLen := ASourceLen * SizeOf(TFDAnsiChar); Move(ASource^, ADest^, iByteLen); end else begin pRes := nil; iByteLen := Statement.FConnection.Encoder.Encode(ASource, ASourceLen, pRes, FEncoding); iMaxChars := ADestLen - 1; if FEncoding = ecUTF16 then iMaxChars := iMaxChars div SizeOf(WideChar); if iByteLen > iMaxChars then if Statement.StrsTrim2Len then iByteLen := iMaxChars else ErrorDataTooLarge(ADestLen, iByteLen); Move(pRes^, ADest^, iByteLen); end; end else iByteLen := 0; ADestLen := iByteLen; end; SQL_DATE: SetPgDate(PInteger(ASource)^, ADest); SQL_TIME, SQL_TIMETZ: SetPgTime(PInteger(ASource)^, ADest); SQL_TIMESTAMP, SQL_TIMESTAMPTZ: SetPgTimeStamp(PSQLTimeStamp(ASource)^, ADest); SQL_INTERVAL: SetPgInterval(PFDSQLTimeInterval(ASource)^, ADest); SQL_TEXT, SQL_JSON, SQL_XML, SQL_NODE_TREE: if (FEncoding = ecANSI) and (Statement.FConnection.Encoder.Encoding = ecANSI) then begin ADestLen := ASourceLen * SizeOf(TFDAnsiChar); if AByRef then ADest := ASource else begin AllocBuffer(ADestLen); Move(ASource^, ADest^, ADestLen); end; end else begin pRes := nil; iByteLen := Statement.FConnection.Encoder.Encode(ASource, ASourceLen, pRes, FEncoding); AllocBuffer(iByteLen); Move(pRes^, ADest^, iByteLen); ADestLen := iByteLen; end; SQL_JSONB: if (FEncoding = ecANSI) and (Statement.FConnection.Encoder.Encoding = ecANSI) then begin ADestLen := (ASourceLen + 1) * SizeOf(TFDAnsiChar); if AByRef then ADest := ASource else begin AllocBuffer(ADestLen); PByte(ADest)^ := JSONB_VER; Move(ASource^, (PByte(ADest) + 1)^, ADestLen - 1); end; end else begin pRes := nil; iByteLen := Statement.FConnection.Encoder.Encode(ASource, ASourceLen, pRes, FEncoding) + 1; AllocBuffer(iByteLen); PByte(ADest)^ := JSONB_VER; Move(pRes^, (PByte(ADest) + 1)^, iByteLen - 1); ADestLen := iByteLen; end; SQL_BYTEA, SQL_ANY, SQL_MACADDR, SQL_MACADDR8, SQL_CIDR, SQL_INET, SQL_BIT, SQL_VARBIT: begin ADestLen := ASourceLen; if AByRef then ADest := ASource else begin AllocBuffer(ADestLen); Move(ASource^, ADest^, ADestLen); end; end; SQL_NUMERIC: SetPgNumeric(PBcd(ASource)^, ADest, ADestLen); SQL_BOOL: PByte(ADest)^ := Byte(PWordBool(ASource)^); SQL_UUID: if Statement.GUIDEndian = Big then PGUID(ADest)^ := TGUID.Create(PByte(ASource)^, True) else PGUID(ADest)^ := PGUID(ASource)^; else ASSERT(False); end; end; {-------------------------------------------------------------------------------} function TPgVariable.GetDumpLabel: String; begin if FDumpLabel <> '' then Result := FDumpLabel else Result := ''; end; {$IFDEF FireDAC_MONITOR} {-------------------------------------------------------------------------------} function TPgVariable.DumpSQLDataType: String; begin Result := TypeRef.DumpType; end; {-------------------------------------------------------------------------------} function TPgVariable.DumpFDValue(ABuffer: Pointer; ALen: Integer): String; var aBuff: array [0 .. 127] of Char; begin if (ABuffer = nil) and (ALen = 0) then Result := 'NULL' else case FTypeOid of SQL_INT2, SQL_SMGR: Result := IntToStr(PSmallInt(ABuffer)^); SQL_INT4: Result := IntToStr(PInteger(ABuffer)^); SQL_OID, SQL_TID, SQL_XID, SQL_CID, SQL_REGPROC, SQL_REGPROCEDURE, SQL_REGOPER, SQL_REGOPERATOR, SQL_REGCLASS, SQL_REGTYPE: Result := Format('%u', [POid(ABuffer)^]); SQL_INT8: Result := IntToStr(PInt64(ABuffer)^); SQL_FLOAT4: Result := FloatToStr(PSingle(ABuffer)^); SQL_FLOAT8: Result := FloatToStr(PDouble(ABuffer)^); SQL_CASH: Result := CurrToStr(PCurrency(ABuffer)^); SQL_NAME, SQL_CHAR, SQL_BPCHAR, SQL_VARCHAR, SQL_TEXT, SQL_JSON, SQL_JSONB, SQL_XML, SQL_NODE_TREE, SQL_REFCURSOR, SQL_UNKNOWN, SQL_ACLITEM: if Statement.FConnection.Encoder.Encoding = ecANSI then if ALen > 1024 then Result := '(truncated at 1024) ''' + Statement.FConnection.Encoder.Decode(ABuffer, 1024, ecANSI) + ' ...''' else Result := '''' + Statement.FConnection.Encoder.Decode(ABuffer, ALen, ecANSI) + '''' else if ALen > 1024 then begin SetString(Result, PWideChar(ABuffer), 1024); Result := '(truncated at 1024) ''' + Result + ' ...'''; end else begin SetString(Result, PWideChar(ABuffer), ALen); Result := '''' + Result + ''''; end; SQL_MACADDR, SQL_MACADDR8, SQL_CIDR, SQL_INET: if FFormat = 0 then if Statement.FConnection.Encoder.Encoding = ecANSI then Result := '''' + Statement.FConnection.Encoder.Decode(ABuffer, ALen, ecANSI) + '''' else begin SetString(Result, PWideChar(ABuffer), ALen); Result := '''' + Result + ''''; end else Result := FDBin2Hex(ABuffer, ALen); SQL_BYTEA, SQL_ANY, SQL_BIT, SQL_VARBIT: if ALen > 512 then Result := '(truncated at 512) ' + FDBin2Hex(ABuffer, 512) + ' ...' else Result := FDBin2Hex(ABuffer, ALen); SQL_DATE: Result := DateToStr(FDDate2DateTime(PInteger(ABuffer)^)); SQL_TIME, SQL_TIMETZ: Result := TimeToStr(FDTime2DateTime(PInteger(ABuffer)^)); SQL_TIMESTAMP, SQL_TIMESTAMPTZ, SQL_RELTIME, SQL_ABSTIME: Result := DateTimeToStr(SQLTimeStampToDateTime(PSQLTimeStamp(ABuffer)^)); SQL_INTERVAL: Result := FDSQLTimeInterval2Str(PFDSQLTimeInterval(ABuffer)^); SQL_NUMERIC: begin FDBCD2Str(aBuff, ALen, PBcd(ABuffer)^, FormatSettings.DecimalSeparator); SetString(Result, aBuff, ALen); end; SQL_BOOL: Result := S_FD_Bools[PWordBool(ABuffer)^]; SQL_UUID: Result := GUIDToString(PGUID(ABuffer)^); SQL_VOID: Result := 'VOID'; else ASSERT(False); Result := ''; end; end; {$ENDIF} {-------------------------------------------------------------------------------} { TPgVariables } {-------------------------------------------------------------------------------} constructor TPgVariables.Create(AOwner: TPgStatement); begin inherited Create; FStatement := AOwner; FList := TFDObjList.Create; end; {-------------------------------------------------------------------------------} destructor TPgVariables.Destroy; begin Count := 0; FDFreeAndNil(FList); inherited Destroy; end; {-------------------------------------------------------------------------------} function TPgVariables.Add: TPgVariable; begin Result := GetVariableClass.Create(Self); Result.FIndex := FList.Add(Result); end; {-------------------------------------------------------------------------------} function TPgVariables.GetCount: Integer; begin Result := FList.Count; end; {-------------------------------------------------------------------------------} procedure TPgVariables.SetCount(AValue: Integer); var i: Integer; begin if AValue = FList.Count then Exit; if AValue < FList.Count then begin for i := FList.Count - 1 downto AValue do FDFree(TPgVariable(FList[i])); FList.Count := AValue; end else for i := FList.Count + 1 to AValue do Add; end; {-------------------------------------------------------------------------------} { TPgParam } {-------------------------------------------------------------------------------} constructor TPgParam.Create(AOwner: TPgVariables); begin inherited Create(AOwner); FArrayIndex := -1; end; {-------------------------------------------------------------------------------} destructor TPgParam.Destroy; begin FreeBuffer; inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TPgParam.CheckBuffer; var iDataSize: LongWord; iBufferSize: LongWord; oRef: TPgType; i: Integer; begin oRef := TypeRef; if paArray in oRef.Attrs then oRef := oRef.Members[0].TypeRef; iDataSize := 0; if paString in oRef.Attrs then begin if FSize = 0 then FSize := max_string_size; case Statement.FConnection.FEncoder.Encoding of ecANSI: iDataSize := FSize * SizeOf(TFDAnsiChar); ecUTF8: iDataSize := FSize * C_FD_MaxUTF8Len; end; end else iDataSize := oRef.PGSize; if [paArray, paFixed] * TypeRef.Attrs = [paArray] then iBufferSize := ARRHDRSZ + (SizeOf(Integer) + iDataSize) * Cardinal(FHBound - FLBound + 1) else iBufferSize := iDataSize; if (FBuffer <> nil) and (iDataSize = FDataSize) and (iBufferSize = FBufferSize) then Exit; FDataSize := iDataSize; FBufferSize := iBufferSize; AllocBuffer(FBufferSize); if [paArray, paFixed] * TypeRef.Attrs = [paArray] then begin WriteInteger(FValueRef, 0, 1); // dimensions WriteInteger(FValueRef, 4, 0); // offset to data (ignored) WriteInteger(FValueRef, 8, TypeRef.Members[0].TypeOid); // element type WriteInteger(FValueRef, 12, FHBound - FLBound + 1); // number of elements WriteInteger(FValueRef, 16, FLBound); // index of first element for i := 0 to FHBound - FLBound do WriteInteger(FValueRef, ARRHDRSZ + (SizeOf(Integer) + FDataSize) * Cardinal(i), -1); FValueSize := ARRHDRSZ + (SizeOf(Integer) + FDataSize) * Cardinal(FHBound - FLBound + 1); FIsNull := False; end; end; {-------------------------------------------------------------------------------} procedure TPgParam.AllocBuffer(ASize: LongWord); begin FreeBuffer; if ASize > 0 then GetMem(FBuffer, ASize); FValueRef := FBuffer; end; {-------------------------------------------------------------------------------} procedure TPgParam.FreeBuffer; begin if FBuffer = nil then Exit; FreeMem(FBuffer); if FBuffer = FValueRef then FValueRef := nil; FBuffer := nil; end; {$IFDEF FireDAC_MONITOR} {-------------------------------------------------------------------------------} function TPgParam.DumpValue: String; var pBuf: Pointer; iLen: LongWord; begin pBuf := nil; iLen := 0; if (FValueRef <> nil) and not FIsNull then begin Pg2FDData(TypeRef, FValueRef, FValueSize, pBuf, iLen, True); if (pBuf = nil) and (iLen > 0) then begin pBuf := Statement.FConnection.FBuffer.Check(iLen); Pg2FDData(TypeRef, FValueRef, FValueSize, pBuf, iLen, False); end; end; Result := DumpFDValue(pBuf, iLen); end; {$ENDIF} {-------------------------------------------------------------------------------} procedure TPgParam.SetTypeOid(AValue: Oid); begin if FTypeOid <> AValue then begin FreeBuffer; inherited SetTypeOid(AValue); end; end; {-------------------------------------------------------------------------------} procedure TPgParam.SetData(ApData: Pointer; ALen: LongWord; AByRef: Boolean); var pItem, pVal: Pointer; iLen: LongWord; iIndex: Integer; begin CheckBuffer; if FArrayIndex >= 0 then begin iIndex := FArrayIndex - FLBound; if paFixed in TypeRef.Attrs then begin iLen := FDataSize div LongWord(TypeRef.FixedLen); pVal := Pointer(NativeUInt(FValueRef) + iLen * LongWord(iIndex)); end else begin pItem := Pointer(NativeUInt(FValueRef) + ARRHDRSZ + (SizeOf(Integer) + FDataSize) * LongWord(iIndex)); pVal := Pointer(NativeUInt(pItem) + SizeOf(Integer)); iLen := FDataSize; if (ApData = nil) and (ALen = 0) or not FD2PgData(FTypeRef.Members[0].TypeRef, ApData, ALen, pVal, iLen, FFormat, False) then iLen := LongWord(-1); WriteInteger(pItem, 0, iLen); end; end else begin FValueSize := FDataSize; FIsNull := not FD2PgData(FTypeRef, ApData, ALen, FValueRef, FValueSize, FFormat, AByRef); end; end; {-------------------------------------------------------------------------------} procedure TPgParam.PackBuffer; var pItem, pVal: Pointer; i: Integer; iLen: LongWord; begin if (TypeRef = nil) or not (paArray in TypeRef.Attrs) or (paFixed in TypeRef.Attrs) then Exit; FValueSize := ARRHDRSZ + (SizeOf(Integer) + FDataSize) * LongWord(FHBound - FLBound + 1); pItem := Pointer(NativeUInt(FValueRef) + ARRHDRSZ); for i := FLBound to FHBound do begin pVal := Pointer(NativeUInt(pItem) + SizeOf(Integer)); iLen := ReadInteger(pItem, 0); if iLen < FDataSize then begin if i < FHBound then Move(Pointer(NativeUInt(pVal) + FDataSize)^, Pointer(NativeUInt(pVal) + iLen)^, (SizeOf(Integer) + FDataSize) * LongWord(FHBound - i)); Dec(FValueSize, FDataSize - iLen); end; pItem := Pointer(NativeUInt(pVal) + iLen); end; end; {-------------------------------------------------------------------------------} procedure TPgParam.SetArrayBounds(ALBound, AHBound: Integer); begin if (FLBound <> ALBound) or (FHBound <> AHBound) then begin CheckArrayBounds(ALBound, ALBound, AHBound); FreeBuffer; FLBound := ALBound; FHBound := AHBound; CheckBuffer; end else FIsNull := False; end; {-------------------------------------------------------------------------------} procedure TPgParam.SetArrayIndex(AValue: Integer); begin if FArrayIndex <> AValue then begin CheckArrayBounds(AValue, FLBound, FHBound); FArrayIndex := AValue; end; end; {-------------------------------------------------------------------------------} { TPgParams } {-------------------------------------------------------------------------------} function TPgParams.GetVariableClass: TPgVariableClass; begin Result := TPgParam; end; {-------------------------------------------------------------------------------} procedure TPgParams.SetCount(AValue: Integer); begin if AValue <> FList.Count then begin FreeMem(FValueRefs); FreeMem(FValueLengths); FreeMem(FValueFormats); FreeMem(FValueTypes); FValueRefs := nil; FValueLengths := nil; FValueFormats := nil; FValueTypes := nil; end; inherited SetCount(AValue); end; {-------------------------------------------------------------------------------} function TPgParams.GetValueTypes: Pointer; var i: Cardinal; begin Result := nil; if Count = 0 then Exit; if FValueTypes = nil then GetMem(FValueTypes, Count * SizeOf(Oid)); for i := 0 to Count - 1 do POid(NativeUInt(FValueTypes) + i * SizeOf(Oid))^ := Items[i].FTypeOid; Result := FValueTypes; end; {-------------------------------------------------------------------------------} function TPgParams.GetValueRefs: Pointer; var i: Cardinal; pRef: PPointer; oItem: TPgParam; begin Result := nil; if Count = 0 then Exit; if FValueRefs = nil then GetMem(FValueRefs, Count * SizeOf(Pointer)); for i := 0 to Count - 1 do begin pRef := PPointer(NativeUInt(FValueRefs) + i * SizeOf(Pointer)); oItem := Items[i]; if not oItem.FIsNull then begin oItem.PackBuffer; // AsWideMemo/AsMemo := '' will lead to FValueRef=nil if oItem.FValueRef = nil then pRef^ := pRef else pRef^ := oItem.FValueRef; end else pRef^ := nil; end; Result := FValueRefs; end; {-------------------------------------------------------------------------------} function TPgParams.GetValueLengths: Pointer; var i: Cardinal; begin Result := nil; if Count = 0 then Exit; if FValueLengths = nil then GetMem(FValueLengths, Count * SizeOf(Integer)); for i := 0 to Count - 1 do PInteger(NativeUInt(FValueLengths) + i * SizeOf(Integer))^ := Items[i].FValueSize; Result := FValueLengths; end; {-------------------------------------------------------------------------------} function TPgParams.GetValueFormats: Pointer; var i: Cardinal; begin Result := nil; if Count = 0 then Exit; if FValueFormats = nil then GetMem(FValueFormats, Count * SizeOf(Integer)); for i := 0 to Count - 1 do PInteger(NativeUInt(FValueFormats) + i * SizeOf(Integer))^ := Items[i].FFormat; Result := FValueFormats; end; {-------------------------------------------------------------------------------} function TPgParams.GetItems(AIndex: Integer): TPgParam; begin Result := TPgParam(FList.Items[AIndex]); end; {-------------------------------------------------------------------------------} { TPgField } {-------------------------------------------------------------------------------} constructor TPgField.Create(AOwner: TPgVariables); begin inherited Create(AOwner); FFormat := 1; FArrayIndex := -1; FFields := TPgFields.Create(Self); end; {-------------------------------------------------------------------------------} destructor TPgField.Destroy; begin FDFreeAndNil(FFields); inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TPgField.SetTypeOid(AValue: Oid); var oField: TPgField; oMember: TPgMember; i: Integer; begin if FTypeOid <> AValue then begin inherited SetTypeOid(AValue); FFields.Count := Length(TypeRef.Members); for i := 0 to Length(TypeRef.Members) - 1 do begin oField := FFields[i]; oMember := TypeRef.Members[i]; oField.FName := oMember.Name; oField.FLen := oMember.Len; oField.FPrec := oMember.Prec; oField.FScale := oMember.Scale; oField.TypeOid := oMember.TypeOid; end; end; end; {-------------------------------------------------------------------------------} procedure TPgField.SetDefaults; var i: Integer; begin if (FFormat = 0) and ([paArray, paRecord, paRange] * TypeRef.Attrs <> []) then FDException(Statement.OwningObj, [S_FD_LPhys, S_FD_PGId], er_FD_PgUnsupTextType, [DumpLabel]); Statement.Connection.TypesManager.GetDefaults(FFormat, FTypeOid, FLen, FPrec, FScale); for i := 0 to FFields.Count - 1 do FFields[i].SetDefaults; end; {-------------------------------------------------------------------------------} function TPgField.GetParentField: TPgField; begin Result := TPgFields(Owner).ParentField; end; {-------------------------------------------------------------------------------} function TPgField.GetPgData(out APgData: Pointer; out APgDataLen: Integer): Boolean; var iFlags, iIndex: Integer; pAttr: PPGresAttValue; begin if ParentField <> nil then if TPgFields(Owner).PgData <> nil then begin APgDataLen := TPgFields(Owner).PgDataLen; APgData := TPgFields(Owner).PgData; Result := APgDataLen >= 0; end else if paRange in ParentField.TypeRef.Attrs then begin Result := ParentField.GetPgData(APgData, APgDataLen); if Result then case FIndex of 0: begin iFlags := PByte(APgData)^; APgData := PByte(APgData) + SizeOf(Byte); if (RANGE_EMPTY or RANGE_LB_NULL or RANGE_LB_INF) and iFlags = 0 then begin // Get lbound APgDataLen := ReadInteger(APgData, 0); APgData := Pointer(NativeUInt(APgData) + SizeOf(Integer)); end else Result := False; end; 1: begin iFlags := PByte(APgData)^; APgData := PByte(APgData) + SizeOf(Byte); if (RANGE_EMPTY or RANGE_LB_NULL or RANGE_LB_INF) and iFlags = 0 then begin // Skip lbound APgDataLen := ReadInteger(APgData, 0); APgData := Pointer(NativeUInt(APgData) + SizeOf(Integer) + Cardinal(APgDataLen)); end; if (RANGE_EMPTY or RANGE_UB_NULL or RANGE_UB_INF) and iFlags = 0 then begin // Get hbound APgDataLen := ReadInteger(APgData, 0); APgData := Pointer(NativeUInt(APgData) + SizeOf(Integer)); end else Result := False; end; 2: begin // Get flags as Int32 iFlags := PByte(APgData)^; APgData := Statement.Connection.FBuffer.Check(SizeOf(Integer)); MoveRotate(@iFlags, APgData, SizeOf(Integer)); APgDataLen := SizeOf(Integer); end; end; end else begin Result := ParentField.GetPgData(APgData, APgDataLen) and (FIndex < ReadInteger(APgData, 0)); if Result then begin APgData := Pointer(NativeUInt(APgData) + 4); iIndex := FIndex; while True do begin APgDataLen := ReadInteger(APgData, 4); APgData := Pointer(NativeUInt(APgData) + 8); Result := APgDataLen >= 0; if iIndex = 0 then Break; if Result then APgData := Pointer(NativeUInt(APgData) + Cardinal(APgDataLen)); Dec(iIndex); end; end; end else begin pAttr := PPGresAttValue(NativeUInt( PPPGresAttValue(NativeUInt(PPGresult(Statement.FHandle)^.tuples) + SizeOf(PPPGresAttValue) * UInt64(Statement.FCurrentRow - Statement.FRowsetOffset))^)); if Statement.Lib.Brand = pbEnterprise then pAttr := PPGresAttValue(NativeUInt(pAttr) + SizeOf(pgresAttValueEDB) * Cardinal(FIndex)) else pAttr := PPGresAttValue(NativeUInt(pAttr) + SizeOf(pgresAttValue) * Cardinal(FIndex)); Result := (pAttr^.len <> NULL_LEN) and (pAttr^.value <> nil); if Result then begin APgData := pAttr^.value; APgDataLen := pAttr^.len; end; end; if not Result then begin APgDataLen := 0; APgData := nil; end; end; {-------------------------------------------------------------------------------} procedure TPgField.GetArrayInfo(ApData: Pointer; out ALBound, AHBound: Integer; out AClosed: Boolean; out ApFirstElem: Pointer); var iDim, iDims: Integer; iOid: Oid; begin if TypeOid = SQL_PATH then begin AClosed := PByte(ApData)^ <> 0; ALBound := 0; AHBound := ReadInteger(ApData, 1) - 1; ApFirstElem := Pointer(NativeUInt(ApData) + 5); end else if TypeOid = SQL_POLYGON then begin AClosed := False; ALBound := 0; AHBound := ReadInteger(ApData, 0) - 1; ApFirstElem := Pointer(NativeUInt(ApData) + 4); end else if paFixed in TypeRef.Attrs then begin AClosed := False; ALBound := 0; AHBound := TypeRef.FixedLen - 1; ApFirstElem := ApData; end else begin AClosed := False; iDims := ReadInteger(ApData, 0); if iDims = 0 then begin ALBound := 0; AHBound := -1; end else begin if iDims > 1 then FDException(Statement.OwningObj, [S_FD_LPhys, S_FD_PGId], er_FD_PgMultiDimArrNotSup, [DumpLabel, iDims]); iOid := Oid(ReadInteger(ApData, 8)); if (Length(TypeRef.Members) <> 1) or ([paArray, paRecord, paRange] * TypeRef.Members[0].TypeRef.Attrs <> []) or (TypeRef.Id <> SQL_ANY + 1) and (iOid <> TypeRef.Members[0].TypeOid) then FDException(Statement.OwningObj, [S_FD_LPhys, S_FD_PGId], er_FD_PgUnsupArrValueTypeNotSup, [DumpLabel, iOid]); iDim := ReadInteger(ApData, 12); ALBound := ReadInteger(ApData, 16); AHBound := ALBound + iDim - 1; ApFirstElem := Pointer(NativeUInt(ApData) + ARRHDRSZ); end; end; end; {-------------------------------------------------------------------------------} procedure TPgField.SetArrayIndex(const AValue: Integer); var pPgData: Pointer; iPgDataLen, iLBound, iHBound, iIndex: Integer; lClosed: Boolean; begin if FArrayIndex <> AValue then begin if AValue >= 0 then begin if GetPgData(pPgData, iPgDataLen) then GetArrayInfo(pPgData, iLBound, iHBound, lClosed, pPgData) else begin iLBound := -1; iHBound := -1; end; CheckArrayBounds(FArrayIndex, iLBound, iHBound); iIndex := AValue - iLBound; if (TypeOid = SQL_PATH) or (TypeOid = SQL_POLYGON) then begin iPgDataLen := 16; pPgData := Pointer(NativeUInt(pPgData) + Cardinal(16 * iIndex)); end else if paFixed in TypeRef.Attrs then begin iPgDataLen := iPgDataLen div TypeRef.FixedLen; pPgData := Pointer(NativeUInt(pPgData) + Cardinal(iPgDataLen * iIndex)); end else while True do begin iPgDataLen := ReadInteger(pPgData, 0); pPgData := Pointer(NativeUInt(pPgData) + 4); if iIndex = 0 then Break; if iPgDataLen >= 0 then pPgData := Pointer(NativeUInt(pPgData) + Cardinal(iPgDataLen)); Dec(iIndex); end; end else begin pPgData := nil; iPgDataLen := 0; end; FArrayIndex := AValue; Fields.FPgData := pPgData; Fields.FPgDataLen := iPgDataLen; end; end; {-------------------------------------------------------------------------------} function TPgField.GetData(var ApData: Pointer; var ALen: LongWord; AByRef: Boolean): Boolean; var pPgData: Pointer; iPgDataLen: Integer; begin Result := GetPgData(pPgData, iPgDataLen); if Result then if iPgDataLen = -1 then Result := False else Result := Pg2FDData(TypeRef, pPgData, iPgDataLen, ApData, ALen, AByRef); end; {-------------------------------------------------------------------------------} function TPgField.GetData(ApData: Pointer; var ALen: LongWord): Boolean; begin Result := GetData(ApData, ALen, False); end; {-------------------------------------------------------------------------------} function TPgField.GetData(ApData: Pointer): Boolean; var iLen: LongWord; begin iLen := 0; Result := GetData(ApData, iLen); end; {-------------------------------------------------------------------------------} function TPgField.GetAsString: String; var pData: Pointer; iLen: LongWord; begin ASSERT([paString, paBlob] * TypeRef.Attrs <> []); pData := nil; iLen := 0; if not GetData(pData, iLen, True) then Result := '' else case Statement.FConnection.Encoder.Encoding of ecANSI: Result := TFDEncoder.Deco(pData, iLen, ecANSI); ecUTF8, ecUTF16: Result := TFDEncoder.Deco(pData, iLen, ecUTF16); end; end; {-------------------------------------------------------------------------------} function TPgField.GetArrayBounds(out ALBound, AHBound: Integer; out AClosed: Boolean): Boolean; var pPgData: Pointer; iPgDataLen: Integer; begin Result := False; if paArray in TypeRef.Attrs then begin Result := GetPgData(pPgData, iPgDataLen); if Result then GetArrayInfo(pPgData, ALBound, AHBound, AClosed, pPgData); end; if not Result then begin AClosed := False; ALBound := 0; AHBound := -1; end; end; {-------------------------------------------------------------------------------} function TPgField.GetDumpLabel: String; begin Result := inherited GetDumpLabel; if Result = '' then Result := FName; end; {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TPgField.DumpValue: String; var pBuf: Pointer; iLen: LongWord; iLBound, iHBound, i: Integer; lClosed: Boolean; begin if paArray in TypeRef.Attrs then begin GetArrayBounds(iLBound, iHBound, lClosed); Result := '{'; for i := iLBound to iHBound do begin if i > iLBound then Result := Result + ','; ArrayIndex := i; try Result := Result + Fields[0].DumpValue; finally ArrayIndex := -1; end; end; Result := Result + '}'; end else if [paRecord, paRange] * TypeRef.Attrs <> [] then begin Result := '('; for i := 0 to Fields.Count - 1 do begin if i > 0 then Result := Result + ','; Result := Result + Fields[i].DumpValue; end; Result := Result + ')'; end else begin pBuf := nil; iLen := 0; GetData(pBuf, iLen, True); if (pBuf = nil) and (iLen > 0) then begin Statement.FConnection.FBuffer.Check(iLen); pBuf := Statement.FConnection.FBuffer.FBuffer; GetData(pBuf, iLen); end; Result := DumpFDValue(pBuf, iLen); end; end; {$ENDIF} {-------------------------------------------------------------------------------} { TPgFields } {-------------------------------------------------------------------------------} constructor TPgFields.Create(AOwner: TPgField); begin inherited Create(AOwner.Owner.Statement); FParentField := AOwner; end; {-------------------------------------------------------------------------------} function TPgFields.GetVariableClass: TPgVariableClass; begin Result := TPgField; end; {-------------------------------------------------------------------------------} function TPgFields.GetItems(AIndex: Integer): TPgField; begin Result := TPgField(FList.Items[AIndex]); end; {-------------------------------------------------------------------------------} { TPgStatement } {-------------------------------------------------------------------------------} constructor TPgStatement.Create(AConnection: TPgConnection; AOwningObj: TObject); begin inherited Create(AConnection.Env, AOwningObj); FConnection := AConnection; FParams := TPgParams.Create(Self); FFields := TPgFields.Create(Self); FGUIDEndian := Big; end; {-------------------------------------------------------------------------------} destructor TPgStatement.Destroy; begin Close; UnPrepare; FDFree(FParams); FDFree(FFields); inherited Destroy; end; {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} procedure TPgStatement.GetStmtName(out AName, AValue: String); begin if FStmtName <> '' then begin AName := 'stmtName'; AValue := FStmtName; end else if FRowsetStmtName <> '' then begin AName := 'rowsetStmtName'; AValue := FRowsetStmtName; end else if FCursorName <> '' then begin AName := 'crsName'; AValue := FCursorName; end else begin AName := '<direct>'; AValue := ''; end; end; {$ENDIF} {-------------------------------------------------------------------------------} procedure TPgStatement.Check(AHandle: PPGresult); begin FConnection.CheckResult(AHandle, OwningObj); end; {-------------------------------------------------------------------------------} procedure TPgStatement.Reset; begin FCurrentRow := -1; FRowsSelected := 0; FRowsAffected := -1; FClosed := True; FEOF := True; FLastRowset := True; FResultFormat := 1; FFields.Count := 0; end; {-------------------------------------------------------------------------------} procedure TPgStatement.Clear; begin if FHandle <> nil then begin Lib.FPQclear(FHandle); FHandle := nil; end; end; {-------------------------------------------------------------------------------} function TPgStatement.InternalPrepare(const ASQL: String; AUseParams: Boolean): String; procedure SQLPrepare(const AStmtName, ASQL: String); var i: Integer; sPrepSQLPrefix: String; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace('PREPARE', ['ppgconn', FConnection.FHandle, 'stmtname', AStmtName, 'sql', ASQL]); end; {$ENDIF} begin sPrepSQLPrefix := 'PREPARE "' + AStmtName + '"'; if AUseParams and (FParams.Count > 0) then begin sPrepSQLPrefix := sPrepSQLPrefix + ' ('; for i := 0 to FParams.Count - 1 do begin if i > 0 then sPrepSQLPrefix := sPrepSQLPrefix + ', '; if FParams[i].TypeRef = nil then sPrepSQLPrefix := sPrepSQLPrefix + 'unknown' else sPrepSQLPrefix := sPrepSQLPrefix + FParams[i].TypeRef.DumpType; end; sPrepSQLPrefix := sPrepSQLPrefix + ')'; end; sPrepSQLPrefix := sPrepSQLPrefix + ' AS '; {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} FConnection.ExecuteQuery(sPrepSQLPrefix + ASQL); end; procedure LibPrepare(const AStmtName, ASQL: String); var hPrepare: PPgresult; sSQL, sStmtName: TFDByteString; iPars: Integer; pValTypes: Pointer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQprepare, ['ppgconn', FConnection.FHandle, 'stmtname', AStmtName, 'sql', ASQL, 'nParams', iPars]); end; {$ENDIF} begin sSQL := FConnection.Encoder.Encode(ASQL); sStmtName := FConnection.Encoder.Encode(AStmtName); if AUseParams then begin iPars := FParams.Count; pValTypes := FParams.GetValueTypes; end else begin iPars := 0; pValTypes := nil; end; {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} hPrepare := Lib.FPQprepare(FConnection.FHandle, PFDAnsiString(PByte(sStmtName)), PByte(PByte(sSQL)), iPars, pValTypes); try Check(hPrepare); finally Lib.FPQclear(hPrepare); end; end; begin Result := FConnection.GenerateName; // libpq version < 8 if not Assigned(Lib.FPQprepare) then SQLPrepare(Result, ASQL) else LibPrepare(Result, ASQL); end; {-------------------------------------------------------------------------------} procedure TPgStatement.PrepareSQL(const ASQL: String); const C_HOLD: array [Boolean] of String = (' ', ' WITH HOLD '); var iAfter: Integer; begin Reset; try if (FDStartsWithKW(ASQL, 'SELECT', iAfter) or FDStartsWithKW(ASQL, 'WITH', iAfter)) and (RowsetSize > 0) and Assigned(Lib.FPQprepare) then begin FCursorName := FConnection.GenerateName; FStmtName := InternalPrepare('DECLARE "' + FCursorName + '" CURSOR' + C_HOLD[WithHold] + 'FOR ' + ASQL, True); FRowsetStmtName := InternalPrepare('FETCH FORWARD ' + IntToStr(RowsetSize) + ' FROM "' + FCursorName + '"', False); end else begin FCursorName := ''; FStmtName := InternalPrepare(ASQL, True); FRowsetStmtName := ''; end; except Unprepare; raise; end; end; {-------------------------------------------------------------------------------} procedure TPgStatement.PrepareCursor(const ACursorName: String); begin Reset; try FCursorName := ACursorName; if RowsetSize > 0 then begin FRowsetStmtName := InternalPrepare('FETCH FORWARD ' + IntToStr(RowsetSize) + ' FROM "' + FCursorName + '"', False); FStmtName := ''; end else begin FRowsetStmtName := ''; FStmtName := InternalPrepare('FETCH ALL FROM "' + FCursorName + '"', False); end; except Unprepare; raise; end; end; {-------------------------------------------------------------------------------} procedure TPgStatement.DescribeFields; var i, iModifier: Integer; oFld: TPgField; {$IFDEF FireDAC_MONITOR} procedure Trace1; var sName: String; sVal: String; begin GetStmtName(sName, sVal); Env.Trace('DescribeFields', ['ppgconn', FConnection.FHandle, sName, sVal, 'nFields', FFields.Count]); end; {$ENDIF} begin FFields.Count := Lib.FPQnfields(FHandle); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} for i := 0 to FFields.Count - 1 do begin oFld := FFields[i]; oFld.FFormat := FResultFormat; oFld.FName := FConnection.Encoder.Decode(Lib.FPQfname(FHandle, i), -1); oFld.TypeOid := Lib.FPQftype(FHandle, i); oFld.FTableOid := Lib.FPQftable(FHandle, i); oFld.FTableCol := Lib.FPQftablecol(FHandle, i); iModifier := Lib.FPQfmod(FHandle, i); oFld.SetDefaults; if (oFld.TypeRef.Attrs = [paArray]) and (oFld.Fields.Count = 1) then oFld := oFld.Fields[0]; if [paArray, paRecord, paRange] * oFld.TypeRef.Attrs = [] then FConnection.TypesManager.DecodeModifier(oFld.FTypeOid, iModifier, oFld.FLen, oFld.FPrec, oFld.FScale); end; end; {-------------------------------------------------------------------------------} procedure TPgStatement.GetResultInfo; var iPos: Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQcmdStatus, ['ppgresult', FHandle, 'stmttype', SQLStmtType, 'rowsaffected', RowsAffected, 'oid', LastInsertOid]); end; procedure Trace2; begin Env.Trace(sPQntuples, ['ppgresult', FHandle, 'rowsselected', RowsSelected]); end; {$ENDIF} begin // retrieve result information // status string may contain LastInsertOid and RowsAffected information FSQLStmtType := FConnection.Encoder.Decode(Lib.FPQcmdStatus(FHandle), -1); iPos := Pos(' ', SQLStmtType); if iPos > 0 then Delete(FSQLStmtType, iPos, Length(SQLStmtType) - iPos + 1); FRowsAffected := StrToIntDef(FConnection.Encoder.Decode(Lib.FPQcmdTuples(FHandle), -1), 0); // FPQoidValue returns InvalidOid if table was created without Oids FLastInsertOid := Lib.FPQoidValue(FHandle); FConnection.FLastInsertOid := LastInsertOid; {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} // records count FRowsSelected := Lib.FPQntuples(FHandle); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace2; {$ENDIF} end; {-------------------------------------------------------------------------------} procedure TPgStatement.InternalExecute(const AStmtName: String; AnParams: Integer; AParamValues: Pointer; AParamLengths: PInteger; AParamFormats: PInteger; AResultFormat: Integer); {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQexecPrepared, ['ppgconn', FConnection.FHandle, 'stmtname', AStmtName, 'nParams', AnParams, 'resultFormat', ResultFormat]); end; {$ENDIF} var sStmtName: TFDByteString; begin Clear; FResultFormat := AResultFormat; {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} sStmtName := FConnection.Encoder.Encode(AStmtName); FHandle := Lib.FPQexecPrepared(FConnection.FHandle, PFDAnsiString(PByte(sStmtName)), AnParams, AParamValues, AParamLengths, AParamFormats, AResultFormat); Check(FHandle); end; {-------------------------------------------------------------------------------} procedure TPgStatement.InternalExecute(AResultFormat: Integer); var pValueRefs: Pointer; begin Reset; FConnection.ClearNotices; FResultFormat := AResultFormat; {$IFDEF FireDAC_MONITOR} if Env.Tracing then DumpInVars; {$ENDIF} if FStmtName <> '' then try pValueRefs := FParams.GetValueRefs; InternalExecute(FStmtName, FParams.Count, pValueRefs, FParams.GetValueLengths, FParams.GetValueFormats, AResultFormat); finally GetResultInfo; end; GetNextRowset; FEOF := False; FClosed := False; FLastRowset := False; end; {-------------------------------------------------------------------------------} procedure TPgStatement.Execute; begin try InternalExecute(1); except on E: EPgNativeException do if (TFDPgError(E[0]).ErrorCode = '42883') and (TFDPgError(E[0]).Message = 'no binary output function available for type void') then InternalExecute(0) else raise; end; end; {-------------------------------------------------------------------------------} procedure TPgStatement.InternalExecuteDirect(const ASQL: String; AResultFormat: Integer); {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQexec, ['ppgconn', FConnection.FHandle, 'sql', ASQL]); end; procedure Trace2; begin Env.Trace(sPQexecParams, ['ppgconn', FConnection.FHandle, 'sql', ASQL, 'nParams', FParams.Count, 'resultFormat', ResultFormat]); end; {$ENDIF} var pValueRefs: Pointer; begin Reset; FConnection.ClearNotices; Clear; try if FParams.Count = 0 then begin FResultFormat := 0; {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} FHandle := Lib.FPQexec(FConnection.FHandle, PByte( FConnection.Encoder.Encode(ASQL))); end else begin FResultFormat := AResultFormat; {$IFDEF FireDAC_MONITOR} if Env.Tracing then begin DumpInVars; Trace2; end; {$ENDIF} pValueRefs := FParams.GetValueRefs; FHandle := Lib.FPQexecParams(FConnection.FHandle, PByte( FConnection.Encoder.Encode(ASQL)), FParams.Count, FParams.GetValueTypes, pValueRefs, FParams.GetValueLengths, FParams.GetValueFormats, AResultFormat); end; Check(FHandle); finally GetResultInfo; end; GetNextRowset; FEOF := False; FClosed := False; FLastRowset := False; end; {-------------------------------------------------------------------------------} procedure TPgStatement.ExecuteDirect(const ASQL: String); begin try InternalExecuteDirect(ASQL, 1); except on E: EPgNativeException do if (TFDPgError(E[0]).ErrorCode = '42883') and (TFDPgError(E[0]).Message = 'no binary output function available for type void') then InternalExecuteDirect(ASQL, 0) else raise; end; end; {-------------------------------------------------------------------------------} procedure TPgStatement.GetNextRowset; var iRows: Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(sPQntuples, ['ppgresult', FHandle, 'rowsselected', iRows]); end; {$ENDIF} begin if FRowsetStmtName = '' then Exit; try InternalExecute(FRowsetStmtName, 0, nil, nil, nil, 1); except FLastRowset := True; FEOF := True; raise; end; iRows := Lib.FPQntuples(FHandle); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} FRowsetOffset := RowsSelected; FRowsSelected := RowsSelected + iRows; FLastRowset := iRows < RowsetSize; end; {-------------------------------------------------------------------------------} function TPgStatement.Fetch: Boolean; {$IFDEF FireDAC_MONITOR} procedure Trace1; var sName: String; sVal: String; begin GetStmtName(sName, sVal); Env.Trace('FETCH', ['ppgresult', FHandle, sName, sVal]); end; procedure Trace2; begin Env.Trace(ekCmdDataOut, esProgress, 'EOF', []); end; {$ENDIF} begin if EOF then begin Result := False; Exit; end; {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} Inc(FCurrentRow); if not FLastRowset and (FCurrentRow = RowsSelected) and (RowsSelected > 0) then GetNextRowset; FEOF := FCurrentRow = RowsSelected; Result := not EOF; if EOF then begin {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace2; {$ENDIF} Close; end {$IFDEF FireDAC_MONITOR} else if Env.Tracing then DumpOutVars; {$ENDIF} end; {-------------------------------------------------------------------------------} procedure TPgStatement.Close; {$IFDEF FireDAC_MONITOR} procedure Trace1; var sName: String; sVal: String; begin GetStmtName(sName, sVal); Env.Trace(sPQclear, ['ppgresult', FHandle, sName, sVal]); end; {$ENDIF} begin if Closed then Exit; try {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} Clear; FClosed := True; FEOF := True; FLastRowset := True; if (FCursorName <> '') and not (FConnection.TransactionStatus in [PQTRANS_INERROR, PQTRANS_UNKNOWN]) then FConnection.ExecuteQuery(sClosePrefix + FCursorName + '"'); except on E: EPgNativeException do if E.Kind <> ekServerGone then raise; end; end; {-------------------------------------------------------------------------------} procedure TPgStatement.InternalUnprepare(var AStmtName: String); var sTmpStmtName: String; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace('DEALLOCATE', ['ppgconn', FConnection.FHandle, 'stmtname', sTmpStmtName]); end; {$ENDIF} begin if AStmtName = '' then Exit; try sTmpStmtName := AStmtName; AStmtName := ''; if not (FConnection.TransactionStatus in [PQTRANS_INERROR, PQTRANS_UNKNOWN]) then begin {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} FConnection.ExecuteQuery(sDeallocatePrefix + sTmpStmtName + '"'); end; except on E: EPgNativeException do if E.Kind <> ekServerGone then raise; end; end; {-------------------------------------------------------------------------------} procedure TPgStatement.Unprepare; begin FCursorName := ''; InternalUnPrepare(FStmtName); InternalUnPrepare(FRowsetStmtName); end; {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} procedure TPgStatement.DumpInVars; var i: Integer; oPar: TPgParam; begin if Env.Tracing and (FParams.Count > 0) then begin Env.Trace(ekCmdDataIn, esStart, 'Sent', []); for i := 0 to FParams.Count - 1 do begin oPar := FParams[i]; Env.Trace(ekCmdDataIn, esProgress, 'Var', [String('N'), i, 'Name', oPar.DumpLabel, '@Type', oPar.DumpSQLDataType, 'Size', oPar.Size, '@Data(0)', oPar.DumpValue]); end; Env.Trace(ekCmdDataIn, esEnd, 'Sent', []); end; end; {-------------------------------------------------------------------------------} procedure TPgStatement.DumpOutVars; var i: Integer; oFld: TPgField; begin if Env.Tracing and (FFields.Count > 0) then begin Env.Trace(ekCmdDataOut, esStart, 'Fetched', []); for i := 0 to FFields.Count - 1 do begin oFld := FFields[i]; Env.Trace(ekCmdDataOut, esProgress, 'Field', [String('N'), i, 'Name', oFld.DumpLabel, '@Type', oFld.DumpSQLDataType, 'Prec', oFld.Prec, 'Scale', oFld.Scale, 'Size', oFld.Len, '@Data', oFld.DumpValue]); end; Env.Trace(ekCmdDataOut, esEnd, 'Fetched', []); end; end; {$ENDIF} {-------------------------------------------------------------------------------} { TPgLargeObject } {-------------------------------------------------------------------------------} constructor TPgLargeObject.Create(AConnection: TPgConnection; AMode: TFDStreamMode; AOwningObj: TObject); begin inherited Create(AConnection.Env, AOwningObj); FConnection := AConnection; FMode := AMode; end; {-------------------------------------------------------------------------------} constructor TPgLargeObject.Create(AConnection: TPgConnection; AMode: TFDStreamMode; AOwningObj: TObject; AObjOid: Oid); begin Create(AConnection, AMode, AOwningObj); FObjOid := AObjOid; end; {-------------------------------------------------------------------------------} destructor TPgLargeObject.Destroy; begin if IsOpen then Close(True); inherited Destroy; end; {-------------------------------------------------------------------------------} function TPgLargeObject.Mode2PGMode: Integer; begin case Mode of smOpenRead: Result := INV_READ; smOpenWrite: Result := INV_WRITE; smOpenReadWrite: Result := INV_READ or INV_WRITE; else begin Result := 0; ASSERT(False); end; end; end; {-------------------------------------------------------------------------------} function TPgLargeObject.GetLen: Integer; var iPosition: Integer; begin iPosition := FPosition; Result := Seek(0, soFromEnd); Seek(iPosition, soFromBeginning); end; {-------------------------------------------------------------------------------} procedure TPgLargeObject.SetLen(const AValue: Integer); var iResult: Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(slo_truncate, ['conn', FConnection.FHandle, 'objoid', FObjOid, 'len', AValue, 'Result', iResult]); end; {$ENDIF} begin ASSERT(IsOpen); CheckReadWrite; if Assigned(Lib.Flo_truncate) then begin iResult := Lib.Flo_truncate(FConnection.FHandle, FObjHandle, AValue); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} if iResult < 0 then Error('truncate', iResult); end; end; {-------------------------------------------------------------------------------} procedure TPgLargeObject.Error(const AOperation: String; AStatus: Integer); var sMsg: String; begin sMsg := FConnection.Encoder.Decode(Lib.FPQerrorMessage(FConnection.FHandle), -1); if sMsg = '' then sMsg := 'cannot ' + AOperation + ' large object'; DoError(sMsg, AStatus); end; {-------------------------------------------------------------------------------} procedure TPgLargeObject.CheckReadWrite; begin if Mode = smOpenRead then Error('write read-only', -1); end; {-------------------------------------------------------------------------------} procedure TPgLargeObject.CreateObj; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(slo_creat, ['conn', FConnection.FHandle, 'objoid', FObjOid]); end; {$ENDIF} begin FObjOid := Lib.Flo_creat(FConnection.FHandle, Mode2PGMode()); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} if FObjOid = InvalidOid then Error('create', FObjOid); end; {-------------------------------------------------------------------------------} procedure TPgLargeObject.Open; var iMode: Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(slo_open, ['conn', FConnection.FHandle, 'objoid', FObjOid, 'mode', iMode, 'objhandle', FObjHandle]); end; {$ENDIF} begin ASSERT(not IsOpen); iMode := Mode2PGMode(); FObjHandle := Lib.Flo_open(FConnection.FHandle, FObjOid, iMode); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} if FObjHandle < 0 then Error('open', FObjHandle); FIsOpen := True; end; {-------------------------------------------------------------------------------} procedure TPgLargeObject.Close(AIgnoreErrors: Boolean); var iResult: Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(slo_close, ['conn', FConnection.FHandle, 'objoid', FObjOid, 'objhandle', FObjHandle, 'Result', iResult]); end; {$ENDIF} begin ASSERT(IsOpen); iResult := Lib.Flo_close(FConnection.FHandle, FObjHandle); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} if (iResult < 0) and not AIgnoreErrors then Error('close', iResult); FIsOpen := False; FPosition := 0; FObjHandle := 0; end; {-------------------------------------------------------------------------------} procedure TPgLargeObject.UnLink; var iResult: Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(slo_unlink, ['conn', FConnection.FHandle, 'objoid', FObjOid, 'Result', iResult]); end; {$ENDIF} begin ASSERT(FObjHandle = 0); CheckReadWrite; iResult := Lib.Flo_unlink(FConnection.FHandle, FObjOid); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} if iResult < 0 then Error('unlink', iResult); end; {-------------------------------------------------------------------------------} function TPgLargeObject.Seek(AOffset: Integer; ASeekOrigin: Word): Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(slo_lseek, ['conn', FConnection.FHandle, 'objoid', FObjOid, 'objhandle', FObjHandle, 'offset', AOffset, 'seekorigin', ASeekOrigin, 'Result', Result]); end; {$ENDIF} begin Result := Lib.Flo_lseek(FConnection.FHandle, FObjHandle, AOffset, ASeekOrigin); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} if Result < 0 then Error('lseek', Result); FPosition := Result; end; {-------------------------------------------------------------------------------} function TPgLargeObject.Read(ABuff: PByte; ABuffLen: Integer): Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(slo_read, ['conn', FConnection.FHandle, 'objoid', FObjOid, 'objhandle', FObjHandle, 'buflen', ABuffLen, 'Result', Result]); end; {$ENDIF} begin ASSERT(IsOpen); Result := Lib.Flo_read(FConnection.FHandle, FObjHandle, ABuff, ABuffLen); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} if Result < 0 then Error('read', Result); Inc(FPosition, Result); end; {-------------------------------------------------------------------------------} function TPgLargeObject.Write(ABuff: PByte; ABuffLen: Integer): Integer; {$IFDEF FireDAC_MONITOR} procedure Trace1; begin Env.Trace(slo_write, ['conn', FConnection.FHandle, 'objoid', FObjOid, 'objhandle', FObjHandle, 'buflen', ABuffLen, 'Result', Result]); end; {$ENDIF} begin ASSERT(IsOpen); CheckReadWrite; Result := Lib.Flo_write(FConnection.FHandle, FObjHandle, ABuff, ABuffLen); {$IFDEF FireDAC_MONITOR} if Env.Tracing then Trace1; {$ENDIF} if Result < 0 then Error('write', Result); Inc(FPosition, Result); end; {-------------------------------------------------------------------------------} { TPgLargeObjectStream } {-------------------------------------------------------------------------------} constructor TPgLargeObjectStream.Create(ALargeObject: TPgLargeObject); begin inherited Create; FLargeObject := ALargeObject; end; {-------------------------------------------------------------------------------} destructor TPgLargeObjectStream.Destroy; begin FDFreeAndNil(FLargeObject); inherited Destroy; end; {-------------------------------------------------------------------------------} function TPgLargeObjectStream.Read(var Buffer; Count: Longint): Longint; begin Result := FLargeObject.Read(PByte(@Buffer), Count); end; {-------------------------------------------------------------------------------} function TPgLargeObjectStream.Write(const Buffer; Count: Longint): Longint; begin Result := FLargeObject.Write(PByte(@Buffer), Count); end; {-------------------------------------------------------------------------------} function TPgLargeObjectStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin Result := FLargeObject.Seek(Offset, Word(Origin)); end; {-------------------------------------------------------------------------------} procedure TPgLargeObjectStream.SetSize(const NewSize: Int64); begin FLargeObject.Len := NewSize; end; {-------------------------------------------------------------------------------} function PgNativeExceptionLoad(const AStorage: IFDStanStorage): TObject; begin Result := EPgNativeException.Create; EPgNativeException(Result).LoadFromStorage(AStorage); end; {-------------------------------------------------------------------------------} initialization FDStorageManager().RegisterClass(EPgNativeException, 'PgNativeException', @PgNativeExceptionLoad, @FDExceptionSave); end.
unit CALENDAR; {updated to delphi 2.0 compatibility} {CALENDAR FUNCTION SUBROUTINES Provides conversion of mm,dd,yy numbers into serial numbers which can be used in math operations and then converted back. {++++++++++++++++++++++++++++++++++++++++++++++++++++++} interface Uses SysUtils, JulCal; const weekDay : array[1..7] of string[5] = ('Mon','Tues','Weds', 'Thurs', 'Fri','Sat','Sun'); mo : array[1..12] of string[3] = ('Jan','Feb','Mar', 'Apr','May', 'Jun','Jul','Aug','Sep', 'Oct','Nov','Dec'); ShortForm = 1; LongForm = 2; type DATEINT = LONGINT; DateFormat = 1..2; daterec = record mm : Month; {type from JULCAL} dd : Day; {type from JULCAL} yyyy : Year; {type from JULCAL -full form- } DOW : byte; end; function mdy2Date (m,d,y:integer) : DATEINT; function LotusDate (m,d,y:integer) : DATEINT; function month(serial : DATEINT) : integer; function day (serial : DATEINT) : integer; function year (serial : DATEINT) : integer; function DayString (serial : DATEINT): string; function MonthString(serial : DATEINT): string; function Today: DATEINT; function DateString(serial :DATEINT; format :DateFormat): string; function TodayString : string; function ParseDateStr(datestr : string) :DATEINT; {++++++++++++++++++++++++++++++++++++++++++++++++++} implementation {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function DateNum(date : daterec): DATEINT; VAR date2 : JCDateRec; BEGIN with date do begin date2.Y := yyyy; date2.D := dd; date2.M := mm; end; DateNum := DATEINT(JULDN(date2)); END; {DateNum} (* OLD ALGORITHM {Converts mm,dd,yy numbers into serial number using HP 12C algorithm ***} var z,x : DATEINT; begin with date do begin z := yy - ord(mm<3) ; x := (40000 * mm + 230000) div 100000 * ord(mm>2) ; datenum := trunc(365.0) * yy + 31 * (mm-1) + dd + trunc(z / 4) - x; end; end; *) {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function mdy2date (m,d,y:integer) : DATEINT; var dates : daterec; begin with dates do begin mm := m; dd := d; yyyy := y end; mdy2date := dateNum(dates); end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function LotusDate (m,d,y:integer) : DATEINT; BEGIN LotusDate := mdy2date(m,d,y) - mdy2date(12,31,1899); END; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} procedure DateConv(var date : daterec; serial : DATEINT); {converts serial to mm,dd,yy. result in DATE} VAR date2 : JCDateRec; BEGIN JULCD(JULIAN(serial),date2); with date do begin yyyy := INTEGER(date2.Y); dd := INTEGER(date2.D); mm := INTEGER(date2.M); end; END; {DateNum} (* OLD ALGORITHM begin date.yy := trunc(serial/365.25+1); date.mm := 1; date.dd := 1; while dateNum(date) > serial do date.yy := date.yy-1; date.mm := trunc((serial - dateNum(date)) / 28.0 + 1); while dateNum(date) > serial do date.mm := date.mm-1; date.dd := trunc(serial - dateNum(date)) + 1; end; *) {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function month(serial : DATEINT) : integer; var date : daterec; begin dateconv(date,serial); month := date.mm end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function day(serial : DATEINT) : integer; var date : daterec; begin dateconv(date,serial); day := date.dd end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function year(serial : DATEINT) : integer; var date : daterec; begin dateconv(date,serial); year := date.yyyy end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function Today: DATEINT; var temp : double; {uses ms-dos function call to get system date} {routine kept for bacward compatibility } begin Today := trunc(date); end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function MonthString (serial : DATEINT): string; begin MonthString := mo[month(serial)]; end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function DayString (serial : DATEINT): string; begin DayString := weekday[(serial - 719540) mod 7 + 1]; end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function DateString(serial : DATEINT; format : DateFormat) : string; {format = 1 : mm/dd/yy; format = 2 : Weekday, Month,day, year } var year, month, day, suffix : string; temp : daterec; begin if format > 2 then format := 2; if format < 1 then format := 1; DateConv(temp, serial); with temp do begin str(yyyy:4,year); {convert to string} str(dd:1,day); str(mm:1,month); { insert leading zeros } IF (dd < 10) THEN day := '0' + day; IF mm < 10 THEN month := '0' + month; case format of 1 : begin DateString := month+'/'+day+'/'+year; end; {case 1} 2 : begin case (dd mod 10) of 0 : suffix := 'th'; 1 : suffix := 'st'; 2 : suffix := 'nd'; 3 : suffix := 'rd'; 4..9 : suffix := 'th'; end; {case dd} case dd of 11..13 : suffix := 'th'; end; {case dd - exception} DateString := DayString(Today)+', ' + MonthString(Today) +' '+ day + suffix + ', '+ year; end; {case 2} end; {case format} end; {with temp do } end; {DateString} {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function TodayString : string; begin TodayString := datestring(today,1); end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function ParseDateStr(datestr : string) : DATEINT; { this makes an educated guess about the century if it only gets the last two digits of a year: more than 50 years less than the current year will be interpeted as the next century. This is useful for financial applications. Override this by simply expressing the year with four digits (i.e. in 1986, '16' is 2016 but '1916' is 1916. Valid years are 100-2500 A.D. } CONST slash = #47; dash = #45; nullstr = ''; TYPE StateType = (GetMonth, GetDay, GetYear); var num,yy,mm,dd, doneOK, i : integer; monthstr,daystr, yearstr, tempstr : string; State : StateType; BEGIN tempstr := nullstr; doneOK := 0; State := GetMonth; i := 1; (* change to zero for Modula *) WHILE i < LENGTH(datestr) + 2 (* - 1 for Modula *) DO BEGIN IF ((datestr[i] = slash) OR (datestr[i] = dash) OR (i = LENGTH(datestr) + 1)) THEN BEGIN CASE State OF GetMonth : monthstr := tempstr; GetDay : daystr := tempstr; GetYear : yearstr := tempstr; END; State := SUCC(State); tempstr := nullstr; END ELSE tempstr := Concat(tempstr,datestr[i]); i := SUCC(i); END; (* WHILE *) {year is not given, assume this year} IF State = GetYear THEN yy := year(Today) ELSE BEGIN val(yearstr,yy,doneOK); IF doneOK = 0 THEN (* this allows you to abbreviate years. A consequence is this routine does not handle any years before 99 AD *) IF (yy +1900) < (year(today) - 50) THEN yy := yy + 2000 ELSE IF yy < 100 THEN yy := yy + 1900; END; (* year *) IF doneOK = 0 THEN val(daystr,dd,doneOK); IF doneOK = 0 THEN val(monthstr,mm,doneOK); IF doneOK = 0 THEN BEGIN IF (yy >0) AND (yy <2500) AND (mm IN [1..12]) AND (dd IN [1..31]) THEN {if parse successful change to serial #} ParseDateStr := mdy2Date(mm,dd,yy) END ELSE ParseDateStr := 0; END; (* ParseDateStr *) {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} {END OF CALENDAR FUNCTIONS} end.
unit Flower_Reservation; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Mask, Vcl.DBCtrls, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Vcl.ExtCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.WinXCtrls; type TReservation_Form = class(TForm) Panel1: TPanel; Label1: TLabel; StatusBar1: TStatusBar; Panel2: TPanel; DBGrid1: TDBGrid; DBNavigator1: TDBNavigator; Insert_Button: TButton; Cancel_Button: TButton; Delete_Button: TButton; Save_Button: TButton; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Refresh_Button: TButton; Reservation_SearchBox: TSearchBox; Label6: TLabel; Label7: TLabel; Label8: TLabel; Flower_DBEdit: TDBEdit; Qty_DBEdit: TDBEdit; Recipient_Name_DBEdit: TDBEdit; Recipient_PhoneNumber_DBEdit: TDBEdit; Recipient_Address_DBEdit: TDBEdit; Receive_DBComboBox: TDBComboBox; Payment_DBComboBox: TDBComboBox; procedure Name_EditKeyPress(Sender: TObject; var Key: Char); procedure Refresh_ButtonClick(Sender: TObject); procedure Insert_ButtonClick(Sender: TObject); procedure Cancel_ButtonClick(Sender: TObject); procedure Delete_ButtonClick(Sender: TObject); procedure Save_ButtonClick(Sender: TObject); procedure Reservation_SearchBoxChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var Reservation_Form: TReservation_Form; implementation {$R *.dfm} uses Flower_Client_DataModule, Flower_ServerMethods; procedure TReservation_Form.Cancel_ButtonClick(Sender: TObject); begin DataModule1.Reservation_ClientDataSet.Cancel; end; procedure TReservation_Form.Delete_ButtonClick(Sender: TObject); begin if MessageDlg('정말 삭제하시겠습니까?', mtConfirmation, [mbYes, mbNo],0) = mrYes then begin try DataModule1.Reservation_ClientDataSet.Delete; DataModule1.Reservation_ClientDataSet.ApplyUpdates(-1); DataModule1.Reservation_ClientDataSet.Refresh; except on e:Exception do ShowMessage('더이상 삭제할 데이터가 없습니다.'); end; end; end; procedure TReservation_Form.Insert_ButtonClick(Sender: TObject); begin DataModule1.Reservation_ClientDataSet.Append; Flower_DBEdit.SetFocus; end; procedure TReservation_Form.Name_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then SelectNext(ActiveControl, true, true); end; procedure TReservation_Form.Refresh_ButtonClick(Sender: TObject); begin DataModule1.Reservation_ClientDataSet.Refresh; end; procedure TReservation_Form.Reservation_SearchBoxChange(Sender: TObject); begin DataModule1.Reservation_ClientDataSet.IndexFieldNames := 'RESERVATION_DATE'; DataModule1.Reservation_ClientDataSet.IndexFieldNames := 'RESERVATION_TIME'; // DataModule1.Reservation_ClientDataSet.IndexFieldNames := 'LIST_NAME_LOOKUP'; DataModule1.Reservation_ClientDataSet.IndexFieldNames := 'RESERVATION_NAME'; DataModule1.Reservation_ClientDataSet.IndexFieldNames := 'RESERVATION_PHONENUMBER'; DataModule1.Reservation_ClientDataSet.IndexFieldNames := 'RECIPIENT_NAME'; DataModule1.Reservation_ClientDataSet.IndexFieldNames := 'RECIPIENT_PHONENUMBER'; DataModule1.Reservation_ClientDataSet.IndexFieldNames := 'RECIPIENT_ADDRESS'; DataModule1.Reservation_ClientDataSet.IndexFieldNames := 'RECEIVE_TYPE'; DataModule1.Reservation_ClientDataSet.IndexFieldNames := 'PAYMENT_TYPE'; DataModule1.Reservation_ClientDataSet.FindNearest([Reservation_SearchBox.Text]); end; procedure TReservation_Form.Save_ButtonClick(Sender: TObject); begin if DataModule1.Reservation_ClientDataSet.UpdateStatus = TUpdateStatus.usInserted then DataModule1.Reservation_ClientDataSet.FieldByName('MEMBER_SEQ').AsInteger := -1; DataModule1.Reservation_ClientDataSet.Post; DataModule1.Reservation_ClientDataSet.ApplyUpdates(0); DataModule1.Reservation_ClientDataSet.Refresh; Reservation_Form.Flower_DBEdit.Clear; Reservation_Form.Qty_DBEdit.Clear; Reservation_Form.Recipient_Name_DBEdit.Clear; Reservation_Form.Recipient_PhoneNumber_DBEdit.Clear; Reservation_Form.Recipient_Address_DBEdit.Clear; Reservation_Form.Receive_DBComboBox.Clear; Reservation_Form.Payment_DBComboBox.Clear; Showmessage('저장 되었습니다.'); end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { Copyright(c) 2012-2017 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit FMX.FontGlyphs.iOS; interface {$SCOPEDENUMS ON} uses System.Types, System.Classes, System.SysUtils, System.UITypes, System.UIConsts, System.Generics.Collections, System.Generics.Defaults, Macapi.ObjectiveC, Macapi.CoreFoundation, iOSapi.CocoaTypes, iOSapi.CoreGraphics, iOSapi.Foundation, iOSapi.CoreText, iOSapi.UIKit, FMX.Types, FMX.Surfaces, FMX.FontGlyphs; type TIOSFontGlyphManager = class(TFontGlyphManager) const BoundsLimit = $FFFF; private FColorSpace: CGColorSpaceRef; FFontRef: CTFontRef; FDefaultBaseline: Single; FDefaultVerticalAdvance: Single; procedure GetDefaultBaseline; function GetPostScriptFontName: CFStringRef; protected procedure LoadResource; override; procedure FreeResource; override; function DoGetGlyph(const Char: UCS4Char; const Settings: TFontGlyphSettings; const UseColorfulPalette: Boolean): TFontGlyph; override; function DoGetBaseline: Single; override; function IsColorfulCharacter(const Char: UCS4Char): Boolean; override; public constructor Create; destructor Destroy; override; end; implementation uses System.Math, System.Character, System.Math.Vectors, FMX.Graphics, FMX.Consts, FMX.Utils, Macapi.Helpers; { TIOSFontGlyphManager } constructor TIOSFontGlyphManager.Create; begin inherited Create; FColorSpace := CGColorSpaceCreateDeviceRGB; end; destructor TIOSFontGlyphManager.Destroy; begin CGColorSpaceRelease(FColorSpace); inherited; end; procedure TIOSFontGlyphManager.LoadResource; const //Rotating matrix to simulate Italic font attribute ItalicMatrix: CGAffineTransform = ( a: 1; b: 0; c: 0.176326981; //~tan(10 degrees) d: 1; tx: 0; ty: 0 ); var NewFontRef: CTFontRef; Matrix: PCGAffineTransform; begin Matrix := nil; FFontRef := CTFontCreateWithName(GetPostScriptFontName, CurrentSettings.Size * CurrentSettings.Scale, nil); try if TFontStyle.fsItalic in CurrentSettings.Style then begin NewFontRef := CTFontCreateCopyWithSymbolicTraits(FFontRef, 0, nil, kCTFontItalicTrait, kCTFontItalicTrait); if NewFontRef <> nil then begin CFRelease(FFontRef); FFontRef := NewFontRef; end else begin Matrix := @ItalicMatrix; //Font has no Italic version, applying transform matrix NewFontRef := CTFontCreateWithName(GetPostScriptFontName, CurrentSettings.Size * CurrentSettings.Scale, @ItalicMatrix); if NewFontRef <> nil then begin CFRelease(FFontRef); FFontRef := NewFontRef; end; end; end; if TFontStyle.fsBold in CurrentSettings.Style then begin NewFontRef := CTFontCreateCopyWithSymbolicTraits(FFontRef, 0, Matrix, kCTFontBoldTrait, kCTFontBoldTrait); if NewFontRef <> nil then begin CFRelease(FFontRef); FFontRef := NewFontRef; end; end; // GetDefaultBaseline; except CFRelease(FFontRef); end; end; procedure TIOSFontGlyphManager.FreeResource; begin if FFontRef <> nil then CFRelease(FFontRef); end; procedure TIOSFontGlyphManager.GetDefaultBaseline; var Chars: string; Str: CFStringRef; Frame: CTFrameRef; Attr: CFMutableAttributedStringRef; Path: CGMutablePathRef; Bounds: CGRect; FrameSetter: CTFramesetterRef; // Metrics Line: CTLineRef; Lines: CFArrayRef; Runs: CFArrayRef; Run: CTRunRef; Ascent, Descent, Leading: CGFloat; BaseLinePos: CGPoint; begin Path := CGPathCreateMutable(); Bounds := CGRectMake(0, 0, BoundsLimit, BoundsLimit); CGPathAddRect(Path, nil, Bounds); if TOSVersion.Check(9) then // yangyxd Chars := '中' else Chars := 'a'; Str := CFStringCreateWithCharacters(kCFAllocatorDefault, PChar(Chars), 1); Attr := CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); CFAttributedStringReplaceString(Attr, CFRangeMake(0, 0), Str); CFAttributedStringBeginEditing(Attr); try // Font if FFontRef <> nil then CFAttributedStringSetAttribute(Attr, CFRangeMake(0, 1), kCTFontAttributeName, FFontRef); finally CFAttributedStringEndEditing(Attr); end; FrameSetter := CTFramesetterCreateWithAttributedString(CFAttributedStringRef(Attr)); CFRelease(Attr); Frame := CTFramesetterCreateFrame(FrameSetter, CFRangeMake(0, 0), Path, nil); CFRelease(FrameSetter); CFRelease(Str); // Metrics Lines := CTFrameGetLines(Frame); Line := CTLineRef(CFArrayGetValueAtIndex(Lines, 0)); Runs := CTLineGetGlyphRuns(Line); Run := CFArrayGetValueAtIndex(Runs, 0); CTRunGetTypographicBounds(Run, CFRangeMake(0, 1), @Ascent, @Descent, @Leading); CTFrameGetLineOrigins(Frame, CFRangeMake(0, 0), @BaseLinePos); FDefaultBaseline := BoundsLimit - BaseLinePos.y; FDefaultVerticalAdvance := FDefaultBaseline + Descent; CFRelease(Frame); CFRelease(Path); end; function TIOSFontGlyphManager.GetPostScriptFontName: CFStringRef; var LUIFont: UIFont; LocalObject: ILocalObject; begin Result := nil; LUIFont := TUIFont.Wrap(TUIFont.OCClass.fontWithName(StrToNSStr(CurrentSettings.Family), CurrentSettings.Size * CurrentSettings.Scale)); if Supports(LUIFont, ILocalObject, LocalObject) then Result := CTFontCopyPostScriptName(LocalObject.GetObjectID); if Result = nil then //In case there is no direct name for the requested font returns source name and let CoreText to select appropriate font Result := CFSTR(CurrentSettings.Family); end; procedure PathApplierFunction(info: Pointer; const element: PCGPathElement); cdecl; var P, P1, P2: PCGPoint; begin P := element^.points; case element.type_ of kCGPathElementMoveToPoint: TPathData(info).MoveTo(TPointF.Create(P.x, P.y)); kCGPathElementAddLineToPoint: TPathData(info).LineTo(TPointF.Create(P.x, P.y)); kCGPathElementAddQuadCurveToPoint: begin P1 := P; Inc(P1); TPathData(info).QuadCurveTo(TPointF.Create(P.x, P.y), TPointF.Create(P1.x, P1.y)); end; kCGPathElementAddCurveToPoint: begin P1 := P; Inc(P1); P2 := P1; Inc(P2); TPathData(info).CurveTo(TPointF.Create(P.x, P.y), TPointF.Create(P1.x, P1.y), TPointF.Create(P2.x, P2.y)); end; kCGPathElementCloseSubpath: TPathData(info).ClosePath; end; end; function TIOSFontGlyphManager.DoGetBaseline: Single; begin Result := FDefaultBaseline; end; function TIOSFontGlyphManager.DoGetGlyph(const Char: UCS4Char; const Settings: TFontGlyphSettings; const UseColorfulPalette: Boolean): TFontGlyph; var CharsString: string; CharsStringLength: Integer; Str: CFStringRef; Frame: CTFrameRef; Attr: CFMutableAttributedStringRef; Path: CGMutablePathRef; Bounds: CGRect; Rgba: array [0..3] of CGFloat; TextColor: CGColorRef; FrameSetter: CTFramesetterRef; Context: CGContextRef; I, J: Integer; Color: TAlphaColorRec; C: Byte; GlyphRect: TRect; // Metrics Line: CTLineRef; Lines: CFArrayRef; Runs: CFArrayRef; Run: CTRunRef; Ascent, Descent, Leading: CGFloat; Size: CGSize; GlyphStyle: TFontGlyphStyles; BaseLinePos: CGPoint; BaseLineOffset: Single; // RunGlyphCount: CFIndex; glyph: CGGlyph; glyphMatrix: CGAffineTransform; position: CGPoint; glyphPath: CGPathRef; M: TMatrix; Bits: PAlphaColorRecArray; ContextSize: TSize; begin Path := CGPathCreateMutable(); Bounds := CGRectMake(0, 0, BoundsLimit, BoundsLimit); CGPathAddRect(Path, nil, Bounds); CharsString := System.Char.ConvertFromUtf32(Char); CharsStringLength := CharsString.Length * 2; Str := CFStringCreateWithCharacters(kCFAllocatorDefault, PChar(CharsString), CharsStringLength); Attr := CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); CFAttributedStringReplaceString(Attr, CFRangeMake(0, 0), Str); CFAttributedStringBeginEditing(Attr); try // Font if FFontRef <> nil then CFAttributedStringSetAttribute(Attr, CFRangeMake(0, CharsStringLength), kCTFontAttributeName, FFontRef); // Color Rgba[0] := 1; Rgba[1] := 1; Rgba[2] := 1; Rgba[3] := 1; TextColor := CGColorCreate(FColorSpace, @Rgba[0]); try CFAttributedStringSetAttribute(Attr, CFRangeMake(0, CharsStringLength), kCTForegroundColorAttributeName, TextColor); finally CFRelease(TextColor); end; finally CFAttributedStringEndEditing(Attr); end; FrameSetter := CTFramesetterCreateWithAttributedString(CFAttributedStringRef(Attr)); CFRelease(Attr); Frame := CTFramesetterCreateFrame(FrameSetter, CFRangeMake(0, 0), Path, nil); CFRelease(FrameSetter); CFRelease(Str); // Metrics Context := CGBitmapContextCreate(nil, 1, 1, 8, 4, FColorSpace, kCGImageAlphaPremultipliedLast); try Lines := CTFrameGetLines(Frame); Line := CTLineRef(CFArrayGetValueAtIndex(Lines, 0)); Runs := CTLineGetGlyphRuns(Line); Run := CFArrayGetValueAtIndex(Runs, 0); Bounds := CTRunGetImageBounds(Run, Context, CFRangeMake(0, 1)); CTRunGetAdvances(Run, CFRangeMake(0, 1), @Size); CTRunGetTypographicBounds(Run, CFRangeMake(0, 1), @Ascent, @Descent, @Leading); GlyphRect := Rect(Trunc(Bounds.origin.x), Max(Trunc(Ascent - Bounds.origin.y - Bounds.size.height) - 1, 0), Ceil(Bounds.origin.x + Bounds.size.width), Round(Ascent + Descent + Descent)); CTFrameGetLineOrigins(Frame, CFRangeMake(0, 0), @BaseLinePos); BaseLineOffset := BoundsLimit - BaseLinePos.y; GlyphStyle := []; if ((Bounds.size.width = 0) and (Bounds.size.height = 0)) or not HasGlyph(Char) then GlyphStyle := [TFontGlyphStyle.NoGlyph]; if TFontGlyphSetting.Path in Settings then GlyphStyle := GlyphStyle + [TFontGlyphStyle.HasPath]; if UseColorfulPalette then GlyphStyle := GlyphStyle + [TFontGlyphStyle.ColorGlyph]; finally CGContextRelease(Context); end; Result := TFontGlyph.Create(Point(GlyphRect.Left, GlyphRect.Top), Size.width, Round(FDefaultVerticalAdvance), GlyphStyle); if (TFontGlyphSetting.Bitmap in Settings) and (HasGlyph(Char) or ((Bounds.size.width > 0) and (Bounds.size.height > 0))) then begin ContextSize := TSize.Create(Max(GlyphRect.Right, GlyphRect.Width), GlyphRect.Bottom); Context := CGBitmapContextCreate(nil, ContextSize.Width, ContextSize.Height, 8, ContextSize.Width * 4, FColorSpace, kCGImageAlphaPremultipliedLast); try Bits := PAlphaColorRecArray(CGBitmapContextGetData(Context)); if GlyphRect.Left < 0 then CGContextTranslateCTM(Context, -GlyphRect.Left, 0); CGContextTranslateCTM(Context, 0, -(BoundsLimit - ContextSize.Height)); if not SameValue(FDefaultBaseline - BaseLineOffset, 0, TEpsilon.Position) then CGContextTranslateCTM(Context, 0, -Abs(FDefaultBaseline - BaseLineOffset)); CTFrameDraw(Frame, Context); Result.Bitmap.SetSize(GlyphRect.Width, GlyphRect.Height, TPixelFormat.BGRA); if TFontGlyphSetting.PremultipliedAlpha in Settings then begin for I := GlyphRect.Top to GlyphRect.Bottom - 1 do Move(Bits^[I * ContextSize.Width + Max(GlyphRect.Left, 0)], Result.Bitmap.GetPixelAddr(0, I - GlyphRect.Top)^, Result.Bitmap.Pitch); end else for I := GlyphRect.Left to GlyphRect.Right - 1 do for J := GlyphRect.Top to GlyphRect.Bottom - 1 do begin Color := Bits[J * ContextSize.Width + Max(I, 0)]; if Color.R > 0 then begin C := (Color.R + Color.G + Color.B) div 3; Result.Bitmap.Pixels[I - GlyphRect.Left, J - GlyphRect.Top] := MakeColor($FF, $FF, $FF, C); end end; finally CGContextRelease(Context); end; end; //Path if TFontGlyphSetting.Path in Settings then begin RunGlyphCount := CTRunGetGlyphCount(Run); for I := 0 to RunGlyphCount - 1 do begin CTRunGetGlyphs(Run, CFRangeMake(I, 1), @glyph); CTRunGetPositions(run, CFRangeMake(I, 1), @position); glyphMatrix := CGAffineTransformTranslate(CGAffineTransformIdentity, position.x, position.y); glyphPath := CTFontCreatePathForGlyph(FFontRef, glyph, @glyphMatrix); if glyphPath <> nil then begin CGPathApply(glyphPath, Result.Path, @PathApplierFunction); CFRelease(glyphPath); end; end; M := TMatrix.Identity; M.m22 := -1; Result.Path.ApplyMatrix(M); end; CFRelease(Frame); CFRelease(Path); end; function TIOSFontGlyphManager.IsColorfulCharacter(const Char: UCS4Char): Boolean; begin Result := inherited or (Char = $1F004) or (Char = $1F0CF) or (Char = $1F170) or (Char = $1F171) or (Char = $1F17E) or (Char = $1F17F) or (Char = $1F18F) or ((Char >= $1F191) and (Char <= $1F19A)) or (Char = $1F201) or (Char = $1F202) or (Char = $1F21A) or (Char = $1F22F) or ((Char >= $1F232) and (Char <= $1F23A)) or (Char = $1F250) or (Char = $1F251) or ((Char >= $1F300) and (Char <= $1F320)) or ((Char >= $1F330) and (Char <= $1F393)) or ((Char >= $1F3A0) and (Char <= $1F3F0)) or ((Char >= $1F400) and (Char <= $1F43E)) or (Char = $1F440) or ((Char >= $1F442) and (Char <= $1F49F)) or ((Char >= $1F4A0) and (Char <= $1F4FC)) or ((Char >= $1F500) and (Char <= $1F53D)) or ((Char >= $1F550) and (Char <= $1F567)) or ((Char >= $1F5FB) and (Char <= $1F64F)) or ((Char >= $1F680) and (Char <= $1F6C5)) or (Char = $2139) or ((Char >= $2194) and (Char <= $2199)) or (Char = $21A9) or (Char = $21AA) or (Char = $231A) or (Char = $231B) or ((Char >= $23E9) and (Char <= $23EC)) or (Char = $23F0) or (Char = $23F3) or (Char = $24C2) or (Char = $25AA) or (Char = $25AB) or (Char = $25B6) or (Char = $25C0) or ((Char >= $25FB) and (Char <= $25FE)) or (Char = $2600) or (Char = $2601) or (Char = $260E) or (Char = $2611) or (Char = $2614) or (Char = $2615) or (Char = $261D) or (Char = $263A) or ((Char >= $2648) and (Char <= $2653)) or (Char = $2660) or (Char = $2663) or (Char = $2665) or (Char = $2666) or (Char = $2668) or (Char = $267B) or (Char = $267F) or (Char = $2693) or (Char = $26A0) or (Char = $26A1) or (Char = $26AA) or (Char = $26AB) or (Char = $26BD) or (Char = $26BE) or (Char = $26C4) or (Char = $26C5) or (Char = $26CE) or (Char = $26D4) or (Char = $26EA) or (Char = $26F2) or (Char = $26F3) or (Char = $26F5) or (Char = $26FA) or (Char = $26FD) or (Char = $2702) or (Char = $2705) or ((Char >= $2708) and (Char <= $270F)) or (Char = $2712) or (Char = $2714) or (Char = $2716) or (Char = $2728) or (Char = $2733) or (Char = $2734) or (Char = $2744) or (Char = $2747) or (Char = $274C) or (Char = $274E) or ((Char >= $2753) and (Char <= $2755)) or (Char = $2757) or (Char = $2764) or ((Char >= $2795) and (Char = $2797)) or (Char = $27B0) or (Char = $27BF) or (Char = $2934) or (Char = $2935) or ((Char >= $2B05) and (Char = $2B07)) or (Char = $2B1B) or (Char = $2B1C) or (Char = $2B50) or (Char = $2B55) or (Char = $3030) or (Char = $303D) or (Char = $3297) or (Char = $3299); end; end.
unit oCoverSheetGrid; interface uses System.Classes, System.Types, System.SysUtils, System.RTLConsts, iCoverSheetIntf; type TCoverSheetGrid = class(TInterfacedObject, ICoverSheetGrid) private fRowCount: integer; fCoordinates: array of TPoint; function getPanelCount: integer; function getRowCount: integer; procedure ErrorCheck(aPanelIndex: integer); function getPanelXY(aPanelIndex: integer): TPoint; function getPanelRow(aPanelIndex: integer): integer; function getPanelColumn(aPanelIndex: integer): integer; procedure setPanelCount(const aValue: integer); public constructor Create; destructor Destroy; override; end; implementation { TCoverSheetGrid } constructor TCoverSheetGrid.Create; begin inherited Create; end; destructor TCoverSheetGrid.Destroy; begin SetLength(fCoordinates, 0); inherited; end; procedure TCoverSheetGrid.ErrorCheck(aPanelIndex: integer); begin if (aPanelIndex < 0) or (aPanelIndex >= Length(fCoordinates)) then raise EListError.CreateFmt(LoadResString(@SListIndexError), [aPanelIndex]) at ReturnAddress; end; function TCoverSheetGrid.getPanelColumn(aPanelIndex: integer): integer; begin ErrorCheck(aPanelIndex); Result := fCoordinates[aPanelIndex].X; end; function TCoverSheetGrid.getPanelCount: integer; begin Result := Length(fCoordinates); end; function TCoverSheetGrid.getPanelRow(aPanelIndex: integer): integer; begin ErrorCheck(aPanelIndex); Result := fCoordinates[aPanelIndex].Y; end; function TCoverSheetGrid.getPanelXY(aPanelIndex: integer): TPoint; begin ErrorCheck(aPanelIndex); Result := fCoordinates[aPanelIndex]; end; function TCoverSheetGrid.getRowCount: integer; begin Result := fRowCount; end; procedure TCoverSheetGrid.setPanelCount(const aValue: integer); begin SetLength(fCoordinates, 0); if (aValue < 1) or (aValue > 12) then raise Exception.CreateFmt('Panel count of %d not currently supported.', [aValue]) else SetLength(fCoordinates, aValue); case aValue of 1: begin fRowCount := 1; fCoordinates[0] := Point(0, 0); end; 2: begin fRowCount := 1; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); end; 3: begin fRowCount := 2; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); fCoordinates[2] := Point(0, 1); end; 4: begin fRowCount := 2; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); fCoordinates[2] := Point(0, 1); fCoordinates[3] := Point(1, 1); end; 5: begin fRowCount := 2; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); fCoordinates[2] := Point(2, 0); fCoordinates[3] := Point(0, 1); fCoordinates[4] := Point(1, 1); end; 6: begin fRowCount := 2; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); fCoordinates[2] := Point(2, 0); fCoordinates[3] := Point(0, 1); fCoordinates[4] := Point(1, 1); fCoordinates[5] := Point(2, 1); end; 7: begin fRowCount := 3; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); fCoordinates[2] := Point(2, 0); fCoordinates[3] := Point(0, 1); fCoordinates[4] := Point(1, 1); fCoordinates[5] := Point(0, 2); fCoordinates[6] := Point(1, 2); end; 8: begin fRowCount := 3; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); fCoordinates[2] := Point(2, 0); fCoordinates[3] := Point(0, 1); fCoordinates[4] := Point(1, 1); fCoordinates[5] := Point(0, 2); fCoordinates[6] := Point(1, 2); fCoordinates[7] := Point(2, 2); end; 9: begin fRowCount := 3; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); fCoordinates[2] := Point(2, 0); fCoordinates[3] := Point(0, 1); fCoordinates[4] := Point(1, 1); fCoordinates[5] := Point(2, 1); fCoordinates[6] := Point(0, 2); fCoordinates[7] := Point(1, 2); fCoordinates[8] := Point(2, 2); end; 10: begin fRowCount := 3; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); fCoordinates[2] := Point(2, 0); fCoordinates[3] := Point(3, 0); fCoordinates[4] := Point(0, 1); fCoordinates[5] := Point(1, 1); fCoordinates[6] := Point(2, 1); fCoordinates[7] := Point(0, 2); fCoordinates[8] := Point(1, 2); fCoordinates[9] := Point(2, 2); end; 11: begin fRowCount := 3; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); fCoordinates[2] := Point(2, 0); fCoordinates[3] := Point(3, 0); fCoordinates[4] := Point(0, 1); fCoordinates[5] := Point(1, 1); fCoordinates[6] := Point(2, 1); fCoordinates[7] := Point(0, 2); fCoordinates[8] := Point(1, 2); fCoordinates[9] := Point(2, 2); fCoordinates[10] := Point(3, 2); end; 12: begin fRowCount := 3; fCoordinates[0] := Point(0, 0); fCoordinates[1] := Point(1, 0); fCoordinates[2] := Point(2, 0); fCoordinates[3] := Point(3, 0); fCoordinates[4] := Point(0, 1); fCoordinates[5] := Point(1, 1); fCoordinates[6] := Point(2, 1); fCoordinates[7] := Point(3, 1); fCoordinates[8] := Point(0, 2); fCoordinates[9] := Point(1, 2); fCoordinates[10] := Point(2, 2); fCoordinates[11] := Point(3, 2); end; else fRowCount := 0; end; end; end.
Unit BaseObject_f; Interface Uses BaseObject_c_FunctionResult; // Function BaseObjectInitialize(): TBaseObjectFunctionResult; // Implementation Uses BaseObject_c; // Function BaseObjectInitialize(): TBaseObjectFunctionResult; Begin If ((SizeOf(TBaseObjectDataContainerS) <> 8) Or (SizeOf(TBaseObjectDataContainerU) <> 4)) Then Begin result := coBaseObjectFunctionResult_InitializationError; End Else Begin result := coBaseObjectFunctionResult_Ok; End; End; // End. // /// // Function BaseObjectFileSave(Const xxBaseObjectBodyPointer: TBaseObjectBodyPointer): TBaseObjectFunctionResult; // Var // fiBaseObjectFile: File; // xxBaseObjectBodyLengthWrited: TBaseObjectDataContainer; // Begin // If (boBaseObjectCatalogDefined) Then // Begin // AssignFile(fiBaseObjectFile, stBaseObjectCatalogName + BaseObjectIDToHexString(xxBaseObjectBodyPointer.ObjectID) + coBaseObjectFileExt); // ReWrite(fiBaseObjectFile, 1); // BlockWrite(fiBaseObjectFile, xxBaseObjectBodyPointer.ObjectType, coBaseObjectBodyLengthInByteFile, xxBaseObjectBodyLengthWrited); // CloseFile(fiBaseObjectFile); // If (xxBaseObjectBodyLengthWrited = coBaseObjectBodyLengthInByteFile) Then // Begin // result := coBOFREnum_Ok; // End // Else // Begin // result := coBOFREnum_WritedNotCompletely; // End; // End // Else // Begin // Raise Exception.Create('Error 4sXgdV'); // result := coBOFREnum_BaseCatalogNotDefined; // End; // End; // // / // // // // // // // // // Function BOObjectListPayloadLengthInByte(Const xxBaseObjectObjectListPayloadPointer: TBaseObjectObjectListPayloadPointer): TBaseObjectDataContainer; // Begin // result := xxBaseObjectObjectListPayloadPointer.ObjectListLengthInPiece * SizeOf(TBaseObjectID); // End; // End. // // Function BOCreateObjBodyArc(Var xxBaseObjectID: TBaseObjectID): TBaseObjectFunctionResult; // Begin // End; // // Function BOCreateObjBodyNone(Var xxBaseObjectID: TBaseObjectID): TBaseObjectFunctionResult; // Begin // End; // // Function BOCreateObjBodyTrack(Var xxBaseObjectID: TBaseObjectID): TBaseObjectFunctionResult; // Begin // End; // // Function BOCreateObjBodyZelect(xxObjectType: TBaseObjectType): TBaseObjectFunctionResult; // Begin // End; // // Function BOCreateRawBody(Const xxBaseObjectBodyPointer: TBaseObjectBodyPointer): TBaseObjectFunctionResult; // Begin // End; // // Function BOCreateRawChildList(Const xxBaseObjectObjectListWithOffsetPayloadPointer: TBaseObjectObjectListWithOffsetPayloadPointer): TBaseObjectFunctionResult; // Begin // End; // // Function BOCreateRawFatherList(Const xxTBaseObjectObjectListPayloadPointer: TBaseObjectObjectListPayloadPointer): TBaseObjectFunctionResult; // Begin // End; // // Function BOCreateRawPayload(Const xxBaseObjectPayloadPointer: TBaseObjectPayloadPointer): TBaseObjectFunctionResult; // Begin // End; // // Function BaseObjectCreate(Const xxBaseObjectBodyPointer: TBaseObjectBodyPointer): TBaseObjectFunctionResult; // Begin // BaseObjectIDCreate(xxBaseObjectBodyPointer.ObjectID); // BaseObjectIDCreate(xxBaseObjectBodyPointer.ObjectChildListID); // BaseObjectIDCreate(xxBaseObjectBodyPointer.ObjectFatherListID); // BaseObjectIDCreate(xxBaseObjectBodyPointer.ObjectPayloadID); // BaseObjectFileSave(xxBaseObjectBodyPointer); // result := coBOFREnum_Ok; // End; // // // Function BOFileObjBodyLoad(Const xxBaseObjectID: TBaseObjectID; Const xxBaseObjectBodyPointer: TBaseObjectBodyPointer): TBaseObjectFunctionResult; // Begin // End; // BaseObject_c_ObjectBody, // BaseObject_c_ObjectType // // // Function BOCreateObjBodyArc(Var xxBaseObjectID: TBaseObjectID): TBaseObjectFunctionResult; // Function BOCreateObjBodyNone(Var xxBaseObjectID: TBaseObjectID): TBaseObjectFunctionResult; // Function BOCreateObjBodyTrack(Var xxBaseObjectID: TBaseObjectID): TBaseObjectFunctionResult; // Function BOCreateObjBodyZelect(xxObjectType: TBaseObjectType): TBaseObjectFunctionResult; // // Function BOCreateRawBody(Const xxBaseObjectBodyPointer: TBaseObjectObjectBodyPointer): TBaseObjectFunctionResult; // Function BOCreateRawPayload(): TBaseObjectFunctionResult; // // // // // // // Function BaseObjectBuferModify(): TBaseObjectFunctionResult; // Const // coBaseObjectBuferLengthStepInByte = 102400; // Begin // xxBaseObjectBuferLengthInByte := coBaseObjectBuferLengthStepInByte; // GetMem(xxBaseObjectBodyPointerArray[0], xxBaseObjectBuferLengthInByte); // result := coBOFREnum_Ok; // End; // // xxBaseObjectBodyPointerArray: Array [0 .. 9] Of TBaseObjectBodyPointer; // Function BOCatalogNameSet(Const stCatalogName: String): TBaseObjectFunctionResult; // Begin // stBaseObjectCatalogName := stCatalogName; // boBaseObjectCatalogDefined := true; // result := coBaseObjectFunctionResult_Ok; // End; // // // Function BOFileObjPayloadVisualizationObjectListLoad(Const xxBaseObjectID: TBaseObjectID; // Const xxTBaseObjectObjectListPayloadPointer: TBaseObjectObjectListPayloadPointer): TBaseObjectFunctionResult; // Begin // End; // // // Function BOFileRawLoad(Const xxBaseObjectID: TBaseObjectID; Const poPointer: Pointer): TBaseObjectFunctionResult; // Begin // End; // // // Function BOFileRawSave(Const poPointer: Pointer): TBaseObjectFunctionResult; // Begin // End; // // // Function BOGetObjectChildListIDFromObjBody(Const xxBaseObjectID: TBaseObjectID; Var xxObjectPayloadID: TBaseObjectID): TBaseObjectFunctionResult; // Begin // End; // // // Function BOGetObjectFatherListIDFromObjBody(Const xxBaseObjectID: TBaseObjectID; Var xxObjectPayloadID: TBaseObjectID): TBaseObjectFunctionResult; // Begin // End; // // // Function BOGetObjectPayloadIDFromObjBody(Const xxBaseObjectID: TBaseObjectID; Var xxObjectPayloadID: TBaseObjectID): TBaseObjectFunctionResult; // Var // xxBaseObjectBodyLengthReaded: TBaseObjectDataContainerU; // xxBaseObjectBodyPointer: TBaseObjectBodyPointer; // fiBaseObjectFile: File; // Begin // AssignFile(fiBaseObjectFile, BaseObjectFileNameGet(xxBaseObjectID)); // Reset(fiBaseObjectFile, 1); // If (FileSize(fiBaseObjectFile) = coBaseObjectBodyLengthInByteFile) Then // Begin // GetMem(xxBaseObjectBodyPointer, coBaseObjectBodyLengthInByteMemory); // BlockRead(fiBaseObjectFile, xxBaseObjectBodyPointer.ObjectType, coBaseObjectBodyLengthInByteFile, xxBaseObjectBodyLengthReaded); // xxObjectPayloadID := xxBaseObjectBodyPointer.ObjectPayloadID; // result := coBaseObjectFunctionResult_Ok // End // Else // Begin // result := coBaseObjectFunctionResult_BaseObjectFileLengthError; // End; // End; // // // // // Function BOPayloadObjectListLengthInByte(Const xxBaseObjectObjectListPayloadPointer: TBaseObjectObjectListPayloadPointer): TBaseObjectDataContainerU; // Begin // End;
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_NetServer * Implements a generic multiplayer game server *********************************************************************************************************************** } Unit TERRA_NetServer; {$I terra.inc} {$DEFINE NETDEBUG} {$DEFINE SAVEPACKETS} Interface Uses TERRA_Application, TERRA_OS, TERRA_IO, TERRA_Sockets, TERRA_Network, TERRA_ThreadPool, TERRA_Utils, TERRA_Classes {$IFDEF SAVEPACKETS},TERRA_NetLogger{$ENDIF}; Type NetPacket = Record Msg:LNetMessage; Dest:SocketAddress; Sock:Socket; Time:Cardinal; End; // Client Info ClientInfo=Class ID:Word; UserName:AnsiString; Password:AnsiString; DeviceID:AnsiString; GUID:Word; Time:Cardinal; //Last contact time Ping:Integer; //If ping<0 then Client connection is dead Socket:TERRA_Sockets.Socket; Address:SocketAddress; Frames:Integer; UserData:Pointer; //Not needed, Application specific use End; NetServer = Class(NetObject) Protected _Mutex:CriticalSection; _ClientList:Array Of ClientInfo; // Clients list _ClientCount:Integer; // Max number of Clients allowed _RefreshTime:Cardinal; // Search for dead connections time _WaitingConnections:Array Of Socket; _WaitingCount:Integer; _Packets:Array Of NetPacket; _PacketCount:Integer; _PacketMutex:CriticalSection; _PacketKeep:Boolean; _PacketImportant:Array[0..255] Of Boolean; _LastPacketUpdate:Cardinal; Procedure RemoveClient(Client:ClientInfo); //Event: When a Client leaves the server Function OnSendFail(Dest:SocketAddress; Sock:Socket; Msg:PNetMessage):Boolean; Override; Procedure OnPacketReceived(Sock:Socket; Msg: PNetMessage); Override; Function IsPacketImportant(Msg:PNetMessage):Boolean; Virtual; Procedure SendDroppedPackets; Public // Creates a new server instance Constructor Create(Name:AnsiString; Version,Port:Word; MaxClients:Word); // Handles messages Procedure Update; Override; // Send a message Procedure SendMessage(Msg:PNetMessage; ClientID:Word); Overload; Virtual; Procedure SendMessage(ClientID:Word; Opcode:Byte; Src:Stream; Owner:Word = 0); Overload; // Broadcast a message Procedure BroadcastMessage(Msg:PNetMessage); // Removes a Client from the server Procedure Kick(ClientID:Word); // Validates client username/password Function ValidateClient(UserName,Password,DeviceID:AnsiString; Var ErrorLog:AnsiString):Integer; Virtual; Function ValidateMessage(Msg:PNetMessage):Boolean; Override; // Shutdown a server and destroy it Destructor Destroy(ErrorCode:Word=errServerShutdown); Reintroduce; // Message handlers Procedure PingMessage(Msg:PNetMessage; Sock:Socket); Procedure JoinMessage(Msg:PNetMessage; Sock:Socket); Procedure DropMessage(Msg:PNetMessage; Sock:Socket); // Gets local Client Function GetClient(ID:Word):ClientInfo; Function GetClientByUsername(Name:AnsiString):ClientInfo; Function GetClientAddress(ID:Word):Cardinal; Function CreateIterator:Iterator; Function GetConnectedClients():Integer; // Network Events Procedure OnClientAdd(Client:ClientInfo);Virtual; //Event: When a new Client enter the server Procedure OnClientRemove(Client:ClientInfo);Virtual; //Event: When a Client leaves the server Property ClientCount:Integer Read _ClientCount; End; NetServerIterator=Class(Iterator) Protected Server:NetServer; Pos,Count:Integer; Public Function HasNext:Boolean;Override; Function GetNext:ListObject;Override; Procedure Discard(Release:Boolean=True);Override; End; Implementation Uses TERRA_Log, TERRA_MultiThreadedServer, TERRA_NetReplayServer; {******************** LNetServer Class ********************} Procedure NetServer.PingMessage(Msg:PNetMessage; Sock:Socket); Var Client:ClientInfo; Begin Client := GetClient(Msg.Owner); If Not Assigned(Client) Then Exit; Client.Ping := Client.Time; Client.Time := GetTime; Client.Ping := Integer(Client.Time) - Client.Ping; End; Procedure NetServer.JoinMessage(Msg:PNetMessage; Sock:Socket); Var N,I,K:Integer; S:Stream; Guid, Version:Word; UserName,Password, DeviceID:AnsiString; Client:ClientInfo; Rm:LNetMessage; ErrorLog:AnsiString; Begin S := MemoryStream.Create(Msg.Size, @(Msg.Data[0])); S.Read(@GUID, 2); S.Read(@Version, 2); S.ReadString(Username); S.ReadString(Password); If (Not S.EOF) Then S.ReadString(DeviceID) Else DeviceID := ''; S.Destroy; If (Sock<>Nil) Then Begin For I:=1 To _ClientCount Do //Search for duplicated GUIDs Begin Client := GetClient(I); If (Assigned(Client)) And(Client.Socket = Sock) Then Exit; End; End; { N:=-1; For I:=1 To _ClientCount Do //Search for duplicated GUIDs Begin Client := GetClient(I); If (Assigned(Client)) And(Client.GUID = GUID) Then Begin N:=I; //If this GUID is the same,then the Client already is in the server Break; End; End; If N<>-1 Then //The Client GUID was found, this Client is already in Begin //Return a duplicated GUID error to the client CreateMessage(Rm,nmServerError, errDuplicatedGUID); ReturnMessage(Sock, @Rm); Exit; End;} If Version<>_Version Then Begin //Return a invalid version error to the client CreateMessage(Rm,nmServerError,errInvalidVersion); ReturnMessage(Sock, @Rm); Exit; End; ErrorLog := ''; K := ValidateClient(UserName,Password, DeviceID, ErrorLog); If K<>0 Then Begin CreateMessage(Rm, nmServerError, K); S := MemoryStream.Create(256, @Rm.Data[2]); S.WriteString(ErrorLog); Rm.Size := S.Position + 2; S.Destroy; ReturnMessage(Sock, @Rm); Exit; End; _Mutex.Lock(); N:=-1; For I:=1 To _ClientCount Do //Search for a dead Client slot If _ClientList[I] = Nil Then Begin N := I; //If this Client is dead, then we can reuse the slot Break; End; _Mutex.Unlock(); If N=-1 Then Begin CreateMessage(Rm,nmServerError,errServerFull); ReturnMessage(Sock, @Rm); Exit; End; _Mutex.Lock(); Client := ClientInfo.Create; Client.Address := _Sender; // Store the new Client IP Client.Ping := 0; // Reset Client ping Client.GUID := GUID; Client.Time := GetTime; Client.UserName := UserName; Client.ID := N; Client.UserData := Nil; Client.Password := Password; Client.DeviceID := DeviceID; Client.Socket := Sock; Client.Frames := 0; _ClientList[N] := Client; _Mutex.Unlock(); {$IFDEF SAVEPACKETS} If (Not (Self Is NetworkReplayServer)) Then NetworkLogger.Instance.LogConnectionStart(N, UserName, Password, DeviceID); {$ENDIF}; CreateMessage(Rm, nmServerAck, N); ReturnMessage(Sock, @Rm); If (Not (Self Is NetMultithreadedServer)) Then OnClientAdd(Client); //Calls the AddClient event End; Procedure NetServer.DropMessage(Msg:PNetMessage; Sock:Socket); Var Client:ClientInfo; Begin Client := GetClient(Msg.Owner); If Assigned(Client) Then RemoveClient(Client) //Calls the remove Client event Else RaiseError('Network.'+_Name+'.DropMessage: Invalid Client. ['+IntToString(Msg.Owner)+']'); End; Constructor NetServer.Create(Name:AnsiString; Version, Port:Word; MaxClients:Word); {Creates a new server instance} Var I:Integer; Begin Inherited Create(); _LocalId := 0; //Servers always have a localID of zero _NetObject := Self; _Name := Name; _Port := Port; _WaitingCount := 0; _ClientCount := MaxClients; _RefreshTime := 0; _Version := Version; _OpcodeList[nmPing] := PingMessage; _OpcodeList[nmClientJoin] := JoinMessage; _OpcodeList[nmClientDrop] := DropMessage; _Mutex := CriticalSection.Create(''); _PacketMutex := CriticalSection.Create(''); SetLength(_ClientList, Succ(_ClientCount)); _ClientList[0] := ClientInfo.Create; With _ClientList[0] Do Begin Name := 'Server'; Ping := 0; GUID := 0; End; For I:=1 To 255 Do _PacketImportant[I] := True; _PacketImportant[nmPing] := False; For I:=1 To _ClientCount Do _ClientList[I] := Nil; End; // Validates a message Function NetServer.ValidateMessage(Msg:PNetMessage):Boolean; Var Client:ClientInfo; Begin {$IFDEF NETDEBUG}WriteLn('Begin validation');{$ENDIF} Result := (Msg.Owner=ID_UNKNOWN) And (Msg.Opcode=nmClientJoin); If Not Result Then Begin {$IFDEF NETDEBUG}WriteLn('Calling getClient()');{$ENDIF} Client := GetClient(Msg.Owner); Result := (Assigned(Client)){ And (Client.Address.Address=_Sender.Address)}; {$IFDEF NETDEBUG}WriteLn('Testing client');{$ENDIF} If Assigned(Client) Then Client.Time := GetTime Else Log(logWarning,'Network',_Name+'.Update: Invalid server message. ['+IntToString(Msg.Owner)+']'); End; {$IFDEF NETDEBUG}WriteLn('End validation');{$ENDIF} End; // Handles messages Procedure NetServer.Update; Var I,J:Integer; Msg:PNetMessage; Rm:LNetMessage; ValidMsg:Boolean; Client:ClientInfo; Sock:Socket; Begin _PacketKeep := True; UpdateIO; Sock := OpenIncomingStream(_Port); If Assigned(Sock) Then Begin Sock.SetBlocking(False); Sock.SetDelay(False); Sock.SetBufferSize(1024*128); Inc(_WaitingCount); SetLength(_WaitingConnections, _WaitingCount); _WaitingConnections[Pred(_WaitingCount)] := Sock; End; {If (Self.GetConnectedClients()>0) Then WriteLn('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Starting update cycle ');} For I:=1 To _ClientCount Do // Search dead connections, by pinging Clients Begin Client := GetClient(I); If (Not Assigned(Client)) Or (Client.Socket = Nil) Then Continue; {$IFDEF NETDEBUG}WriteLn('Processing client: ',Client.Username);{$ENDIF} J := 0; Repeat If ReceivePacket(Client.Socket, @RM) Then Begin If (IsPacketImportant(@RM)) Then Inc(J); Client.Time := GetTime(); Inc(Client.Frames); End Else Break; Until (J>=5); {$IFDEF NETDEBUG}WriteLn('Packets received: ',J);{$ENDIF} End; I:=0; While (I<_WaitingCount) Do Begin {$IFDEF NETDEBUG}WriteLn('Processing waiting connection #',I);{$ENDIF} If (ReceivePacket(_WaitingConnections[I], @RM)) Then Begin _WaitingConnections[I] := _WaitingConnections[Pred(_WaitingCount)]; Dec(_WaitingCount); End Else Inc(I); End; For I:=1 To _ClientCount Do // Search dead connections, by pinging Clients Begin Client := GetClient(I); If (Not Assigned(Client)) Or (Not Assigned(Client.Socket)) Then Continue; If (Client.Socket.Closed) Or (GetTime() - Client.Time>1000*60*2) Then Begin Log(logWarning,'Network',_Name+'.Update: ClientID='+IntToString(I)+' is dead.'); RemoveClient(Client); // Call RemoveClient event End Else If (GetTime-Client.Time)>PING_TIME Then Begin CreateShortMessage(Rm,nmPing); SendMessage(@Rm, I); // Pings the Client, to see if its alive End; End; Self.SendDroppedPackets(); End; Function NetServer.IsPacketImportant(Msg:PNetMessage):Boolean; Begin Result := Msg.Opcode>=10; End; Function NetServer.GetClientAddress(ID:Word):Cardinal; Var Info:ClientInfo; Begin Info := Self.GetClient(ID); If Info = Nil Then Begin Result := 0; Exit; End; Result := Info.Socket.Address; End; Function NetServer.GetClientByUsername(Name:AnsiString):ClientInfo; Var I:Integer; Begin Result := Nil; Name := UpStr(Name); _Mutex.Lock(); For I:=1 To _ClientCount Do If (_ClientList[I]<>Nil) And (UpStr(_ClientList[I].UserName)=Name) Then Begin Result := _ClientList[I]; Break; End; _Mutex.Unlock(); End; Function NetServer.GetClient(ID:Word):ClientInfo; Begin _Mutex.Lock(); If (ID>0) And (ID<=_ClientCount) Then Begin If (_ClientList[ID]=Nil) Then Result := Nil Else Begin Result := _ClientList[ID]; End; End Else Result := Nil; _Mutex.Unlock(); End; Procedure NetServer.OnClientAdd(Client:ClientInfo); Begin End; Procedure NetServer.OnClientRemove(Client:ClientInfo); Begin End; Procedure NetServer.RemoveClient(Client:ClientInfo); Var I:Integer; Done:boolean; Begin If (Client = Nil) Then Exit; If (Not (Self Is NetMultithreadedServer)) Then Begin Self.OnClientRemove(Client); End; _Mutex.Lock(); Done := (_ClientList[Client.ID] = Nil); _ClientList[Client.ID] := Nil; _Mutex.Unlock(); If (Done) Then Exit; {$IFDEF SAVEPACKETS} If (Not (Self Is NetworkReplayServer)) Then NetworkLogger.Instance.LogConnectionEnd(Client.ID); {$ENDIF}; Client.GUID := 0; Client.Address.Address := 0; If (Assigned(Client.Socket)) Then Begin _PacketMutex.Lock(); For I:=0 To Pred(_PacketCount) Do If (_Packets[I].Sock = Client.Socket) Then _Packets[I].Sock := Nil; _PacketMutex.Unlock(); If (Not (Self Is NetworkReplayServer)) Then Client.Socket.Destroy; Client.Socket := Nil; End; Client.Destroy; End; Function NetServer.ValidateClient(UserName,Password, DeviceID:AnsiString; Var ErrorLog:AnsiString):Integer; Begin Log(logDebug,'Network',_Name+'.Validate: User='+Username+' Pass='+Password+' DeviceID='+DeviceID); Result := 0; End; // Send a message Procedure NetServer.SendMessage(Msg:PNetMessage; ClientID:Word); Var Client:ClientInfo; Begin {$IFDEF NETDEBUG}WriteLn('Fetching client'); {$ENDIF} Client := GetClient(ClientID); {$IFDEF NETDEBUG}If Assigned(Client) Then WriteLn('Client: ',Client.ID) Else WriteLn('Client not found'); {$ENDIF} If Assigned(Client) Then Begin {$IFDEF NETDEBUG}WriteLn('Sending packet'); {$ENDIF} SendPacket(Client.Address, Client.Socket, Msg); {$IFDEF NETDEBUG}WriteLn('Packet sent'); {$ENDIF} End Else Log(logWarning,'Network',_Name+'.SendMessage: Invalid client.['+IntToString(ClientID)+']'); End; Procedure NetServer.SendMessage(ClientID:Word; Opcode:Byte; Src:Stream; Owner:Word = 0); Var Msg:LNetMessage; Begin FillChar(Msg, SizeOf(Msg), 0); Msg.Opcode := Opcode; Msg.Owner := Owner; If (Src<>Nil) Then Begin Msg.Size := Stream(Src).Position; Stream(Src).Seek(0); Stream(Src).Read(@Msg.Data[0], Msg.Size); End; SendMessage(@Msg, ClientID); End; // Broadcast a message Procedure NetServer.BroadcastMessage(Msg:PNetMessage); Var I:Integer; Begin For I:=1 To _ClientCount Do If (I<>Msg.Owner) And (Assigned(GetClient(I))) Then SendMessage(Msg,I); End; // Removes a Client from the server Procedure NetServer.Kick(ClientID:Word); Var Msg:LNetMessage; Client:ClientInfo; Begin Client := GetClient(ClientID); If Assigned(Client) Then Begin CreateMessage(Msg,nmServerShutdown,errKicked); SendMessage(@Msg, ClientID); RemoveClient(Client); End; End; // Shutdown a server and destroy it Destructor NetServer.Destroy(ErrorCode:Word=errServerShutdown); Var Client:ClientInfo; I:Integer; Msg:LNetMessage; Begin CreateMessage(Msg,nmServerShutdown,ErrorCode); //Zero means normal shutdown BroadcastMessage(@Msg); //Notify Clients of the server shutdown For I:=1 To _ClientCount Do //Search for duplicated GUIDs Begin Client := GetClient(I); If (Assigned(Client)) And (Client.Socket <>Nil) Then Begin Client.Socket.Destroy; Client.Socket := Nil; End; End; Inherited Destroy; _Mutex.Destroy; End; Function NetServer.CreateIterator:Iterator; Begin Result := NetServerIterator.Create; NetServerIterator(Result).Pos:=0; NetServerIterator(Result).Count:=0; NetServerIterator(Result).Server:=Self; End; // LNetServerIterator Function NetServerIterator.GetNext:ListObject; Begin Inc(Pos); Result := Server.GetClient(Pos); If Result=Nil Then Result := GetNext Else Inc(Count); End; Function NetServerIterator.HasNext:Boolean; Begin Result := (Count< NetServer(Server)._ClientCount); End; Procedure NetServerIterator.Discard(Release:Boolean=True); Begin RaiseError('Network.'+Server._Name+'.Iterator.Discard: Cannot discard.'); End; Function NetServer.GetConnectedClients: Integer; Var I:Integer; Begin Result := 0; For I:=1 To _ClientCount Do If Assigned(GetClient(I)) Then Inc(Result); End; Function NetServer.OnSendFail(Dest: SocketAddress; Sock: Socket; Msg: PNetMessage):Boolean; Begin Result := False; If (Not _PacketKeep) Or (Not _PacketImportant[Msg.Opcode]) Then Exit; _PacketMutex.Lock(); Inc(_PacketCount); SetLength(_Packets, _PacketCount); Move(Msg^, _Packets[Pred(_PacketCount)].Msg, SizeOf(LNetMessage)); _Packets[Pred(_PacketCount)].Dest := Dest; _Packets[Pred(_PacketCount)].Sock := Sock; _Packets[Pred(_PacketCount)].Time := GetTime(); _PacketMutex.Unlock(); End; Procedure NetServer.SendDroppedPackets; Var I, J:Integer; Begin If (GetTime()-_LastPacketUpdate<1000) Then Exit; _LastPacketUpdate := GetTime(); _PacketMutex.Lock(); I := 0; _PacketKeep := False; While (I<_PacketCount) Do Begin {$IFDEF NETDEBUG}WriteLn('Sending delayed packet: opcode ',_Packets[I].Msg.Opcode);{$ENDIF} If (_Packets[I].Sock=Nil) Or (GetTime() - _Packets[I].Time>1000*60) Or (Self.SendPacket(_Packets[I].Dest, _Packets[I].Sock, @_Packets[I].Msg)) Then Begin For J:=0 To _PacketCount-2 Do _Packets[I] := _Packets[I+1]; Dec(_PacketCount); End Else Inc(I); End; _PacketKeep := True; _PacketMutex.Unlock(); End; Procedure NetServer.OnPacketReceived(Sock:Socket; Msg: PNetMessage); Var I, N:Integer; Begin {$IFDEF SAVEPACKETS} If (Not (Self Is NetworkReplayServer)) Then Begin _Mutex.Lock(); N := -1; For I:=1 To _ClientCount Do //Search for a dead Client slot If (_ClientList[I]<>Nil) And (_ClientList[I].Socket = Sock) Then Begin N := I; //If this Client is dead, then we can reuse the slot Break; End; _Mutex.Unlock(); If (N>=0) Then NetworkLogger.Instance.LogPacket(N, Msg); End; {$ENDIF}; End; End.
unit ArticleLocDTOU; interface type TArticleLocDTO=class private Flastprixachat: double; Flastqteachat: double; Fqtestock: double; Fprixvente: double; Fidarticleloc: string; Fuart: string; Fdesarticleloc: string; procedure Setdesarticleloc(const Value: string); procedure Setidarticleloc(const Value: string); procedure Setlastprixachat(const Value: double); procedure Setlastqteachat(const Value: double); procedure Setprixvente(const Value: double); procedure Setqtestock(const Value: double); procedure Setuart(const Value: string); public constructor create();overload; constructor create(id:string);overload; property lastprixachat: double read Flastprixachat write Setlastprixachat; property lastqteachat: double read Flastqteachat write Setlastqteachat; property qtestock: double read Fqtestock write Setqtestock; property prixvente: double read Fprixvente write Setprixvente; property idarticleloc: string read Fidarticleloc write Setidarticleloc; property uart: string read Fuart write Setuart; property desarticleloc: string read Fdesarticleloc write Setdesarticleloc; end; implementation { TArticleLocDTO } constructor TArticleLocDTO.create(); begin end; constructor TArticleLocDTO.create(id: string); begin Self.idarticleloc:=id; end; procedure TArticleLocDTO.Setdesarticleloc(const Value: string); begin Fdesarticleloc := Value; end; procedure TArticleLocDTO.Setidarticleloc(const Value: string); begin Fidarticleloc := Value; end; procedure TArticleLocDTO.Setlastprixachat(const Value: double); begin Flastprixachat := Value; end; procedure TArticleLocDTO.Setlastqteachat(const Value: double); begin Flastqteachat := Value; end; procedure TArticleLocDTO.Setprixvente(const Value: double); begin Fprixvente := Value; end; procedure TArticleLocDTO.Setqtestock(const Value: double); begin Fqtestock := Value; end; procedure TArticleLocDTO.Setuart(const Value: string); begin Fuart := Value; end; end.
unit uSortInfo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Actions, FMX.ActnList, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Edit, FMX.Controls.Presentation, xSortInfo; type TfSortInfo = class(TForm) lbl1: TLabel; edtSortName: TEdit; lbl2: TLabel; mmoSortRemark: TMemo; pnl3: TPanel; btnOK: TButton; btnCancel: TButton; private { Private declarations } FSortInfo : TSortInfo; public { Public declarations } /// <summary> /// 显示信息 /// </summary> procedure ShowInfo(ASortInfo : TSortInfo); /// <summary> /// 保存信息 /// </summary> procedure SaveInfo; end; var fSortInfo: TfSortInfo; implementation {$R *.fmx} { TfSortInfo } procedure TfSortInfo.SaveInfo; begin if Assigned(FSortInfo) then begin FSortInfo.SortName := edtSortName.Text; FSortInfo.SortRemark := mmoSortRemark.Text; end; end; procedure TfSortInfo.ShowInfo(ASortInfo: TSortInfo); begin if Assigned(ASortInfo) then begin FSortInfo := ASortInfo; edtSortName.Text := FSortInfo.SortName; mmoSortRemark.Text := FSortInfo.SortRemark; end; end; end.
{********************************************} { TeeChart Pro Charting Library } { Calendar Series Editor } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {********************************************} unit TeeCalendarEditor; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, {$ENDIF} TeCanvas, TeeProcs, TeePenDlg, TeeCustomShapeEditor, TeeCalendar; type TCalendarSeriesEditor = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; ButtonPen1: TButtonPen; CBWeekDays: TCheckBox; CBWeekUpper: TCheckBox; CBTrailing: TCheckBox; CBToday: TCheckBox; TabSheet2: TTabSheet; PageControl2: TPageControl; TabSheet3: TTabSheet; PageControl3: TPageControl; TabSheet4: TTabSheet; PageControl4: TPageControl; TabSheet5: TTabSheet; PageControl5: TPageControl; TabSheet6: TTabSheet; PageControl6: TPageControl; CBMonths: TCheckBox; TabSheet7: TTabSheet; PageControl7: TPageControl; CBMonthUpper: TCheckBox; CBPrevious: TCheckBox; CBNext: TCheckBox; procedure FormShow(Sender: TObject); procedure CBWeekDaysClick(Sender: TObject); procedure CBWeekUpperClick(Sender: TObject); procedure CBTrailingClick(Sender: TObject); procedure CBTodayClick(Sender: TObject); procedure CBMonthsClick(Sender: TObject); procedure CBMonthUpperClick(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure CheckBox2Click(Sender: TObject); private { Private declarations } IDays, ISunday, IToday, ITrailing, IMonths, IWeekDays : TFormTeeShape; Calendar : TCalendarSeries; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses TeeConst; procedure TCalendarSeriesEditor.FormShow(Sender: TObject); Procedure Check(AForm:TFormTeeShape); begin AForm.RefreshControls(AForm.TheShape); end; begin Calendar:=TCalendarSeries(Tag); if Assigned(Calendar) then begin With Calendar do begin ButtonPen1.LinkPen(Pen); IDays:=InsertTeeObjectForm(PageControl2,Days); IWeekDays:=InsertTeeObjectForm(PageControl3,WeekDays); ISunday:=InsertTeeObjectForm(PageControl5,Sunday); ITrailing:=InsertTeeObjectForm(PageControl6,Trailing); IToday:=InsertTeeObjectForm(PageControl4,Today); IMonths:=InsertTeeObjectForm(PageControl7,Months); CBWeekDays.Checked:=WeekDays.Visible; CBTrailing.Checked:=Trailing.Visible; CBMonths.Checked:=Months.Visible; CBToday.Checked:=Today.Visible; CBWeekUpper.Checked:=WeekDays.UpperCase; CBMonthUpper.Checked:=Months.UpperCase; CBPrevious.Checked:=PreviousMonthButton.Visible; CBNext.Checked:=NextMonthButton.Visible; end; Check(IDays); Check(IWeekDays); Check(IToday); Check(ISunday); Check(ITrailing); Check(IMonths); Align:=alClient; { align Form to parent container } end; if not TeeLanguageCanUpper then begin CBWeekUpper.Visible:=False; CBMonthUpper.Visible:=False; end; end; procedure TCalendarSeriesEditor.CBWeekDaysClick(Sender: TObject); begin Calendar.WeekDays.Visible:=CBWeekDays.Checked; end; procedure TCalendarSeriesEditor.CBWeekUpperClick(Sender: TObject); begin Calendar.WeekDays.UpperCase:=CBWeekUpper.Checked; end; procedure TCalendarSeriesEditor.CBTrailingClick(Sender: TObject); begin Calendar.Trailing.Visible:=CBTrailing.Checked; end; procedure TCalendarSeriesEditor.CBTodayClick(Sender: TObject); begin Calendar.Today.Visible:=CBToday.Checked; end; procedure TCalendarSeriesEditor.CBMonthsClick(Sender: TObject); begin Calendar.Months.Visible:=CBMonths.Checked; end; procedure TCalendarSeriesEditor.CBMonthUpperClick(Sender: TObject); begin Calendar.Months.UpperCase:=CBMonthUpper.Checked; end; procedure TCalendarSeriesEditor.CheckBox1Click(Sender: TObject); begin Calendar.PreviousMonthButton.Visible:=(Sender as TCheckBox).Checked; end; procedure TCalendarSeriesEditor.CheckBox2Click(Sender: TObject); begin Calendar.NextMonthButton.Visible:=(Sender as TCheckBox).Checked; end; initialization RegisterClass(TCalendarSeriesEditor); end.
unit ncaFrmEditContato; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxLabel, PngImage, ExtCtrls, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, Menus, StdCtrls, cxButtons, ImgList, ncMyImage, ncaFrmCliPesq2, ncDebCredValidator; type TFrmEditContato = class(TForm) panPri: TLMDSimplePanel; lbNome: TcxLabel; imgs: TcxImageList; Img: TMyImage; cxImageList1: TcxImageList; lbRemove: TcxLabel; panDeb: TLMDSimplePanel; lbDebito: TcxLabel; lbValorDebito: TcxLabel; panFid: TLMDSimplePanel; lbPontos: TcxLabel; lbQuantPontos: TcxLabel; panCred: TLMDSimplePanel; lbCredito: TcxLabel; lbValorCredito: TcxLabel; procedure FormCreate(Sender: TObject); procedure lbNomeClick(Sender: TObject); procedure ImgClick(Sender: TObject); procedure imgRemoverCliClick(Sender: TObject); procedure lbRemoveClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FID: Integer; FNome: String; FFornecedor: Boolean; FFidPontos: Double; FCredito: Currency; FDebito: Currency; FLimiteDeb: Variant; FMostrarCred: Boolean; FDCValidator : TncDebCredValidator; FOnChange: TNotifyEvent; procedure SetID(const Value: Integer); procedure SetNome(const Value: String); procedure SetFornecedor(const Value: Boolean); procedure SetFidPontos(const Value: Double); procedure UpdateInfos; procedure SetDCValidator(const Value: TncDebCredValidator); protected procedure Atualiza; virtual; procedure AtualizaValidator; public procedure Pesquisa; property DCValidator: TncDebCredValidator read FDCValidator write SetDCValidator; property Debito: Currency read FDebito; property LimiteDeb: Variant read FLimiteDeb; property Credito: Currency read FCredito; { Private declarations } property ID: Integer read FID write SetID; property MostrarCred: Boolean read FMostrarCred write FMostrarCred; property Nome: String read FNome write SetNome; property Fornecedor: Boolean read FFornecedor write SetFornecedor; property FidPontos: Double read FFidPontos write SetFidPontos; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; var FrmEditContato: TFrmEditContato; resourcestring rsF5Cliente = 'Selecione um cliente (F5)'; rsF5Fornecedor = 'Selecione um fornecedor (F5)'; implementation uses ncaDM, ncaFrmCadCli, ncaFrmCadFornecedor, ncaFrmPesqFor, ncClassesBase; {$R *.dfm} { TFrmEditContato } procedure TFrmEditContato.AtualizaValidator; begin if FDCValidator<>nil then FDCValidator.SetNewCli(FID, FDebito, FCredito, FLimiteDeb); end; procedure TFrmEditContato.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmEditContato.FormCreate(Sender: TObject); begin FID := 0; FFidPontos := 0; FCredito := 0; FDebito := 0; FNome := ''; FOnChange := nil; FFornecedor := False; FMostrarCred := True; FDCValidator := nil; end; procedure TFrmEditContato.ImgClick(Sender: TObject); begin with Dados do if ID=0 then Pesquisa else if tbCli.Locate('ID', FID, []) then begin if not FFornecedor then begin TFrmCadCli.Create(Self).Editar(tbCli, nil); Nome := tbCliNome.Value; FidPontos := tbCliFidPontos.Value; FCredito := tbCliValorCred.Value; FDEbito := tbCliDebito.Value; end else begin TFrmCadFornecedor.Create(Self).Editar(tbCli, nil); Nome := tbCliNome.Value; FCredito := 0; FDebito := 0; FidPontos := 0; end; end; end; procedure TFrmEditContato.imgRemoverCliClick(Sender: TObject); begin ID := 0; end; procedure TFrmEditContato.lbNomeClick(Sender: TObject); begin Pesquisa; lbNome.Invalidate; lbNome.Update; end; procedure TFrmEditContato.lbRemoveClick(Sender: TObject); begin ID := 0; end; procedure TFrmEditContato.Pesquisa; var cliPesq: TFrmCliPesq2; forPesq: TFrmPesqFor; begin if not FFornecedor then begin cliPesq := gCliPesq2List.GetFrm; try if cliPesq.Pesquisar(FID, FNome, FFidPontos, FCredito, FDebito) then ID := FID; finally gCliPesq2List.ReleaseFrm(cliPesq); end; end else begin forPesq := gPesqForList.GetFrm; try if forPesq.Pesquisar(FID, FNome, FFidPontos) then Atualiza; finally gPesqForList.ReleaseFrm(forPesq); end; end; end; procedure TFrmEditContato.SetDCValidator(const Value: TncDebCredValidator); begin FDCValidator := Value; end; procedure TFrmEditContato.SetFidPontos(const Value: Double); begin FFidPontos := Value; end; procedure TFrmEditContato.SetFornecedor(const Value: Boolean); begin Img.ImageIndex := Integer(Value); FFornecedor := Value; Atualiza; end; procedure TFrmEditContato.SetID(const Value: Integer); begin FID := Value; with Dados do if Value=0 then begin FFidPontos := 0; FNome := ''; FCredito := 0; FDebito := 0; FLimiteDeb := null; panDeb.Visible := False; end else if tbCli.Locate('ID', Value, []) then begin FNome := tbCliNome.Value; FFidPontos := tbCliFidPontos.Value; FCredito := tbCliValorCred.Value; FDebito := tbCliDebito.Value; FLimiteDeb := tbCliLimiteDebito.AsVariant; end; Atualiza; AtualizaValidator; if Assigned(FOnChange) then FOnChange(Self); end; procedure TFrmEditContato.SetNome(const Value: String); begin FNome := Value; Atualiza; end; procedure TFrmEditContato.Atualiza; begin if FID>0 then begin lbNome.Caption := FNome; lbNome.Style.TextColor := clBlack; lbNome.Style.TextStyle := []; lbNome.StyleHot.TextStyle := [fsUnderline]; lbNome.Style.Font.Size := 16; Img.MouseOffDrawMode := idmNormal; lbRemove.Style.TextColor := clSilver; end else begin lbNome.Style.TextColor := $004E4E4E; lbNome.Style.TextStyle := []; lbNome.StyleHot.TextStyle := [fsUnderline]; lbNome.Style.Font.Size := 12; Img.MouseOffDrawMode := idmFaded; if FFornecedor then lbNome.Caption := rsF5Fornecedor else lbNome.Caption := rsF5Cliente; lbRemove.Style.TextColor := clBtnFace; end; UpdateInfos; end; function LabelWidth(L: TcxLabel): Integer; begin Result := cxTextWidth(L.Style.Font, L.Caption); if L.AlignWithMargins then Result := Result + L.Margins.Left + L.Margins.Right; end; function BiggerInt(A, B: Integer): Integer; begin if A>B then Result := A else Result := B; end; function BiggerWidth(A, B: TcxLabel): Integer; begin Result := BiggerInt(LabelWidth(A), LabelWidth(B)); end; procedure TFrmEditContato.UpdateInfos; begin lbValorDebito.Caption := CurrencyToStr(FDebito); panDeb.Visible := FDebito>0.001; panDeb.Width := lbDebito.Width + lbValorDebito.Width + 10; lbValorCredito.Caption := CurrencyToStr(FCredito); panCred.Visible := (FCredito>0.001) and FMostrarCred; // panCred.Width := BiggerWidth(lbCredito, lbValorCredito); lbQuantPontos.Caption := PontosFidToStr(FFidPontos); panFid.Visible := FFidPontos>=0.1; // panFid.Width := BiggerWidth(lbQuantPontos, lbPontos); end; end.
unit fTIUView; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ORFN, StdCtrls, ExtCtrls, ORCtrls, ComCtrls, ORDtTm, Spin, uTIU, fBase508Form, VA508AccessibilityManager; type TfrmTIUView = class(TfrmBase508Form) pnlBase: TORAutoPanel; lblBeginDate: TLabel; calBeginDate: TORDateBox; lblEndDate: TLabel; calEndDate: TORDateBox; lblStatus: TLabel; lstStatus: TORListBox; lblAuthor: TLabel; cmdOK: TButton; cmdCancel: TButton; cboAuthor: TORComboBox; lblMaxDocs: TLabel; edMaxDocs: TCaptionEdit; lblContains: TLabel; txtKeyword: TCaptionEdit; Bevel1: TBevel; grpListView: TGroupBox; radListSort: TRadioGroup; lblSortBy: TLabel; cboSortBy: TORComboBox; grpTreeView: TGroupBox; lblGroupBy: TOROffsetLabel; cboGroupBy: TORComboBox; radTreeSort: TRadioGroup; Bevel2: TBevel; cmdClear: TButton; ckShowSubject: TCheckBox; grpWhereEitherOf: TGroupBox; ckTitle: TCheckBox; ckSubject: TCheckBox; procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); procedure lstStatusSelect(Sender: TObject); procedure cboAuthorNeedData(Sender: TObject; const StartFrom: String; Direction, InsertAt: Integer); procedure cmdClearClick(Sender: TObject); private FChanged: Boolean; FBeginDate: string; FFMBeginDate: TFMDateTime; FEndDate: string; FFMEndDate: TFMDateTime; FStatus: string; FAuthor: Int64; FMaxDocs: integer; FShowSubject: Boolean; FSortBy: string; FListAscending: Boolean; FGroupBy: string; FTreeAscending: Boolean; FSearchField: string; FKeyWord: string; FFiltered: Boolean; FCurrentContext: TTIUContext; end; function SelectTIUView(FontSize: Integer; ShowForm: Boolean; CurrentContext: TTIUContext; var TIUContext: TTIUContext): boolean ; implementation {$R *.DFM} uses rCore, uCore, rTIU(*, fNotes, fDCSumm, rDCSumm*); const TX_DATE_ERR = 'Enter valid beginning and ending dates or press Cancel.'; TX_DATE_ERR_CAP = 'Error in Date Range'; TX_AUTH_ERR = 'You must select an author for this retrieval method.'; TX_AUTH_ERR_CAP = 'No author selected'; function SelectTIUView(FontSize: Integer; ShowForm: Boolean; CurrentContext: TTIUContext; var TIUContext: TTIUContext): boolean ; { displays select form for Notes and returns a record of the selection } var frmTIUView: TfrmTIUView; W, H: Integer; CurrentAuthor: Int64; CurrentStatus: string; begin frmTIUView := TfrmTIUView.Create(Application); try with frmTIUView do begin Font.Size := FontSize; W := ClientWidth; H := ClientHeight; ResizeToFont(FontSize, W, H); ClientWidth := W; pnlBase.Width := W; ClientHeight := H; pnlBase.Height := H; FChanged := False; FFiltered := False; FCurrentContext := CurrentContext; calBeginDate.Text := CurrentContext.BeginDate; calEndDate.Text := CurrentContext.EndDate; if calEndDate.Text = '' then calEndDate.Text := 'TODAY'; CurrentStatus := CurrentContext.Status; with lstStatus do if CurrentStatus <> '' then SelectByID(CurrentStatus) else SelectByID('1'); //lstStatusSelect(frmTIUView); moved down - v24.1 (RV) CurrentAuthor := CurrentContext.Author; with cboAuthor do if CurrentAuthor > 0 then begin InitLongList(ExternalName(CurrentAuthor, 200)); if Enabled then SelectByIEN(CurrentAuthor); FAuthor := CurrentAuthor; end else begin InitLongList(User.Name); SelectByIEN(User.DUZ); FAuthor := ItemIEN; end; if CurrentContext.MaxDocs > 0 then edMaxDocs.Text := IntToStr(CurrentContext.MaxDocs) else edMaxDocs.Text := ''; FMaxDocs := StrToIntDef(edMaxDocs.Text, 0); txtKeyword.Text := CurrentContext.Keyword; if CurrentContext.SearchField <> '' then begin ckTitle.Checked := CharInSet(CurrentContext.SearchField[1], ['T','B']) and (CurrentContext.Keyword <> ''); ckSubject.Checked := CharInSet(CurrentContext.SearchField[1], ['S','B']) and (CurrentContext.Keyword <> ''); end; ckShowSubject.Checked := CurrentContext.ShowSubject; //with radTreeSort do if SortNotesAscending then ItemIndex := 1 else ItemIndex := 0; with radTreeSort do if CurrentContext.TreeAscending then ItemIndex := 0 else ItemIndex := 1; with radListSort do if CurrentContext.ListAscending then ItemIndex := 0 else ItemIndex := 1; cboSortBy.SelectByID(CurrentContext.SortBy); cboGroupBy.SelectByID(CurrentContext.GroupBy); lstStatusSelect(frmTIUView); // from above in v24.1, (RV) if ShowForm then ShowModal else cmdOKClick(frmTIUView); with TIUContext do begin Changed := FChanged; BeginDate := FBeginDate; FMBeginDate := FFMBeginDate; EndDate := FEndDate; FMEndDate := FFMEndDate; Status := FStatus; Author := FAuthor; MaxDocs := FMaxDocs; ShowSubject := FShowSubject; SortBy := FSortBy; ListAscending := FListAscending; GroupBy := FGroupBy; TreeAscending := FTreeAscending; SearchField := FSearchField; KeyWord := FKeyWord; Filtered := FFiltered; Result := Changed ; end; end; {with frmTIUView} finally frmTIUView.Release; end; end; procedure TfrmTIUView.cmdOKClick(Sender: TObject); var bdate, edate: TFMDateTime; begin FStatus := lstStatus.ItemID; if calBeginDate.Text <> '' then bdate := StrToFMDateTime(calBeginDate.Text) else bdate := 0 ; if calEndDate.Text <> '' then edate := StrToFMDateTime(calEndDate.Text) else edate := 0 ; if (bdate <= edate) then begin FBeginDate := calBeginDate.Text; FFMBeginDate := bdate; FEndDate := calEndDate.Text; FFMEndDate := edate; end else begin InfoBox(TX_DATE_ERR, TX_DATE_ERR_CAP, MB_OK or MB_ICONWARNING); Exit; end; FAuthor := cboAuthor.ItemIEN; if (FStatus = '4') and (FAuthor = 0) then begin InfoBox(TX_AUTH_ERR, TX_AUTH_ERR_CAP, MB_OK or MB_ICONWARNING); Exit; end; FSortBy := cboSortBy.ItemID; if FSortBy = '' then FSortBy := 'R'; FListAscending := (radListSort.ItemIndex = 0); FTreeAscending := (radTreeSort.ItemIndex = 0); FKeyWord := txtKeyWord.Text; if (ckTitle.Checked) and (ckSubject.Checked) then FSearchField := 'B' else if ckTitle.Checked then FSearchField := 'T' else if ckSubject.Checked then FSearchField := 'S' else if not (ckTitle.Checked or ckSubject.Checked) then begin FKeyWord := ''; FSearchField := ''; end; if (FKeyword <> '') then FFiltered := True; if ckSubject.Checked then ckShowSubject.Checked := True; FShowSubject := ckShowSubject.Checked; FMaxDocs := StrToIntDef(edMaxDocs.Text, 0); if cboGroupBy.ItemID <> '' then FGroupBy := cboGroupBy.ItemID else FGroupBy := ''; FChanged := True; Close; end; procedure TfrmTIUView.cmdCancelClick(Sender: TObject); begin FChanged := False; Close; end; procedure TfrmTIUView.lstStatusSelect(Sender: TObject); var EnableDates: Boolean; begin EnableDates := (lstStatus.ItemID <> '1'); lblBeginDate.Enabled := EnableDates; calBeginDate.Enabled := EnableDates; lblEndDate.Enabled := EnableDates; calEndDate.Enabled := EnableDates; if not EnableDates then begin calBeginDate.Text := ''; calEndDate.Text := ''; end else begin calBeginDate.Text := FCurrentContext.BeginDate; calEndDate.Text := FCurrentContext.EndDate; if FCurrentContext.EndDate = '' then calEndDate.FMDateTime := FMToday; end; if lstStatus.ItemID = '3' then lblAuthor.Caption := 'Expected Cosigner:' else lblAuthor.Caption := 'Author:'; cboAuthor.Caption := lblAuthor.Caption; if (lstStatus.ItemID = '1') or (lstStatus.ItemID = '5') then begin cboAuthor.ItemIndex := -1; cboAuthor.Enabled := False; lblAuthor.Enabled := False; if FMaxDocs > 0 then edMaxDocs.Text := IntToStr(FMaxDocs) else edMaxDocs.Text := ''; edMaxDocs.Enabled := True; lblMaxDocs.Enabled := True; end else begin cboAuthor.Enabled := True; cboAuthor.SelectByIEN(FAuthor); lblAuthor.Enabled := True; edMaxDocs.Text := ''; edMaxDocs.Enabled := False; lblMaxDocs.Enabled := False; end; end; procedure TfrmTIUView.cboAuthorNeedData(Sender: TObject; const StartFrom: string; Direction, InsertAt: Integer); begin cboAuthor.ForDataUse(SubSetOfActiveAndInactivePersons(StartFrom, Direction)); end; procedure TfrmTIUView.cmdClearClick(Sender: TObject); begin cboSortBy.ItemIndex := -1; cboGroupBy.ItemIndex := -1; ckTitle.Checked := False; ckSubject.Checked := False; txtKeyWord.Text := ''; radTreeSort.ItemIndex := 1; radListSort.ItemIndex := 1; end; end.
unit MediaStream.Framer.AvcAny; interface uses Windows,SysUtils,Classes, BufferedStream, MediaProcessing.Definitions, MediaStream.Framer,Avc, Avc.avcodec, Avc.avformat, Avc.samplefmt; type TStreamFramerAvcAny = class (TStreamFramer) private FStream: TStream; FAvcMediaStream: AVC.IMediaStream; FAvcMediaStreamContext: Avc.TMediaStreamContext; FProcessedFrameCount: int64; FProcessedVideoFrameCount : int64; public constructor Create; override; destructor Destroy; override; procedure OpenStream(aStream: TStream); override; function GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal):boolean; overload; override; function VideoStreamType: TStreamType; override; function AudioStreamType: TStreamType; override; function StreamInfo: TBytes; override; end; implementation { TStreamFramerAvcAny } constructor TStreamFramerAvcAny.Create; begin inherited; end; destructor TStreamFramerAvcAny.Destroy; begin inherited; FStream:=nil; FAvcMediaStream:=nil; end; function TStreamFramerAvcAny.GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal): boolean; var aAvPacket: PAVPacket; aStream: PAVStream; begin aOutFormat.Clear; aOutData:=nil; aOutDataSize:=0; aOutInfo:=nil; aOutInfoSize:=0; result:=true; while result do begin AvcCheck(FAvcMediaStream.ReadFrame(aAvPacket)); result:=(aAvPacket<>nil) and (aAvPacket.stream_index>=0) and (aAvPacket.stream_index<FAvcMediaStreamContext.StreamCount); if not result then exit; aStream:=FAvcMediaStreamContext.Streams[aAvPacket.stream_index]; aOutFormat.biStreamType:=aStream.codec.codec_tag; if (AV_PKT_FLAG_KEY and aAvPacket.flags)<>0 then Include(aOutFormat.biFrameFlags,ffKeyFrame); aOutFormat.TimeKoeff:=1; aOutData:=aAvPacket.data; aOutDataSize:=aAvPacket.size; aOutInfo:=aStream.codec.extradata; aOutInfoSize:=aStream.codec.extradata_size; if aAvPacket.stream_index=FAvcMediaStreamContext.PreferredVideoStreamIndex then begin aOutFormat.biMediaType:=mtVideo; aOutFormat.VideoWidth:=aStream.codec.coded_width; aOutFormat.VideoHeight:=aStream.codec.coded_height; aOutFormat.VideoBitCount:=24; //??? if (aStream.r_frame_rate.num<>0) and (aStream.r_frame_rate.den<>0) then begin aOutFormat.TimeStamp:=Trunc(FProcessedVideoFrameCount*1000*aStream.r_frame_rate.den/aStream.r_frame_rate.num); end else begin aOutFormat.TimeStamp:=aAvPacket.pts* aStream.time_base.num div aStream.time_base.den; end; inc(FProcessedVideoFrameCount); break; end else if aAvPacket.stream_index=FAvcMediaStreamContext.PreferredAudioStreamIndex then begin aOutFormat.biMediaType:=mtAudio; aOutFormat.AudioChannels:=aStream.codec.channels; aOutFormat.AudioSamplesPerSec:=aStream.codec.sample_rate; if aStream.codec.sample_fmt in [AV_SAMPLE_FMT_U8,AV_SAMPLE_FMT_U8P] then aOutFormat.AudioBitsPerSample:=8 else if aStream.codec.sample_fmt in [AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_S16P] then aOutFormat.AudioBitsPerSample:=16 else if aStream.codec.sample_fmt in [AV_SAMPLE_FMT_S32,AV_SAMPLE_FMT_S32P,AV_SAMPLE_FMT_FLT,AV_SAMPLE_FMT_FLTP] then aOutFormat.AudioBitsPerSample:=32 else if aStream.codec.sample_fmt in [AV_SAMPLE_FMT_DBL,AV_SAMPLE_FMT_DBLP] then aOutFormat.AudioBitsPerSample:=64 else aOutFormat.AudioBitsPerSample:=8; //??? break; end; end; end; procedure TStreamFramerAvcAny.OpenStream(aStream: TStream); begin FStream:=aStream; AvcCheck(CreateMediaStream(FAvcMediaStream)); if aStream is TFileStream then begin AvcCheck(FAvcMediaStream.OpenFile(PAnsiChar(AnsiString(TFileStream(aStream).FileName)),FAvcMediaStreamContext)); end else begin Assert(false); end; FProcessedFrameCount:=0; end; function TStreamFramerAvcAny.StreamInfo: TBytes; begin result:=nil; end; function TStreamFramerAvcAny.VideoStreamType: TStreamType; begin result:=stUNIV; end; function TStreamFramerAvcAny.AudioStreamType: TStreamType; begin result:=stUNIV; end; end.
unit FUNC_SUB_MENU_MODIFICAR; interface uses FUNC_REG_Pacientes, FUNC_REG_Estadisticas, ARCH_REG_Pacientes, ARCH_REG_Estadisticas; procedure Modificar_Registro(VAR ARCH_Pacientes: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas;VAR R_Persona: REG_Persona; VAR R_Estadisticas: REG_Estadisticas); implementation uses FUNC_Registros, FUNC_ARCH_REGITROS_PACIENTES_Y_ESTADISTICAS, Funciones_Buscar, FUNC_REG_Provincias, graph, wincrt, Graph_Graficos; procedure Cargar_DNI_Modificar(VAR ARCH_Pacientes: ARCHIVO_Pacientes; VAR R_Persona: REG_Persona); var DNI_ANTERIOR: LongWord; DNI_SRT: string; Existencia_de_DNI: Boolean; begin DNI_ANTERIOR:= R_Persona.DNI; Existencia_de_DNI:= False; repeat Cargar_DNI(R_Persona.DNI); if R_Persona.DNI > 0 then begin Abrir_archivo_pacientes_para_lectura_escritura(ARCH_Pacientes); Existencia_de_DNI:= Verificar_Existencia_del_DNI(ARCH_Pacientes, R_Persona.DNI); Close(ARCH_Pacientes); if (Existencia_de_DNI = False) OR (R_Persona.DNI = DNI_ANTERIOR) then begin end else begin Str(R_Persona.DNI, DNI_SRT); Mostrar_MSJ('Error, el DNI ' + DNI_SRT + ' ya existe','Pulse una tecla para volver a igresar el DNI...'); Readkey; Bar(2*16, 10*16, 57*16,18*16); end; end; until((Existencia_de_DNI = False) OR (R_Persona.DNI = DNI_ANTERIOR)); end; procedure Elijo_campo(VAR ARCH_Pacientes: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas; VAR R_Persona: REG_Persona; VAR R_Estadisticas: REG_Estadisticas; opcion: Char; pos: LongInt); begin CASE opcion Of 'A', 'C'..'G', 'I'..'K': begin CASE opcion OF 'A': begin Cargar_Apellido_y_Nombre(R_Persona.Apellido_y_Nombre); end; 'C': begin Cargar_Calle(R_Persona.Domicilio.Calle); end; 'D': begin Cargar_numero_de_calle(R_Persona.Domicilio.Numero); end; 'E': begin Cargar_el_Piso(R_Persona.Domicilio.Piso); end; 'F': begin Cargar_Ciudad(R_Persona.Domicilio.Ciudad); end; 'G': begin Cargar_Codigo_postal(R_Persona.Domicilio.Codigo_Postal); end; 'I': begin Cargar_Numero_de_telefono(R_Persona.Domicilio.Telefono_de_contacto); end; 'J': begin Cargar_Email(R_Persona.Email); end; 'K': begin Cargar_fecha_de_nacimiento(R_Persona.Fecha_de_nacimiento.dia, R_Persona.Fecha_de_nacimiento.mes, R_Persona.Fecha_de_nacimiento.ano); end; end; end; 'B', 'H','L'..'N': begin CASE opcion OF 'B': begin Cargar_DNI_Modificar(ARCH_Pacientes, R_Persona); R_Estadisticas.DNI:= R_Persona.DNI; end; 'H': begin Cargar_Registro_Provincia_y_le_paso_el_nombre_al_registro_persona(R_Estadisticas.Codigo_Provincia); R_Persona.Domicilio.Codigo_Provincia:= R_Estadisticas.Codigo_Provincia; end; 'L': begin Cargo_estado_del_paciente(R_Estadisticas.Estado); end; 'M': begin Cargo_Forma_de_contagio(R_Estadisticas.Forma_de_contagio); end; 'N': begin Cargar_DNI_Modificar(ARCH_Pacientes, R_Persona); Cargar_Datos(R_Persona, R_Estadisticas); end; end; end; end; if R_Persona.DNI > 0 then begin Bar((3*16), (15*16), 68*16,(34*16)); Rectangle(3*16, 18*16, 63*16, 32*16); SetFillStyle(SolidFill, 92); bar(3*16+1, 18*16+1, 63*16-1, 32*16-1); SetFillStyle(SolidFill, 91); Mostrar_Datos_del_paciente(R_Persona, R_Estadisticas); end; end; procedure Elijo_campo_a_modificar(Var Opcion: Char); begin Rectangle(3*16, (16*16), (57*16),16*34); SetFillStyle(SolidFill, 92); bar((3*16)+1, (16*16)+1, 57*16-1,16*34-1); SetFillStyle(SolidFill, 91); OutTextXY(4*16, 17*16,'[A]-Apellido y nombre'); OutTextXY(4*16, 18*16,'[B]-DNI'); OutTextXY(4*16, 19*16,'[C]-Nombre de la Calle'); OutTextXY(4*16, 20*16,'[D]-Numero de Calle'); OutTextXY(4*16, 21*16,'[E]-Piso'); OutTextXY(4*16, 22*16,'[F]-Ciudad'); OutTextXY(4*16, 23*16,'[G]-Codigo Postal'); OutTextXY(4*16, 24*16,'[H]-Provincia'); OutTextXY(4*16, 25*16,'[I]-Numero de telefono'); OutTextXY(4*16, 26*16,'[J]-Email'); OutTextXY(4*16, 27*16,'[K]-Fecha de Nacimiento'); OutTextXY(4*16, 28*16,'[L]-Estado del Paciente'); OutTextXY(4*16, 29*16,'[M]-Forma de Contagio'); OutTextXY(4*16, 31*16,'[N]-Re-Cargar Paciente'); OutTextXY(4*16, 32*16,'[ESC]-Volver al Menu General'); repeat Opcion:= readkey; until((Opcion in ['A'..'N', 'a'..'n']) OR (Opcion = #27)); Bar((57*16), (16*16), 3*16,16*34); if Opcion in ['a'..'n'] then Opcion:= upcase(Opcion); end; procedure Modificar_Registro(VAR ARCH_Pacientes: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas;VAR R_Persona: REG_Persona; VAR R_Estadisticas: REG_Estadisticas); var pos: LongInt; Opcion, op: Char; DNI_SRT: String; begin Abrir_ARCHIVO_pacientes_y_Estadisticas(ARCH_Pacientes, ARCH_Estadisticas); if IoResult <> 0 then begin Mostrar_MSJ('Error, archivo no encontrado', 'Presione una tecla para volver al menu principal'); Readkey; Bar(3*15, 16*10, 57*16,16*16); end else begin Inicializar_Registro_Persona(R_Persona); Inicializar_Registro_Estadisticas(R_Estadisticas); Cargar_DNI(R_Persona.DNI); if R_Persona.DNI > 0 then begin BBIN_DNI(ARCH_Pacientes, R_Persona.DNI, pos); Str(R_Persona.DNI, DNI_SRT); if pos > -1 then begin Bar((57*16), (152+16*23), 3*16,256); cargar_un_elemento_del_archivo_estadisticas_una_posicion_especifica(ARCH_Estadisticas, R_Estadisticas, pos); if R_Estadisticas.Dado_de_baja = False then begin cargar_un_elemento_del_archivo_pacientes_una_posicion_especifica(ARCH_Pacientes, R_Persona, pos); Cerrar_ARCHIVO_pacientes_y_Estadisticas(ARCH_Pacientes, ARCH_Estadisticas); Elijo_campo_a_modificar(Opcion); if Opcion in ['A'..'N'] then begin Elijo_campo(ARCH_Pacientes, ARCH_Estadisticas, R_Persona, R_Estadisticas, opcion, pos); if R_Persona.DNI > 0 then begin Mostrar_MSJ('Esta seguro que desea realizar la modificacion?', '[Y] / [N]'); repeat op:= Upcase(readkey); until(op in ['Y','N']); Bar(3*15, 16*10, 57*16,16*16); if (op = 'Y') then begin if (opcion in ['A', 'C'..'G', 'I'..'K']) then begin Abrir_archivo_pacientes_para_lectura_escritura(ARCH_Pacientes); Sobre_escribir_un_elemento_en_archivo_paciente(ARCH_Pacientes, R_Persona, pos); Close(ARCH_Pacientes); end else begin if (opcion in ['B', 'H','L'..'N']) then begin Abrir_ARCHIVO_pacientes_y_Estadisticas(ARCH_Pacientes, ARCH_Estadisticas); Sobre_escribir_un_elemento_en_archivo_pacientes_y_estadisticas(ARCH_Pacientes, ARCH_Estadisticas, R_Persona, R_Estadisticas, pos); Cerrar_ARCHIVO_pacientes_y_Estadisticas(ARCH_Pacientes, ARCH_Estadisticas); end; end; Mostrar_MSJ('El registro se sobre escribio con exito.', 'Presione una tecla para continuar...'); Readkey; Bar(3*15, 16*10, 57*16,16*16); end; end; end; end else begin Cerrar_ARCHIVO_pacientes_y_Estadisticas(ARCH_Pacientes, ARCH_Estadisticas); Mostrar_MSJ('El usuario con DNI '+ DNI_SRT + ' esta dado de baja', 'Presione una tecla para continuar'); Readkey; Bar(3*15, 16*10, 57*16,16*16); end; end else begin Cerrar_ARCHIVO_pacientes_y_Estadisticas(ARCH_Pacientes, ARCH_Estadisticas); Mostrar_MSJ('No se encontro ningun paciente con el DNI ' + DNI_SRT, 'Presione una tecla para continuar'); Readkey; Bar(3*15, 16*10, 57*16,16*16); end; end else Cerrar_ARCHIVO_pacientes_y_Estadisticas(ARCH_Pacientes, ARCH_Estadisticas) end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // { : GLSCUDAContext <p> <b>History : </b><font size=-1><ul> <li>19/03/10 - Yar - Creation </ul></font><p> } unit GLSCUDAContext; interface {$I GLScene.inc} uses System.Classes, System.SysUtils, //GLS GLBaseClasses, GLSCUDAApi, GLSCUDARunTime, GLSCLPlatform, GLContext, GLSGenerics, GLSLog; type // TCUDADimensions // TCUDADimensions = class(TGLUpdateAbleObject) private { Private declarations } FXYZ: TDim3; FMaxXYZ: TDim3; FReadOnly: Boolean; function GetDimComponent(index: Integer): Integer; procedure SetDimComponent(index: Integer; Value: Integer); function GetMaxDimComponent(index: Integer): Integer; procedure SetMaxDimComponent(index: Integer; Value: Integer); public { Public declarations } constructor Create(AOwner: TPersistent); override; procedure Assign(Source: TPersistent); override; property MaxSizeX: Integer index 0 read GetMaxDimComponent write SetMaxDimComponent; property MaxSizeY: Integer index 1 read GetMaxDimComponent write SetMaxDimComponent; property MaxSizeZ: Integer index 2 read GetMaxDimComponent write SetMaxDimComponent; property ReadOnlyValue: Boolean read FReadOnly write FReadOnly; published { Published Properties } property SizeX: Integer index 0 read GetDimComponent write SetDimComponent default 1; property SizeY: Integer index 1 read GetDimComponent write SetDimComponent default 1; property SizeZ: Integer index 2 read GetDimComponent write SetDimComponent default 1; end; TCUDAContext = class; TOnOpenGLInteropInit = procedure(out Context: TGLContext) of object; TCUDADevice = class(TPersistent) private { Private declarations } fID: Integer; fHandle: TCUdevice; fGFlops: Integer; fDeviceProperties: TCudaDeviceProp; FSuitable: Boolean; FUsed: Boolean; fMaxThreadsDim: TCUDADimensions; fMaxGridSize: TCUDADimensions; protected { Protected declarations } function GetName: string; public { Public declarations } constructor Create; reintroduce; destructor Destroy; override; procedure Assign(Source: TPersistent); override; { : Returns in bytes the total amount of memory available on the device dev in bytes. } function TotalMemory: Cardinal; published { Published declarations } property Name: string read GetName; property TotalGlobalMem: TSize_t read fDeviceProperties.TotalGlobalMem; property SharedMemPerBlock: TSize_t read fDeviceProperties.SharedMemPerBlock; property RegsPerBlock: Integer read fDeviceProperties.RegsPerBlock; property WarpSize: Integer read fDeviceProperties.WarpSize; property MemPitch: TSize_t read fDeviceProperties.MemPitch; property MaxThreadsPerBlock: Integer read fDeviceProperties.MaxThreadsPerBlock; property MaxThreadsDim: TCUDADimensions read fMaxThreadsDim; property MaxGridSize: TCUDADimensions read fMaxGridSize; property ClockRate: Integer read fDeviceProperties.ClockRate; property TotalConstMem: TSize_t read fDeviceProperties.TotalConstMem; property Major: Integer read fDeviceProperties.Major; property Minor: Integer read fDeviceProperties.Minor; property TextureAlignment: TSize_t read fDeviceProperties.TextureAlignment; property DeviceOverlap: Integer read fDeviceProperties.DeviceOverlap; property MultiProcessorCount: Integer read fDeviceProperties.MultiProcessorCount; end; TGLSCUDADevice = class(TComponent) private { Private declarations } FSelectDeviceName: string; function GetDevice: TCUDADevice; procedure SetDevice(AValue: TCUDADevice); procedure SetDeviceName(const AName: string); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Suitable: Boolean; published { Published declarations } property SelectDevice: string read FSelectDeviceName write SetDeviceName; property Device: TCUDADevice read GetDevice write SetDevice; end; TCUDAHandlesMaster = class(TComponent) protected function GetContext: TCUDAContext; virtual; abstract; procedure AllocateHandles; virtual; procedure DestroyHandles; virtual; end; TCUDAHandleList = GThreadList<TCUDAHandlesMaster>; TCUDAContext = class(TObject) private { Private declarations } fHandle: PCUcontext; FDevice: TCUDADevice; FOnOpenGLInteropInit: TOnOpenGLInteropInit; FHandleList: TCUDAHandleList; procedure SetDevice(ADevice: TCUDADevice); protected { Protected declarations } public { Public declarations } constructor Create; destructor Destroy; override; { : Destroy all handles based of this context. } procedure DestroyAllHandles; { : Pushes context onto CPU threadís stack of current contexts. } procedure Requires; { : Pops context from current CPU thread. } procedure Release; function IsValid: Boolean; inline; property Device: TCUDADevice read FDevice write SetDevice; property OnOpenGLInteropInit: TOnOpenGLInteropInit read FOnOpenGLInteropInit write FOnOpenGLInteropInit; end; TCUDADeviceList = GList<TCUDADevice>; TCUDAContextList = GList<TCUDAContext>; // CUDAContextManager // { : Static class of CUDA contexts manager. } CUDAContextManager = class private { Private declarations } class var fDeviceList: TCUDADeviceList; class var fContextList: TCUDAContextList; class var FContextStacks: array of TCUDAContextList; protected { Protected declarations } class function GetDevice(i: Integer): TCUDADevice; class function GetNextUnusedDevice: TCUDADevice; class procedure RegisterContext(aContext: TCUDAContext); class procedure UnRegisterContext(aContext: TCUDAContext); class function GetThreadStack: TCUDAContextList; class function GetContext(i: Integer): TCUDAContext; public { Public declarations } { : Managment. } class procedure Init; class procedure Done; class procedure CreateContext(aContext: TCUDAContext); class procedure DestroyContext(aContext: TCUDAContext); class procedure CreateContextOf(ADevice: TCUDADevice); class procedure DestroyContextOf(ADevice: TCUDADevice); class procedure PushContext(aContext: TCUDAContext); class function PopContext: TCUDAContext; { : Fill unused device list to show its in property. } class procedure FillUnusedDeviceList(var AList: TStringList); { : Return device by name. } class function GetDeviceByName(const AName: string): TCUDADevice; { : Returns the number of CUDA compatiable devices. } class function DeviceCount: Integer; { : Access to devices list. } property Devices[i: Integer]: TCUDADevice read GetDevice; { : Returns a device that has a maximum Giga flops. } class function GetMaxGflopsDevice: TCUDADevice; { : Returns the number of TCUDAcontext object. } class function ContextCount: Integer; { : Return CUDA context of current thread. } class function GetCurrentThreadContext: TCUDAContext; { : Access to contexts list. } property Contexts[i: Integer]: TCUDAContext read GetContext; end; implementation resourcestring cudasInvalidContextReg = 'Invalid context registration.'; cudasContextNotInit = 'Context not initialized'; cudasNoDeviceToCreate = 'No device to create CUDA context'; cudasThreadBusy = 'Unable to create CUDA context - thread is busy by another context'; cudasMakeFloatingFail = 'Unable to make context floating after creation'; cudasUnbalansedUsage = 'Unbalansed CUDA context usage'; cudasInvalidGLContext = 'Unable to create CUDA context with OpenGL interop' + ' - OpenGL context not ready'; threadvar vStackIndex: Cardinal; // ------------------ // ------------------ TCUDADimensions ------------------ // ------------------ {$IFDEF GLS_REGION}{$REGION 'TCUDADimensions'}{$ENDIF} constructor TCUDADimensions.Create(AOwner: TPersistent); const cXYZone: TDim3 = (1, 1, 1); cXYZmax: TDim3 = (MaxInt, MaxInt, MaxInt); begin inherited Create(AOwner); FReadOnly := False; FXYZ := cXYZone; FMaxXYZ := cXYZmax; end; procedure TCUDADimensions.Assign(Source: TPersistent); begin if Source is TCUDADimensions then begin FMaxXYZ[0] := TCUDADimensions(Source).FMaxXYZ[0]; FMaxXYZ[1] := TCUDADimensions(Source).FMaxXYZ[1]; FMaxXYZ[2] := TCUDADimensions(Source).FMaxXYZ[2]; FXYZ[0] := TCUDADimensions(Source).FXYZ[0]; FXYZ[1] := TCUDADimensions(Source).FXYZ[1]; FXYZ[2] := TCUDADimensions(Source).FXYZ[2]; NotifyChange(Self); end; inherited Assign(Source); end; function TCUDADimensions.GetDimComponent(index: Integer): Integer; begin Result := FXYZ[index]; end; procedure TCUDADimensions.SetDimComponent(index: Integer; Value: Integer); var v: LongWord; begin if not FReadOnly then begin if Value < 1 then v := 1 else v := LongWord(Value); if v > FMaxXYZ[index] then v := FMaxXYZ[index]; FXYZ[index] := v; NotifyChange(Self); end; end; function TCUDADimensions.GetMaxDimComponent(index: Integer): Integer; begin Result := FMaxXYZ[index]; end; procedure TCUDADimensions.SetMaxDimComponent(index: Integer; Value: Integer); begin if not FReadOnly then begin if Value > 0 then begin FMaxXYZ[index] := LongWord(Value); if FXYZ[index] > FMaxXYZ[index] then FXYZ[index] := FMaxXYZ[index]; NotifyChange(Self); end; end; end; {$IFDEF GLS_REGION}{$ENDREGION}{$ENDIF} // ------------------ // ------------------ TCUDADevice ------------------ // ------------------ {$IFDEF GLS_REGION}{$REGION 'TCUDAdevice'}{$ENDIF} // Create // constructor TCUDADevice.Create; begin fMaxThreadsDim := TCUDADimensions.Create(Self); fMaxThreadsDim.ReadOnlyValue := True; fMaxGridSize := TCUDADimensions.Create(Self); fMaxGridSize.ReadOnlyValue := True; if IsCUDAInitialized then begin fID := CUDAContextManager.fDeviceList.Count; FUsed := False; FSuitable := cuDeviceGet(fHandle, fID) = CUDA_SUCCESS; if FSuitable then begin cuDeviceGetName(@fDeviceProperties.name[0], SizeOf(fDeviceProperties.name), fHandle); cuDeviceTotalMem(@fDeviceProperties.TotalGlobalMem, fHandle); cuDeviceGetAttribute(@fDeviceProperties.SharedMemPerBlock, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, fHandle); cuDeviceGetAttribute(@fDeviceProperties.RegsPerBlock, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, fHandle); cuDeviceGetAttribute(@fDeviceProperties.WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, fHandle); cuDeviceGetAttribute(@fDeviceProperties.MemPitch, CU_DEVICE_ATTRIBUTE_MAX_PITCH, fHandle); cuDeviceGetAttribute(@fDeviceProperties.MaxThreadsPerBlock, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, fHandle); cuDeviceGetAttribute(@fDeviceProperties.MaxThreadsDim[0], CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, fHandle); cuDeviceGetAttribute(@fDeviceProperties.MaxThreadsDim[1], CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, fHandle); cuDeviceGetAttribute(@fDeviceProperties.MaxThreadsDim[2], CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, fHandle); cuDeviceGetAttribute(@fDeviceProperties.MaxGridSize[0], CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, fHandle); cuDeviceGetAttribute(@fDeviceProperties.MaxGridSize[1], CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, fHandle); cuDeviceGetAttribute(@fDeviceProperties.MaxGridSize[2], CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, fHandle); cuDeviceGetAttribute(@fDeviceProperties.ClockRate, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, fHandle); cuDeviceGetAttribute(@fDeviceProperties.TotalConstMem, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, fHandle); cuDeviceComputeCapability(fDeviceProperties.Major, fDeviceProperties.Minor, fHandle); cuDeviceGetAttribute(@fDeviceProperties.TextureAlignment, CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, fHandle); cuDeviceGetAttribute(@fDeviceProperties.DeviceOverlap, CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, fHandle); cuDeviceGetAttribute(@fDeviceProperties.DeviceOverlap, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, fHandle); fGFlops := fDeviceProperties.MultiProcessorCount * fDeviceProperties.ClockRate; fMaxThreadsDim.FXYZ[0] := fDeviceProperties.MaxThreadsDim[0]; fMaxThreadsDim.FXYZ[1] := fDeviceProperties.MaxThreadsDim[1]; fMaxThreadsDim.FXYZ[2] := fDeviceProperties.MaxThreadsDim[2]; fMaxGridSize.FXYZ[0] := fDeviceProperties.MaxGridSize[0]; fMaxGridSize.FXYZ[1] := fDeviceProperties.MaxGridSize[1]; fMaxGridSize.FXYZ[2] := fDeviceProperties.MaxGridSize[2]; end; end; end; // Destroy // destructor TCUDADevice.Destroy; begin fMaxThreadsDim.Destroy; fMaxGridSize.Destroy; inherited; end; // Assign // procedure TCUDADevice.Assign(Source: TPersistent); var dev: TCUDADevice; begin if Source is TCUDADevice then begin dev := TCUDADevice(Source); fID := dev.fID; fHandle := dev.fHandle; fGFlops := dev.fGFlops; fDeviceProperties := dev.fDeviceProperties; FSuitable := dev.FSuitable; fMaxThreadsDim.Assign(dev.fMaxThreadsDim); fMaxGridSize.Assign(dev.fMaxGridSize); end; inherited Assign(Source); end; // GetName // function TCUDADevice.GetName: string; begin Result := Format('%s (%d)', [string(fDeviceProperties.name), fID + 1]); end; // TotalMemory // function TCUDADevice.TotalMemory: Cardinal; begin cuDeviceTotalMem(@fDeviceProperties.TotalGlobalMem, fHandle); Result := fDeviceProperties.TotalGlobalMem; end; {$IFDEF GLS_REGION}{$ENDREGION}{$ENDIF} // ------------------ // ------------------ TGLSCUDADevice ------------------ // ------------------ {$IFDEF GLS_REGION}{$REGION 'TGLSCUDADevice'}{$ENDIF} // Create // constructor TGLSCUDADevice.Create(AOwner: TComponent); var LDevice: TCUDADevice; begin inherited Create(AOwner); LDevice := CUDAContextManager.GetNextUnusedDevice; if Assigned(LDevice) and LDevice.FSuitable then begin FSelectDeviceName := LDevice.name; LDevice.FUsed := True; end else begin FSelectDeviceName := ''; end; end; destructor TGLSCUDADevice.Destroy; var Device: TCUDADevice; begin inherited; Device := CUDAContextManager.GetDeviceByName(FSelectDeviceName); if Assigned(Device) then Device.FUsed := False; end; function TGLSCUDADevice.GetDevice: TCUDADevice; begin Result := CUDAContextManager.GetDeviceByName(FSelectDeviceName); end; function TGLSCUDADevice.Suitable: Boolean; var LDevice: TCUDADevice; begin LDevice := GetDevice; Result := Assigned(LDevice); if Result then Result := LDevice.FSuitable; end; procedure TGLSCUDADevice.SetDevice(AValue: TCUDADevice); begin end; procedure TGLSCUDADevice.SetDeviceName(const AName: string); begin if FSelectDeviceName <> AName then begin CUDAContextManager.DestroyContextOf(Self.Device); FSelectDeviceName := AName; CUDAContextManager.CreateContextOf(Self.Device); end; end; {$IFDEF GLS_REGION}{$ENDREGION}{$ENDIF} // ------------------ // ------------------ TCUDAContextManager ------------------ // ------------------ {$IFDEF GLS_REGION}{$REGION 'TCUDAcontextManager'}{$ENDIF} // Init // class procedure CUDAContextManager.Init; var dCount: Integer; status: TCUresult; i: Integer; begin if InitCUDA and not Assigned(fDeviceList) then begin fDeviceList := TCUDADeviceList.Create; fContextList := TCUDAContextList.Create; dCount := 0; status := cuInit(0); if status = CUDA_SUCCESS then cuDeviceGetCount(dCount); // Fill devices list for i := 0 to dCount - 1 do fDeviceList.Add(TCUDADevice.Create); end; end; // Done // class procedure CUDAContextManager.Done; var I, J: Integer; begin if Assigned(fDeviceList) then for i := 0 to fDeviceList.Count - 1 do fDeviceList[i].Free; for I := 0 to High(FContextStacks) do begin if FContextStacks[I].Count > 0 then begin GLSLogger.LogError(cudasUnbalansedUsage); for J := FContextStacks[I].Count - 1 to 0 do FContextStacks[I][J].Release; end; FContextStacks[I].Destroy; end; fDeviceList.Free; fContextList.Free; CloseCUDA; end; // RegisterContext // class procedure CUDAContextManager.RegisterContext(aContext: TCUDAContext); begin if fContextList.IndexOf(aContext) >= 0 then begin GLSLogger.LogError(cudasInvalidContextReg); Abort; end else fContextList.Add(aContext); end; // UnRegisterContext // class procedure CUDAContextManager.UnRegisterContext(aContext: TCUDAContext); begin if fContextList.IndexOf(aContext) < 0 then begin GLSLogger.LogError(cudasInvalidContextReg); Abort; end else begin fContextList.Remove(aContext); end; end; // ContextCount // class function CUDAContextManager.ContextCount: Integer; begin Result := fContextList.Count; end; // DeviceCount // class function CUDAContextManager.DeviceCount: Integer; begin Result := fDeviceList.Count; end; // GetDevice // class function CUDAContextManager.GetDevice(i: Integer): TCUDADevice; begin Result := nil; if i < fDeviceList.Count then Result := fDeviceList[i]; end; // GetContext // class function CUDAContextManager.GetContext(i: Integer): TCUDAContext; begin Result := nil; if i < fContextList.Count then Result := fContextList[i]; end; // FillUnusedDeviceList // class procedure CUDAContextManager.FillUnusedDeviceList(var AList: TStringList); var i: Integer; begin if not Assigned(AList) then AList := TStringList.Create else AList.Clear; for i := 0 to fDeviceList.Count - 1 do if not fDeviceList[i].FUsed then AList.Add(fDeviceList[i].name); end; // GetDeviceByName // class function CUDAContextManager.GetDeviceByName(const AName: string) : TCUDADevice; var i: Integer; Device: TCUDADevice; begin Result := nil; if Length(AName) = 0 then exit; for i := 0 to fDeviceList.Count - 1 do begin Device := fDeviceList[i]; if Device.name = AName then begin Result := Device; exit; end; end; end; // GetMaxGflopsDevice // class function CUDAContextManager.GetMaxGflopsDevice: TCUDADevice; var max_gflops: Integer; i: Integer; Device: TCUDADevice; begin Device := nil; max_gflops := 0; for i := 0 to fDeviceList.Count - 1 do begin if max_gflops < fDeviceList.Items[i].fGFlops then begin Device := fDeviceList.Items[i]; max_gflops := Device.fGFlops; end; end; Result := Device; end; // GetNextUnusedDevice // class function CUDAContextManager.GetNextUnusedDevice: TCUDADevice; var i: Integer; Device: TCUDADevice; begin Result := nil; for i := 0 to fDeviceList.Count - 1 do begin Device := fDeviceList[i]; if not Device.FUsed then begin Result := Device; exit; end; end; end; class procedure CUDAContextManager.CreateContext(aContext: TCUDAContext); var status: TCUresult; cuOldContext, cuContext: PCUcontext; LGLContext: TGLContext; LStack: TCUDAContextList; begin if not Assigned(aContext.FDevice) or not aContext.FDevice.FSuitable then begin GLSLogger.LogError(cudasNoDeviceToCreate); Abort; end; if GetThreadStack.Count > 0 then begin if cuCtxPopCurrent(cuOldContext) <> CUDA_SUCCESS then begin GLSLogger.LogError(cudasThreadBusy); Abort; end; end else cuOldContext := nil; if aContext.IsValid then DestroyContext(aContext); RegisterContext(aContext); status := CUDA_SUCCESS; if Assigned(aContext.FOnOpenGLInteropInit) then begin aContext.FOnOpenGLInteropInit(LGLContext); if Assigned(LGLContext) and LGLContext.IsValid then begin LGLContext.Activate; cuContext := nil; status := cuGLCtxCreate(cuContext, 0, aContext.FDevice.fHandle); LGLContext.Deactivate; end else begin GLSLogger.LogError(cudasInvalidGLContext); UnRegisterContext(aContext); Abort; end; end else begin status := cuCtxCreate(cuContext, 0, aContext.FDevice.fHandle); end; if (status <> CUDA_SUCCESS) then begin GLSLogger.LogError(cudaGetLastErrorString); UnRegisterContext(aContext); cuCtxDetach(cuContext); Abort; end; aContext.fHandle := cuContext; // Make context be floating to use it in different thread if cuCtxPopCurrent(cuContext) <> CUDA_SUCCESS then begin LStack := GetThreadStack; LStack.Insert(LStack.Count - 1, aContext); GLSLogger.LogWarning(cudasMakeFloatingFail); end; if Assigned(cuOldContext) then cuCtxPushCurrent(cuOldContext); end; class procedure CUDAContextManager.CreateContextOf(ADevice: TCUDADevice); var i: Integer; begin if Assigned(ADevice) and ADevice.FSuitable then begin for i := 0 to fContextList.Count do if fContextList[i].FDevice = ADevice then CreateContext(fContextList[i]); end; end; class procedure CUDAContextManager.DestroyContext(aContext: TCUDAContext); begin if aContext.IsValid then begin aContext.DestroyAllHandles; cuCtxDestroy(aContext.fHandle); aContext.fHandle := nil; CUDAContextManager.UnRegisterContext(aContext); end; end; class procedure CUDAContextManager.DestroyContextOf(ADevice: TCUDADevice); var i: Integer; begin if Assigned(ADevice) and ADevice.FSuitable then begin for i := 0 to fContextList.Count - 1 do if fContextList[i].FDevice = ADevice then DestroyContext(fContextList[i]); end; end; class function CUDAContextManager.GetThreadStack: TCUDAContextList; begin if vStackIndex = 0 then begin SetLength(FContextStacks, Length(FContextStacks)+1); FContextStacks[High(FContextStacks)] := TCUDAContextList.Create; vStackIndex := High(FContextStacks)+1; end; Result := FContextStacks[vStackIndex-1]; end; // GetCurrentThreadContext // class function CUDAContextManager.GetCurrentThreadContext: TCUDAContext; begin if GetThreadStack.Count > 0 then Result := GetThreadStack.Last else Result := nil; end; class procedure CUDAContextManager.PushContext(aContext: TCUDAContext); var LContext: TCUDAContext; cuContext: PCUcontext; begin LContext := GetCurrentThreadContext; if LContext <> aContext then begin // Pop current if Assigned(LContext) then if cuCtxPopCurrent(cuContext) = CUDA_SUCCESS then begin if LContext.fHandle <> cuContext then begin GLSLogger.LogError(cudasUnbalansedUsage); Abort; end; end else Abort; // Push required if cuCtxPushCurrent(aContext.fHandle) <> CUDA_SUCCESS then Abort; end; GetThreadStack.Add(aContext); end; class function CUDAContextManager.PopContext: TCUDAContext; var C: Integer; LContext: TCUDAContext; cuContext: PCUcontext; begin C := GetThreadStack.Count; if C = 0 then begin GLSLogger.LogError(cudasUnbalansedUsage); Abort; end; Result := GetThreadStack.Last; GetThreadStack.Delete(C - 1); LContext := GetCurrentThreadContext; if Result <> LContext then begin if cuCtxPopCurrent(cuContext) = CUDA_SUCCESS then begin if Result.fHandle <> cuContext then begin GLSLogger.LogError(cudasUnbalansedUsage); Abort; end; end else Abort; if Assigned(LContext) and (cuCtxPushCurrent(LContext.fHandle) <> CUDA_SUCCESS) then Abort; end; end; {$IFDEF GLS_REGION}{$ENDREGION}{$ENDIF} // ------------------ // ------------------ TCUDAHandlesMaster ------------------ // ------------------ {$IFDEF GLS_REGION}{$REGION 'TCUDAHandlesMaster'}{$ENDIF} // AllocateHandles // procedure TCUDAHandlesMaster.AllocateHandles; var LList: TCUDAHandleList.TLockableList; begin LList := GetContext.FHandleList.LockList; if LList.IndexOf(Self) < 0 then LList.Add(Self); GetContext.FHandleList.UnlockList; end; // DestroyHandles // procedure TCUDAHandlesMaster.DestroyHandles; begin GetContext.FHandleList.Remove(Self); end; {$IFDEF GLS_REGION}{$ENDREGION}{$ENDIF} // ------------------ // ------------------ TCUDAContext ------------------ // ------------------ {$IFDEF GLS_REGION}{$REGION 'TCUDAcontext'}{$ENDIF} // Create // constructor TCUDAContext.Create; begin inherited Create; fHandle := nil; FDevice := nil; FHandleList := TCUDAHandleList.Create; end; // Destroy // destructor TCUDAContext.Destroy; begin DestroyAllHandles; CUDAContextManager.DestroyContext(Self); FHandleList.Destroy; inherited; end; procedure TCUDAContext.SetDevice(ADevice: TCUDADevice); begin if FDevice <> ADevice then begin CUDAContextManager.DestroyContext(Self); FDevice := ADevice; end; end; procedure TCUDAContext.Requires; begin if not IsValid then begin GLSLogger.LogError(cudasContextNotInit); Abort; end; CUDAContextManager.PushContext(Self); end; procedure TCUDAContext.Release; begin CUDAContextManager.PopContext; end; procedure TCUDAContext.DestroyAllHandles; var i: Integer; LList: TCUDAHandleList.TLockableList; begin Requires; LList := FHandleList.LockList; try for i := LList.Count - 1 downto 0 do LList[i].DestroyHandles; finally FHandleList.Clear; FHandleList.UnlockList; Release; end; end; function TCUDAContext.IsValid: Boolean; begin Result := Assigned(fHandle); end; {$IFDEF GLS_REGION}{$ENDREGION}{$ENDIF} // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterClasses([TGLSCUDADevice]); CUDAContextManager.Init; finalization CUDAContextManager.Done; end.
unit PlotReader; {$mode objfpc}{$H+} interface uses Classes, Plots; type // Intermediator between TPlot, TDataReaders and user. // GUI (User) TDataReader // \ / // TPlotReader // | // TPlotSet TPlotReader = class private FPlot: TPlot; public constructor Create(APlot: TPlot); destructor Destroy; override; procedure AddFileDialog; class procedure AddFileDialog(APlot: TPlot); end; implementation uses SysUtils, Controls, Forms, OriUtils_Gui, SpectrumTypes, SpectrumSettings, SpectrumStrings, PlotReaders; {%region Dialog Invokers} function OpenGraphsDialog(AFileNames: TStrings; out AFilterIndex: Integer): Boolean; var Params: TFileDialogParams; begin FillChar(Params{%H-}, SizeOf(TFileDialogParams), 0); Params.Title := Dlg_OpenGraphs; Params.Filters := TFileReaders.FileFilters; Params.FileNames := AFileNames; Params.MultiSelect:= True; Params.InitialDir := Preferences.GraphsOpenCurDir; Params.FilterIndex := Preferences.GraphsOpenFilter; Result := OpenFileDialog(Params); if Result then begin Preferences.GraphsOpenFilter := Params.FilterIndex; Preferences.GraphsOpenCurDir := ExtractFilePath(Params.FileName); AFilterIndex := Params.FilterIndex; end; end; {function OpenTableDialog(var AFileName: String): Boolean; begin with TOpenDialog.Create(nil) do try Title := Constant('Dlg_OpenTable'); Filter := OpenTableFilters; DefaultExt := 'txt'; FileName := ''; Options := Options + [ofPathMustExist, ofFileMustExist, ofDontAddToRecent]; FilterIndex := Preferences.GraphsOpenFilterTable; InitialDir := Preferences.GraphsOpenCurDir; Result := Execute; if Result then begin Preferences.GraphsOpenFilterTable := FilterIndex; Preferences.GraphsOpenCurDir := ExtractFilePath(FileName); AFileName := FileName; end; finally Free; end; end; function OpenFolderDialog: Boolean; var CurDir: String; begin CurDir := Preferences.GraphsOpenCurDir; // TODO: свой диалог выбора папки, в котором сразу же можно будет задать // фильтр и, возможно, посмотреть какие файлы будут выбраны. Result := OriUtils.OpenFolderDialog(Constant('Dlg_OpenFolder'), CurDir); if Result then Preferences.GraphsOpenCurDir := CurDir; end;} {%endregion Dialog Invokers} {%region Static shortcuts to methods} class procedure TPlotReader.AddFileDialog(APlot: TPlot); begin with TPlotReader.Create(APlot) do try AddFileDialog finally Free end; end; {%endregion Static methods} constructor TPlotReader.Create(APlot: TPlot); begin FPlot := APlot; end; destructor TPlotReader.Destroy; begin inherited; end; procedure TPlotReader.AddFileDialog; var I, J: Integer; InputFiles: TStringList; InputFile: String; ErrorMsg: String; FilterIndex: Integer; ReaderClass: TDataReaderClass; PerFileReader: Boolean; Reader: TDataReader = nil; SavedCur: TCursor; begin InputFiles := TStringList.Create; try if not OpenGraphsDialog(InputFiles, FilterIndex) then exit; ReaderClass := TFileReaders.ReaderByFilter(FilterIndex); if Assigned(ReaderClass) then begin Reader := ReaderClass.Create; if not Reader.Configure then exit; PerFileReader := False; end else PerFileReader := True; for I := 0 to InputFiles.Count-1 do try InputFile := InputFiles[I]; if PerFileReader then begin ReaderClass := TFileReaders.ReaderByExt(InputFile); if not Assigned(ReaderClass) then raise ESpectrumError.CreateFmt(Err_UnsupportedFile, [InputFile]); Reader := ReaderClass.Create; if not Reader.Configure then begin Reader.Free; continue; end; end; SavedCur := Screen.Cursor; Screen.Cursor := crHourGlass; try Reader.Read(InputFile); for J := 0 to Reader.ResultCount-1 do FPlot.AddGraph(TGraph.Create(Reader.Result[J], InputFile)); finally if PerFileReader then FreeAndNil(Reader); Screen.Cursor := SavedCur; end; except on e: Exception do begin ErrorMsg := Format(Err_ReadData, [InputFile]) + NL2 + e.Message; if I < InputFiles.Count-1 then begin // Some files are waiting to be opened. Should we continue with error? if not ConfirmDlg(ErrorMsg + NL2 + Err_FileTryNext) then break; end else ErrorDlg(ErrorMsg); end; end; finally FreeAndNil(Reader); InputFiles.Free; end; end; end.
{ GMPolyline unit ES: contiene las clases bases necesarias para mostrar polilineas y polígonos en un mapa de Google Maps mediante el componente TGMMap EN: includes the base classes needed to show polylines and polygons on Google Map map using the component TGMMap ========================================================================= MODO DE USO/HOW TO USE ES: poner el componente en el formulario, linkarlo a un TGMMap y poner las polilineas o polígonos a mostrar EN: put the component into a form, link to a TGMMap and put the polylines or polygons to show ========================================================================= History: ver 1.1.0 ES: nuevo: TCurveLine -> nueva clase para hacer polilineas curvas. cambio: TBasePolyline -> método AddLinePoint modificado para acelerar la creación de las polilineas. error: TBasePolyline -> mejorado rendimiento en métodos AddLinePoint y GetPath (GC: issue 9). nuevo: TBasePolyline -> se añade el método GetCenter. EN: new: TCurveLine -> new class to do curved polylines. change: TBasePolyline -> modified AddLinePoint method to accelerate the creation of polylines. bug: TBasePolyline -> improved performance on GetPath and AddLinePoint methods (GC: issue 9). new: TBasePolyline -> added GetCenter method. ver 1.0.0 ES: cambio: TCustomIconSequence -> se elimina la propiedad Icon para que sea definida en los hijos como TSymbol. nuevo: TBasePolyline -> ZoomToPoints, establece el zoom óptimo para visualizar la polilínea. EN: change: TCustomIconSequence -> Icon property is removed to be defined in descendents as TSymbol. new: TBasePolyline -> ZoomToPoints, sets the optimal zoom to display the polyline. ver 0.1.9 ES: nuevo: documentación nuevo: se hace compatible con FireMonkey EN: new: documentation new: now compatible with FireMonkey ver 0.1.8 ES: cambio: TBasePolyline -> las clases TLinePoints y TLinePoint se desvinculan de TPolyline y se traspasan a GMClasses cambio: TBasePolyline -> implementa la interfaz ILinePoint EN: change: TBasePolyline -> class TLinePoints and TLinePoint is disassociated from TPolyline and they are transferred to GMClasses change: TBasePolyline -> implements ILinePoint interface ver 0.1.7 ES: cambio: modificados métodos Set y ShowElement para que usen el nuevo método ChangeProperties heredado de TLinkedComponent cambio: creada clase intermedia (TBasePolyline) entre TLinkedComponent y TPolyline cambio: creada clase intermedia (TGMBasePolyline) entre TGMLinkedComponent y TGMPolyline. cambio: TPolyline -> nueva propiedad Icon para definir el tipo de linea de la polilinea. EN: change: modified all Set and ShowElements methods to use the new method ChangeProperties inherited from TLinkedComponent change: created new class (TBasePolyline) between TLinkedComponent and TPolyline change: created new class (TGMBasePolyline) between TGMLinkedComponent and TGMPolyline. cambio: TPolyline -> added Icon property to define the line of polyline. ver 0.1.6 ES: error: TGMPolyline -> corregido error cuando se intentaba mostrar una polilinea sin TLinePoints EN: bug: TGMPolyline -> bug fixed when we try to show a polyline without TLinePoints ver 0.1.5 ES: nuevo: TPolyline -> añadida propiedad CountLinePoints nuevo: TLinePoint -> añadido método ToStr nuevo: TLinePoint -> añadida método StringToReal EN: new: TPolyline -> CountLinePoints property added new: TLinePoint -> ToStr method added new: TLinePoint -> StringToReal method added ver 0.1.4 ES: cambio: cambio en el JavaScript de algunos métodos Set EN: change: JavaScript changed from some Set methods ver 0.1.3 ES: cambio: métodos Set cambiados para evitar duplicidad de código EN: change: changed Set methods to avoid duplicate code ver 0.1.2 ES: cambio: cuando cambia la lat/lng de un TLinePoint, se actualiza en el mapa error: implementado SetPath en JavaScript EN: change: when change the lat/lng of a TLinePoint, the map is updated bug: implemented SetPath into JavaScript ver 0.1.1: ES- primera versión EN- first version ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a: gmlib@cadetill.com IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion, please send me a mail to: gmlib@cadetill.com ========================================================================= Copyright (©) 2012, by Xavier Martinez (cadetill) @author Xavier Martinez (cadetill) @web http://www.cadetill.com } {*------------------------------------------------------------------------------ The GMPolyline unit includes the base classes needed to show polylines and polygons on Google Map map using the component TGMMap. @author Xavier Martinez (cadetill) @version 1.5.3 -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ La unit GMPolyline contiene las clases bases necesarias para mostrar polilineas y polígonos en un mapa de Google Maps mediante el componente TGMMap. @author Xavier Martinez (cadetill) @version 1.5.3 -------------------------------------------------------------------------------} unit GMPolyline; {$I ..\gmlib.inc} interface uses {$IFDEF DELPHIXE2} System.Classes, {$ELSE} Classes, {$ENDIF} GMLinkedComponents, GMConstants, GMClasses; type TBasePolyline = class; {*------------------------------------------------------------------------------ Class to determine the symbol to show along the path. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase para determinar el símbolo a mostrar a lo largo del camino. -------------------------------------------------------------------------------} TCustomSymbol = class(TPersistent) private {*------------------------------------------------------------------------------ Symbol to display. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Símbolo a mostrar. -------------------------------------------------------------------------------} FPath: TSymbolPath; {*------------------------------------------------------------------------------ The stroke width in pixels. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Anchura del trazo en píxeles. -------------------------------------------------------------------------------} FStrokeWeight: Integer; {*------------------------------------------------------------------------------ The fill opacity between 0.0 and 1.0. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Opacidad del relleno entre 0.0 y 1.0. -------------------------------------------------------------------------------} FFillOpacity: Real; {*------------------------------------------------------------------------------ The stroke opacity between 0.0 and 1.0. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Opacidad del trazo entre 0.0 y 1.0. -------------------------------------------------------------------------------} FStrokeOpacity: Real; {*------------------------------------------------------------------------------ OnChange is fired when some property change. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ El evento OnChange se dispara cuando cambia alguna propiedad. -------------------------------------------------------------------------------} FOnChange: TNotifyEvent; procedure SetFillOpacity(const Value: Real); procedure SetPath(const Value: TSymbolPath); procedure SetStrokeOpacity(const Value: Real); procedure SetStrokeWeight(const Value: Integer); protected {*------------------------------------------------------------------------------ This method returns the assigned color to the FillColor property defined into its descendents. @return String with the color in RGB format -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Método que devuelve el color asignado a la propiedad FillColor definida en los descendientes. @return Cadena con el color en formato RGB -------------------------------------------------------------------------------} function GetFillColor: string; virtual; abstract; {*------------------------------------------------------------------------------ This method returns the assigned color to the StrokeColor property defined into its descendents. @return String with the color in RGB format -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Método que devuelve el color asignado a la propiedad StrokeColor definida en los descendientes. @return Cadena con el color en formato RGB -------------------------------------------------------------------------------} function GetStrokeColor: string; virtual; abstract; property OnChange: TNotifyEvent read FOnChange write FOnChange; public {*------------------------------------------------------------------------------ Constructor class -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Constructor de la clase -------------------------------------------------------------------------------} constructor Create; virtual; {*------------------------------------------------------------------------------ Assign method copies the contents of another similar object. @param Source object to copy content -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ El método Assign copia el contenido de un objeto similar. @param Source objeto a copiar el contenido -------------------------------------------------------------------------------} procedure Assign(Source: TPersistent); override; published property FillOpacity: Real read FFillOpacity write SetFillOpacity; // 0 to 1 property Path: TSymbolPath read FPath write SetPath default spNONE; property StrokeOpacity: Real read FStrokeOpacity write SetStrokeOpacity; // 0 to 1 property StrokeWeight: Integer read FStrokeWeight write SetStrokeWeight default 0; // 1 to 10 end; {*------------------------------------------------------------------------------ Class to determine the repetition of the showed icon. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase para determinar la repetición del icono mostrado. -------------------------------------------------------------------------------} TValue = class(TPersistent) private {*------------------------------------------------------------------------------ Measure value. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Valor de la medida. -------------------------------------------------------------------------------} FValue: Integer; {*------------------------------------------------------------------------------ Measure type (pixels or percentage). -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Valor de la medida (píxeles o porcentaje). -------------------------------------------------------------------------------} FMeasure: TMeasure; {*------------------------------------------------------------------------------ OnChange is fired when some property change. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ El evento OnChange se dispara cuando cambia alguna propiedad. -------------------------------------------------------------------------------} FOnChange: TNotifyEvent; procedure SetMeasure(const Value: TMeasure); procedure SetValue(const Value: Integer); protected property OnChange: TNotifyEvent read FOnChange write FOnChange; public {*------------------------------------------------------------------------------ Constructor class -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Constructor de la clase -------------------------------------------------------------------------------} constructor Create; virtual; {*------------------------------------------------------------------------------ Assign method copies the contents of another similar object. @param Source object to copy content -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ El método Assign copia el contenido de un objeto similar. @param Source objeto a copiar el contenido -------------------------------------------------------------------------------} procedure Assign(Source: TPersistent); override; published property Value: Integer read FValue write SetValue default 100; property Measure: TMeasure read FMeasure write SetMeasure default mPercentage; end; {*------------------------------------------------------------------------------ Class to determine the icon and repetition to show. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase para determinar el icono y la repetición a mostrar. -------------------------------------------------------------------------------} TCustomIconSequence = class(TPersistent) private FOwner: TBasePolyline; {*------------------------------------------------------------------------------ Repetition properties. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Propiedades de repetición. -------------------------------------------------------------------------------} FDistRepeat: TValue; {*------------------------------------------------------------------------------ OffSet properties. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Propiedades del OffSet. -------------------------------------------------------------------------------} FOffSet: TValue; {*------------------------------------------------------------------------------ OnChange is fired when some property change. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ El evento OnChange se dispara cuando cambia alguna propiedad. -------------------------------------------------------------------------------} FOnChange: TNotifyEvent; protected {*------------------------------------------------------------------------------ Response to OnChange event of OffSet property. @param Sender Object that fire event -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Respuesta al evento del OnChange de la propiedad OffSet. @param Sender Objecto que dispara el evento -------------------------------------------------------------------------------} procedure OnOffSetChange(Sender: TObject); {*------------------------------------------------------------------------------ Response to OnChange event of DistRepeat property. @param Sender Object that fire event -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Respuesta al evento del OnChange de la propiedad DistRepeat. @param Sender Objecto que dispara el evento -------------------------------------------------------------------------------} procedure OnDistRepeatChange(Sender: TObject); {*------------------------------------------------------------------------------ Response to OnChange event of Icon property. @param Sender Object that fire event -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Respuesta al evento del OnChange de la propiedad Icon. @param Sender Objecto que dispara el evento -------------------------------------------------------------------------------} procedure OnIconChange(Sender: TObject); {*------------------------------------------------------------------------------ Create the properties that contains some color value. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Crea las propiedades que contienen algún valor de color. -------------------------------------------------------------------------------} procedure CreatePropertiesWithColor; virtual; abstract; property OnChange: TNotifyEvent read FOnChange write FOnChange; public {*------------------------------------------------------------------------------ Constructor class @param aOwner Owner. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Constructor de la clase @param aOwner Propietario. -------------------------------------------------------------------------------} constructor Create(aOwner: TBasePolyline); virtual; {*------------------------------------------------------------------------------ Destructor class -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Destructor de la clase -------------------------------------------------------------------------------} destructor Destroy; override; {*------------------------------------------------------------------------------ Assign method copies the contents of another similar object. @param Source object to copy content -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ El método Assign copia el contenido de un objeto similar. @param Source objeto a copiar el contenido -------------------------------------------------------------------------------} procedure Assign(Source: TPersistent); override; published property OffSet: TValue read FOffSet write FOffSet; property DistRepeat: TValue read FDistRepeat write FDistRepeat; end; {*------------------------------------------------------------------------------ Class to determine the curve line properties. Based on Curved Line Plugin for Google Maps Api. Plugin web site http://curved_lines.overfx.net/ -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase para determinar las propiedades de una línea curva. Basado en Curved Line Plugin for Google Maps Api. Página web del plugin http://curved_lines.overfx.net/ -------------------------------------------------------------------------------} TCurveLine = class(TPersistent) private {*------------------------------------------------------------------------------ For horizontal or vertical lines. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Para lineas horizontales o verticales. -------------------------------------------------------------------------------} FHorizontal: Boolean; {*------------------------------------------------------------------------------ Number multiplying the curved line roundness. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Multiplicador para la línea curva. -------------------------------------------------------------------------------} FMultiplier: Integer; {*------------------------------------------------------------------------------ Activate curve line. If active, only will be consider the incial and final point of path. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Activar línea curva. Si se activa, sólo se tendrán en cuenta los puntos inicial y final del path. -------------------------------------------------------------------------------} FActive: Boolean; {*------------------------------------------------------------------------------ Number to define how much points there will be in a curved line. For example 0.1 means there will be a point every 10% of the width of the line, 0.05 means there will be a point every 5% of the width of the line. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Numero para definir cuántos puntos habrá en la línea curva. Por ejemplo, 0.1 significa que habrá un punto cada 10% a lo largo de la línea, 0.05 significa que habrá un punto cada 5% a lo largo de la línea. -------------------------------------------------------------------------------} FResolution: Real; {*------------------------------------------------------------------------------ Event fired when a property change. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Evento disparado cuando cambia alguna propiedad. -------------------------------------------------------------------------------} FOnChange: TNotifyEvent; procedure SetActive(const Value: Boolean); procedure SetHorizontal(const Value: Boolean); procedure SetMultiplier(const Value: Integer); procedure SetResolution(const Value: Real); public {*------------------------------------------------------------------------------ Constructor class -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Constructor de la clase -------------------------------------------------------------------------------} constructor Create; virtual; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property Active: Boolean read FActive write SetActive default False; property Horizontal: Boolean read FHorizontal write SetHorizontal default True; property Multiplier: Integer read FMultiplier write SetMultiplier default 1; property Resolution: Real read FResolution write SetResolution; end; {*------------------------------------------------------------------------------ Base class for polylines and polygons. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase base para las polilineas y polígonos. -------------------------------------------------------------------------------} TBasePolyline = class(TLinkedComponent, ILinePoint) private {*------------------------------------------------------------------------------ Whether this polyline is visible on the map. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Si la polilínea es visible en el mapa. -------------------------------------------------------------------------------} FVisible: Boolean; {*------------------------------------------------------------------------------ The stroke width in pixels. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Anchura del trazo en píxeles. -------------------------------------------------------------------------------} FStrokeWeight: Integer; {*------------------------------------------------------------------------------ When true, render each edge as a geodesic (a segment of a "great circle"). A geodesic is the shortest path between two points along the surface of the Earth. When false, render each edge as a straight line on screen. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Si se establece a true, muestra cada arista como una geodésica (un segmento de un "gran círculo"). Una geodésica es el camino más corto entre dos puntos de la superfície terrestre. Si es false, muestra cada arista como una línea recta en pantalla. -------------------------------------------------------------------------------} FGeodesic: Boolean; {*------------------------------------------------------------------------------ Indicates whether this polyline handles mouse events. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Indica si la polilínea recibe eventos del ratón. -------------------------------------------------------------------------------} FClickable: Boolean; {*------------------------------------------------------------------------------ The stroke opacity between 0.0 and 1.0. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Opacidad del trazo entre 0.0 y 1.0. -------------------------------------------------------------------------------} FStrokeOpacity: Real; {*------------------------------------------------------------------------------ If set to true, the user can edit this shape by dragging the control points shown at the vertices and on each segment. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Si se establece a true, el usuario puede editar la figura arrastrando los puntos de control mostrados en los vertices y en cada segmento. -------------------------------------------------------------------------------} FEditable: Boolean; {*------------------------------------------------------------------------------ The ordered sequence of coordinates of the Polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Secuencia ordenada de coordenadas de la polilínea. -------------------------------------------------------------------------------} FLinePoints: TLinePoints; {*------------------------------------------------------------------------------ If set to true, each time you change the route on the map will update the array of LinePoints. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Si se establece a true, cada vez que se modifique el recorrido en el mapa, se actualizará el array de LinePoints. -------------------------------------------------------------------------------} FAutoUpdatePath: Boolean; FIsUpdating: Boolean; { TInterfaced Persistent } FOwnerInterface: IInterface; procedure SetClickable(const Value: Boolean); procedure SetEditable(const Value: Boolean); procedure SetGeodesic(const Value: Boolean); procedure SetStrokeOpacity(const Value: Real); procedure SetStrokeWeight(const Value: Integer); procedure SetVisible(const Value: Boolean); function GetItems(I: Integer): TLinePoint; protected {*------------------------------------------------------------------------------ This method returns the assigned color to the StrokeColor property defined into its descendents. @return String with the color in RGB format. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Método que devuelve el color asignado a la propiedad StrokeColor definida en los descendientes. @return Cadena con el color en formato RGB. -------------------------------------------------------------------------------} function GetStrokeColor: string; virtual; abstract; {*------------------------------------------------------------------------------ Return the number of LinePoints. @return Number of LinePoints. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Devuelve la cantidad de LinePoints. @return Numero de LinePoints. -------------------------------------------------------------------------------} function GetCountLinePoints: Integer; { ILinePoint } procedure LinePointChanged; { IInterface } {*------------------------------------------------------------------------------ Returns a reference to a specified interface if the object supports that interface. @param IID See delphi documentation. @param Obj See delphi documentation. @return Reference. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Devuelve una referencia a la interfaz especificada si el objeto soporta esta interfaz. @param IID Ver la documentación de Delphi. @param Obj Ver la documentación de Delphi. @return Referencia. -------------------------------------------------------------------------------} function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; {*------------------------------------------------------------------------------ Increments the reference count for this interface. @return Number of references. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Incrementa el contador de referencia para esta interfaz. @return Numero de referencias. -------------------------------------------------------------------------------} function _AddRef: Integer; stdcall; {*------------------------------------------------------------------------------ Decrements the reference count for this interface. @return Number of references. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Decrementa el contador de referencia para esta interfaz. @return Numero de referencias. -------------------------------------------------------------------------------} function _Release: Integer; stdcall; public { TInterfaced Persistent } {*------------------------------------------------------------------------------ Responds after the last constructor executes. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Respuesta después de la ejecución del último constructor. -------------------------------------------------------------------------------} procedure AfterConstruction; override; constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; {*------------------------------------------------------------------------------ Returns the polyline's center. @param LL TLatLng with the center. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Devuelve el centro de la polilinea. @param LL TLatLng con el centro. -------------------------------------------------------------------------------} procedure GetCenter(LL: TLatLng); {*------------------------------------------------------------------------------ Sets the optimal zoom to display the polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Establece el zoom óptimo para visualizar la polilínea. -------------------------------------------------------------------------------} procedure ZoomToPoints; {*------------------------------------------------------------------------------ Converts to string the set of LinePoints. The elements are separated by semicolon (;) and the coordinates (lat/lng) by a pipe (|). @return String with conversion. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Convierte en una cadena el conjunto de LinePoints. Los elementos están separados por punto y coma (;) y las coordenadas (lat/lng) separados por una barra vertical (|). @return Cadena con la conversión. -------------------------------------------------------------------------------} function PolylineToStr: string; {*------------------------------------------------------------------------------ Returns the area of a closed path. The computed area uses the same units as the Radius. The radius defaults to the Earth's radius in meters, in which case the area is in square meters. @param Radius Radius to use. @return Area. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Devuelve el area de una ruta cerrada. El area calculada usa las mismas unidades que Radius. El radio por defecto es el radio de la Tierra en metros, en cuyo caso el área es en metros cuadrados. @param Radius Radio a usar. @return Area. -------------------------------------------------------------------------------} function ComputeArea(Radius: Real = -1): Real; {*------------------------------------------------------------------------------ Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#poly @param LatLng Point to compute. @param Tolerance Tolerance. @return True if the point lies on or near to a polyline, or the edge of a polygon. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Calcula si el punto dado se encuentra en o cerca de una polilínea, o el borde de un polígono, dentro de una tolerancia especificada. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#poly @param LatLng Punto a calcular. @param Tolerance Tolerancia. @return True si el punto se encuentra en o cerca de una polilínea, o el borde de un polígono. -------------------------------------------------------------------------------} function IsLocationOnEdge(LatLng: TLatLng; Tolerance: Integer = -1): Boolean; overload; {*------------------------------------------------------------------------------ Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#poly @param Lat Latitude to compute. @param Lng Longitude to compute. @param Tolerance Tolerance. -1 no tolerance. @return True if the point lies on or near to a polyline, or the edge of a polygon. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Calcula si el punto dado se encuentra en o cerca de una polilínea, o el borde de un polígono, dentro de una tolerancia especificada. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#poly @param Lat Latitud a calcular. @param Lng Longitud a calcular. @param Tolerance Tolerancia. -1 sin tolerancia. @return True si el punto se encuentra en o cerca de una polilínea, o el borde de un polígono. -------------------------------------------------------------------------------} function IsLocationOnEdge(Lat, Lng: Real; Tolerance: Integer = -1): Boolean; overload; {*------------------------------------------------------------------------------ Encodes a sequence of LatLngs into an encoded path string. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#encoding @return Encoded string. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Codifica una secuencia de LatLng en un string codificado. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#encoding @return String codificado. -------------------------------------------------------------------------------} function EncodePath: string; {*------------------------------------------------------------------------------ Decodes an encoded path string into a sequence of LatLngs. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#encoding @param EncodedPath Path to decode. @param Add If true, the points resulting of decoding are added to current. If false (by default) , before to load the newest points resulting of decoding, the actual points will be deleted. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Decodifica un string codificado en una secuencia de LatLng. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#encoding @param EncodedPath Path a decodificar. @param Add Si es true, se añaden los puntos resultantes de la decodificación a los actuales. Si es false (por defecto), antes de cargar los nuevos puntos resultantes de la decodificación, se borrarán los puntos actuales. -------------------------------------------------------------------------------} procedure DecodePath(EncodedPath: string; Add: Boolean = False); procedure CenterMapTo; override; {*------------------------------------------------------------------------------ Get path changes. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Recupera los cambios en el path realizados. -------------------------------------------------------------------------------} procedure GetPath; {*------------------------------------------------------------------------------ Set new path. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Establece el nuevo recorrido. -------------------------------------------------------------------------------} procedure SetPath; {*------------------------------------------------------------------------------ Creates a new polyline point. @param Lat Point latitude. @param Lng Point longitude. @return New TLinePoint. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Crea un nuevo punto en la polilinea. @param Lat Latitud del punto. @param Lng Longitud del punto. @return Nuevo TLinePoint. -------------------------------------------------------------------------------} function AddLinePoint(Lat: Real = 0; Lng: Real = 0): TLinePoint; overload; {*------------------------------------------------------------------------------ Creates a new polyline point. @param Lat Point latitude. @param Lng Point longitude. @return New TLinePoint. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Crea un nuevo punto en la polilinea. @param Lat Latitud del punto. @param Lng Longitud del punto. @return Nuevo TLinePoint. -------------------------------------------------------------------------------} function AddLinePoint(Lat, Lng: string): TLinePoint; overload; {*------------------------------------------------------------------------------ Inserts a new polyline point at specified index. @param Index Position to insert. @param Lat Point latitude. @param Lng Point longitude. @return New TLinePoint. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Inserta un nuevo punto en la polilinea en el índice especificado. @param Index Posición en la que insertar. @param Lat Latitud del punto. @param Lng Longitud del punto. @return Nuevo TLinePoint. -------------------------------------------------------------------------------} function InsertLinePoint(Index: Integer; Lat, Lng: Real): TLinePoint; {*------------------------------------------------------------------------------ Deletes a single point. @param Index Position to delete. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Borra un punto. @param Index Posición a borrar. -------------------------------------------------------------------------------} procedure DeleteLinePoint(Index: Integer); {*------------------------------------------------------------------------------ Moves a point to a new position into LinePoints array. @param CurIndex Index of Item to move. @param NewIndex Destination index. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Mueve un punto a una nueva posición dentro del array de LinePoints. @param CurIndex Índice del elemento a mover. @param NewIndex Índice destino. -------------------------------------------------------------------------------} procedure MoveLinePoint(CurIndex, NewIndex: Integer); {*------------------------------------------------------------------------------ Deletes all points. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Borra todos los puntos. -------------------------------------------------------------------------------} procedure ClearLinePoints; property CountLinePoints: Integer read GetCountLinePoints; {*------------------------------------------------------------------------------ Array with the collection items. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Array con la colección de elementos. -------------------------------------------------------------------------------} property Items[I: Integer]: TLinePoint read GetItems; default; published property Clickable: Boolean read FClickable write SetClickable default True; property Editable: Boolean read FEditable write SetEditable default False; property Geodesic: Boolean read FGeodesic write SetGeodesic default False; property StrokeOpacity: Real read FStrokeOpacity write SetStrokeOpacity; // 0 to 1 property StrokeWeight: Integer read FStrokeWeight write SetStrokeWeight default 2; // 1 to 10 property Visible: Boolean read FVisible write SetVisible default True; property AutoUpdatePath: Boolean read FAutoUpdatePath write FAutoUpdatePath default True; // ES/EN: TCollection property LinePoints: TLinePoints read FLinePoints write FLinePoints; {*------------------------------------------------------------------------------ InfoWindows associated object. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ InfoWindows asociado al objeto. -------------------------------------------------------------------------------} property InfoWindow; {*------------------------------------------------------------------------------ This property is used, if applicable, to establish the name that appears in the collection editor. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Esta propiedad se usa, si procede, para establecer el nombre que aparece en el editor de la colección. -------------------------------------------------------------------------------} property Text; end; {*------------------------------------------------------------------------------ Base class for polylines and polygons collection. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase base para la colección de polilineas y polígonos. -------------------------------------------------------------------------------} TBasePolylines = class(TLinkedComponents) private procedure SetItems(I: Integer; const Value: TBasePolyline); function GetItems(I: Integer): TBasePolyline; protected function GetOwner: TPersistent; override; public function Add: TBasePolyline; function Insert(Index: Integer): TBasePolyline; {*------------------------------------------------------------------------------ Lists the polylines in the collection. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Lista de polilineas en la colección. -------------------------------------------------------------------------------} property Items[I: Integer]: TBasePolyline read GetItems write SetItems; default; end; {*------------------------------------------------------------------------------ Base class for GMPolyline component. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#Polyline -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase base para el componente GMPolyline. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#Polyline -------------------------------------------------------------------------------} TGMBasePolyline = class(TGMLinkedComponent) private {*------------------------------------------------------------------------------ This event is fired when a polyline is right-clicked on. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando en una polilínea se pulsa el botón derecho del ratón. -------------------------------------------------------------------------------} FOnRightClick: TLatLngIdxEvent; {*------------------------------------------------------------------------------ This event is fired for a mousedown on the polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento se dispara al pulsar en el polilínea. -------------------------------------------------------------------------------} FOnMouseDown: TLatLngIdxEvent; {*------------------------------------------------------------------------------ This event is fired when mousemove on the polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento se dispara cuando el ratón se mueve por encima del polilínea. -------------------------------------------------------------------------------} FOnMouseMove: TLatLngIdxEvent; {*------------------------------------------------------------------------------ This event is fired for a mouseup on the polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento se dispara al soltar el polilínea. -------------------------------------------------------------------------------} FOnMouseUp: TLatLngIdxEvent; {*------------------------------------------------------------------------------ This event is fired on polyline mouseout. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento se dispara cuando el ratón sale del polilínea. -------------------------------------------------------------------------------} FOnMouseOut: TLatLngIdxEvent; {*------------------------------------------------------------------------------ This event occurs when the user double-clicks a polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando el usuario hace doble click una polilínea. -------------------------------------------------------------------------------} FOnDblClick: TLatLngIdxEvent; {*------------------------------------------------------------------------------ This event is fired when the mouse enters the area of the polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento se dispara cuando el ratón entra en el área del polilínea. -------------------------------------------------------------------------------} FOnMouseOver: TLatLngIdxEvent; {*------------------------------------------------------------------------------ This event occurs when the user click a polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando el usuario pulsa una polilínea. -------------------------------------------------------------------------------} FOnClick: TLatLngIdxEvent; {*------------------------------------------------------------------------------ This event is fired when the polyline's StrokeColor property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad StrokeColor de una polilínea. -------------------------------------------------------------------------------} FOnStrokeColorChange: TLinkedComponentChange; {*------------------------------------------------------------------------------ This event is fired when the polyline's Visible property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad Visible de una polilínea. -------------------------------------------------------------------------------} FOnVisibleChange: TLinkedComponentChange; {*------------------------------------------------------------------------------ This event is fired when the polyline's StrokeWeight property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad StrokeWeight de una polilínea. -------------------------------------------------------------------------------} FOnStrokeWeightChange: TLinkedComponentChange; {*------------------------------------------------------------------------------ This event is fired when the polyline's Geodesic property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad Geodesic de una polilínea. -------------------------------------------------------------------------------} FOnGeodesicChange: TLinkedComponentChange; {*------------------------------------------------------------------------------ This event is fired when the polyline's Clickable property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad Clickable de una polilínea. -------------------------------------------------------------------------------} FOnClickableChange: TLinkedComponentChange; {*------------------------------------------------------------------------------ This event is fired when the polyline's StrokeOpacity property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad StrokeOpacity de una polilínea. -------------------------------------------------------------------------------} FOnStrokeOpacityChange: TLinkedComponentChange; {*------------------------------------------------------------------------------ This event is fired when the polyline's Editable property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad Editable de una polilínea. -------------------------------------------------------------------------------} FOnEditableChange: TLinkedComponentChange; {*------------------------------------------------------------------------------ This event is fired when the polyline's Path property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad Path de una polilínea. -------------------------------------------------------------------------------} FOnPathChange: TLinkedComponentChange; protected function GetItems(I: Integer): TBasePolyline; procedure EventFired(EventType: TEventType; Params: array of const); override; public {*------------------------------------------------------------------------------ GetPath method retrieve changes realized by user directly into the polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ El método GetPath recupera los cambios realizados por el usuario directamente en la polilinea. -------------------------------------------------------------------------------} procedure GetPath; {*------------------------------------------------------------------------------ SetPath method sets new LinePoints to the polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ El método SetPath establece los nuevos LinePoints a la polilínea. -------------------------------------------------------------------------------} procedure SetPath; {*------------------------------------------------------------------------------ Array with the collection items. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Array con la colección de elementos. -------------------------------------------------------------------------------} property Items[I: Integer]: TBasePolyline read GetItems; default; published {*------------------------------------------------------------------------------ Collection items. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Colección de elementos. -------------------------------------------------------------------------------} property VisualObjects; // eventos // events // from map property OnClick: TLatLngIdxEvent read FOnClick write FOnClick; property OnDblClick: TLatLngIdxEvent read FOnDblClick write FOnDblClick; property OnMouseDown: TLatLngIdxEvent read FOnMouseDown write FOnMouseDown; property OnMouseMove: TLatLngIdxEvent read FOnMouseMove write FOnMouseMove; property OnMouseOut: TLatLngIdxEvent read FOnMouseOut write FOnMouseOut; property OnMouseOver: TLatLngIdxEvent read FOnMouseOver write FOnMouseOver; property OnMouseUp: TLatLngIdxEvent read FOnMouseUp write FOnMouseUp; property OnRightClick: TLatLngIdxEvent read FOnRightClick write FOnRightClick; // from properties property OnClickableChange: TLinkedComponentChange read FOnClickableChange write FOnClickableChange; property OnEditableChange: TLinkedComponentChange read FOnEditableChange write FOnEditableChange; property OnGeodesicChange: TLinkedComponentChange read FOnGeodesicChange write FOnGeodesicChange; property OnStrokeColorChange: TLinkedComponentChange read FOnStrokeColorChange write FOnStrokeColorChange; property OnStrokeOpacityChange: TLinkedComponentChange read FOnStrokeOpacityChange write FOnStrokeOpacityChange; property OnStrokeWeightChange: TLinkedComponentChange read FOnStrokeWeightChange write FOnStrokeWeightChange; property OnVisibleChange: TLinkedComponentChange read FOnVisibleChange write FOnVisibleChange; property OnPathChange: TLinkedComponentChange read FOnPathChange write FOnPathChange; end; implementation uses {$IFDEF DELPHIXE2} System.SysUtils, {$ELSE} SysUtils, {$ENDIF} Lang, GMFunctions; { TCustomIconSequence } procedure TCustomIconSequence.Assign(Source: TPersistent); begin inherited; if Source is TCustomIconSequence then begin DistRepeat.Assign(TCustomIconSequence(Source).DistRepeat); OffSet.Assign(TCustomIconSequence(Source).OffSet); end; end; constructor TCustomIconSequence.Create(aOwner: TBasePolyline); begin FOwner := aOwner; FOffSet := TValue.Create; FOffSet.FValue := 100; FOffSet.FMeasure := mPercentage; FOffSet.OnChange := OnOffSetChange; FDistRepeat := TValue.Create; FDistRepeat.FValue := 0; FDistRepeat.FMeasure := mPixels; FDistRepeat.OnChange := OnDistRepeatChange; CreatePropertiesWithColor; end; destructor TCustomIconSequence.Destroy; begin if Assigned(FOffSet) then FreeAndNil(FOffSet); if Assigned(FDistRepeat) then FreeAndNil(FDistRepeat); inherited; end; procedure TCustomIconSequence.OnDistRepeatChange(Sender: TObject); begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomIconSequence.OnIconChange(Sender: TObject); begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomIconSequence.OnOffSetChange(Sender: TObject); begin if Assigned(FOnChange) then FOnChange(Self); end; { TCustomSymbol } procedure TCustomSymbol.Assign(Source: TPersistent); begin inherited; if Source is TCustomSymbol then begin FillOpacity := TCustomSymbol(Source).FillOpacity; Path := TCustomSymbol(Source).Path; StrokeOpacity := TCustomSymbol(Source).StrokeOpacity; StrokeWeight := TCustomSymbol(Source).StrokeWeight; end; end; constructor TCustomSymbol.Create; begin FPath := spNONE; end; procedure TCustomSymbol.SetFillOpacity(const Value: Real); begin if FFillOpacity = Value then Exit; FFillOpacity := Value; if FFillOpacity < 0 then FFillOpacity := 0; if FFillOpacity > 1 then FFillOpacity := 1; FFillOpacity := Trunc(FFillOpacity * 100) / 100; if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomSymbol.SetPath(const Value: TSymbolPath); begin if FPath = Value then Exit; FPath := Value; if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomSymbol.SetStrokeOpacity(const Value: Real); begin if FStrokeOpacity = Value then Exit; FStrokeOpacity := Value; if FStrokeOpacity < 0 then FStrokeOpacity := 0; if FStrokeOpacity > 1 then FStrokeOpacity := 1; FStrokeOpacity := Trunc(FStrokeOpacity * 100) / 100; if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomSymbol.SetStrokeWeight(const Value: Integer); begin if FStrokeWeight = Value then Exit; FStrokeWeight := Value; if FStrokeWeight < 1 then FStrokeWeight := 1; if FStrokeWeight > 10 then FStrokeWeight := 10; if Assigned(FOnChange) then FOnChange(Self); end; { TValue } procedure TValue.Assign(Source: TPersistent); begin inherited; if Source is TValue then begin Value := TValue(Source).Value; Measure := TValue(Source).Measure; end; end; constructor TValue.Create; begin FValue := 0; FMeasure := mPixels; end; procedure TValue.SetMeasure(const Value: TMeasure); begin if FMeasure = Value then Exit; FMeasure := Value; if Assigned(FOnChange) then FOnChange(Self); end; procedure TValue.SetValue(const Value: Integer); begin if FValue = Value then Exit; FValue := Value; if Assigned(FOnChange) then FOnChange(Self); end; { TBasePolyline } function TBasePolyline.AddLinePoint(Lat, Lng: string): TLinePoint; begin Result := LinePoints.Add; Result.Lat := Result.StringToReal(Lat); Result.Lng := Result.StringToReal(Lng); end; procedure TBasePolyline.AfterConstruction; begin inherited; if GetOwner <> nil then GetOwner.GetInterface(IInterface, FOwnerInterface); end; function TBasePolyline.AddLinePoint(Lat, Lng: Real): TLinePoint; begin FIsUpdating := True; Result := LinePoints.Add; Result.Lat := Lat; Result.Lng := Lng; FIsUpdating := False; ChangeProperties; end; procedure TBasePolyline.Assign(Source: TPersistent); begin inherited; if Source is TBasePolyline then begin Clickable := TBasePolyline(Source).Clickable; Editable := TBasePolyline(Source).Editable; Geodesic := TBasePolyline(Source).Geodesic; StrokeOpacity := TBasePolyline(Source).StrokeOpacity; StrokeWeight := TBasePolyline(Source).StrokeWeight; Visible := TBasePolyline(Source).Visible; LinePoints.Assign(TBasePolyline(Source).LinePoints); AutoUpdatePath := TBasePolyline(Source).AutoUpdatePath; end; end; procedure TBasePolyline.ZoomToPoints; var Points: array of TLatLng; i: Integer; begin if not Assigned(Collection) or not (Collection is TBasePolylines) or not Assigned(TBasePolylines(Collection).FGMLinkedComponent) or not Assigned(TBasePolylines(Collection).FGMLinkedComponent.Map) or (LinePoints.Count = 0) then Exit; SetLength(Points, CountLinePoints); for i := 0 to CountLinePoints - 1 do Points[i] := LinePoints[i].GetLatLng; TBasePolylines(Collection).FGMLinkedComponent.Map.ZoomToPoints(Points); end; procedure TBasePolyline.CenterMapTo; var LL: TLatLng; begin inherited; if Assigned(Collection) and (Collection is TLinkedComponents) and Assigned(TBasePolylines(Collection).FGMLinkedComponent) and Assigned(TBasePolylines(Collection).FGMLinkedComponent.Map) and (CountLinePoints > 0) then begin LL := TLatLng.Create; try GetCenter(LL); TBasePolylines(Collection).FGMLinkedComponent.Map.SetCenter(LL); finally FreeAndNil(LL); end; end; end; procedure TBasePolyline.ClearLinePoints; begin LinePoints.Clear; end; function TBasePolyline.ComputeArea(Radius: Real): Real; begin Result := TGeometry.ComputeArea(TBasePolylines(Collection).FGMLinkedComponent.Map, PolylineToStr, Radius); end; constructor TBasePolyline.Create(Collection: TCollection); begin inherited; FIsUpdating := False; FClickable := True; FEditable := False; FGeodesic := False; FStrokeOpacity := 1; FStrokeWeight := 2; FVisible := True; FLinePoints := TLinePoints.Create(Self, TLinePoint); FAutoUpdatePath := True; end; procedure TBasePolyline.DecodePath(EncodedPath: string; Add: Boolean); var Points: string; L,P: TStringList; i: Integer; begin if not Add then ClearLinePoints; Points := TGeometry.DecodePath(TBasePolylines(Collection).FGMLinkedComponent.Map, EncodedPath); if Points = '' then Exit; L := TStringList.Create; P := TStringList.Create; try L.Delimiter := ';'; P.Delimiter := '|'; {$IFDEF DELPHI2005} L.StrictDelimiter := True; P.StrictDelimiter := True; {$ENDIF} L.DelimitedText := Points; for i := 0 to L.Count - 1 do begin P.DelimitedText := L[i]; AddLinePoint(P[0], P[1]); end; finally if Assigned(L) then FreeAndNil(L); if Assigned(P) then FreeAndNil(P); end; end; procedure TBasePolyline.DeleteLinePoint(Index: Integer); begin LinePoints.Delete(Index); end; destructor TBasePolyline.Destroy; begin if Assigned(FLinePoints) then FreeAndNil(FLinePoints); inherited; end; function TBasePolyline.EncodePath: string; begin Result := TGeometry.EncodePath(TBasePolylines(Collection).FGMLinkedComponent.Map, PolylineToStr); end; procedure TBasePolyline.GetCenter(LL: TLatLng); const StrParams = '%s,%s'; var Params: string; begin if not Assigned(Collection) or not (Collection is TBasePolylines) or not Assigned(TBasePolylines(Collection).FGMLinkedComponent) or not Assigned(TBasePolylines(Collection).FGMLinkedComponent.Map) or not Assigned(LL) then Exit; LL.Lat := 0; LL.Lng := 0; Params := Format(StrParams, [IntToStr(IdxList), IntToStr(Index)]); if not TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).ExecuteScript('PolylineGetCenter', Params) then Exit; LL.Lat := TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).GetFloatField(PolylineForm, PolylineFormLat); LL.Lng := TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).GetFloatField(PolylineForm, PolylineFormLng); end; function TBasePolyline.GetCountLinePoints: Integer; begin Result := LinePoints.Count; end; function TBasePolyline.GetItems(I: Integer): TLinePoint; begin Result := TLinePoint(FLinePoints[i]); end; procedure TBasePolyline.GetPath; const StrParams = '%s,%s'; var Params: string; Path: string; i: Integer; L1, L2: TStringList; IsEqual: Boolean; LL: TLatLng; begin if not Assigned(Collection) or not (Collection is TBasePolylines) or not Assigned(TBasePolylines(Collection).FGMLinkedComponent) or not Assigned(TBasePolylines(Collection).FGMLinkedComponent.Map) or not FAutoUpdatePath then Exit; Params := Format(StrParams, [IntToStr(IdxList), IntToStr(Index)]); if not TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).ExecuteScript('PolylineGetPath', Params) then Exit; Path := TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).GetStringField(PolylineForm, PolylineFormPath); if Path = '' then Exit; L1 := TStringList.Create; L2 := TStringList.Create; LL := TLatLng.Create; try L1.Delimiter := ';'; L2.Delimiter := '|'; L1.DelimitedText := Path; // ES: miramos si no ha cambiado // EN: check if not have changed if LinePoints.Count = L1.Count then begin IsEqual := True; for i := 0 to L1.Count - 1 do begin L2.DelimitedText := L1[i]; LL.Lat := LL.StringToReal(L2[0]); LL.Lng := LL.StringToReal(L2[1]); if not LL.IsEqual(Items[i].GetLatLng) then begin IsEqual := False; Break; end; end; if IsEqual then begin if Assigned(LL) then FreeAndNil(LL); if Assigned(L1) then FreeAndNil(L1); if Assigned(L2) then FreeAndNil(L2); Exit; end; end; FIsUpdating := True; LinePoints.Clear; for i := 0 to L1.Count - 1 do begin L2.DelimitedText := L1[i]; if L2.Count <> 2 then Break; AddLinePoint(L2[0], L2[1]); end; finally FIsUpdating := False; if Assigned(LL) then FreeAndNil(LL); if Assigned(L1) then FreeAndNil(L1); if Assigned(L2) then FreeAndNil(L2); end; if Assigned(TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).OnPathChange) then TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).OnPathChange(TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent), Index, Self); end; function TBasePolyline.InsertLinePoint(Index: Integer; Lat, Lng: Real): TLinePoint; begin Result := LinePoints.Insert(Index); Result.Lat := Lat; Result.Lng := Lng; end; function TBasePolyline.IsLocationOnEdge(LatLng: TLatLng; Tolerance: Integer): Boolean; begin Result := TGeometry.IsLocationOnEdge(TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent), Index, LatLng, Tolerance); end; function TBasePolyline.IsLocationOnEdge(Lat, Lng: Real; Tolerance: Integer): Boolean; var LatLng: TLatLng; begin LatLng := TLatLng.Create(Lat, Lng); try Result := IsLocationOnEdge(LatLng, Tolerance); finally FreeAndNil(LatLng); end; end; procedure TBasePolyline.LinePointChanged; begin if FIsUpdating then Exit; ChangeProperties; end; procedure TBasePolyline.MoveLinePoint(CurIndex, NewIndex: Integer); begin LinePoints.Move(CurIndex, NewIndex); end; function TBasePolyline.PolylineToStr: string; var Points: array of TLatLng; i: Integer; begin Result := ''; if not Assigned(Collection) or not Assigned(TBasePolylines(Collection).FGMLinkedComponent) or not Assigned(TBasePolylines(Collection).FGMLinkedComponent.Map) then Exit; SetLength(Points, CountLinePoints); for i := 0 to LinePoints.Count - 1 do Points[i] := LinePoints[i].GetLatLng; Result := TGMGenFunc.PointsToStr(Points, TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).GetMapPrecision); end; function TBasePolyline.QueryInterface(const IID: TGUID; out Obj): HResult; const E_NOINTERFACE = HResult($80004002); begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; procedure TBasePolyline.SetClickable(const Value: Boolean); begin if FClickable = Value then Exit; FClickable := Value; ChangeProperties; if Assigned(TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnClickableChange) then TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnClickableChange( TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent), Index, Self); end; procedure TBasePolyline.SetEditable(const Value: Boolean); begin if FEditable = Value then Exit; FEditable := Value; ChangeProperties; if Assigned(TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnEditableChange) then TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnEditableChange( TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent), Index, Self); end; procedure TBasePolyline.SetGeodesic(const Value: Boolean); begin if FGeodesic = Value then Exit; FGeodesic := Value; ChangeProperties; if Assigned(TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnGeodesicChange) then TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnGeodesicChange( TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent), Index, Self); end; procedure TBasePolyline.SetPath; begin ChangeProperties; end; procedure TBasePolyline.SetStrokeOpacity(const Value: Real); begin if FStrokeOpacity = Value then Exit; FStrokeOpacity := Value; if FStrokeOpacity < 0 then FStrokeOpacity := 0; if FStrokeOpacity > 1 then FStrokeOpacity := 1; FStrokeOpacity := Trunc(FStrokeOpacity * 100) / 100; ChangeProperties; if Assigned(TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnStrokeOpacityChange) then TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnStrokeOpacityChange( TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent), Index, Self); end; procedure TBasePolyline.SetStrokeWeight(const Value: Integer); begin if FStrokeWeight = Value then Exit; FStrokeWeight := Value; if FStrokeWeight < 1 then FStrokeWeight := 1; if FStrokeWeight > 10 then FStrokeWeight := 10; ChangeProperties; if Assigned(TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnStrokeWeightChange) then TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnStrokeWeightChange( TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent), Index, Self); end; procedure TBasePolyline.SetVisible(const Value: Boolean); begin if FVisible = Value then Exit; FVisible := Value; ChangeProperties; if Assigned(TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnVisibleChange) then TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent).FOnVisibleChange( TGMBasePolyline(TBasePolylines(Collection).FGMLinkedComponent), Index, Self); end; function TBasePolyline._AddRef: Integer; begin if FOwnerInterface <> nil then Result := FOwnerInterface._AddRef else Result := -1; end; function TBasePolyline._Release: Integer; begin if FOwnerInterface <> nil then Result := FOwnerInterface._Release else Result := -1; end; { TGMBasePolyline } procedure TGMBasePolyline.EventFired(EventType: TEventType; Params: array of const); var LL: TLatLng; begin inherited; if EventType = etInfoWinCloseClick then Exit; if High(Params) <> 2 then raise Exception.Create(GetTranslateText('Número de parámetros incorrecto', Map.Language)); if (Params[0].VType <> vtExtended) or (Params[1].VType <> vtExtended) then raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language)); if Params[2].VType <> vtInteger then raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language)); if Params[2].VInteger > VisualObjects.Count - 1 then raise Exception.Create(GetTranslateText('Valor de parámetro incorrecto', Map.Language)); LL := TLatLng.Create(ControlPrecision(Params[0].VExtended^, GetMapPrecision), ControlPrecision(Params[1].VExtended^, GetMapPrecision)); try case EventType of etPolylineClick: if Assigned(FOnClick) then FOnClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]); etPolylineDblClick: if Assigned(FOnDblClick) then FOnDblClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]); etPolylineMouseDown: if Assigned(FOnMouseDown) then FOnMouseDown(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]); etPolylineMouseMove: if Assigned(FOnMouseMove) then FOnMouseMove(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]); etPolylineMouseOut: if Assigned(FOnMouseOut) then FOnMouseOut(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]); etPolylineMouseOver: if Assigned(FOnMouseOver) then FOnMouseOver(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]); etPolylineMouseUp: if Assigned(FOnMouseUp) then FOnMouseUp(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]); etPolylineRightClick: if Assigned(FOnRightClick) then FOnRightClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]); end; finally FreeAndNil(LL); end; end; function TGMBasePolyline.GetItems(I: Integer): TBasePolyline; begin Result := TBasePolyline(inherited Items[i]); end; procedure TGMBasePolyline.GetPath; var i: Integer; begin if not Assigned(Map) then Exit; for i := 0 to VisualObjects.Count - 1 do Items[i].GetPath; end; procedure TGMBasePolyline.SetPath; var i: Integer; begin if not Assigned(Map) then Exit; for i := 0 to VisualObjects.Count - 1 do Items[i].SetPath; end; { TBasePolylines } function TBasePolylines.Add: TBasePolyline; begin Result := TBasePolyline(inherited Add); end; function TBasePolylines.GetItems(I: Integer): TBasePolyline; begin Result := TBasePolyline(inherited Items[I]); end; function TBasePolylines.GetOwner: TPersistent; begin Result := TGMBasePolyline(inherited GetOwner); end; function TBasePolylines.Insert(Index: Integer): TBasePolyline; begin Result := TBasePolyline(inherited Insert(Index)); end; procedure TBasePolylines.SetItems(I: Integer; const Value: TBasePolyline); begin inherited SetItem(I, Value); end; { TCurveLine } constructor TCurveLine.Create; begin inherited; FResolution := 0.1; FHorizontal := True; FMultiplier := 1; FActive := False; end; procedure TCurveLine.SetActive(const Value: Boolean); begin if Value = FActive then Exit; FActive := Value; if Assigned(FOnChange) then FOnChange(Self); end; procedure TCurveLine.SetHorizontal(const Value: Boolean); begin if Value = FHorizontal then Exit; FHorizontal := Value; if Assigned(FOnChange) then FOnChange(Self); end; procedure TCurveLine.SetMultiplier(const Value: Integer); begin if Value = FMultiplier then Exit; FMultiplier := Value; if Assigned(FOnChange) then FOnChange(Self); end; procedure TCurveLine.SetResolution(const Value: Real); begin if Value = FResolution then Exit; FResolution := Value; if FResolution < 0 then FResolution := 0; if FResolution > 1 then FResolution := 1; FResolution := Round(FResolution * 100) / 100; if Assigned(FOnChange) then FOnChange(Self); end; end.
unit h_Net; interface uses winApi.wininet, IdFTP, IdFTPCommon, v_env, Classes, Windows, SysUtils, WinSock, StdCtrls, IdTCPConnection, IdTCPClient, IdSSLOpenSSL, IdExplicitTLSClientServerBase; type conncheckKind = (cckFullVerification, cckPartialVerification); type TNet = class(TObject) public class function ConnStatus(cck: conncheckKind = cckFullVerification): boolean; class procedure ConfigFTP(var cmpFTP: tidFTP); class function getAllPc: TStringlist; end; var m_ftp: tidFTP; m_Connect_Status: boolean; implementation { TNet } class procedure TNet.ConfigFTP(var cmpFTP: tidFTP); begin if cmpFTP = nil then begin cmpFTP := tidFTP.Create(nil); cmpFTP.Host := TEnv.TServerFTP.Host; cmpFTP.Username := TEnv.TServerFTP.user; cmpFTP.Password := TEnv.TServerFTP.Password; cmpFTP.Port := 21; cmpFTP.TransferType := ftBinary; cmpFTP.CurrentTransferMode := dmStream; cmpFTP.ReadTimeout := 1000000; cmpFTP.TransferTimeout := 1000000; cmpFTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(cmpFTP); cmpFTP.UseTLS := utUseExplicitTLS; cmpFTP.DataPortProtection := ftpdpsPrivate; cmpFTP.Passive := true; cmpFTP.NATKeepAlive := TIdFTPKeepAlive.Create; cmpFTP.NATKeepAlive.IdleTimeMS := 600000; cmpFTP.NATKeepAlive.IntervalMS := 5000; if not cmpFTP.connected then begin cmpFTP.disConnect; cmpFTP.Connect; end; end; end; class function TNet.ConnStatus(cck: conncheckKind = cckFullVerification): boolean; var connflags: cardinal; begin case cck of cckFullVerification: begin if InternetGetConnectedState(@connflags, 0) then m_Connect_Status := InternetCheckConnection(PwideChar('http://www.google.com.br'), 1, 0) else m_Connect_Status := false; end; cckPartialVerification: ; end; result := m_Connect_Status; end; class function TNet.getAllPc: TStringlist; type PNetResourceArray = ^TNetResourceArray; TNetResourceArray = array [0 .. 100] of TNetResource; function CreateNetResourceList(ResourceType: DWord; NetResource: PNetResource; out Entries: DWord; out List: PNetResourceArray): boolean; var EnumHandle: THandle; BufSize: DWord; Res: DWord; begin result := false; List := Nil; Entries := 0; if WNetOpenEnum(RESOURCE_GLOBALNET, ResourceType, 0, NetResource, EnumHandle) = NO_ERROR then begin try BufSize := $4000; // 16 kByte GetMem(List, BufSize); try repeat Entries := DWord(-1); FillChar(List^, BufSize, 0); Res := WNetEnumResource(EnumHandle, Entries, List, BufSize); if Res = ERROR_MORE_DATA then begin ReAllocMem(List, BufSize); end; until Res <> ERROR_MORE_DATA; result := Res = NO_ERROR; if not result then begin FreeMem(List); List := Nil; Entries := 0; end; except FreeMem(List); raise; end; finally WNetCloseEnum(EnumHandle); end; end; end; procedure ScanNetworkResources(ResourceType, DisplayType: DWord; List: TStringlist); procedure ScanLevel(NetResource: PNetResource); var Entries: DWord; NetResourceList: PNetResourceArray; i: Integer; begin if CreateNetResourceList(ResourceType, NetResource, Entries, NetResourceList) then try for i := 0 to Integer(Entries) - 1 do begin if (DisplayType = RESOURCEDISPLAYTYPE_GENERIC) or (NetResourceList[i].dwDisplayType = DisplayType) then begin List.addObject(NetResourceList[i].lpRemoteName, Pointer(NetResourceList[i].dwDisplayType)); end; if (NetResourceList[i].dwUsage and RESOURCEUSAGE_CONTAINER) <> 0 then ScanLevel(@NetResourceList[i]); end; finally FreeMem(NetResourceList); end; end; begin ScanLevel(Nil); end; var ListPC: TStringlist; begin ListPC := TStringlist.Create; ScanNetworkResources(RESOURCETYPE_DISK, RESOURCEDISPLAYTYPE_SERVER, ListPC); result := ListPC; end; end.
//Cr ́eese un programa que solicite al usuario dos valores enteros positivos y calcule utilizando el algoritmo de Euclides su m ́aximo com ́un divisor y su m ́ınimo com ́un m ́ultiplo. El programa debe sacar ambos valores por pantalla. program Euclides; var a,b,aux:integer; function euclides(a,b:integer):integer; var aux:integer; begin while (a mod b)<>0 do begin aux:=b; b:=(a mod b); a:=aux; end; euclides:=b; end; begin writeln(); write('Introduzca el primer entero: '); readln(a); write('Introduzca el segundo entero: '); readln(b); writeln(euclides(a,b)); end.
object Preferences: TPreferences Left = 206 Top = 128 HelpContext = 2400 BorderStyle = bsDialog BorderWidth = 6 Caption = 'Preferences' ClientHeight = 162 ClientWidth = 440 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poScreenCenter OnClose = FormClose OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object lLanguage: TLabel Left = 236 Top = 16 Width = 51 Height = 13 Caption = 'Language:' end object lScan: TLabel Left = 290 Top = 293 Width = 92 Height = 13 Alignment = taRightJustify Caption = 'Time for scan flags:' Enabled = False Visible = False end object bCancel: TButton Left = 280 Top = 138 Width = 74 Height = 23 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 1 end object bHelp: TButton Left = 360 Top = 138 Width = 75 Height = 23 Caption = 'Help' TabOrder = 2 OnClick = bHelpClick end object cbLanguage: TComboBox Left = 298 Top = 13 Width = 137 Height = 21 Style = csDropDownList ItemHeight = 13 TabOrder = 3 Items.Strings = ( 'English ('#1040#1085#1075#1083#1080#1081#1089#1082#1080#1081')' 'Russian ('#1056#1091#1089#1089#1082#1080#1081')') end object seTime: TxSpinEdit Left = 390 Top = 289 Width = 49 Height = 22 AutoSize = False Enabled = False MaxValue = 60 MinValue = 1 TabOrder = 4 Value = 1 Visible = False end object gbColors: TGroupBox Left = 8 Top = 8 Width = 209 Height = 121 Caption = ' Colors ' TabOrder = 5 object Shape1: TShape Left = 11 Top = 24 Width = 73 Height = 9 OnMouseUp = Shape1MouseUp end object lBackColor: TLabel Left = 99 Top = 21 Width = 52 Height = 13 Caption = 'Back Color' end object Shape2: TShape Left = 11 Top = 40 Width = 73 Height = 9 OnMouseUp = Shape2MouseUp end object lForeColor: TLabel Left = 99 Top = 38 Width = 48 Height = 13 Caption = 'Fore Color' end object DefaultColors: TButton Left = 104 Top = 65 Width = 97 Height = 21 Caption = 'Default Colors' TabOrder = 0 OnClick = DefaultColorsClick end object sbSystemColors: TButton Left = 104 Top = 89 Width = 97 Height = 21 Caption = 'System Colors' TabOrder = 1 OnClick = sbSystemColorsClick end object cbColor: TComboBox Left = 8 Top = 89 Width = 89 Height = 21 Style = csDropDownList ItemHeight = 13 TabOrder = 2 OnChange = tbMainChange Items.Strings = ( 'Gauge' 'Logger' 'BadWazoo' 'OldMail7' 'OldMail14' 'OldMail21' 'OldMail28') end end object cbStandartFlags: TCheckBox Left = 225 Top = 264 Width = 216 Height = 17 Caption = 'Use Standart Flags' TabOrder = 6 Visible = False end object bOK: TButton Left = 200 Top = 138 Width = 75 Height = 23 Caption = 'O&K' Default = True ModalResult = 1 TabOrder = 0 end object gbBOptions: TGroupBox Left = 232 Top = 36 Width = 201 Height = 93 Caption = 'Boolean Options' TabOrder = 7 object clOptions: TCheckListBox Left = 3 Top = 18 Width = 192 Height = 66 BorderStyle = bsNone Color = clBtnFace Ctl3D = True ItemHeight = 13 Items.Strings = ( 'Always In Tray' 'Use `Space'#39' to Flush Timeout' 'Show Balloon Tooltips' 'Show Balloon Minimized' 'Create SESSION.OK Flag' 'Create SESSION.FAIL Flag' 'Disable HtmlHelp') ParentCtl3D = False TabOrder = 0 end end object cdColorSelect: TColorDialog Left = 172 Top = 24 end end
unit ncEncBlockciphers; // To disable as much of RTTI as possible (Delphi 2009/2010), // Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position {$IF CompilerVersion >= 21.0} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$ENDIF} interface uses System.Classes, System.Sysutils, ncEnccrypt2; { ****************************************************************************** } { Base type definition for 64 bit block ciphers } type TncEnc_blockcipher64 = class(TncEnc_blockcipher) private IV, CV: array [0 .. 7] of byte; procedure IncCounter; public class function GetBlockSize: integer; override; { Get the block size of the cipher (in bits) } procedure Reset; override; { Reset any stored chaining information } procedure Burn; override; { Clear all stored key information and chaining information } procedure SetIV(const Value); override; { Sets the IV to Value and performs a reset } procedure GetIV(var Value); override; { Returns the current chaining information, not the actual IV } procedure Init(const Key; Size: longword; InitVector: pointer); override; { Do key setup based on the data in Key, size is in bits } procedure EncryptCBC(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data using the CBC method of encryption } procedure DecryptCBC(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data using the CBC method of decryption } procedure EncryptCFB8bit(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data using the CFB (8 bit) method of encryption } procedure DecryptCFB8bit(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data using the CFB (8 bit) method of decryption } procedure EncryptCFBblock(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data using the CFB (block) method of encryption } procedure DecryptCFBblock(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data using the CFB (block) method of decryption } procedure EncryptOFB(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data using the OFB method of encryption } procedure DecryptOFB(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data using the OFB method of decryption } procedure EncryptCTR(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data using the CTR method of encryption } procedure DecryptCTR(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data using the CTR method of decryption } end; { ****************************************************************************** } { Base type definition for 128 bit block ciphers } type TncEnc_blockcipher128 = class(TncEnc_blockcipher) private IV, CV: array [0 .. 15] of byte; procedure IncCounter; public class function GetBlockSize: integer; override; { Get the block size of the cipher (in bits) } procedure Reset; override; { Reset any stored chaining information } procedure Burn; override; { Clear all stored key information and chaining information } procedure SetIV(const Value); override; { Sets the IV to Value and performs a reset } procedure GetIV(var Value); override; { Returns the current chaining information, not the actual IV } procedure Init(const Key; Size: longword; InitVector: pointer); override; { Do key setup based on the data in Key, size is in bits } procedure EncryptCBC(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data using the CBC method of encryption } procedure DecryptCBC(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data using the CBC method of decryption } procedure EncryptCFB8bit(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data using the CFB (8 bit) method of encryption } procedure DecryptCFB8bit(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data using the CFB (8 bit) method of decryption } procedure EncryptCFBblock(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data using the CFB (block) method of encryption } procedure DecryptCFBblock(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data using the CFB (block) method of decryption } procedure EncryptOFB(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data using the OFB method of encryption } procedure DecryptOFB(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data using the OFB method of decryption } procedure EncryptCTR(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data using the CTR method of encryption } procedure DecryptCTR(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data using the CTR method of decryption } end; implementation { ** TncEnc_blockcipher64 ******************************************************** } procedure TncEnc_blockcipher64.IncCounter; var i: integer; begin Inc(CV[7]); i := 7; while (i > 0) and (CV[i] = 0) do begin Inc(CV[i - 1]); Dec(i); end; end; class function TncEnc_blockcipher64.GetBlockSize: integer; begin Result := 64; end; procedure TncEnc_blockcipher64.Init(const Key; Size: longword; InitVector: pointer); begin inherited Init(Key, Size, InitVector); InitKey(Key, Size); if InitVector = nil then begin FillChar(IV, 8, 0); EncryptECB(IV, IV); Reset; end else begin Move(InitVector^, IV, 8); Reset; end; end; procedure TncEnc_blockcipher64.SetIV(const Value); begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); Move(Value, IV, 8); Reset; end; procedure TncEnc_blockcipher64.GetIV(var Value); begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); Move(CV, Value, 8); end; procedure TncEnc_blockcipher64.Reset; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized') else Move(IV, CV, 8); end; procedure TncEnc_blockcipher64.Burn; begin FillChar(IV, 8, $FF); FillChar(CV, 8, $FF); inherited Burn; end; procedure TncEnc_blockcipher64.EncryptCBC(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: pointer; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 8) do begin Move(p1^, p2^, 8); XorBlock(p2^, CV, 8); EncryptECB(p2^, p2^); Move(p2^, CV, 8); p1 := pointer(longword(p1) + 8); p2 := pointer(longword(p2) + 8); end; if (Size mod 8) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 8); XorBlock(p2^, CV, Size mod 8); end; end; procedure TncEnc_blockcipher64.DecryptCBC(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: pointer; Temp: array [0 .. 7] of byte; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 8) do begin Move(p1^, p2^, 8); Move(p1^, Temp, 8); DecryptECB(p2^, p2^); XorBlock(p2^, CV, 8); Move(Temp, CV, 8); p1 := pointer(longword(p1) + 8); p2 := pointer(longword(p2) + 8); end; if (Size mod 8) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 8); XorBlock(p2^, CV, Size mod 8); end; end; procedure TncEnc_blockcipher64.EncryptCFB8bit(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: Pbyte; Temp: array [0 .. 7] of byte; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to Size do begin EncryptECB(CV, Temp); p2^ := p1^ xor Temp[0]; Move(CV[1], CV[0], 8 - 1); CV[7] := p2^; Inc(p1); Inc(p2); end; end; procedure TncEnc_blockcipher64.DecryptCFB8bit(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: Pbyte; TempByte: byte; Temp: array [0 .. 7] of byte; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to Size do begin TempByte := p1^; EncryptECB(CV, Temp); p2^ := p1^ xor Temp[0]; Move(CV[1], CV[0], 8 - 1); CV[7] := TempByte; Inc(p1); Inc(p2); end; end; procedure TncEnc_blockcipher64.EncryptCFBblock(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: Pbyte; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 8) do begin EncryptECB(CV, CV); Move(p1^, p2^, 8); XorBlock(p2^, CV, 8); Move(p2^, CV, 8); p1 := pointer(longword(p1) + 8); p2 := pointer(longword(p2) + 8); end; if (Size mod 8) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 8); XorBlock(p2^, CV, Size mod 8); end; end; procedure TncEnc_blockcipher64.DecryptCFBblock(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: Pbyte; Temp: array [0 .. 7] of byte; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 8) do begin Move(p1^, Temp, 8); EncryptECB(CV, CV); Move(p1^, p2^, 8); XorBlock(p2^, CV, 8); Move(Temp, CV, 8); p1 := pointer(longword(p1) + 8); p2 := pointer(longword(p2) + 8); end; if (Size mod 8) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 8); XorBlock(p2^, CV, Size mod 8); end; end; procedure TncEnc_blockcipher64.EncryptOFB(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: pointer; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 8) do begin EncryptECB(CV, CV); Move(p1^, p2^, 8); XorBlock(p2^, CV, 8); p1 := pointer(longword(p1) + 8); p2 := pointer(longword(p2) + 8); end; if (Size mod 8) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 8); XorBlock(p2^, CV, Size mod 8); end; end; procedure TncEnc_blockcipher64.DecryptOFB(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: pointer; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 8) do begin EncryptECB(CV, CV); Move(p1^, p2^, 8); XorBlock(p2^, CV, 8); p1 := pointer(longword(p1) + 8); p2 := pointer(longword(p2) + 8); end; if (Size mod 8) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 8); XorBlock(p2^, CV, Size mod 8); end; end; procedure TncEnc_blockcipher64.EncryptCTR(const Indata; var Outdata; Size: longword); var Temp: array [0 .. 7] of byte; i: longword; p1, p2: pointer; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 8) do begin EncryptECB(CV, Temp); IncCounter; Move(p1^, p2^, 8); XorBlock(p2^, Temp, 8); p1 := pointer(longword(p1) + 8); p2 := pointer(longword(p2) + 8); end; if (Size mod 8) <> 0 then begin EncryptECB(CV, Temp); IncCounter; Move(p1^, p2^, Size mod 8); XorBlock(p2^, Temp, Size mod 8); end; end; procedure TncEnc_blockcipher64.DecryptCTR(const Indata; var Outdata; Size: longword); var Temp: array [0 .. 7] of byte; i: longword; p1, p2: pointer; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 8) do begin EncryptECB(CV, Temp); IncCounter; Move(p1^, p2^, 8); XorBlock(p2^, Temp, 8); p1 := pointer(longword(p1) + 8); p2 := pointer(longword(p2) + 8); end; if (Size mod 8) <> 0 then begin EncryptECB(CV, Temp); IncCounter; Move(p1^, p2^, Size mod 8); XorBlock(p2^, Temp, Size mod 8); end; end; { ** TncEnc_blockcipher128 ******************************************************** } procedure TncEnc_blockcipher128.IncCounter; var i: integer; begin Inc(CV[15]); i := 15; while (i > 0) and (CV[i] = 0) do begin Inc(CV[i - 1]); Dec(i); end; end; class function TncEnc_blockcipher128.GetBlockSize: integer; begin Result := 128; end; procedure TncEnc_blockcipher128.Init(const Key; Size: longword; InitVector: pointer); begin inherited Init(Key, Size, InitVector); InitKey(Key, Size); if InitVector = nil then begin FillChar(IV, 16, 0); EncryptECB(IV, IV); Reset; end else begin Move(InitVector^, IV, 16); Reset; end; end; procedure TncEnc_blockcipher128.SetIV(const Value); begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); Move(Value, IV, 16); Reset; end; procedure TncEnc_blockcipher128.GetIV(var Value); begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); Move(CV, Value, 16); end; procedure TncEnc_blockcipher128.Reset; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized') else Move(IV, CV, 16); end; procedure TncEnc_blockcipher128.Burn; begin FillChar(IV, 16, $FF); FillChar(CV, 16, $FF); inherited Burn; end; procedure TncEnc_blockcipher128.EncryptCBC(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: pointer; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 16) do begin Move(p1^, p2^, 16); XorBlock(p2^, CV, 16); EncryptECB(p2^, p2^); Move(p2^, CV, 16); p1 := pointer(longword(p1) + 16); p2 := pointer(longword(p2) + 16); end; if (Size mod 16) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 16); XorBlock(p2^, CV, Size mod 16); end; end; procedure TncEnc_blockcipher128.DecryptCBC(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: pointer; Temp: array [0 .. 15] of byte; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 16) do begin Move(p1^, p2^, 16); Move(p1^, Temp, 16); DecryptECB(p2^, p2^); XorBlock(p2^, CV, 16); Move(Temp, CV, 16); p1 := pointer(longword(p1) + 16); p2 := pointer(longword(p2) + 16); end; if (Size mod 16) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 16); XorBlock(p2^, CV, Size mod 16); end; end; procedure TncEnc_blockcipher128.EncryptCFB8bit(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: Pbyte; Temp: array [0 .. 15] of byte; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to Size do begin EncryptECB(CV, Temp); p2^ := p1^ xor Temp[0]; Move(CV[1], CV[0], 15); CV[15] := p2^; Inc(p1); Inc(p2); end; end; procedure TncEnc_blockcipher128.DecryptCFB8bit(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: Pbyte; TempByte: byte; Temp: array [0 .. 15] of byte; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to Size do begin TempByte := p1^; EncryptECB(CV, Temp); p2^ := p1^ xor Temp[0]; Move(CV[1], CV[0], 15); CV[15] := TempByte; Inc(p1); Inc(p2); end; end; procedure TncEnc_blockcipher128.EncryptCFBblock(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: Pbyte; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 16) do begin EncryptECB(CV, CV); Move(p1^, p2^, 16); XorBlock(p2^, CV, 16); Move(p2^, CV, 16); p1 := pointer(longword(p1) + 16); p2 := pointer(longword(p2) + 16); end; if (Size mod 16) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 16); XorBlock(p2^, CV, Size mod 16); end; end; procedure TncEnc_blockcipher128.DecryptCFBblock(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: Pbyte; Temp: array [0 .. 15] of byte; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 16) do begin Move(p1^, Temp, 16); EncryptECB(CV, CV); Move(p1^, p2^, 16); XorBlock(p2^, CV, 16); Move(Temp, CV, 16); p1 := pointer(longword(p1) + 16); p2 := pointer(longword(p2) + 16); end; if (Size mod 16) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 16); XorBlock(p2^, CV, Size mod 16); end; end; procedure TncEnc_blockcipher128.EncryptOFB(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: pointer; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 16) do begin EncryptECB(CV, CV); Move(p1^, p2^, 16); XorBlock(p2^, CV, 16); p1 := pointer(longword(p1) + 16); p2 := pointer(longword(p2) + 16); end; if (Size mod 16) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 16); XorBlock(p2^, CV, Size mod 16); end; end; procedure TncEnc_blockcipher128.DecryptOFB(const Indata; var Outdata; Size: longword); var i: longword; p1, p2: pointer; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 16) do begin EncryptECB(CV, CV); Move(p1^, p2^, 16); XorBlock(p2^, CV, 16); p1 := pointer(longword(p1) + 16); p2 := pointer(longword(p2) + 16); end; if (Size mod 16) <> 0 then begin EncryptECB(CV, CV); Move(p1^, p2^, Size mod 16); XorBlock(p2^, CV, Size mod 16); end; end; procedure TncEnc_blockcipher128.EncryptCTR(const Indata; var Outdata; Size: longword); var Temp: array [0 .. 15] of byte; i: longword; p1, p2: pointer; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 16) do begin EncryptECB(CV, Temp); IncCounter; Move(p1^, p2^, 16); XorBlock(p2^, Temp, 16); p1 := pointer(longword(p1) + 16); p2 := pointer(longword(p2) + 16); end; if (Size mod 16) <> 0 then begin EncryptECB(CV, Temp); IncCounter; Move(p1^, p2^, Size mod 16); XorBlock(p2^, Temp, Size mod 16); end; end; procedure TncEnc_blockcipher128.DecryptCTR(const Indata; var Outdata; Size: longword); var Temp: array [0 .. 15] of byte; i: longword; p1, p2: pointer; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); p1 := @Indata; p2 := @Outdata; for i := 1 to (Size div 16) do begin EncryptECB(CV, Temp); IncCounter; Move(p1^, p2^, 16); XorBlock(p2^, Temp, 16); p1 := pointer(longword(p1) + 16); p2 := pointer(longword(p2) + 16); end; if (Size mod 16) <> 0 then begin EncryptECB(CV, Temp); IncCounter; Move(p1^, p2^, Size mod 16); XorBlock(p2^, Temp, Size mod 16); end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} /// <summary>Unit that holds functionality relative to process MIME parts from/to a network message</summary> unit System.Net.Mime; interface {$SCOPEDENUMS ON} uses System.Classes, System.Sysutils, System.Generics.Collections, System.Generics.Defaults; type /// <summary>Class to manage multipart form data</summary> TMultipartFormData = class (TObject) private FOwnsOutputStream: Boolean; FBoundary: string; FStream: TMemoryStream; FLastBoundaryWrited: Boolean; function GetMimeTypeHeader: string; function GenerateBoundary: string; procedure WriteStringLn(const AString: string); function GetStream: TMemoryStream; procedure AdjustLastBoundary; public /// <summary>Create a multipart form data object</summary> constructor Create(AOwnsOutputStream: Boolean = True); destructor Destroy; override; /// <summary>Add a form data field</summary> procedure AddField(const AField, AValue: string); /// <summary>Add a form data stream</summary> procedure AddStream(const AField: string; AStream: TStream; const AFileName: string = ''; const AContentType: string = ''); /// <summary>Add a form data file</summary> procedure AddFile(const AField, AFilePath: string; const AContentType: string = ''); /// <summary>Add a form data bytes</summary> procedure AddBytes(const AField: string; const ABytes: TBytes; const AFileName: string = ''; const AContentType: string = ''); /// <summary>Property to access to the stream which will be sent</summary> property Stream: TMemoryStream read GetStream; /// <summary>Return mime type to be sent in http headers</summary> property MimeTypeHeader: string read GetMimeTypeHeader; end; TMimeTypes = class (TObject) public type TKind = (Undefined, Binary, Text); TIterateFunc = reference to function (const AExt, AType: string; AKind: TKind): Boolean; private type TInfo = class FExt: string; FType: string; FKind: TKind; end; strict private class var FLock: TObject; FDefault: TMimeTypes; class constructor Create; class destructor Destroy; class function GetDefault: TMimeTypes; static; private FExtDict: TDictionary<string, TInfo>; FTypeDict: TDictionary<string, TInfo>; FInfos: TObjectDictionary<string, TInfo>; function NormalizeExt(const AExt: string): string; public constructor Create; destructor Destroy; override; function GetFileInfo(const AFileName: string; out AType: string; out AKind: TKind): Boolean; function GetExtInfo(const AExt: string; out AType: string; out AKind: TKind): Boolean; function GetTypeInfo(const AType: string; out AExt: string; out AKind: TKind): Boolean; procedure Clear; procedure AddDefTypes; procedure AddOSTypes; procedure AddType(const AExt, AType: string; AKind: TKind = TKind.Undefined; AIgnoreDups: Boolean = False); procedure ForAll(const AExtMask, ATypeMask: string; AFunc: TIterateFunc); procedure ForExts(const AExtMask: string; AFunc: TIterateFunc); procedure ForTypes(const ATypeMask: string; AFunc: TIterateFunc); class property Default: TMimeTypes read GetDefault; end; TAcceptValueItem = class (TObject) private FName: string; FWeight: Double; FOrder: Integer; FParams: TStrings; function GetParams: TStrings; protected procedure Parse; virtual; public destructor Destroy; override; property Name: string read FName; property Weight: Double read FWeight; property Order: Integer read FOrder; property Params: TStrings read GetParams; end; TAcceptValueListBase<T: TAcceptValueItem, constructor> = class (TObject) public type TAcceptFunc = reference to function (const AName: string; AWeight: Double; AItem: T): Boolean; private type TMatchMode = (Forward, Reverse, Intersect); private FInvariant: TFormatSettings; FItems: TObjectList<T>; FUpdates: Integer; function GetCount: Integer; function GetNames(AIndex: Integer): string; function GetWeights(AIndex: Integer): Double; function GetItems(AIndex: Integer): T; function InternalNegotiate(AAcceptList: TAcceptValueListBase<T>; AAcceptFunc: TAcceptFunc; var AMode: TMatchMode; out AWeight: Double): string; public constructor Create; overload; constructor Create(const AValue: string); overload; destructor Destroy; override; function GetEnumerator: TEnumerator<T>; procedure BeginUpdate; procedure EndUpdate; procedure Clear; procedure Delete(AIndex: Integer); procedure Add(const AName: string; AWeight: Double = 1; AExtra: TStrings = nil); procedure Assign(const AAcceptList: TAcceptValueListBase<T>); procedure Parse(const AValue: string); function ToString: string; override; function Negotiate(const AAcceptList: TAcceptValueListBase<T>; out AWeight: Double; AAcceptFunc: TAcceptFunc): string; overload; function Negotiate(const AAcceptList: string; out AWeight: Double; AAcceptFunc: TAcceptFunc): string; overload; procedure Intersect(const AAcceptList: TAcceptValueListBase<T>); class function CompareWeights(AWeight1, AWeight2: Double): Integer; static; property Count: Integer read GetCount; property Names[AIndex: Integer]: string read GetNames; default; property Weights[AIndex: Integer]: Double read GetWeights; property Items[AIndex: Integer]: T read GetItems; end; TAcceptValueList = TAcceptValueListBase<TAcceptValueItem>; THeaderValueList = class (TObject) private type TFlag = (Quoted, KeyOnly); TFlags = set of TFlag; TItem = record FName, FValue: string; FFlags: TFlags; end; private FItems: TList<TItem>; FSubject: string; function GetNames(AIndex: Integer): string; function GetValue(const AName: string): string; function GetValues(AIndex: Integer): string; function IndexOfName(const AName: string): Integer; procedure Add(const AItem: TItem); overload; function GetCount: Integer; public constructor Create; overload; constructor Create(const AValue: string); overload; destructor Destroy; override; procedure Clear; procedure Delete(AIndex: Integer); procedure Add(const AName: string); overload; procedure Add(const AName, AValue: string; AQuoteVal: Boolean = True); overload; procedure Assign(const AValueList: THeaderValueList); procedure Parse(const AValue: string); function ToString: string; override; procedure Merge(const AValueList: THeaderValueList); overload; procedure Merge(const AValue: string); overload; property Count: Integer read GetCount; property Subject: string read FSubject write FSubject; property Names[AIndex: Integer]: string read GetNames; property Values[AIndex: Integer]: string read GetValues; property Value[const AName: string]: string read GetValue; default; end; // -------------------------------------------------------------------------------- // // -------------------------------------------------------------------------------- // implementation uses {$IFDEF MACOS} Macapi.CoreFoundation, {$ENDIF} {$IFDEF MSWINDOWS} Winapi.Windows, System.Win.Registry, {$ENDIF} {$IFDEF POSIX} System.IOUtils, {$ENDIF} System.Masks, System.NetConsts; { TMultipartFormData } constructor TMultipartFormData.Create(AOwnsOutputStream: Boolean); begin inherited Create; FOwnsOutputStream := AOwnsOutputStream; FBoundary := GenerateBoundary; FStream := TMemoryStream.Create; end; destructor TMultipartFormData.Destroy; begin if FOwnsOutputStream then FStream.Free else // Check that last boundary is written GetStream; inherited; end; procedure TMultipartFormData.AddField(const AField, AValue: string); begin AdjustLastBoundary; WriteStringLn('--' + FBoundary); // We need 2 line breaks here WriteStringLn(sContentDisposition + ': form-data; name="' + AField + '"' + #13#10); // do not localize WriteStringLn(AValue); end; procedure TMultipartFormData.AddStream(const AField: string; AStream: TStream; const AFileName: string; const AContentType: string); var LLine, LType: string; LKind: TMimeTypes.TKind; begin AdjustLastBoundary; WriteStringLn('--' + FBoundary); LLine := sContentDisposition + ': form-data; name="' + AField + '"'; // do not localize if AFileName <> '' then LLine := LLine + '; filename="' + AFileName + '"'; // do not localize WriteStringLn(LLine); LType := AContentType; if LType = '' then TMimeTypes.Default.GetFileInfo(AFileName, LType, LKind); // We need 2 line breaks here WriteStringLn(sContentType + ': ' + LType + #13#10); FStream.CopyFrom(AStream, 0); WriteStringLn(''); end; procedure TMultipartFormData.AddFile(const AField, AFilePath: string; const AContentType: string); var LFileStream: TFileStream; begin LFileStream := TFileStream.Create(AFilePath, fmOpenRead or fmShareDenyWrite); try AddStream(AField, LFileStream, ExtractFileName(AFilePath), AContentType); finally LFileStream.Free; end; end; procedure TMultipartFormData.AddBytes(const AField: string; const ABytes: TBytes; const AFileName, AContentType: string); var LBytesStream: TBytesStream; begin LBytesStream := TBytesStream.Create(ABytes); try AddStream(AField, LBytesStream, AFileName, AContentType); finally LBytesStream.Free; end; end; procedure TMultipartFormData.AdjustLastBoundary; begin if FLastBoundaryWrited then begin FStream.Position := FStream.Size - (Length(FBoundary) + 4); FLastBoundaryWrited := False; end; end; function TMultipartFormData.GetMimeTypeHeader: string; begin Result := 'multipart/form-data; boundary=' + FBoundary; // do not localize end; function TMultipartFormData.GetStream: TMemoryStream; begin if not FLastBoundaryWrited then begin WriteStringLn('--' + FBoundary + '--'); FLastBoundaryWrited := True; end; Result := FStream; end; procedure TMultipartFormData.WriteStringLn(const AString: string); var Buff: TBytes; begin Buff := TEncoding.UTF8.GetBytes(AString + #13#10); FStream.WriteBuffer(Buff, Length(Buff)); end; function TMultipartFormData.GenerateBoundary: string; begin Randomize; Result := '-------Embt-Boundary--' + IntToHex(Random(MaxInt), 8) + IntToHex(Random(MaxInt), 8); // do not localize end; { TMimeTypes } constructor TMimeTypes.Create; begin inherited Create; FExtDict := TDictionary<string, TInfo>.Create(1024); FTypeDict := TDictionary<string, TInfo>.Create(1024); FInfos := TObjectDictionary<string, TInfo>.Create([doOwnsValues], 1024); end; destructor TMimeTypes.Destroy; begin Clear; FTypeDict.Free; FExtDict.Free; FInfos.Free; inherited Destroy; end; class function TMimeTypes.GetDefault: TMimeTypes; var LMime: TMimeTypes; begin if FDefault = nil then begin TMonitor.Enter(FLock); try if FDefault = nil then begin LMime := TMimeTypes.Create; LMime.AddDefTypes; LMime.AddOSTypes; FDefault := LMime; end; finally TMonitor.Exit(FLock); end; end; Result := FDefault; end; class constructor TMimeTypes.Create; begin FLock := TObject.Create; end; class destructor TMimeTypes.Destroy; begin FreeAndNil(FDefault); FreeAndNil(FLock); end; procedure TMimeTypes.AddDefTypes; begin {$REGION 'MIME CONST'} AddType('ez', 'application/andrew-inset'); // do not localize AddType('aw', 'application/applixware'); // do not localize AddType('atom', 'application/atom+xml', TMimeTypes.TKind.Text); // do not localize AddType('atomcat', 'application/atomcat+xml', TMimeTypes.TKind.Text); // do not localize AddType('atomsvc', 'application/atomsvc+xml', TMimeTypes.TKind.Text); // do not localize AddType('bson', 'application/bson', TMimeTypes.TKind.Binary); // do not localize AddType('ccxml', 'application/ccxml+xml', TMimeTypes.TKind.Text); // do not localize AddType('cdmia', 'application/cdmi-capability'); // do not localize AddType('cdmic', 'application/cdmi-container'); // do not localize AddType('cdmid', 'application/cdmi-domain'); // do not localize AddType('cdmio', 'application/cdmi-object'); // do not localize AddType('cdmiq', 'application/cdmi-queue'); // do not localize AddType('cu', 'application/cu-seeme'); // do not localize AddType('davmount', 'application/davmount+xml', TMimeTypes.TKind.Text); // do not localize AddType('dbk', 'application/docbook+xml', TMimeTypes.TKind.Text); // do not localize AddType('dssc', 'application/dssc+der'); // do not localize AddType('xdssc', 'application/dssc+xml', TMimeTypes.TKind.Text); // do not localize AddType('ecma', 'application/ecmascript', TMimeTypes.TKind.Text); // do not localize AddType('emma', 'application/emma+xml', TMimeTypes.TKind.Text); // do not localize AddType('epub', 'application/epub+zip', TMimeTypes.TKind.Binary); // do not localize AddType('exi', 'application/exi'); // do not localize AddType('pfr', 'application/font-tdpfr'); // do not localize AddType('gml', 'application/gml+xml', TMimeTypes.TKind.Text); // do not localize AddType('gpx', 'application/gpx+xml', TMimeTypes.TKind.Text); // do not localize AddType('gxf', 'application/gxf'); // do not localize AddType('stk', 'application/hyperstudio'); // do not localize AddType('ink', 'application/inkml+xml', TMimeTypes.TKind.Text); // do not localize AddType('inkml', 'application/inkml+xml', TMimeTypes.TKind.Text); // do not localize AddType('ipfix', 'application/ipfix'); // do not localize AddType('jar', 'application/java-archive', TMimeTypes.TKind.Binary); // do not localize AddType('ser', 'application/java-serialized-object', TMimeTypes.TKind.Binary); // do not localize AddType('class', 'application/java-vm', TMimeTypes.TKind.Binary); // do not localize AddType('js', 'application/javascript', TMimeTypes.TKind.Text); // do not localize AddType('json', 'application/json', TMimeTypes.TKind.Text); // do not localize AddType('map', 'application/json', TMimeTypes.TKind.Text); // do not localize AddType('jsonml', 'application/jsonml+json', TMimeTypes.TKind.Text); // do not localize AddType('lostxml', 'application/lost+xml', TMimeTypes.TKind.Text); // do not localize AddType('hqx', 'application/mac-binhex40'); // do not localize AddType('cpt', 'application/mac-compactpro'); // do not localize AddType('mads', 'application/mads+xml', TMimeTypes.TKind.Text); // do not localize AddType('mrc', 'application/marc'); // do not localize AddType('mrcx', 'application/marcxml+xml', TMimeTypes.TKind.Text); // do not localize AddType('ma', 'application/mathematica'); // do not localize AddType('nb', 'application/mathematica'); // do not localize AddType('mb', 'application/mathematica'); // do not localize AddType('mathml', 'application/mathml+xml', TMimeTypes.TKind.Text); // do not localize AddType('mbox', 'application/mbox'); // do not localize AddType('mscml', 'application/mediaservercontrol+xml', TMimeTypes.TKind.Text); // do not localize AddType('metalink', 'application/metalink+xml', TMimeTypes.TKind.Text); // do not localize AddType('meta4', 'application/metalink4+xml', TMimeTypes.TKind.Text); // do not localize AddType('mets', 'application/mets+xml', TMimeTypes.TKind.Text); // do not localize AddType('mods', 'application/mods+xml', TMimeTypes.TKind.Text); // do not localize AddType('m21', 'application/mp21'); // do not localize AddType('mp21', 'application/mp21'); // do not localize AddType('mp4s', 'application/mp4'); // do not localize AddType('doc', 'application/msword'); // do not localize AddType('dot', 'application/msword'); // do not localize AddType('mxf', 'application/mxf'); // do not localize AddType('bin', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('bpk', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('class', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('deploy', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('dist', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('distz', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('dmg', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('dms', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('dump', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('elc', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('iso', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('lha', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('lrf', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('lzh', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('mar', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('pkg', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('so', 'application/octet-stream', TMimeTypes.TKind.Binary); // do not localize AddType('oda', 'application/oda'); // do not localize AddType('opf', 'application/oebps-package+xml', TMimeTypes.TKind.Text); // do not localize AddType('ogx', 'application/ogg'); // do not localize AddType('omdoc', 'application/omdoc+xml', TMimeTypes.TKind.Text); // do not localize AddType('onetoc', 'application/onenote'); // do not localize AddType('onetoc2', 'application/onenote'); // do not localize AddType('onetmp', 'application/onenote'); // do not localize AddType('onepkg', 'application/onenote'); // do not localize AddType('oxps', 'application/oxps'); // do not localize AddType('xer', 'application/patch-ops-error+xml', TMimeTypes.TKind.Text); // do not localize AddType('pdf', 'application/pdf', TMimeTypes.TKind.Binary); // do not localize AddType('pgp', 'application/pgp-encrypted'); // do not localize AddType('asc', 'application/pgp-signature'); // do not localize AddType('sig', 'application/pgp-signature'); // do not localize AddType('prf', 'application/pics-rules'); // do not localize AddType('p10', 'application/pkcs10'); // do not localize AddType('p7m', 'application/pkcs7-mime'); // do not localize AddType('p7c', 'application/pkcs7-mime'); // do not localize AddType('p7s', 'application/pkcs7-signature'); // do not localize AddType('p8', 'application/pkcs8'); // do not localize AddType('ac', 'application/pkix-attr-cert'); // do not localize AddType('cer', 'application/pkix-cert'); // do not localize AddType('crl', 'application/pkix-crl'); // do not localize AddType('pkipath', 'application/pkix-pkipath'); // do not localize AddType('pki', 'application/pkixcmp'); // do not localize AddType('pls', 'application/pls+xml', TMimeTypes.TKind.Text); // do not localize AddType('ai', 'application/postscript'); // do not localize AddType('eps', 'application/postscript'); // do not localize AddType('ps', 'application/postscript'); // do not localize AddType('cww', 'application/prs.cww'); // do not localize AddType('pskcxml', 'application/pskc+xml', TMimeTypes.TKind.Text); // do not localize AddType('rdf', 'application/rdf+xml', TMimeTypes.TKind.Text); // do not localize AddType('rif', 'application/reginfo+xml', TMimeTypes.TKind.Text); // do not localize AddType('rnc', 'application/relax-ng-compact-syntax'); // do not localize AddType('rl', 'application/resource-lists+xml', TMimeTypes.TKind.Text); // do not localize AddType('rld', 'application/resource-lists-diff+xml', TMimeTypes.TKind.Text); // do not localize AddType('rs', 'application/rls-services+xml', TMimeTypes.TKind.Text); // do not localize AddType('gbr', 'application/rpki-ghostbusters'); // do not localize AddType('mft', 'application/rpki-manifest'); // do not localize AddType('roa', 'application/rpki-roa'); // do not localize AddType('rsd', 'application/rsd+xml', TMimeTypes.TKind.Text); // do not localize AddType('rss', 'application/rss+xml', TMimeTypes.TKind.Text); // do not localize AddType('rtf', 'application/rtf'); // do not localize AddType('sbml', 'application/sbml+xml', TMimeTypes.TKind.Text); // do not localize AddType('scq', 'application/scvp-cv-request'); // do not localize AddType('scs', 'application/scvp-cv-response'); // do not localize AddType('spq', 'application/scvp-vp-request'); // do not localize AddType('spp', 'application/scvp-vp-response'); // do not localize AddType('sdp', 'application/sdp'); // do not localize AddType('setpay', 'application/set-payment-initiation'); // do not localize AddType('setreg', 'application/set-registration-initiation'); // do not localize AddType('shf', 'application/shf+xml', TMimeTypes.TKind.Text); // do not localize AddType('smi', 'application/smil+xml', TMimeTypes.TKind.Text); // do not localize AddType('smil', 'application/smil+xml', TMimeTypes.TKind.Text); // do not localize AddType('soap', 'application/soap+xml', TMimeTypes.TKind.Text); // do not localize AddType('rq', 'application/sparql-query'); // do not localize AddType('srx', 'application/sparql-results+xml', TMimeTypes.TKind.Text); // do not localize AddType('gram', 'application/srgs'); // do not localize AddType('grxml', 'application/srgs+xml', TMimeTypes.TKind.Text); // do not localize AddType('sru', 'application/sru+xml', TMimeTypes.TKind.Text); // do not localize AddType('ssdl', 'application/ssdl+xml', TMimeTypes.TKind.Text); // do not localize AddType('ssml', 'application/ssml+xml', TMimeTypes.TKind.Text); // do not localize AddType('tei', 'application/tei+xml', TMimeTypes.TKind.Text); // do not localize AddType('teicorpus', 'application/tei+xml', TMimeTypes.TKind.Text); // do not localize AddType('tfi', 'application/thraud+xml', TMimeTypes.TKind.Text); // do not localize AddType('tsd', 'application/timestamped-data'); // do not localize AddType('plb', 'application/vnd.3gpp.pic-bw-large'); // do not localize AddType('psb', 'application/vnd.3gpp.pic-bw-small'); // do not localize AddType('pvb', 'application/vnd.3gpp.pic-bw-var'); // do not localize AddType('tcap', 'application/vnd.3gpp2.tcap'); // do not localize AddType('pwn', 'application/vnd.3m.post-it-notes'); // do not localize AddType('aso', 'application/vnd.accpac.simply.aso'); // do not localize AddType('imp', 'application/vnd.accpac.simply.imp'); // do not localize AddType('acu', 'application/vnd.acucobol'); // do not localize AddType('atc', 'application/vnd.acucorp'); // do not localize AddType('acutc', 'application/vnd.acucorp'); // do not localize AddType('air', 'application/vnd.adobe.air-application-installer-package+zip'); // do not localize AddType('fcdt', 'application/vnd.adobe.formscentral.fcdt'); // do not localize AddType('fxp', 'application/vnd.adobe.fxp'); // do not localize AddType('fxpl', 'application/vnd.adobe.fxp'); // do not localize AddType('xdp', 'application/vnd.adobe.xdp+xml', TMimeTypes.TKind.Text); // do not localize AddType('xfdf', 'application/vnd.adobe.xfdf'); // do not localize AddType('ahead', 'application/vnd.ahead.space'); // do not localize AddType('azf', 'application/vnd.airzip.filesecure.azf'); // do not localize AddType('azs', 'application/vnd.airzip.filesecure.azs'); // do not localize AddType('azw', 'application/vnd.amazon.ebook'); // do not localize AddType('acc', 'application/vnd.americandynamics.acc'); // do not localize AddType('ami', 'application/vnd.amiga.ami'); // do not localize AddType('apk', 'application/vnd.android.package-archive'); // do not localize AddType('cii', 'application/vnd.anser-web-certificate-issue-initiation'); // do not localize AddType('fti', 'application/vnd.anser-web-funds-transfer-initiation'); // do not localize AddType('atx', 'application/vnd.antix.game-component'); // do not localize AddType('mpkg', 'application/vnd.apple.installer+xml', TMimeTypes.TKind.Text); // do not localize AddType('m3u8', 'application/vnd.apple.mpegurl'); // do not localize AddType('swi', 'application/vnd.aristanetworks.swi'); // do not localize AddType('iota', 'application/vnd.astraea-software.iota'); // do not localize AddType('aep', 'application/vnd.audiograph'); // do not localize AddType('mpm', 'application/vnd.blueice.multipass'); // do not localize AddType('bmi', 'application/vnd.bmi'); // do not localize AddType('rep', 'application/vnd.businessobjects'); // do not localize AddType('cdxml', 'application/vnd.chemdraw+xml', TMimeTypes.TKind.Text); // do not localize AddType('mmd', 'application/vnd.chipnuts.karaoke-mmd'); // do not localize AddType('cdy', 'application/vnd.cinderella'); // do not localize AddType('cla', 'application/vnd.claymore'); // do not localize AddType('rp9', 'application/vnd.cloanto.rp9'); // do not localize AddType('c4g', 'application/vnd.clonk.c4group'); // do not localize AddType('c4d', 'application/vnd.clonk.c4group'); // do not localize AddType('c4f', 'application/vnd.clonk.c4group'); // do not localize AddType('c4p', 'application/vnd.clonk.c4group'); // do not localize AddType('c4u', 'application/vnd.clonk.c4group'); // do not localize AddType('c11amc', 'application/vnd.cluetrust.cartomobile-config'); // do not localize AddType('c11amz', 'application/vnd.cluetrust.cartomobile-config-pkg'); // do not localize AddType('csp', 'application/vnd.commonspace'); // do not localize AddType('cdbcmsg', 'application/vnd.contact.cmsg'); // do not localize AddType('cmc', 'application/vnd.cosmocaller'); // do not localize AddType('clkx', 'application/vnd.crick.clicker'); // do not localize AddType('clkk', 'application/vnd.crick.clicker.keyboard'); // do not localize AddType('clkp', 'application/vnd.crick.clicker.palette'); // do not localize AddType('clkt', 'application/vnd.crick.clicker.template'); // do not localize AddType('clkw', 'application/vnd.crick.clicker.wordbank'); // do not localize AddType('wbs', 'application/vnd.criticaltools.wbs+xml', TMimeTypes.TKind.Text); // do not localize AddType('pml', 'application/vnd.ctc-posml'); // do not localize AddType('ppd', 'application/vnd.cups-ppd'); // do not localize AddType('car', 'application/vnd.curl.car'); // do not localize AddType('pcurl', 'application/vnd.curl.pcurl'); // do not localize AddType('dart', 'application/vnd.dart'); // do not localize AddType('rdz', 'application/vnd.data-vision.rdz'); // do not localize AddType('uvf', 'application/vnd.dece.data'); // do not localize AddType('uvvf', 'application/vnd.dece.data'); // do not localize AddType('uvd', 'application/vnd.dece.data'); // do not localize AddType('uvvd', 'application/vnd.dece.data'); // do not localize AddType('uvt', 'application/vnd.dece.ttml+xml', TMimeTypes.TKind.Text); // do not localize AddType('uvvt', 'application/vnd.dece.ttml+xml', TMimeTypes.TKind.Text); // do not localize AddType('uvx', 'application/vnd.dece.unspecified'); // do not localize AddType('uvvx', 'application/vnd.dece.unspecified'); // do not localize AddType('uvz', 'application/vnd.dece.zip'); // do not localize AddType('uvvz', 'application/vnd.dece.zip'); // do not localize AddType('fe_launch', 'application/vnd.denovo.fcselayout-link'); // do not localize AddType('dna', 'application/vnd.dna'); // do not localize AddType('mlp', 'application/vnd.dolby.mlp'); // do not localize AddType('dpg', 'application/vnd.dpgraph'); // do not localize AddType('dfac', 'application/vnd.dreamfactory'); // do not localize AddType('kpxx', 'application/vnd.ds-keypoint'); // do not localize AddType('ait', 'application/vnd.dvb.ait'); // do not localize AddType('svc', 'application/vnd.dvb.service'); // do not localize AddType('geo', 'application/vnd.dynageo'); // do not localize AddType('mag', 'application/vnd.ecowin.chart'); // do not localize AddType('nml', 'application/vnd.enliven'); // do not localize AddType('esf', 'application/vnd.epson.esf'); // do not localize AddType('msf', 'application/vnd.epson.msf'); // do not localize AddType('qam', 'application/vnd.epson.quickanime'); // do not localize AddType('slt', 'application/vnd.epson.salt'); // do not localize AddType('ssf', 'application/vnd.epson.ssf'); // do not localize AddType('es3', 'application/vnd.eszigno3+xml', TMimeTypes.TKind.Text); // do not localize AddType('et3', 'application/vnd.eszigno3+xml', TMimeTypes.TKind.Text); // do not localize AddType('ez2', 'application/vnd.ezpix-album'); // do not localize AddType('ez3', 'application/vnd.ezpix-package'); // do not localize AddType('fdf', 'application/vnd.fdf'); // do not localize AddType('mseed', 'application/vnd.fdsn.mseed'); // do not localize AddType('seed', 'application/vnd.fdsn.seed'); // do not localize AddType('dataless', 'application/vnd.fdsn.seed'); // do not localize AddType('json', 'application/vnd.embarcadero.firedac+json', TMimeTypes.TKind.Text); // do not localize AddType('xml', 'application/vnd.embarcadero.firedac+xml', TMimeTypes.TKind.Text); // do not localize AddType('bin', 'application/vnd.embarcadero.firedac+bin', TMimeTypes.TKind.Binary); // do not localize AddType('gph', 'application/vnd.flographit'); // do not localize AddType('ftc', 'application/vnd.fluxtime.clip'); // do not localize AddType('fm', 'application/vnd.framemaker'); // do not localize AddType('frame', 'application/vnd.framemaker'); // do not localize AddType('maker', 'application/vnd.framemaker'); // do not localize AddType('book', 'application/vnd.framemaker'); // do not localize AddType('fnc', 'application/vnd.frogans.fnc'); // do not localize AddType('ltf', 'application/vnd.frogans.ltf'); // do not localize AddType('fsc', 'application/vnd.fsc.weblaunch'); // do not localize AddType('oas', 'application/vnd.fujitsu.oasys'); // do not localize AddType('oa2', 'application/vnd.fujitsu.oasys2'); // do not localize AddType('oa3', 'application/vnd.fujitsu.oasys3'); // do not localize AddType('fg5', 'application/vnd.fujitsu.oasysgp'); // do not localize AddType('bh2', 'application/vnd.fujitsu.oasysprs'); // do not localize AddType('ddd', 'application/vnd.fujixerox.ddd'); // do not localize AddType('xdw', 'application/vnd.fujixerox.docuworks'); // do not localize AddType('xbd', 'application/vnd.fujixerox.docuworks.binder'); // do not localize AddType('fzs', 'application/vnd.fuzzysheet'); // do not localize AddType('txd', 'application/vnd.genomatix.tuxedo'); // do not localize AddType('ggb', 'application/vnd.geogebra.file'); // do not localize AddType('ggt', 'application/vnd.geogebra.tool'); // do not localize AddType('gex', 'application/vnd.geometry-explorer'); // do not localize AddType('gre', 'application/vnd.geometry-explorer'); // do not localize AddType('gxt', 'application/vnd.geonext'); // do not localize AddType('g2w', 'application/vnd.geoplan'); // do not localize AddType('g3w', 'application/vnd.geospace'); // do not localize AddType('gmx', 'application/vnd.gmx'); // do not localize AddType('kml', 'application/vnd.google-earth.kml+xml', TMimeTypes.TKind.Text); // do not localize AddType('kmz', 'application/vnd.google-earth.kmz'); // do not localize AddType('gqf', 'application/vnd.grafeq'); // do not localize AddType('gqs', 'application/vnd.grafeq'); // do not localize AddType('gac', 'application/vnd.groove-account'); // do not localize AddType('ghf', 'application/vnd.groove-help'); // do not localize AddType('gim', 'application/vnd.groove-identity-message'); // do not localize AddType('grv', 'application/vnd.groove-injector'); // do not localize AddType('gtm', 'application/vnd.groove-tool-message'); // do not localize AddType('tpl', 'application/vnd.groove-tool-template'); // do not localize AddType('vcg', 'application/vnd.groove-vcard'); // do not localize AddType('hal', 'application/vnd.hal+xml', TMimeTypes.TKind.Text); // do not localize AddType('zmm', 'application/vnd.handheld-entertainment+xml', TMimeTypes.TKind.Text); // do not localize AddType('hbci', 'application/vnd.hbci'); // do not localize AddType('les', 'application/vnd.hhe.lesson-player'); // do not localize AddType('hpgl', 'application/vnd.hp-hpgl'); // do not localize AddType('hpid', 'application/vnd.hp-hpid'); // do not localize AddType('hps', 'application/vnd.hp-hps'); // do not localize AddType('jlt', 'application/vnd.hp-jlyt'); // do not localize AddType('pcl', 'application/vnd.hp-pcl'); // do not localize AddType('pclxl', 'application/vnd.hp-pclxl'); // do not localize AddType('sfd-hdstx', 'application/vnd.hydrostatix.sof-data'); // do not localize AddType('mpy', 'application/vnd.ibm.minipay'); // do not localize AddType('afp', 'application/vnd.ibm.modcap'); // do not localize AddType('listafp', 'application/vnd.ibm.modcap'); // do not localize AddType('list3820', 'application/vnd.ibm.modcap'); // do not localize AddType('irm', 'application/vnd.ibm.rights-management'); // do not localize AddType('sc', 'application/vnd.ibm.secure-container'); // do not localize AddType('icc', 'application/vnd.iccprofile'); // do not localize AddType('icm', 'application/vnd.iccprofile'); // do not localize AddType('igl', 'application/vnd.igloader'); // do not localize AddType('ivp', 'application/vnd.immervision-ivp'); // do not localize AddType('ivu', 'application/vnd.immervision-ivu'); // do not localize AddType('igm', 'application/vnd.insors.igm'); // do not localize AddType('xpw', 'application/vnd.intercon.formnet'); // do not localize AddType('xpx', 'application/vnd.intercon.formnet'); // do not localize AddType('i2g', 'application/vnd.intergeo'); // do not localize AddType('qbo', 'application/vnd.intu.qbo'); // do not localize AddType('qfx', 'application/vnd.intu.qfx'); // do not localize AddType('rcprofile', 'application/vnd.ipunplugged.rcprofile'); // do not localize AddType('irp', 'application/vnd.irepository.package+xml', TMimeTypes.TKind.Text); // do not localize AddType('xpr', 'application/vnd.is-xpr'); // do not localize AddType('fcs', 'application/vnd.isac.fcs'); // do not localize AddType('jam', 'application/vnd.jam'); // do not localize AddType('rms', 'application/vnd.jcp.javame.midlet-rms'); // do not localize AddType('jisp', 'application/vnd.jisp'); // do not localize AddType('joda', 'application/vnd.joost.joda-archive'); // do not localize AddType('ktz', 'application/vnd.kahootz'); // do not localize AddType('ktr', 'application/vnd.kahootz'); // do not localize AddType('karbon', 'application/vnd.kde.karbon'); // do not localize AddType('chrt', 'application/vnd.kde.kchart'); // do not localize AddType('kfo', 'application/vnd.kde.kformula'); // do not localize AddType('flw', 'application/vnd.kde.kivio'); // do not localize AddType('kon', 'application/vnd.kde.kontour'); // do not localize AddType('kpr', 'application/vnd.kde.kpresenter'); // do not localize AddType('kpt', 'application/vnd.kde.kpresenter'); // do not localize AddType('ksp', 'application/vnd.kde.kspread'); // do not localize AddType('kwd', 'application/vnd.kde.kword'); // do not localize AddType('kwt', 'application/vnd.kde.kword'); // do not localize AddType('htke', 'application/vnd.kenameaapp'); // do not localize AddType('kia', 'application/vnd.kidspiration'); // do not localize AddType('kne', 'application/vnd.kinar'); // do not localize AddType('knp', 'application/vnd.kinar'); // do not localize AddType('skp', 'application/vnd.koan'); // do not localize AddType('skd', 'application/vnd.koan'); // do not localize AddType('skt', 'application/vnd.koan'); // do not localize AddType('skm', 'application/vnd.koan'); // do not localize AddType('sse', 'application/vnd.kodak-descriptor'); // do not localize AddType('lasxml', 'application/vnd.las.las+xml', TMimeTypes.TKind.Text); // do not localize AddType('lbd', 'application/vnd.llamagraphics.life-balance.desktop'); // do not localize AddType('lbe', 'application/vnd.llamagraphics.life-balance.exchange+xml', TMimeTypes.TKind.Text); // do not localize AddType('123', 'application/vnd.lotus-1-2-3'); // do not localize AddType('apr', 'application/vnd.lotus-approach'); // do not localize AddType('pre', 'application/vnd.lotus-freelance'); // do not localize AddType('nsf', 'application/vnd.lotus-notes'); // do not localize AddType('org', 'application/vnd.lotus-organizer'); // do not localize AddType('scm', 'application/vnd.lotus-screencam'); // do not localize AddType('lwp', 'application/vnd.lotus-wordpro'); // do not localize AddType('portpkg', 'application/vnd.macports.portpkg'); // do not localize AddType('mcd', 'application/vnd.mcd'); // do not localize AddType('mc1', 'application/vnd.medcalcdata'); // do not localize AddType('cdkey', 'application/vnd.mediastation.cdkey'); // do not localize AddType('mwf', 'application/vnd.mfer'); // do not localize AddType('mfm', 'application/vnd.mfmp'); // do not localize AddType('flo', 'application/vnd.micrografx.flo'); // do not localize AddType('igx', 'application/vnd.micrografx.igx'); // do not localize AddType('mif', 'application/vnd.mif'); // do not localize AddType('daf', 'application/vnd.mobius.daf'); // do not localize AddType('dis', 'application/vnd.mobius.dis'); // do not localize AddType('mbk', 'application/vnd.mobius.mbk'); // do not localize AddType('mqy', 'application/vnd.mobius.mqy'); // do not localize AddType('msl', 'application/vnd.mobius.msl'); // do not localize AddType('plc', 'application/vnd.mobius.plc'); // do not localize AddType('txf', 'application/vnd.mobius.txf'); // do not localize AddType('mpn', 'application/vnd.mophun.application'); // do not localize AddType('mpc', 'application/vnd.mophun.certificate'); // do not localize AddType('xul', 'application/vnd.mozilla.xul+xml', TMimeTypes.TKind.Text); // do not localize AddType('cil', 'application/vnd.ms-artgalry'); // do not localize AddType('cab', 'application/vnd.ms-cab-compressed'); // do not localize AddType('xls', 'application/vnd.ms-excel'); // do not localize AddType('xlm', 'application/vnd.ms-excel'); // do not localize AddType('xla', 'application/vnd.ms-excel'); // do not localize AddType('xlc', 'application/vnd.ms-excel'); // do not localize AddType('xlt', 'application/vnd.ms-excel'); // do not localize AddType('xlw', 'application/vnd.ms-excel'); // do not localize AddType('xlam', 'application/vnd.ms-excel.addin.macroenabled.12'); // do not localize AddType('xlsb', 'application/vnd.ms-excel.sheet.binary.macroenabled.12'); // do not localize AddType('xlsm', 'application/vnd.ms-excel.sheet.macroenabled.12'); // do not localize AddType('xltm', 'application/vnd.ms-excel.template.macroenabled.12'); // do not localize AddType('eot', 'application/vnd.ms-fontobject'); // do not localize AddType('chm', 'application/vnd.ms-htmlhelp'); // do not localize AddType('ims', 'application/vnd.ms-ims'); // do not localize AddType('lrm', 'application/vnd.ms-lrm'); // do not localize AddType('thmx', 'application/vnd.ms-officetheme'); // do not localize AddType('cat', 'application/vnd.ms-pki.seccat'); // do not localize AddType('stl', 'application/vnd.ms-pki.stl'); // do not localize AddType('ppt', 'application/vnd.ms-powerpoint'); // do not localize AddType('pps', 'application/vnd.ms-powerpoint'); // do not localize AddType('pot', 'application/vnd.ms-powerpoint'); // do not localize AddType('ppam', 'application/vnd.ms-powerpoint.addin.macroenabled.12'); // do not localize AddType('pptm', 'application/vnd.ms-powerpoint.presentation.macroenabled.12'); // do not localize AddType('sldm', 'application/vnd.ms-powerpoint.slide.macroenabled.12'); // do not localize AddType('ppsm', 'application/vnd.ms-powerpoint.slideshow.macroenabled.12'); // do not localize AddType('potm', 'application/vnd.ms-powerpoint.template.macroenabled.12'); // do not localize AddType('mpp', 'application/vnd.ms-project'); // do not localize AddType('mpt', 'application/vnd.ms-project'); // do not localize AddType('docm', 'application/vnd.ms-word.document.macroenabled.12'); // do not localize AddType('dotm', 'application/vnd.ms-word.template.macroenabled.12'); // do not localize AddType('wps', 'application/vnd.ms-works'); // do not localize AddType('wks', 'application/vnd.ms-works'); // do not localize AddType('wcm', 'application/vnd.ms-works'); // do not localize AddType('wdb', 'application/vnd.ms-works'); // do not localize AddType('wpl', 'application/vnd.ms-wpl'); // do not localize AddType('xps', 'application/vnd.ms-xpsdocument'); // do not localize AddType('mseq', 'application/vnd.mseq'); // do not localize AddType('mus', 'application/vnd.musician'); // do not localize AddType('msty', 'application/vnd.muvee.style'); // do not localize AddType('taglet', 'application/vnd.mynfc'); // do not localize AddType('nlu', 'application/vnd.neurolanguage.nlu'); // do not localize AddType('ntf', 'application/vnd.nitf'); // do not localize AddType('nitf', 'application/vnd.nitf'); // do not localize AddType('nnd', 'application/vnd.noblenet-directory'); // do not localize AddType('nns', 'application/vnd.noblenet-sealer'); // do not localize AddType('nnw', 'application/vnd.noblenet-web'); // do not localize AddType('ngdat', 'application/vnd.nokia.n-gage.data'); // do not localize AddType('n-gage', 'application/vnd.nokia.n-gage.symbian.install'); // do not localize AddType('rpst', 'application/vnd.nokia.radio-preset'); // do not localize AddType('rpss', 'application/vnd.nokia.radio-presets'); // do not localize AddType('edm', 'application/vnd.novadigm.edm'); // do not localize AddType('edx', 'application/vnd.novadigm.edx'); // do not localize AddType('FExt', 'application/vnd.novadigm.FExt'); // do not localize AddType('odc', 'application/vnd.oasis.opendocument.chart'); // do not localize AddType('otc', 'application/vnd.oasis.opendocument.chart-template'); // do not localize AddType('odb', 'application/vnd.oasis.opendocument.database'); // do not localize AddType('odf', 'application/vnd.oasis.opendocument.formula'); // do not localize AddType('odft', 'application/vnd.oasis.opendocument.formula-template'); // do not localize AddType('odg', 'application/vnd.oasis.opendocument.graphics'); // do not localize AddType('otg', 'application/vnd.oasis.opendocument.graphics-template'); // do not localize AddType('odi', 'application/vnd.oasis.opendocument.image'); // do not localize AddType('oti', 'application/vnd.oasis.opendocument.image-template'); // do not localize AddType('odp', 'application/vnd.oasis.opendocument.presentation'); // do not localize AddType('otp', 'application/vnd.oasis.opendocument.presentation-template'); // do not localize AddType('ods', 'application/vnd.oasis.opendocument.spreadsheet'); // do not localize AddType('ots', 'application/vnd.oasis.opendocument.spreadsheet-template'); // do not localize AddType('odt', 'application/vnd.oasis.opendocument.text'); // do not localize AddType('odm', 'application/vnd.oasis.opendocument.text-master'); // do not localize AddType('ott', 'application/vnd.oasis.opendocument.text-template'); // do not localize AddType('oth', 'application/vnd.oasis.opendocument.text-web'); // do not localize AddType('xo', 'application/vnd.olpc-sugar'); // do not localize AddType('dd2', 'application/vnd.oma.dd2+xml', TMimeTypes.TKind.Text); // do not localize AddType('oxt', 'application/vnd.openofficeorg.extension'); // do not localize AddType('pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'); // do not localize AddType('sldx', 'application/vnd.openxmlformats-officedocument.presentationml.slide'); // do not localize AddType('ppsx', 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'); // do not localize AddType('potx', 'application/vnd.openxmlformats-officedocument.presentationml.template'); // do not localize AddType('xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // do not localize AddType('xltx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'); // do not localize AddType('docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'); // do not localize AddType('dotx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'); // do not localize AddType('mgp', 'application/vnd.osgeo.mapguide.package'); // do not localize AddType('dp', 'application/vnd.osgi.dp'); // do not localize AddType('esa', 'application/vnd.osgi.subsystem'); // do not localize AddType('pdb', 'application/vnd.palm'); // do not localize AddType('pqa', 'application/vnd.palm'); // do not localize AddType('oprc', 'application/vnd.palm'); // do not localize AddType('paw', 'application/vnd.pawaafile'); // do not localize AddType('str', 'application/vnd.pg.format'); // do not localize AddType('ei6', 'application/vnd.pg.osasli'); // do not localize AddType('efif', 'application/vnd.picsel'); // do not localize AddType('wg', 'application/vnd.pmi.widget'); // do not localize AddType('plf', 'application/vnd.pocketlearn'); // do not localize AddType('pbd', 'application/vnd.powerbuilder6'); // do not localize AddType('box', 'application/vnd.previewsystems.box'); // do not localize AddType('mgz', 'application/vnd.proteus.magazine'); // do not localize AddType('qps', 'application/vnd.publishare-delta-tree'); // do not localize AddType('ptid', 'application/vnd.pvi.ptid1'); // do not localize AddType('qxd', 'application/vnd.quark.quarkxpress'); // do not localize AddType('qxt', 'application/vnd.quark.quarkxpress'); // do not localize AddType('qwd', 'application/vnd.quark.quarkxpress'); // do not localize AddType('qwt', 'application/vnd.quark.quarkxpress'); // do not localize AddType('qxl', 'application/vnd.quark.quarkxpress'); // do not localize AddType('qxb', 'application/vnd.quark.quarkxpress'); // do not localize AddType('bed', 'application/vnd.realvnc.bed'); // do not localize AddType('mxl', 'application/vnd.recordare.musicxml'); // do not localize AddType('musicxml', 'application/vnd.recordare.musicxml+xml', TMimeTypes.TKind.Text); // do not localize AddType('cryptonote', 'application/vnd.rig.cryptonote'); // do not localize AddType('cod', 'application/vnd.rim.cod'); // do not localize AddType('rm', 'application/vnd.rn-realmedia'); // do not localize AddType('rmvb', 'application/vnd.rn-realmedia-vbr'); // do not localize AddType('link66', 'application/vnd.route66.link66+xml', TMimeTypes.TKind.Text); // do not localize AddType('st', 'application/vnd.sailingtracker.track'); // do not localize AddType('see', 'application/vnd.seemail'); // do not localize AddType('sema', 'application/vnd.sema'); // do not localize AddType('semd', 'application/vnd.semd'); // do not localize AddType('semf', 'application/vnd.semf'); // do not localize AddType('ifm', 'application/vnd.shana.informed.formdata'); // do not localize AddType('itp', 'application/vnd.shana.informed.formtemplate'); // do not localize AddType('iif', 'application/vnd.shana.informed.interchange'); // do not localize AddType('ipk', 'application/vnd.shana.informed.package'); // do not localize AddType('twd', 'application/vnd.simtech-mindmapper'); // do not localize AddType('twds', 'application/vnd.simtech-mindmapper'); // do not localize AddType('mmf', 'application/vnd.smaf'); // do not localize AddType('teacher', 'application/vnd.smart.teacher'); // do not localize AddType('sdkm', 'application/vnd.solent.sdkm+xml', TMimeTypes.TKind.Text); // do not localize AddType('sdkd', 'application/vnd.solent.sdkm+xml', TMimeTypes.TKind.Text); // do not localize AddType('dxp', 'application/vnd.spotfire.dxp'); // do not localize AddType('sfs', 'application/vnd.spotfire.sfs'); // do not localize AddType('sdc', 'application/vnd.stardivision.calc'); // do not localize AddType('sda', 'application/vnd.stardivision.draw'); // do not localize AddType('sdd', 'application/vnd.stardivision.impress'); // do not localize AddType('smf', 'application/vnd.stardivision.math'); // do not localize AddType('sdw', 'application/vnd.stardivision.writer'); // do not localize AddType('vor', 'application/vnd.stardivision.writer'); // do not localize AddType('sgl', 'application/vnd.stardivision.writer-global'); // do not localize AddType('smzip', 'application/vnd.stepmania.package'); // do not localize AddType('sm', 'application/vnd.stepmania.stepchart'); // do not localize AddType('sxc', 'application/vnd.sun.xml.calc'); // do not localize AddType('stc', 'application/vnd.sun.xml.calc.template'); // do not localize AddType('sxd', 'application/vnd.sun.xml.draw'); // do not localize AddType('std', 'application/vnd.sun.xml.draw.template'); // do not localize AddType('sxi', 'application/vnd.sun.xml.impress'); // do not localize AddType('sti', 'application/vnd.sun.xml.impress.template'); // do not localize AddType('sxm', 'application/vnd.sun.xml.math'); // do not localize AddType('sxw', 'application/vnd.sun.xml.writer'); // do not localize AddType('sxg', 'application/vnd.sun.xml.writer.global'); // do not localize AddType('stw', 'application/vnd.sun.xml.writer.template'); // do not localize AddType('sus', 'application/vnd.sus-calendar'); // do not localize AddType('susp', 'application/vnd.sus-calendar'); // do not localize AddType('svd', 'application/vnd.svd'); // do not localize AddType('sis', 'application/vnd.symbian.install'); // do not localize AddType('sisx', 'application/vnd.symbian.install'); // do not localize AddType('xsm', 'application/vnd.syncml+xml', TMimeTypes.TKind.Text); // do not localize AddType('bdm', 'application/vnd.syncml.dm+wbxml'); // do not localize AddType('xdm', 'application/vnd.syncml.dm+xml', TMimeTypes.TKind.Text); // do not localize AddType('tao', 'application/vnd.tao.intent-module-archive'); // do not localize AddType('pcap', 'application/vnd.tcpdump.pcap'); // do not localize AddType('cap', 'application/vnd.tcpdump.pcap'); // do not localize AddType('dmp', 'application/vnd.tcpdump.pcap'); // do not localize AddType('tmo', 'application/vnd.tmobile-livetv'); // do not localize AddType('tpt', 'application/vnd.trid.tpt'); // do not localize AddType('mxs', 'application/vnd.triscape.mxs'); // do not localize AddType('tra', 'application/vnd.trueapp'); // do not localize AddType('ufd', 'application/vnd.ufdl'); // do not localize AddType('ufdl', 'application/vnd.ufdl'); // do not localize AddType('utz', 'application/vnd.uiq.theme'); // do not localize AddType('umj', 'application/vnd.umajin'); // do not localize AddType('unityweb', 'application/vnd.unity'); // do not localize AddType('uoml', 'application/vnd.uoml+xml', TMimeTypes.TKind.Text); // do not localize AddType('vcx', 'application/vnd.vcx'); // do not localize AddType('vsd', 'application/vnd.visio'); // do not localize AddType('vst', 'application/vnd.visio'); // do not localize AddType('vss', 'application/vnd.visio'); // do not localize AddType('vsw', 'application/vnd.visio'); // do not localize AddType('vis', 'application/vnd.visionary'); // do not localize AddType('vsf', 'application/vnd.vsf'); // do not localize AddType('wbxml', 'application/vnd.wap.wbxml'); // do not localize AddType('wmlc', 'application/vnd.wap.wmlc'); // do not localize AddType('wmlsc', 'application/vnd.wap.wmlscriptc'); // do not localize AddType('wtb', 'application/vnd.webturbo'); // do not localize AddType('nbp', 'application/vnd.wolfram.player'); // do not localize AddType('wpd', 'application/vnd.wordperfect'); // do not localize AddType('wqd', 'application/vnd.wqd'); // do not localize AddType('stf', 'application/vnd.wt.stf'); // do not localize AddType('xar', 'application/vnd.xara'); // do not localize AddType('xfdl', 'application/vnd.xfdl'); // do not localize AddType('hvd', 'application/vnd.yamaha.hv-dic'); // do not localize AddType('hvs', 'application/vnd.yamaha.hv-script'); // do not localize AddType('hvp', 'application/vnd.yamaha.hv-voice'); // do not localize AddType('osf', 'application/vnd.yamaha.openscoreformat'); // do not localize AddType('osfpvg', 'application/vnd.yamaha.openscoreformat.osfpvg+xml', TMimeTypes.TKind.Text); // do not localize AddType('saf', 'application/vnd.yamaha.smaf-audio'); // do not localize AddType('spf', 'application/vnd.yamaha.smaf-phrase'); // do not localize AddType('cmp', 'application/vnd.yellowriver-custom-menu'); // do not localize AddType('zir', 'application/vnd.zul'); // do not localize AddType('zirz', 'application/vnd.zul'); // do not localize AddType('zaz', 'application/vnd.zzazz.deck+xml', TMimeTypes.TKind.Text); // do not localize AddType('vxml', 'application/voicexml+xml', TMimeTypes.TKind.Text); // do not localize AddType('wgt', 'application/widget'); // do not localize AddType('hlp', 'application/winhlp'); // do not localize AddType('wsdl', 'application/wsdl+xml', TMimeTypes.TKind.Text); // do not localize AddType('wspolicy', 'application/wspolicy+xml', TMimeTypes.TKind.Text); // do not localize AddType('7z', 'application/x-7z-compressed'); // do not localize AddType('abw', 'application/x-abiword'); // do not localize AddType('ace', 'application/x-ace-compressed'); // do not localize AddType('dmg', 'application/x-apple-diskimage'); // do not localize AddType('aab', 'application/x-authorware-bin'); // do not localize AddType('x32', 'application/x-authorware-bin'); // do not localize AddType('u32', 'application/x-authorware-bin'); // do not localize AddType('vox', 'application/x-authorware-bin'); // do not localize AddType('aam', 'application/x-authorware-map'); // do not localize AddType('aas', 'application/x-authorware-seg'); // do not localize AddType('bcpio', 'application/x-bcpio'); // do not localize AddType('torrent', 'application/x-bittorrent'); // do not localize AddType('blb', 'application/x-blorb'); // do not localize AddType('blorb', 'application/x-blorb'); // do not localize AddType('bz', 'application/x-bzip'); // do not localize AddType('bz2', 'application/x-bzip2'); // do not localize AddType('boz', 'application/x-bzip2'); // do not localize AddType('cbr', 'application/x-cbr'); // do not localize AddType('cba', 'application/x-cbr'); // do not localize AddType('cbt', 'application/x-cbr'); // do not localize AddType('cbz', 'application/x-cbr'); // do not localize AddType('cb7', 'application/x-cbr'); // do not localize AddType('vcd', 'application/x-cdlink'); // do not localize AddType('cfs', 'application/x-cfs-compressed'); // do not localize AddType('chat', 'application/x-chat'); // do not localize AddType('pgn', 'application/x-chess-pgn'); // do not localize AddType('nsc', 'application/x-conference'); // do not localize AddType('cpio', 'application/x-cpio'); // do not localize AddType('csh', 'application/x-csh'); // do not localize AddType('deb', 'application/x-debian-package'); // do not localize AddType('udeb', 'application/x-debian-package'); // do not localize AddType('dgc', 'application/x-dgc-compressed'); // do not localize AddType('dir', 'application/x-director'); // do not localize AddType('dcr', 'application/x-director'); // do not localize AddType('dxr', 'application/x-director'); // do not localize AddType('cst', 'application/x-director'); // do not localize AddType('cct', 'application/x-director'); // do not localize AddType('cxt', 'application/x-director'); // do not localize AddType('w3d', 'application/x-director'); // do not localize AddType('fgd', 'application/x-director'); // do not localize AddType('swa', 'application/x-director'); // do not localize AddType('wad', 'application/x-doom'); // do not localize AddType('ncx', 'application/x-dtbncx+xml', TMimeTypes.TKind.Text); // do not localize AddType('dtb', 'application/x-dtbook+xml', TMimeTypes.TKind.Text); // do not localize AddType('res', 'application/x-dtbresource+xml', TMimeTypes.TKind.Text); // do not localize AddType('dvi', 'application/x-dvi'); // do not localize AddType('evy', 'application/x-envoy'); // do not localize AddType('eva', 'application/x-eva'); // do not localize AddType('bdf', 'application/x-font-bdf'); // do not localize AddType('gsf', 'application/x-font-ghostscript'); // do not localize AddType('psf', 'application/x-font-linux-psf'); // do not localize AddType('otf', 'application/x-font-otf'); // do not localize AddType('pcf', 'application/x-font-pcf'); // do not localize AddType('snf', 'application/x-font-snf'); // do not localize AddType('ttf', 'application/x-font-ttf'); // do not localize AddType('ttc', 'application/x-font-ttf'); // do not localize AddType('pfa', 'application/x-font-type1'); // do not localize AddType('pfb', 'application/x-font-type1'); // do not localize AddType('pfm', 'application/x-font-type1'); // do not localize AddType('afm', 'application/x-font-type1'); // do not localize AddType('woff', 'application/x-font-woff'); // do not localize AddType('arc', 'application/x-freearc'); // do not localize AddType('spl', 'application/x-futuresplash'); // do not localize AddType('gca', 'application/x-gca-compressed'); // do not localize AddType('ulx', 'application/x-glulx'); // do not localize AddType('gnumeric', 'application/x-gnumeric'); // do not localize AddType('gramps', 'application/x-gramps-xml'); // do not localize AddType('gtar', 'application/x-gtar'); // do not localize AddType('hdf', 'application/x-hdf'); // do not localize AddType('install', 'application/x-install-instructions'); // do not localize AddType('iso', 'application/x-iso9660-image'); // do not localize AddType('jnlp', 'application/x-java-jnlp-file'); // do not localize AddType('latex', 'application/x-latex'); // do not localize AddType('lzh', 'application/x-lzh-compressed'); // do not localize AddType('lha', 'application/x-lzh-compressed'); // do not localize AddType('mie', 'application/x-mie'); // do not localize AddType('prc', 'application/x-mobipocket-ebook'); // do not localize AddType('mobi', 'application/x-mobipocket-ebook'); // do not localize AddType('application', 'application/x-ms-application'); // do not localize AddType('lnk', 'application/x-ms-shortcut'); // do not localize AddType('wmd', 'application/x-ms-wmd'); // do not localize AddType('wmz', 'application/x-ms-wmz'); // do not localize AddType('xbap', 'application/x-ms-xbap'); // do not localize AddType('mdb', 'application/x-msaccess'); // do not localize AddType('obd', 'application/x-msbinder'); // do not localize AddType('crd', 'application/x-mscardfile'); // do not localize AddType('clp', 'application/x-msclip'); // do not localize AddType('exe', 'application/x-msdownload'); // do not localize AddType('dll', 'application/x-msdownload'); // do not localize AddType('com', 'application/x-msdownload'); // do not localize AddType('bat', 'application/x-msdownload'); // do not localize AddType('msi', 'application/x-msdownload'); // do not localize AddType('mvb', 'application/x-msmediaview'); // do not localize AddType('m13', 'application/x-msmediaview'); // do not localize AddType('m14', 'application/x-msmediaview'); // do not localize AddType('wmf', 'application/x-msmetafile'); // do not localize AddType('wmz', 'application/x-msmetafile'); // do not localize AddType('emf', 'application/x-msmetafile'); // do not localize AddType('emz', 'application/x-msmetafile'); // do not localize AddType('mny', 'application/x-msmoney'); // do not localize AddType('pub', 'application/x-mspublisher'); // do not localize AddType('scd', 'application/x-msschedule'); // do not localize AddType('trm', 'application/x-msterminal'); // do not localize AddType('wri', 'application/x-mswrite'); // do not localize AddType('nc', 'application/x-netcdf'); // do not localize AddType('cdf', 'application/x-netcdf'); // do not localize AddType('nzb', 'application/x-nzb'); // do not localize AddType('p12', 'application/x-pkcs12'); // do not localize AddType('pfx', 'application/x-pkcs12'); // do not localize AddType('p7b', 'application/x-pkcs7-certificates'); // do not localize AddType('spc', 'application/x-pkcs7-certificates'); // do not localize AddType('p7r', 'application/x-pkcs7-certreqresp'); // do not localize AddType('rar', 'application/x-rar-compressed'); // do not localize AddType('ris', 'application/x-research-info-systems'); // do not localize AddType('sh', 'application/x-sh'); // do not localize AddType('shar', 'application/x-shar'); // do not localize AddType('swf', 'application/x-shockwave-flash'); // do not localize AddType('xap', 'application/x-silverlight-app'); // do not localize AddType('sql', 'application/x-sql'); // do not localize AddType('sit', 'application/x-stuffit'); // do not localize AddType('sitx', 'application/x-stuffitx'); // do not localize AddType('srt', 'application/x-subrip'); // do not localize AddType('sv4cpio', 'application/x-sv4cpio'); // do not localize AddType('sv4crc', 'application/x-sv4crc'); // do not localize AddType('t3', 'application/x-t3vm-image'); // do not localize AddType('gam', 'application/x-tads'); // do not localize AddType('tar', 'application/x-tar'); // do not localize AddType('tcl', 'application/x-tcl'); // do not localize AddType('tex', 'application/x-tex'); // do not localize AddType('tfm', 'application/x-tex-tfm'); // do not localize AddType('texinfo', 'application/x-texinfo'); // do not localize AddType('texi', 'application/x-texinfo'); // do not localize AddType('obj', 'application/x-tgif'); // do not localize AddType('ustar', 'application/x-ustar'); // do not localize AddType('src', 'application/x-wais-source'); // do not localize AddType('der', 'application/x-x509-ca-cert'); // do not localize AddType('crt', 'application/x-x509-ca-cert'); // do not localize AddType('fig', 'application/x-xfig'); // do not localize AddType('xlf', 'application/x-xliff+xml', TMimeTypes.TKind.Text); // do not localize AddType('xpi', 'application/x-xpinstall'); // do not localize AddType('xz', 'application/x-xz'); // do not localize AddType('yaml', 'application/x-yaml', TMimeTypes.TKind.Text); // do not localize AddType('z1', 'application/x-zmachine'); // do not localize AddType('z2', 'application/x-zmachine'); // do not localize AddType('z3', 'application/x-zmachine'); // do not localize AddType('z4', 'application/x-zmachine'); // do not localize AddType('z5', 'application/x-zmachine'); // do not localize AddType('z6', 'application/x-zmachine'); // do not localize AddType('z7', 'application/x-zmachine'); // do not localize AddType('z8', 'application/x-zmachine'); // do not localize AddType('xaml', 'application/xaml+xml', TMimeTypes.TKind.Text); // do not localize AddType('xdf', 'application/xcap-diff+xml', TMimeTypes.TKind.Text); // do not localize AddType('xenc', 'application/xenc+xml', TMimeTypes.TKind.Text); // do not localize AddType('xhtml', 'application/xhtml+xml', TMimeTypes.TKind.Text); // do not localize AddType('xht', 'application/xhtml+xml', TMimeTypes.TKind.Text); // do not localize AddType('xml', 'application/xml', TMimeTypes.TKind.Text); // do not localize AddType('xsl', 'application/xml', TMimeTypes.TKind.Text); // do not localize AddType('dtd', 'application/xml-dtd', TMimeTypes.TKind.Text); // do not localize AddType('xop', 'application/xop+xml', TMimeTypes.TKind.Text); // do not localize AddType('xpl', 'application/xproc+xml', TMimeTypes.TKind.Text); // do not localize AddType('xslt', 'application/xslt+xml', TMimeTypes.TKind.Text); // do not localize AddType('xspf', 'application/xspf+xml', TMimeTypes.TKind.Text); // do not localize AddType('mxml', 'application/xv+xml', TMimeTypes.TKind.Text); // do not localize AddType('xhvml', 'application/xv+xml', TMimeTypes.TKind.Text); // do not localize AddType('xvml', 'application/xv+xml', TMimeTypes.TKind.Text); // do not localize AddType('xvm', 'application/xv+xml', TMimeTypes.TKind.Text); // do not localize AddType('yang', 'application/yang'); // do not localize AddType('yin', 'application/yin+xml', TMimeTypes.TKind.Text); // do not localize AddType('zip', 'application/zip', TMimeTypes.TKind.Binary); // do not localize AddType('adp', 'audio/adpcm', TMimeTypes.TKind.Binary); // do not localize AddType('au', 'audio/basic', TMimeTypes.TKind.Binary); // do not localize AddType('snd', 'audio/basic', TMimeTypes.TKind.Binary); // do not localize AddType('mid', 'audio/midi', TMimeTypes.TKind.Binary); // do not localize AddType('midi', 'audio/midi', TMimeTypes.TKind.Binary); // do not localize AddType('kar', 'audio/midi', TMimeTypes.TKind.Binary); // do not localize AddType('rmi', 'audio/midi', TMimeTypes.TKind.Binary); // do not localize AddType('mp4a', 'audio/mp4', TMimeTypes.TKind.Binary); // do not localize AddType('mpga', 'audio/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('mp2', 'audio/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('mp2a', 'audio/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('mp3', 'audio/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('m2a', 'audio/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('m3a', 'audio/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('oga', 'audio/ogg', TMimeTypes.TKind.Binary); // do not localize AddType('ogg', 'audio/ogg', TMimeTypes.TKind.Binary); // do not localize AddType('spx', 'audio/ogg', TMimeTypes.TKind.Binary); // do not localize AddType('s3m', 'audio/s3m', TMimeTypes.TKind.Binary); // do not localize AddType('sil', 'audio/silk', TMimeTypes.TKind.Binary); // do not localize AddType('uva', 'audio/vnd.dece.audio', TMimeTypes.TKind.Binary); // do not localize AddType('uvva', 'audio/vnd.dece.audio', TMimeTypes.TKind.Binary); // do not localize AddType('eol', 'audio/vnd.digital-winds', TMimeTypes.TKind.Binary); // do not localize AddType('dra', 'audio/vnd.dra', TMimeTypes.TKind.Binary); // do not localize AddType('dts', 'audio/vnd.dts', TMimeTypes.TKind.Binary); // do not localize AddType('dtshd', 'audio/vnd.dts.hd', TMimeTypes.TKind.Binary); // do not localize AddType('lvp', 'audio/vnd.lucent.voice', TMimeTypes.TKind.Binary); // do not localize AddType('pya', 'audio/vnd.ms-playready.media.pya', TMimeTypes.TKind.Binary); // do not localize AddType('ecelp4800', 'audio/vnd.nuera.ecelp4800', TMimeTypes.TKind.Binary); // do not localize AddType('ecelp7470', 'audio/vnd.nuera.ecelp7470', TMimeTypes.TKind.Binary); // do not localize AddType('ecelp9600', 'audio/vnd.nuera.ecelp9600', TMimeTypes.TKind.Binary); // do not localize AddType('rip', 'audio/vnd.rip', TMimeTypes.TKind.Binary); // do not localize AddType('weba', 'audio/webm', TMimeTypes.TKind.Binary); // do not localize AddType('aac', 'audio/x-aac', TMimeTypes.TKind.Binary); // do not localize AddType('aif', 'audio/x-aiff', TMimeTypes.TKind.Binary); // do not localize AddType('aiff', 'audio/x-aiff', TMimeTypes.TKind.Binary); // do not localize AddType('aifc', 'audio/x-aiff', TMimeTypes.TKind.Binary); // do not localize AddType('caf', 'audio/x-caf', TMimeTypes.TKind.Binary); // do not localize AddType('flac', 'audio/x-flac', TMimeTypes.TKind.Binary); // do not localize AddType('mka', 'audio/x-matroska', TMimeTypes.TKind.Binary); // do not localize AddType('m3u', 'audio/x-mpegurl', TMimeTypes.TKind.Binary); // do not localize AddType('wax', 'audio/x-ms-wax', TMimeTypes.TKind.Binary); // do not localize AddType('wma', 'audio/x-ms-wma', TMimeTypes.TKind.Binary); // do not localize AddType('ram', 'audio/x-pn-realaudio', TMimeTypes.TKind.Binary); // do not localize AddType('ra', 'audio/x-pn-realaudio', TMimeTypes.TKind.Binary); // do not localize AddType('rmp', 'audio/x-pn-realaudio-plugin', TMimeTypes.TKind.Binary); // do not localize AddType('wav', 'audio/x-wav', TMimeTypes.TKind.Binary); // do not localize AddType('xm', 'audio/xm', TMimeTypes.TKind.Binary); // do not localize AddType('cdx', 'chemical/x-cdx'); // do not localize AddType('cif', 'chemical/x-cif'); // do not localize AddType('cmdf', 'chemical/x-cmdf'); // do not localize AddType('cml', 'chemical/x-cml'); // do not localize AddType('csml', 'chemical/x-csml'); // do not localize AddType('xyz', 'chemical/x-xyz'); // do not localize AddType('bmp', 'image/bmp', TMimeTypes.TKind.Binary); // do not localize AddType('cgm', 'image/cgm', TMimeTypes.TKind.Binary); // do not localize AddType('g3', 'image/g3fax', TMimeTypes.TKind.Binary); // do not localize AddType('gif', 'image/gif', TMimeTypes.TKind.Binary); // do not localize AddType('ief', 'image/ief', TMimeTypes.TKind.Binary); // do not localize AddType('jpeg', 'image/jpeg', TMimeTypes.TKind.Binary); // do not localize AddType('jpg', 'image/jpeg', TMimeTypes.TKind.Binary); // do not localize AddType('jpe', 'image/jpeg', TMimeTypes.TKind.Binary); // do not localize AddType('ktx', 'image/ktx', TMimeTypes.TKind.Binary); // do not localize AddType('png', 'image/png', TMimeTypes.TKind.Binary); // do not localize AddType('btif', 'image/prs.btif', TMimeTypes.TKind.Binary); // do not localize AddType('sgi', 'image/sgi', TMimeTypes.TKind.Binary); // do not localize AddType('svg', 'image/svg+xml', TMimeTypes.TKind.Binary); // do not localize AddType('svgz', 'image/svg+xml', TMimeTypes.TKind.Binary); // do not localize AddType('tiff', 'image/tiff', TMimeTypes.TKind.Binary); // do not localize AddType('tif', 'image/tiff', TMimeTypes.TKind.Binary); // do not localize AddType('psd', 'image/vnd.adobe.photoshop', TMimeTypes.TKind.Binary); // do not localize AddType('uvi', 'image/vnd.dece.graphic', TMimeTypes.TKind.Binary); // do not localize AddType('uvvi', 'image/vnd.dece.graphic', TMimeTypes.TKind.Binary); // do not localize AddType('uvg', 'image/vnd.dece.graphic', TMimeTypes.TKind.Binary); // do not localize AddType('uvvg', 'image/vnd.dece.graphic', TMimeTypes.TKind.Binary); // do not localize AddType('sub', 'image/vnd.dvb.subtitle', TMimeTypes.TKind.Binary); // do not localize AddType('djvu', 'image/vnd.djvu', TMimeTypes.TKind.Binary); // do not localize AddType('djv', 'image/vnd.djvu', TMimeTypes.TKind.Binary); // do not localize AddType('dwg', 'image/vnd.dwg', TMimeTypes.TKind.Binary); // do not localize AddType('dxf', 'image/vnd.dxf', TMimeTypes.TKind.Binary); // do not localize AddType('fbs', 'image/vnd.fastbidsheet', TMimeTypes.TKind.Binary); // do not localize AddType('fpx', 'image/vnd.fpx', TMimeTypes.TKind.Binary); // do not localize AddType('fst', 'image/vnd.fst', TMimeTypes.TKind.Binary); // do not localize AddType('mmr', 'image/vnd.fujixerox.edmics-mmr', TMimeTypes.TKind.Binary); // do not localize AddType('rlc', 'image/vnd.fujixerox.edmics-rlc', TMimeTypes.TKind.Binary); // do not localize AddType('mdi', 'image/vnd.ms-modi', TMimeTypes.TKind.Binary); // do not localize AddType('wdp', 'image/vnd.ms-photo', TMimeTypes.TKind.Binary); // do not localize AddType('npx', 'image/vnd.net-fpx', TMimeTypes.TKind.Binary); // do not localize AddType('wbmp', 'image/vnd.wap.wbmp', TMimeTypes.TKind.Binary); // do not localize AddType('xif', 'image/vnd.xiff', TMimeTypes.TKind.Binary); // do not localize AddType('webp', 'image/webp', TMimeTypes.TKind.Binary); // do not localize AddType('3ds', 'image/x-3ds', TMimeTypes.TKind.Binary); // do not localize AddType('ras', 'image/x-cmu-raster', TMimeTypes.TKind.Binary); // do not localize AddType('cmx', 'image/x-cmx', TMimeTypes.TKind.Binary); // do not localize AddType('fh', 'image/x-freehand', TMimeTypes.TKind.Binary); // do not localize AddType('fhc', 'image/x-freehand', TMimeTypes.TKind.Binary); // do not localize AddType('fh4', 'image/x-freehand', TMimeTypes.TKind.Binary); // do not localize AddType('fh5', 'image/x-freehand', TMimeTypes.TKind.Binary); // do not localize AddType('fh7', 'image/x-freehand', TMimeTypes.TKind.Binary); // do not localize AddType('ico', 'image/x-icon', TMimeTypes.TKind.Binary); // do not localize AddType('sid', 'image/x-mrsid-image', TMimeTypes.TKind.Binary); // do not localize AddType('pcx', 'image/x-pcx', TMimeTypes.TKind.Binary); // do not localize AddType('pic', 'image/x-pict', TMimeTypes.TKind.Binary); // do not localize AddType('pct', 'image/x-pict', TMimeTypes.TKind.Binary); // do not localize AddType('pnm', 'image/x-portable-anymap', TMimeTypes.TKind.Binary); // do not localize AddType('pbm', 'image/x-portable-bitmap', TMimeTypes.TKind.Binary); // do not localize AddType('pgm', 'image/x-portable-graymap', TMimeTypes.TKind.Binary); // do not localize AddType('ppm', 'image/x-portable-pixmap', TMimeTypes.TKind.Binary); // do not localize AddType('rgb', 'image/x-rgb', TMimeTypes.TKind.Binary); // do not localize AddType('tga', 'image/x-tga', TMimeTypes.TKind.Binary); // do not localize AddType('xbm', 'image/x-xbitmap', TMimeTypes.TKind.Binary); // do not localize AddType('xpm', 'image/x-xpixmap', TMimeTypes.TKind.Binary); // do not localize AddType('xwd', 'image/x-xwindowdump', TMimeTypes.TKind.Binary); // do not localize AddType('eml', 'message/rfc822'); // do not localize AddType('mime', 'message/rfc822'); // do not localize AddType('igs', 'model/iges'); // do not localize AddType('iges', 'model/iges'); // do not localize AddType('msh', 'model/mesh'); // do not localize AddType('mesh', 'model/mesh'); // do not localize AddType('silo', 'model/mesh'); // do not localize AddType('dae', 'model/vnd.collada+xml', TMimeTypes.TKind.Text); // do not localize AddType('dwf', 'model/vnd.dwf'); // do not localize AddType('gdl', 'model/vnd.gdl'); // do not localize AddType('gtw', 'model/vnd.gtw'); // do not localize AddType('mts', 'model/vnd.mts'); // do not localize AddType('vtu', 'model/vnd.vtu'); // do not localize AddType('wrl', 'model/vrml'); // do not localize AddType('vrml', 'model/vrml'); // do not localize AddType('x3db', 'model/x3d+binary'); // do not localize AddType('x3dbz', 'model/x3d+binary'); // do not localize AddType('x3dv', 'model/x3d+vrml'); // do not localize AddType('x3dvz', 'model/x3d+vrml'); // do not localize AddType('x3d', 'model/x3d+xml', TMimeTypes.TKind.Text); // do not localize AddType('x3dz', 'model/x3d+xml', TMimeTypes.TKind.Text); // do not localize AddType('appcache', 'text/cache-manifest', TMimeTypes.TKind.Text); // do not localize AddType('manifest', 'text/cache-manifest', TMimeTypes.TKind.Text); // do not localize AddType('ics', 'text/calendar', TMimeTypes.TKind.Text); // do not localize AddType('ifb', 'text/calendar', TMimeTypes.TKind.Text); // do not localize AddType('cmd', 'text/cmd', TMimeTypes.TKind.Text); // do not localize AddType('css', 'text/css', TMimeTypes.TKind.Text); // do not localize AddType('csv', 'text/csv', TMimeTypes.TKind.Text); // do not localize AddType('html', 'text/html', TMimeTypes.TKind.Text); // do not localize AddType('htm', 'text/html', TMimeTypes.TKind.Text); // do not localize AddType('n3', 'text/n3', TMimeTypes.TKind.Text); // do not localize AddType('txt', 'text/plain', TMimeTypes.TKind.Text); // do not localize AddType('text', 'text/plain', TMimeTypes.TKind.Text); // do not localize AddType('conf', 'text/plain', TMimeTypes.TKind.Text); // do not localize AddType('def', 'text/plain', TMimeTypes.TKind.Text); // do not localize AddType('list', 'text/plain', TMimeTypes.TKind.Text); // do not localize AddType('log', 'text/plain', TMimeTypes.TKind.Text); // do not localize AddType('in', 'text/plain', TMimeTypes.TKind.Text); // do not localize AddType('dsc', 'text/prs.lines.tag', TMimeTypes.TKind.Text); // do not localize AddType('rtx', 'text/richtext', TMimeTypes.TKind.Text); // do not localize AddType('sgml', 'text/sgml', TMimeTypes.TKind.Text); // do not localize AddType('sgm', 'text/sgml', TMimeTypes.TKind.Text); // do not localize AddType('tsv', 'text/tab-separated-values', TMimeTypes.TKind.Text); // do not localize AddType('t', 'text/troff', TMimeTypes.TKind.Text); // do not localize AddType('tr', 'text/troff', TMimeTypes.TKind.Text); // do not localize AddType('roff', 'text/troff', TMimeTypes.TKind.Text); // do not localize AddType('man', 'text/troff', TMimeTypes.TKind.Text); // do not localize AddType('me', 'text/troff', TMimeTypes.TKind.Text); // do not localize AddType('ms', 'text/troff', TMimeTypes.TKind.Text); // do not localize AddType('ttl', 'text/turtle', TMimeTypes.TKind.Text); // do not localize AddType('uri', 'text/uri-list', TMimeTypes.TKind.Text); // do not localize AddType('uris', 'text/uri-list', TMimeTypes.TKind.Text); // do not localize AddType('urls', 'text/uri-list', TMimeTypes.TKind.Text); // do not localize AddType('vcard', 'text/vcard', TMimeTypes.TKind.Text); // do not localize AddType('curl', 'text/vnd.curl', TMimeTypes.TKind.Text); // do not localize AddType('dcurl', 'text/vnd.curl.dcurl', TMimeTypes.TKind.Text); // do not localize AddType('scurl', 'text/vnd.curl.scurl', TMimeTypes.TKind.Text); // do not localize AddType('mcurl', 'text/vnd.curl.mcurl', TMimeTypes.TKind.Text); // do not localize AddType('sub', 'text/vnd.dvb.subtitle', TMimeTypes.TKind.Text); // do not localize AddType('fly', 'text/vnd.fly', TMimeTypes.TKind.Text); // do not localize AddType('flx', 'text/vnd.fmi.flexstor', TMimeTypes.TKind.Text); // do not localize AddType('gv', 'text/vnd.graphviz', TMimeTypes.TKind.Text); // do not localize AddType('3dml', 'text/vnd.in3d.3dml', TMimeTypes.TKind.Text); // do not localize AddType('spot', 'text/vnd.in3d.spot', TMimeTypes.TKind.Text); // do not localize AddType('jad', 'text/vnd.sun.j2me.app-descriptor', TMimeTypes.TKind.Text); // do not localize AddType('wml', 'text/vnd.wap.wml', TMimeTypes.TKind.Text); // do not localize AddType('wmls', 'text/vnd.wap.wmlscript', TMimeTypes.TKind.Text); // do not localize AddType('s', 'text/x-asm', TMimeTypes.TKind.Text); // do not localize AddType('asm', 'text/x-asm', TMimeTypes.TKind.Text); // do not localize AddType('c', 'text/x-c', TMimeTypes.TKind.Text); // do not localize AddType('cc', 'text/x-c', TMimeTypes.TKind.Text); // do not localize AddType('cxx', 'text/x-c', TMimeTypes.TKind.Text); // do not localize AddType('cpp', 'text/x-c', TMimeTypes.TKind.Text); // do not localize AddType('h', 'text/x-c', TMimeTypes.TKind.Text); // do not localize AddType('hh', 'text/x-c', TMimeTypes.TKind.Text); // do not localize AddType('dic', 'text/x-c', TMimeTypes.TKind.Text); // do not localize AddType('f', 'text/x-fortran', TMimeTypes.TKind.Text); // do not localize AddType('for', 'text/x-fortran', TMimeTypes.TKind.Text); // do not localize AddType('f77', 'text/x-fortran', TMimeTypes.TKind.Text); // do not localize AddType('f90', 'text/x-fortran', TMimeTypes.TKind.Text); // do not localize AddType('java', 'text/x-java-source', TMimeTypes.TKind.Text); // do not localize AddType('opml', 'text/x-opml', TMimeTypes.TKind.Text); // do not localize AddType('p', 'text/x-pascal', TMimeTypes.TKind.Text); // do not localize AddType('pas', 'text/x-pascal', TMimeTypes.TKind.Text); // do not localize AddType('nfo', 'text/x-nfo', TMimeTypes.TKind.Text); // do not localize AddType('etx', 'text/x-setext', TMimeTypes.TKind.Text); // do not localize AddType('sfv', 'text/x-sfv', TMimeTypes.TKind.Text); // do not localize AddType('uu', 'text/x-uuencode', TMimeTypes.TKind.Text); // do not localize AddType('vcs', 'text/x-vcalendar', TMimeTypes.TKind.Text); // do not localize AddType('vcf', 'text/x-vcard', TMimeTypes.TKind.Text); // do not localize AddType('vcf', 'text/x-yaml', TMimeTypes.TKind.Text); // do not localize AddType('xml', 'text/xml', TMimeTypes.TKind.Text); // do not localize AddType('xsl', 'text/xml', TMimeTypes.TKind.Text); // do not localize AddType('dtd', 'text/xml-dtd', TMimeTypes.TKind.Text); // do not localize AddType('yaml', 'text/yaml', TMimeTypes.TKind.Text); // do not localize AddType('3gp', 'video/3gpp', TMimeTypes.TKind.Binary); // do not localize AddType('3g2', 'video/3gpp2', TMimeTypes.TKind.Binary); // do not localize AddType('h261', 'video/h261', TMimeTypes.TKind.Binary); // do not localize AddType('h263', 'video/h263', TMimeTypes.TKind.Binary); // do not localize AddType('h264', 'video/h264', TMimeTypes.TKind.Binary); // do not localize AddType('jpgv', 'video/jpeg', TMimeTypes.TKind.Binary); // do not localize AddType('jpm', 'video/jpm', TMimeTypes.TKind.Binary); // do not localize AddType('jpgm', 'video/jpm', TMimeTypes.TKind.Binary); // do not localize AddType('mj2', 'video/mj2', TMimeTypes.TKind.Binary); // do not localize AddType('mjp2', 'video/mj2', TMimeTypes.TKind.Binary); // do not localize AddType('mp4', 'video/mp4', TMimeTypes.TKind.Binary); // do not localize AddType('mp4v', 'video/mp4', TMimeTypes.TKind.Binary); // do not localize AddType('mpg4', 'video/mp4', TMimeTypes.TKind.Binary); // do not localize AddType('mpeg', 'video/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('mpg', 'video/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('mpe', 'video/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('m1v', 'video/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('m2v', 'video/mpeg', TMimeTypes.TKind.Binary); // do not localize AddType('ogv', 'video/ogg', TMimeTypes.TKind.Binary); // do not localize AddType('qt', 'video/quicktime', TMimeTypes.TKind.Binary); // do not localize AddType('mov', 'video/quicktime', TMimeTypes.TKind.Binary); // do not localize AddType('uvh', 'video/vnd.dece.hd', TMimeTypes.TKind.Binary); // do not localize AddType('uvvh', 'video/vnd.dece.hd', TMimeTypes.TKind.Binary); // do not localize AddType('uvm', 'video/vnd.dece.mobile', TMimeTypes.TKind.Binary); // do not localize AddType('uvvm', 'video/vnd.dece.mobile', TMimeTypes.TKind.Binary); // do not localize AddType('uvp', 'video/vnd.dece.pd', TMimeTypes.TKind.Binary); // do not localize AddType('uvvp', 'video/vnd.dece.pd', TMimeTypes.TKind.Binary); // do not localize AddType('uvs', 'video/vnd.dece.sd', TMimeTypes.TKind.Binary); // do not localize AddType('uvvs', 'video/vnd.dece.sd', TMimeTypes.TKind.Binary); // do not localize AddType('uvv', 'video/vnd.dece.video', TMimeTypes.TKind.Binary); // do not localize AddType('uvvv', 'video/vnd.dece.video', TMimeTypes.TKind.Binary); // do not localize AddType('dvb', 'video/vnd.dvb.file', TMimeTypes.TKind.Binary); // do not localize AddType('fvt', 'video/vnd.fvt', TMimeTypes.TKind.Binary); // do not localize AddType('mxu', 'video/vnd.mpegurl', TMimeTypes.TKind.Binary); // do not localize AddType('m4u', 'video/vnd.mpegurl', TMimeTypes.TKind.Binary); // do not localize AddType('pyv', 'video/vnd.ms-playready.media.pyv', TMimeTypes.TKind.Binary); // do not localize AddType('uvu', 'video/vnd.uvvu.mp4', TMimeTypes.TKind.Binary); // do not localize AddType('uvvu', 'video/vnd.uvvu.mp4', TMimeTypes.TKind.Binary); // do not localize AddType('viv', 'video/vnd.vivo', TMimeTypes.TKind.Binary); // do not localize AddType('webm', 'video/webm', TMimeTypes.TKind.Binary); // do not localize AddType('f4v', 'video/x-f4v', TMimeTypes.TKind.Binary); // do not localize AddType('fli', 'video/x-fli', TMimeTypes.TKind.Binary); // do not localize AddType('flv', 'video/x-flv', TMimeTypes.TKind.Binary); // do not localize AddType('m4v', 'video/x-m4v', TMimeTypes.TKind.Binary); // do not localize AddType('mkv', 'video/x-matroska', TMimeTypes.TKind.Binary); // do not localize AddType('mk3d', 'video/x-matroska', TMimeTypes.TKind.Binary); // do not localize AddType('mks', 'video/x-matroska', TMimeTypes.TKind.Binary); // do not localize AddType('mng', 'video/x-mng', TMimeTypes.TKind.Binary); // do not localize AddType('asf', 'video/x-ms-asf', TMimeTypes.TKind.Binary); // do not localize AddType('asx', 'video/x-ms-asf', TMimeTypes.TKind.Binary); // do not localize AddType('vob', 'video/x-ms-vob', TMimeTypes.TKind.Binary); // do not localize AddType('wm', 'video/x-ms-wm', TMimeTypes.TKind.Binary); // do not localize AddType('wmv', 'video/x-ms-wmv', TMimeTypes.TKind.Binary); // do not localize AddType('wmx', 'video/x-ms-wmx', TMimeTypes.TKind.Binary); // do not localize AddType('wvx', 'video/x-ms-wvx', TMimeTypes.TKind.Binary); // do not localize AddType('avi', 'video/x-msvideo', TMimeTypes.TKind.Binary); // do not localize AddType('movie', 'video/x-sgi-movie', TMimeTypes.TKind.Binary); // do not localize AddType('smv', 'video/x-smv', TMimeTypes.TKind.Binary); // do not localize AddType('ice', 'x-conference/x-cooltalk'); // do not localize {$ENDREGION} end; procedure TMimeTypes.AddOSTypes; {$IF DEFINED(MSWINDOWS)} procedure LoadRegistry; const CExtsKey = '\'; CTypesKey = '\MIME\Database\Content Type\'; // do not localize var LReg: TRegistry; LKeys: TStringList; LExt, LType: string; begin LReg := TRegistry.Create; try LKeys := TStringList.Create; try LReg.RootKey := HKEY_CLASSES_ROOT; if LReg.OpenKeyReadOnly(CExtsKey) then begin LReg.GetKeyNames(LKeys); LReg.CloseKey; for LExt in LKeys do if LExt.StartsWith('.') then if LReg.OpenKeyReadOnly(CExtsKey + LExt) then begin LType := LReg.ReadString('Content Type'); // do not localize if LType <> '' then AddType(LExt, LType, TKind.Undefined, True); LReg.CloseKey; end; end; if LReg.OpenKeyReadOnly(CTypesKey) then begin LReg.GetKeyNames(LKeys); LReg.CloseKey; for LType in LKeys do if LReg.OpenKeyReadOnly(CTypesKey + LType) then begin LExt := LReg.ReadString('Extension'); // do not localize if LExt <> '' then AddType(LExt, LType, TKind.Undefined, True); LReg.CloseKey; end; end; finally LKeys.Free; end; finally LReg.Free; end; end; {$ENDIF} {$IF DEFINED(LINUX)} procedure LoadFile(const AFileName: string); var LTypes: TStringList; LItem: string; LArr: TArray<string>; i, j: Integer; begin if not FileExists(AFileName) then Exit; LTypes := TStringList.Create; try try LTypes.LoadFromFile(AFileName); except // if file is not accessible (eg, no rights), then just exit Exit; end; for j := 0 to LTypes.Count - 1 do begin LItem := LTypes[j].Trim; if (LItem <> '') and not LItem.StartsWith('#') then begin LArr := LItem.Split([' ', #9], TStringSplitOptions.ExcludeEmpty); for i := 1 to Length(LArr) - 1 do AddType(LArr[i], LArr[0], TKind.Undefined, True); end; end; finally LTypes.Free; end; end; {$ENDIF} {$IF DEFINED(MACOS) and not DEFINED(IOS)} procedure LoadFile(const AFileName: string); const CBinary: RawByteString = 'bplist'; var LItems, LExts: TStringList; i: Integer; LArr: TArray<string>; LType: string; LMode: Integer; j: Integer; LFile: TFileStream; LHeader: RawByteString; begin if not FileExists(AFileName) then Exit; LItems := TStringList.Create; try LExts := TStringList.Create; try try LFile := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try SetLength(LHeader, Length(CBinary)); // ignore binary plist if (LFile.Read(LHeader[1], Length(CBinary)) = Length(CBinary)) and (LHeader = CBinary) then Exit; LFile.Position := 0; LItems.LoadFromStream(LFile); finally LFile.Free; end; except // if file is not accessible (eg, no rights), then just exit Exit; end; LMode := -1; for i := 0 to LItems.Count - 1 do begin LArr := LItems[i].Split(['<', '>', #9, ' '], TStringSplitOptions.ExcludeEmpty); if Length(LArr) = 3 then begin if SameText(LArr[0], 'key') and SameText(LArr[1], 'CFBundleTypeExtensions') then // do not localize LMode := 0 else if SameText(LArr[0], 'key') and SameText(LArr[1], 'CFBundleTypeMIMETypes') then // do not localize LMode := 1 else if SameText(LArr[0], 'key') then // do not localize LMode := 2 else if SameText(LArr[0], 'string') then // do not localize begin if LMode = 0 then LExts.Add(LArr[1]) else if LMode = 1 then LType := LArr[1]; end end else if (Length(LArr) = 1) and SameText(LArr[0], '/dict') and (LMode >= 0) then // do not localize begin if LType <> '' then for j := 0 to LExts.Count - 1 do AddType(LExts[j], LType, TKind.Undefined, True); LMode := -1; LExts.Clear; LType := ''; end end; finally LExts.Free; end; finally LItems.Free; end; end; {$ENDIF} {$IF DEFINED(LINUX)} const CTypeFile = 'mime.types'; // do not localize {$ENDIF} {$IF DEFINED(MACOS) and not DEFINED(IOS)} const CTypeFile = '/Applications/Safari.app/Contents/Info.plist'; // do not localize {$ENDIF} begin {$IF DEFINED(MSWINDOWS)} LoadRegistry; {$ENDIF} {$IF DEFINED(LINUX)} LoadFile(TPath.Combine(TPath.GetHomePath, '.' + CTypeFile)); LoadFile('/etc/' + CTypeFile); // do not localize {$ENDIF} {$IF DEFINED(MACOS) and not DEFINED(IOS)} LoadFile(CTypeFile); {$ENDIF} end; procedure TMimeTypes.Clear; begin FTypeDict.Clear; FExtDict.Clear; FInfos.Clear; end; function TMimeTypes.NormalizeExt(const AExt: string): string; begin Result := AExt.Trim.ToLower; if (Result <> '') and (Result[Low(Result)] = '.') then Result := Result.Substring(1); end; function TMimeTypes.GetFileInfo(const AFileName: string; out AType: string; out AKind: TKind): Boolean; begin Result := GetExtInfo(ExtractFileExt(AFileName), AType, AKind); end; function TMimeTypes.GetExtInfo(const AExt: string; out AType: string; out AKind: TKind): Boolean; var LExt: string; LInfo: TInfo; begin LExt := NormalizeExt(AExt); Result := FExtDict.TryGetValue(LExt, LInfo); if Result then begin AType := LInfo.FType; AKind := LInfo.FKind; end else begin GetExtInfo('bin', AType, AKind); // do not localize AKind := TMimeTypes.TKind.Undefined; end; end; function TMimeTypes.GetTypeInfo(const AType: string; out AExt: string; out AKind: TKind): Boolean; var LInfo: TInfo; LType: string; begin LType := AType.Trim.ToLower; Result := FTypeDict.TryGetValue(AType, LInfo); if Result then begin AExt := LInfo.FExt; AKind := LInfo.FKind; end else begin GetExtInfo('bin', LType, AKind); // do not localize AKind := TMimeTypes.TKind.Undefined; end; end; procedure TMimeTypes.AddType(const AExt, AType: string; AKind: TKind; AIgnoreDups: Boolean); var LInfo, LTmp1, LTmp2: TInfo; LType, LKey: string; begin LType := AType.Trim.ToLower; if LType = '' then raise EArgumentOutOfRangeException.CreateRes(@SMimeTypeEmpty); LInfo := TInfo.Create; LInfo.FExt := NormalizeExt(AExt); LInfo.FType := LType; LInfo.FKind := AKind; LKey := LInfo.FExt + '=' + LInfo.FType; if FInfos.ContainsKey(LKey) then begin LInfo.Free; if AIgnoreDups then Exit; raise EListError.CreateRes(@SMimeDuplicateType); end; FInfos.Add(LKey, LInfo); LTmp1 := nil; LTmp2 := nil; if (LInfo.FExt <> '') and not FExtDict.TryGetValue(LInfo.FExt, LTmp1) then FExtDict.Add(LInfo.FExt, LInfo); if (LInfo.FType <> '') and not FTypeDict.TryGetValue(LInfo.FType, LTmp2) then FTypeDict.Add(LInfo.FType, LInfo); if LInfo.FKind = TKind.Undefined then if (LTmp1 <> nil) and (LTmp1.FKind <> TKind.Undefined) then LInfo.FKind := LTmp1.FKind else if (LTmp2 <> nil) and (LTmp2.FKind <> TKind.Undefined) then LInfo.FKind := LTmp2.FKind; end; procedure TMimeTypes.ForAll(const AExtMask, ATypeMask: string; AFunc: TIterateFunc); var S: string; LExtMask: TMask; LTypeMask: TMask; LInfo: TInfo; begin LExtMask := nil; LTypeMask := nil; try S := NormalizeExt(AExtMask); if S <> '' then LExtMask := TMask.Create(S); S := ATypeMask.Trim.ToLower; if S <> '' then LTypeMask := TMask.Create(S); for LInfo in FInfos.Values do if ((LExtMask = nil) or LExtMask.Matches(LInfo.FExt)) and ((LTypeMask = nil) or LTypeMask.Matches(LInfo.FType)) then if AFunc(LInfo.FExt, LInfo.FType, LInfo.FKind) then Break; finally LTypeMask.Free; LExtMask.Free; end; end; procedure TMimeTypes.ForExts(const AExtMask: string; AFunc: TIterateFunc); begin ForAll(AExtMask, '', AFunc); end; procedure TMimeTypes.ForTypes(const ATypeMask: string; AFunc: TIterateFunc); begin ForAll('', ATypeMask, AFunc); end; { TAcceptValueItem } destructor TAcceptValueItem.Destroy; begin FParams.Free; inherited Destroy; end; function TAcceptValueItem.GetParams: TStrings; begin if FParams = nil then FParams := TStringList.Create; Result := FParams; end; procedure TAcceptValueItem.Parse; begin // nothing end; { TAcceptValueListBase } constructor TAcceptValueListBase<T>.Create; begin inherited Create; FInvariant.DecimalSeparator := '.'; FItems := TObjectList<T>.Create(TDelegatedComparer<T>.Create( function (const Left, Right: T): Integer begin Result := - CompareWeights(Left.FWeight, Right.FWeight); if Result = 0 then if Left.FOrder < Right.FOrder then Result := -1 else if Left.FOrder > Right.FOrder then Result := 1; end), True); end; constructor TAcceptValueListBase<T>.Create(const AValue: string); begin Create; Parse(AValue); end; destructor TAcceptValueListBase<T>.Destroy; begin FItems.Free; inherited Destroy; end; class function TAcceptValueListBase<T>.CompareWeights(AWeight1, AWeight2: Double): Integer; begin if Abs(AWeight1 - AWeight2) <= 0.001 then Result := 0 else if AWeight1 < AWeight2 then Result := -1 else if AWeight1 > AWeight2 then Result := 1; end; function TAcceptValueListBase<T>.GetCount: Integer; begin Result := FItems.Count; end; function TAcceptValueListBase<T>.GetNames(AIndex: Integer): string; begin Result := FItems[AIndex].Name; end; function TAcceptValueListBase<T>.GetWeights(AIndex: Integer): Double; begin Result := FItems[AIndex].Weight; end; function TAcceptValueListBase<T>.GetItems(AIndex: Integer): T; begin Result := FItems[AIndex]; end; function TAcceptValueListBase<T>.GetEnumerator: TEnumerator<T>; begin Result := FItems.GetEnumerator; end; procedure TAcceptValueListBase<T>.BeginUpdate; begin Inc(FUpdates); end; procedure TAcceptValueListBase<T>.EndUpdate; begin if FUpdates > 0 then begin Dec(FUpdates); if FUpdates = 0 then FItems.Sort; end; end; procedure TAcceptValueListBase<T>.Clear; begin BeginUpdate; try FItems.Clear; finally EndUpdate; end; end; procedure TAcceptValueListBase<T>.Delete(AIndex: Integer); begin FItems.Delete(AIndex); end; procedure TAcceptValueListBase<T>.Add(const AName: string; AWeight: Double; AExtra: TStrings); var LItem: T; LName, LType: string; LIndex: Integer; LKind: TMimeTypes.TKind; begin LName := AName.Trim.ToLower; if LName = '' then raise EArgumentOutOfRangeException.CreateRes(@SMimeValueEmpty); if (AWeight < 0) or (AWeight > 1) then raise EArgumentOutOfRangeException.CreateRes(@SMimeWeightOutOfRange); if TMimeTypes.Default.GetExtInfo(LName, LType, LKind) then LName := LType; BeginUpdate; try for LItem in FItems do if LItem.Name = LName then begin if LItem.Weight <> 0 then if AWeight = 0 then LItem.FWeight := 0 else if AWeight > LItem.Weight then LItem.FWeight := AWeight; Exit; end; LItem := T.Create; try LItem.FName := LName; LItem.FWeight := AWeight; LItem.FOrder := FItems.Count; if (AExtra <> nil) and (AExtra.Count > 0) then LItem.Params.AddStrings(AExtra); LItem.Parse; except LItem.Free; raise; end; FItems.Add(LItem); finally EndUpdate; end; end; procedure TAcceptValueListBase<T>.Assign(const AAcceptList: TAcceptValueListBase<T>); var LItem: T; begin BeginUpdate; try Clear; for LItem in AAcceptList do Add(LItem.Name, LItem.Weight, LItem.FParams); finally EndUpdate; end; end; procedure TAcceptValueListBase<T>.Parse(const AValue: string); var i, j: Integer; LItem, LParam, LName, LValue: string; LWeight: Double; LItems, LParams: TArray<string>; LExtra: TStringList; begin BeginUpdate; LExtra := TStringList.Create; try Clear; LItems := AValue.Split([','], TStringSplitOptions.ExcludeEmpty); for LItem in LItems do begin LParams := LItem.Split([';'], TStringSplitOptions.ExcludeEmpty); if (Length(LParams) > 0) and (LParams[0].Trim <> '') then begin LWeight := 1; LExtra.Clear; for i := 1 to Length(LParams) - 1 do begin LParam := LParams[i]; j := LParam.IndexOf('='); if j < 0 then j := LParam.Length; LName := LParam.Substring(0, j).Trim.ToLower; LValue := LParam.Substring(j + 1, MaxInt).Trim.ToLower; if LName = 'q' then LWeight := StrToFloatDef(LValue, 0, FInvariant) else if LValue <> '' then LExtra.AddPair(LName, LValue) else LExtra.Add(LName); end; Add(LParams[0], LWeight, LExtra); end; end; finally LExtra.Free; EndUpdate; end; end; function TAcceptValueListBase<T>.ToString: string; var LItem: T; LParam: string; begin for LItem in Self do begin if Result <> '' then Result := Result + ', '; Result := Result + LItem.Name; if LItem.Weight <> 1 then Result := Result + ';q=' + // do not localize FloatToStrF(LItem.Weight, ffGeneral, 3, 3, FInvariant); if LItem.FParams <> nil then for LParam in LItem.Params do Result := Result + ';' + LParam; end; end; function TAcceptValueListBase<T>.InternalNegotiate(AAcceptList: TAcceptValueListBase<T>; AAcceptFunc: TAcceptFunc; var AMode: TMatchMode; out AWeight: Double): string; var i, j: Integer; LMask1: TMask; LName1, LName2: string; LNewWeight: Double; LIgnoreLiterals: Boolean; begin Result := ''; AWeight := 0; LIgnoreLiterals := (AMode = TMatchMode.Reverse); for i := 0 to Count - 1 do begin if Weights[i] = 0 then Continue; LName1 := Names[i]; if (AAcceptList = nil) or (AAcceptList.Count = 0) then begin if (not Assigned(AAcceptFunc) or AAcceptFunc(LName1, Weights[i], Items[i])) then begin AWeight := Weights[i]; Exit(LName1); end; Continue; end; LMask1 := nil; try for j := 0 to AAcceptList.Count - 1 do begin LNewWeight := Weights[i] * AAcceptList.Weights[j]; if LNewWeight < AWeight then Break; if j = 0 then if LName1.Contains('*') then LMask1 := TMask.Create(LName1) else if (AMode <> TMatchMode.Intersect) and LIgnoreLiterals then Break; LName2 := AAcceptList.Names[j]; if LName2.Contains('*') and (AMode <> TMatchMode.Intersect) and not LIgnoreLiterals then begin AMode := TMatchMode.Reverse; Continue; end; if (LNewWeight <> 0) and ((LMask1 <> nil) and LMask1.Matches(LName2) or (LMask1 = nil) and (LName1 = LName2)) and (not Assigned(AAcceptFunc) or AAcceptFunc(LName2, LNewWeight, AAcceptList.Items[j])) then if AWeight < LNewWeight then begin Result := LName2; AWeight := LNewWeight; end; end; finally LMask1.Free; end; end; end; function TAcceptValueListBase<T>.Negotiate(const AAcceptList: TAcceptValueListBase<T>; out AWeight: Double; AAcceptFunc: TAcceptFunc): string; var LItem: string; LWeight: Double; LMode: TMatchMode; begin if Count > 0 then begin LMode := TMatchMode.Forward; Result := InternalNegotiate(AAcceptList, AAcceptFunc, LMode, AWeight); end else LMode := TMatchMode.Reverse; if LMode = TMatchMode.Reverse then begin LItem := AAcceptList.InternalNegotiate(Self, AAcceptFunc, LMode, LWeight); if LWeight > AWeight then begin Result := LItem; AWeight := LWeight; end; end; end; function TAcceptValueListBase<T>.Negotiate(const AAcceptList: string; out AWeight: Double; AAcceptFunc: TAcceptFunc): string; var LList: TAcceptValueListBase<T>; begin LList := TAcceptValueListBase<T>.Create(AAcceptList); try Result := Negotiate(LList, AWeight, AAcceptFunc); finally LList.Free; end; end; procedure TAcceptValueListBase<T>.Intersect(const AAcceptList: TAcceptValueListBase<T>); var LList: TAcceptValueListBase<T>; LWeight: Double; LFunc: TAcceptFunc; LMode: TMatchMode; begin LList := TAcceptValueListBase<T>.Create; try LList.BeginUpdate; try LFunc := function (const AName: string; AWeight: Double; AItem: T): Boolean begin LList.Add(AName, AWeight, AItem.FParams); Result := False; end; LMode := TMatchMode.Intersect; InternalNegotiate(AAcceptList, LFunc, LMode, LWeight); AAcceptList.InternalNegotiate(Self, LFunc, LMode, LWeight); finally LList.EndUpdate; end; FreeAndNil(FItems); FItems := LList.FItems; LList.FItems := nil; finally LList.Free; end; end; { THeaderValueList } constructor THeaderValueList.Create; begin inherited Create; FItems := TList<TItem>.Create; end; constructor THeaderValueList.Create(const AValue: string); begin Create; Parse(AValue); end; destructor THeaderValueList.Destroy; begin Clear; FItems.Free; inherited Destroy; end; function THeaderValueList.GetNames(AIndex: Integer): string; begin Result := FItems[AIndex].FName; end; function THeaderValueList.GetValues(AIndex: Integer): string; begin Result := FItems[AIndex].FValue; end; function THeaderValueList.GetValue(const AName: string): string; var i: Integer; begin i := IndexOfName(AName); if i >= 0 then Result := FItems.List[i].FValue else Result := ''; end; function THeaderValueList.GetCount: Integer; begin Result := FItems.Count; end; function THeaderValueList.IndexOfName(const AName: string): Integer; var i: Integer; begin for i := 0 to Count - 1 do if FItems.List[i].FName = AName then Exit(i); Result := -1; end; procedure THeaderValueList.Clear; begin FSubject := ''; FItems.Clear; end; procedure THeaderValueList.Delete(AIndex: Integer); begin FItems.Delete(AIndex); end; procedure THeaderValueList.Add(const AItem: TItem); var i: Integer; begin if AItem.FName <> '' then begin i := IndexOfName(AItem.FName); if i >= 0 then FItems[i] := AItem else FItems.Add(AItem); end; end; procedure THeaderValueList.Add(const AName: string); var LItem: TItem; begin LItem.FName := AName; LItem.FValue := ''; LItem.FFlags := [TFlag.KeyOnly]; Add(LItem); end; procedure THeaderValueList.Add(const AName, AValue: string; AQuoteVal: Boolean); var LItem: TItem; begin LItem.FName := AName; LItem.FValue := AValue; if AQuoteVal then LItem.FFlags := [TFlag.Quoted] else LItem.FFlags := []; Add(LItem); end; procedure THeaderValueList.Assign(const AValueList: THeaderValueList); var i: Integer; begin Clear; Subject := AValueList.Subject; for i := 0 to AValueList.Count - 1 do FItems.Add(AValueList.FItems.List[i]); end; procedure THeaderValueList.Parse(const AValue: string); var s: string; LItems: TArray<string>; LItem: string; LValue: TItem; i: Integer; begin Clear; s := AValue.Trim; if s.IsEmpty then Exit; i := s.IndexOfAny(['"', ',', ';', '=', ' ']); if i >= 0 then begin while (i < s.Length) and (s.Chars[i] = ' ') do Inc(i); if (i < s.Length) and not ((s.Chars[i] = '"') or (s.Chars[i] = ',') or (s.Chars[i] = ';') or (s.Chars[i] = '=')) then begin Subject := s.Substring(0, i - 1).Trim; s := s.Substring(i, MaxInt); end; end else begin Subject := s; Exit; end; LItems := s.Split([','], '"', '"', TStringSplitOptions.ExcludeEmpty); for LItem in LItems do begin i := LItem.IndexOf('='); if i < 0 then begin LValue.FName := LItem.Trim; LValue.FValue := ''; LValue.FFlags := [TFlag.KeyOnly]; end else begin LValue.FName := LItem.Substring(0, i).Trim; LValue.FValue := LItem.Substring(i + 1).Trim; if LValue.FValue.StartsWith('"') and LValue.FValue.EndsWith('"') then begin LValue.FValue := LValue.FValue.Substring(1, LValue.FValue.Length - 2); LValue.FFlags := [TFlag.Quoted]; end else LValue.FFlags := []; end; Add(LValue); end; end; function THeaderValueList.ToString: string; var i: Integer; begin if Subject <> '' then Result := Subject else Result := ''; for i := 0 to Count - 1 do begin if (i = 0) and (Result <> '') then Result := Result + ' ' else if i > 0 then Result := Result + ', '; Result := Result + FItems.List[i].FName; if not (TFlag.KeyOnly in FItems.List[i].FFlags) then begin Result := Result + '='; if TFlag.Quoted in FItems.List[i].FFlags then Result := Result + '"' + FItems.List[i].FValue + '"' else Result := Result + FItems.List[i].FValue; end; end; end; procedure THeaderValueList.Merge(const AValueList: THeaderValueList); var i: Integer; begin if (Subject = '') and (AValueList.Subject <> '') then Subject := AValueList.Subject; for i := 0 to AValueList.Count - 1 do Add(AValueList.FItems.List[i]); end; procedure THeaderValueList.Merge(const AValue: string); var LValueList: THeaderValueList; begin LValueList := THeaderValueList.Create(AValue); try Merge(LValueList); finally LValueList.Free; end; end; end.
// Tableau/Liste contenant la référence des extensions connues // Nous nous servirons des index de ces Clef pour référencer // ailleurs les liens avec ces extensions (gains de place) // unit Extensions; interface uses classes, sysUtils; type TExtensions = class(TStringList) protected // (object associé) mysuminfo : Tsuminfo; private function GetExtensionType(Key : String) : String; procedure SetExtensionType(Key : String; value : String); public constructor Create(); destructor Destroy; override; property ExtensionType[Key : String] : String read GetExtensionType write SetExtensionType; procedure AddExtensionType(Ext: String; ExtType: String); end; EExtensionsNotUnique = class(Exception); implementation constructor TExtensions.Create(); begin Duplicates := dupError; OwnsObjects := False; Sorted := True; end; destructor TExtensions.Destroy; begin inherited Destroy; end; procedure TExtensions.AddExtensionType(Ext: String; ExtType: string); var Dup : string; begin try Values[Ext] := ExtType; except on EStringListError do begin Dup := Values[Ext]; raise EExtensionsNotUnique.create('['+ExtType+Ext+'] duplicates on type ['+Dup+']'); end; end; end; function TExtensions.GetExtensionType(Key : String) : String; begin result := Values[Key]; end; procedure TExtensions.SetExtensionType(Key : String; value : String); begin Values[Key] := Value; end; end.
(* Chapter 8 - Program 1 *) program EnumeratedTypes; type Days = (Mon,Tue,Wed,Thu,Fri,Sat,Sun); TimeOfDay = (Morning,Afternoon,Evening,Night); var Day : Days; Time : TimeOfDay; RegularRate : real; EveningPremium : real; NightPremium : real; WeekendPremium : real; TotalPay : real; begin (* main program *) Writeln('Pay rate table':33); Writeln; Write(' DAY Morning Afternoon'); Writeln(' Evening Night'); Writeln; RegularRate := 12.00; (* This is the normal pay rate *) EveningPremium := 1.10; (* 10 percent extra for working late *) NightPremium := 1.33; (* 33 percent extra for graveyard *) WeekendPremium := 1.25; (* 25 percent extra for weekends *) for Day := Mon to Sun do begin case Day of Mon : Write('Monday '); Tue : Write('Tuesday '); Wed : Write('Wednesday'); Thu : Write('Thursday '); Fri : Write('Friday '); Sat : Write('Saturday '); Sun : Write('Sunday '); end; (* of case statement *) for Time := Morning to Night do begin case Time of Morning : TotalPay := RegularRate; Afternoon : TotalPay := RegularRate; Evening : TotalPay := RegularRate * EveningPremium; Night : TotalPay := RegularRate * NightPremium; end; (* of case statement *) case Day of Sat : TotalPay := TotalPay * WeekendPremium; Sun : TotalPay := TotalPay * WeekendPremium; end; (* of case statement *) Write(TotalPay:10:2); end; (* of "for Time" loop *) Writeln; end; (* of "for Day" loop *) end. (* of main program *) { Result of execution Pay rate table DAY Morning Afternoon Evening Night Monday 12.00 12.00 13.20 15.96 Tuesday 12.00 12.00 13.20 15.96 Wednesday 12.00 12.00 13.20 15.96 Thursday 12.00 12.00 13.20 15.96 Friday 12.00 12.00 13.20 15.96 Saturday 15.00 15.00 16.50 19.95 Sunday 15.00 15.00 16.50 19.95 } 
unit UniqueInstanceBase; {$mode objfpc}{$H+} interface uses Classes, SysUtils, simpleipc; const ParamsSeparator = '|'; var FIPCServer: TSimpleIPCServer; procedure InitializeUniqueServer(const ServerId: String); function GetFormattedParams: String; function GetServerId(const Identifier: String): String; implementation uses SimpleIPCWrapper; const BaseServerId = 'tuniqueinstance_'; procedure InitializeUniqueServer(const ServerId: String); begin //It's the first instance. Init the server if FIPCServer = nil then begin FIPCServer := TSimpleIPCServer.Create(nil); FIPCServer.ServerID := ServerId; FIPCServer.Global := True; InitServer(FIPCServer); end; end; function GetFormattedParams: String; var i: Integer; begin Result := ''; for i := 1 to ParamCount do Result := Result + ParamStr(i) + ParamsSeparator; end; function GetServerId(const Identifier: String): String; begin if Identifier <> '' then Result := BaseServerId + Identifier else Result := BaseServerId + ExtractFileName(ParamStr(0)); end; finalization FIPCServer.Free; end.
unit Unit1; interface Uses Windows, WinSpool, Printers; Function PrinterSupportsPostscript: Boolean; procedure SendRawPostscript( const Data: string ); implementation {: Check if the currently selected printer supports postscript. Only applicable on Win2K/XP! } Function PrinterSupportsPostscript: Boolean; Const POSTSCRIPT_PASSTHROUGH = 4115; POSTSCRIPT_IDENTIFY = 4117; Escapes: Array [0..2] of Cardinal = ( POSTSCRIPT_DATA, POSTSCRIPT_IDENTIFY, POSTSCRIPT_PASSTHROUGH ); Var res: Integer; i: Integer; Begin Result := false; For i:= Low( Escapes ) to High( Escapes ) Do Begin res := ExtEscape( printer.Handle, QUERYESCSUPPORT, sizeof(Escapes[0]), @Escapes[i], 0, nil ); If res <> 0 Then Begin Result := true; Break; End; End; End; procedure SendRawPostscript( const Data: string ); type TBufferRec = packed record Len: Word; Characters: array [0..0] of Char; end; PBufferRec = ^TBufferRec; var pBuf: PBufferRec; begin if Data <> '' then begin Assert( Length(Data) <= High(Word)); GetMem(pBuf, Length(Data)+Sizeof(Word)); try pBuf^.Len := Length(Data); Move(Data[1], pBuf^.Characters, Length(Data)); ExtEscape( Printer.Handle, POSTSCRIPT_PASSTHROUGH, Length(Data)+Sizeof(Word), PChar(pBuf), 0, nil ); finally FreeMem(pBuf); end; end; end; end.
unit Router4DelphiDemo.View.Pages.Cadastros; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, Router4D.Interfaces; type TPageCadastros = class(TForm, iRouter4DComponent) Layout1: TLayout; Label1: TLabel; private { Private declarations } public { Public declarations } function Render : TFMXObject; procedure UnRender; end; var PageCadastros: TPageCadastros; implementation {$R *.fmx} { TForm2 } function TPageCadastros.Render: TFMXObject; begin Result := Layout1; end; procedure TPageCadastros.UnRender; begin end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, REST.Backend.PushTypes, System.JSON, REST.Backend.EMSPushDevice, System.PushNotification, REST.Backend.EMSProvider, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.BindSource, REST.Backend.PushDevice; type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; memoDeviceToken: TMemo; memoDeviceID: TMemo; memoMensagem: TMemo; Button1: TButton; PushEvents1: TPushEvents; EMSProvider1: TEMSProvider; procedure PushEvents1DeviceTokenReceived(Sender: TObject); procedure PushEvents1PushReceived(Sender: TObject; const AData: TPushData); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.FormActivate(Sender: TObject); var Notificacao : TPushData; I : Integer; begin try Notificacao := Self.PushEvents1.StartupNotification; if Assigned(Notificacao) then begin if not PushEvents1.StartupNotification.GCM.Message.Equals(EmptyStr) then begin for I := 0 to Pred(Notificacao.Extras.Count) do memoMensagem.Lines.Add(Notificacao.Extras[I].Key + ' - ' + Notificacao.Extras[I].Value); end; end; finally Notificacao.DisposeOf; Notificacao := nil; end; end; procedure TForm1.PushEvents1DeviceTokenReceived(Sender: TObject); begin memoDeviceToken.Lines.Clear; memoDeviceToken.Lines.Add(PushEvents1.DeviceToken); memoDeviceID.Lines.Clear; memoDeviceID.Lines.Add(PushEvents1.DeviceID); end; procedure TForm1.PushEvents1PushReceived(Sender: TObject; const AData: TPushData); var I : Integer; begin memoMensagem.Lines.Clear; memoMensagem.Lines.Add(AData.Message); memoMensagem.Lines.Add('-------------'); memoMensagem.Lines.Add(EmptyStr); for I := 0 to Pred(AData.Extras.Count) do memoMensagem.Lines.Add(AData.Extras[I].Key + ' - ' + AData.Extras[I].Value); end; end.
unit SpeakingFrame; interface uses Global, LTClasses, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TfmSpeaking = class(TFrame) lbQuestionInput: TLabel; lbQuestion: TLabel; lbNumber: TLabel; private { Private declarations } public { Public declarations } procedure Binding(Quiz: TQuiz); end; implementation {$R *.dfm} { TfmSpeaking } procedure TfmSpeaking.Binding(Quiz: TQuiz); begin lbNumber.Caption := IntToStr(TSpeaking(Quiz).QuizNumber); lbQuestion.Caption := TSpeaking(Quiz).Quiz; end; end.
{=============================================================================== 数据库连接基类 ===============================================================================} unit xDBConn; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.FMXUI.Wait, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, {$IFDEF MSWINDOWS} FireDAC.Phys.MSSQLDef, FireDAC.Phys.MSSQL, FireDAC.Phys.MSAccDef, FireDAC.Phys.MySQLDef, FireDAC.Phys.MySQL, FireDAC.Phys.ODBCBase, FireDAC.Phys.MSAcc, {$ENDIF} FireDAC.Comp.UI, Data.DB, FireDAC.Comp.Client, xVCL_FMX; type TDBConn = class private FGUIxWaitCursor: TFDGUIxWaitCursor; {$IFDEF MSWINDOWS} FMSAccessDriverLink: TFDPhysMSAccessDriverLink; FMySQLDriverLink: TFDPhysMySQLDriverLink; FMSSQLDriverLink: TFDPhysMSSQLDriverLink; {$ENDIF} FSQLiteDriverLink: TFDPhysSQLiteDriverLink; FConnection: TFDConnection; function GetConnStr: string; procedure SetConnStr(const Value: string); protected public constructor Create; destructor Destroy; override; property Connection: TFDConnection read FConnection; /// <summary> /// 连接字符串 /// SQLite :'DriverID=SQLite; Database=C:\Temp\FDDemo.sdb' /// MSAccess :'DriverID=MSAcc;Database=C:\Temp\dbdemos.mdb' /// MSSQL :'DriverID=MSSQL;Database=2008ES;Password=ckm2008byx;Server=127.0.0.1;User_Name=sa' /// MySQL :'' /// </summary> property ConnStr : string read GetConnStr write SetConnStr; end; var ADBConn : TDBConn; implementation { TDBConn } constructor TDBConn.Create; begin FGUIxWaitCursor := TFDGUIxWaitCursor.Create(Application); {$IFDEF MSWINDOWS} FMSAccessDriverLink:= TFDPhysMSAccessDriverLink.Create(Application); FMySQLDriverLink := TFDPhysMySQLDriverLink.Create(Application); FMSSQLDriverLink := TFDPhysMSSQLDriverLink.Create(Application); {$ENDIF} FSQLiteDriverLink := TFDPhysSQLiteDriverLink.Create(Application); FConnection := TFDConnection.Create(Application); end; destructor TDBConn.Destroy; begin inherited; end; function TDBConn.GetConnStr: string; begin Result := FConnection.ConnectionString; end; procedure TDBConn.SetConnStr(const Value: string); begin FConnection.ConnectionString := Value; FConnection.Connected := True; end; end.
unit Vigilante.Conexao.JSON.Impl; interface uses System.JSON, Vigilante.Conexao.JSON, System.Net.HTTPClientComponent; type TConexaoJSON = class(TInterfacedObject, IConexaoJSON) private FURL: string; FHttpClient: TNetHttpClient; function ConsultarAPI: TJSONObject; public constructor Create(const AURL: string); destructor Destroy; override; function PegarBuild: TJSONObject; function PegarCompilacao: TJSONObject; function PegarPipeline: TJSONObject; end; implementation uses System.Net.HttpClient, System.Classes, System.SysUtils, System.Threading; const CONEXAO_OK = 200; NAO_IMPLEMENTADO = 'Método %s.%s não implementado'; constructor TConexaoJSON.Create(const AURL: string); begin FURL := AURL; FHttpClient := TNetHttpClient.Create(nil); end; destructor TConexaoJSON.Destroy; begin FreeAndNil(FHttpClient); inherited; end; function TConexaoJSON.PegarBuild: TJSONObject; begin Result := ConsultarAPI; end; function TConexaoJSON.PegarCompilacao: TJSONObject; begin Result := ConsultarAPI end; function TConexaoJSON.ConsultarAPI: TJSONObject; var _response: IHTTPResponse; _content: string; begin Result := nil; try _response := FHttpClient.Get(FURL); if _response.StatusCode <> CONEXAO_OK then Exit; _content := _response.ContentAsString(); if _content.Trim.IsEmpty then Exit; Result := TJSONObject.ParseJSONValue(_content) as TJSONObject; except { TODO : Adicionar geração de Logs } end; end; function TConexaoJSON.PegarPipeline: TJSONObject; begin raise ENotImplemented.CreateFmt(NAO_IMPLEMENTADO, [Self.QualifiedClassName, 'PegarPipeline']); end; end.
{$mode objfpc} unit AST; interface uses List, Tokenizer; type TToken = Tokenizer.TToken; type TTokenList = Tokenizer.TTokenList; type TTokenListIterator = Tokenizer.TTokenListIterator; type TType = Tokenizer.TType; type EAST = class end; type TNode = class public procedure PrintParenthesised; virtual; procedure PrintReversePolish; virtual; end; type TValueNode = class(TNode) private _Token : TToken; public constructor CreateFromToken( t: TToken ); procedure PrintParenthesised; override; procedure PrintReversePolish; override; end; type TBinaryOperationNode = class(TNode) private _LeftOperand : TNode; _RightOperand : TNode; _Operation : TToken; public constructor CreateFromToken( t: TToken ); procedure SetLeftOperand( n: TNode ); procedure SetRightOperand( n: TNode ); procedure PrintParenthesised; override; procedure PrintReversePolish; override; end; type TTree = class private _Root : TNode; function TreeFromTokenList( tli : TTokenListIterator; ctx : TNode ) : TNode; function GetRightOperand( priority : integer; tli : TTokenListIterator ) : TNode; function FetchParenthesisedSubexpression( tli: TTokenListIterator ) : TTokenList; public constructor CreateFromTokenList( toks : TTokenList ); procedure PrintParenthesised; procedure PrintReversePolish; end; implementation procedure TNode.PrintParenthesised; begin WriteLn('PURE VIRTUAL CALL!!! WTF!!!'); end; procedure TNode.PrintReversePolish; begin WriteLn('PURE VIRTUAL CALL!!! WTF!!!'); end; procedure TTree.PrintParenthesised; begin Write('Parenthesised infix form: '); _Root.PrintParenthesised; WriteLn(''); end; procedure TTree.PrintReversePolish; begin Write('Reverse polish form: '); _Root.PrintReversePolish; WriteLn(''); end; procedure TValueNode.PrintParenthesised; begin Write(' ', _Token.Original, ' '); end; procedure TValueNode.PrintReversePolish; begin Write(' ', _Token.Original, ' '); end; procedure TBinaryOperationNode.PrintParenthesised; begin Write('('); _LeftOperand.PrintParenthesised; Write(' ', _Operation.Original, ' '); _RightOperand.PrintParenthesised; Write(')'); end; procedure TBinaryOperationNode.PrintReversePolish; begin _LeftOperand.PrintReversePolish; _RightOperand.PrintReversePolish; Write(' ', _Operation.Original, ' '); end; constructor TValueNode.CreateFromToken( t: TToken ); begin _Token := t; end; constructor TBinaryOperationNode.CreateFromToken( t: TToken ); begin _Operation := t; end; procedure TBinaryOperationNode.SetLeftOperand( n: TNode ); begin _LeftOperand := n; end; procedure TBinaryOperationNode.SetRightOperand( n: TNode ); begin _RightOperand := n; end; constructor TTree.CreateFromTokenList( toks : TTokenList ); var tli : TTokenListIterator; begin tli := toks.GetConstIterator; _Root := TreeFromTokenList( tli, nil ); end; function TTree.GetRightOperand( priority : integer; tli : TTokenListIterator ) : TNode; var firstTok: TToken; var secondTok: TToken; var subExpression: TTokenList; var subExpressionIterator: TTokenListIterator; begin firstTok := tli.GetNext; case firstTok.TokenType of TType.literal, TType.identifier: begin if tli.HasNext then begin secondTok := tli.Peek; if secondTok.Priority > priority then begin tli.StepBack; Result := TreeFromTokenList( tli, nil ); end else begin Result := TValueNode.CreateFromToken( firstTok ); end; end else begin Result := TValueNode.CreateFromToken( firstTok ); end; end; TType.parenthesis_l: begin tli.StepBack; subExpression := FetchParenthesisedSubexpression( tli ); subExpressionIterator := subExpression.GetConstIterator; Result := TreeFromTokenList( subExpression.GetConstIterator, nil ); end; else begin WriteLn('Expected either literal or identifier. Got ', firstTok.TokenType, ' at ', firstTok.Position); raise EAST.Create; end; end end; function TTree.FetchParenthesisedSubexpression( tli: TTokenListIterator ) : TTokenList; var depth: integer; var toks : TTokenList; var tok : TToken; begin if tli.Peek.TokenType <> TType.parenthesis_l then begin WriteLn('Expected parenthesis_l. Got ', tli.Peek.TokenType, ' at ', tli.Peek.Position); raise EAST.Create; end; tli.GetNext; depth := 1; toks := TTokenList.Create; while depth > 0 do begin tok := tli.GetNext; case tok.TokenType of TType.parenthesis_l: begin depth := depth + 1; end; TType.parenthesis_r: begin depth := depth - 1; end; end; toks.PushBack( tok ); end; toks.PopBack; //WriteLn('Fetched ', toks.GetCount, ' tokens into subexpression'); Result := toks; end; function TTree.TreeFromTokenList( tli : TTokenListIterator; ctx : TNode ) : TNode; var leftOperand: TNode; var rightOperand: TNode; var binaryOperation: TBinaryOperationNode; var opToken: TToken; var subExpression: TTokenList; var subExpressionIterator: TTokenListIterator; begin if ctx = nil then begin (* empty tree. Next token expected: either literal or identifier *) case tli.Peek.TokenType of TType.literal, TType.identifier: begin ctx := TValueNode.CreateFromToken( tli.GetNext ); Result := TreeFromTokenList( tli, ctx ); end; TType.parenthesis_l: begin subExpression := FetchParenthesisedSubexpression( tli ); subExpressionIterator := subExpression.GetConstIterator; Result := TreeFromTokenList( tli, TreeFromTokenList( subExpression.GetConstIterator, nil ) ); end; else WriteLn('Expected either literal or identifier. Got ', tli.Peek.TokenType, ' at ', tli.Peek.Position); raise EAST.Create; end; end else begin case tli.Peek.TokenType of TType.op_mult, TType.op_div, TType.op_plus, TType.op_minus, TType.op_pow : begin leftOperand := ctx; opToken := tli.GetNext; binaryOperation := TBinaryOperationNode.CreateFromToken( opToken ); binaryOperation.SetLeftOperand( leftOperand ); rightOperand := GetRightOperand( opToken.Priority, tli ); binaryOperation.SetRightOperand( rightOperand ); ctx := binaryOperation; if tli.HasNext then begin Result := TreeFromTokenList( tli, ctx ); end else begin Result := ctx; end; end; end; end; end; end.
unit ccPNJunctionCapFrame; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, ExtCtrls, StdCtrls, Spin, IniFiles, ccBaseFrame; type { TPNJunctionCapFrame } TPNJunctionCapFrame = class(TBaseFrame) Bevel2: TBevel; Bevel3: TBevel; CbEMaxUnits: TComboBox; CbMaterial: TComboBox; CbJctType: TComboBox; CbDepletionWidthUnits: TComboBox; CbNdUnits: TComboBox; CbDeltaConcUnits: TComboBox; EdNa: TEdit; CbTempUnits: TComboBox; LblBuiltinVoltag1: TLabel; LblCapaPerAreaUnits: TLabel; Panel1: TPanel; TxtCapaPerArea: TEdit; TxtDepletionWidth: TEdit; EdNd: TEdit; EdDeltaConc: TEdit; EdTemp: TEdit; CbNaUnits: TComboBox; EdVoltage: TFloatSpinEdit; LblEMax: TLabel; LblBuiltinVoltag: TLabel; LblNa: TLabel; LblDepletionWidth: TLabel; LblNd: TLabel; LblMaterial: TLabel; LblJctType: TLabel; LblDeltaConc: TLabel; LblDeltaConcPerMicron: TLabel; LblTemp: TLabel; LblVoltage: TLabel; LblVoltageUnits: TLabel; LblBuiltinVoltageUnits: TLabel; TxtEMax: TEdit; TxtBuiltinVoltage: TEdit; procedure CbJctTypeChange(Sender: TObject); private { private declarations } protected procedure ClearResults; override; procedure SetEditLeft(AValue: Integer); override; public { public declarations } constructor Create(AOwner: TComponent); override; procedure Calculate; override; procedure ReadFromIni(ini: TCustomIniFile); override; function ValidData(out AMsg: String; out AControl: TWinControl): Boolean; override; procedure WriteToIni(ini: TCustomIniFile); override; end; implementation {$R *.lfm} uses Math, ccGlobal, ccStrings; type TMathFunc = function(x: extended; const params: array of extended) : extended; { Finds the zero of the function f in the interval [x1, x2] with precision tol. The result is false if an intersection is not found. Algorithmus: Van Wijngaarden-Dekker-Brent-Methode (Press, Num Recipes, p 283) } function FindRoot(f: TMathFunc; x1,x2,tol: extended; const Params:array of extended; var x0: extended): boolean; const ItMax = 100; FloatEps = 3.4E-9; var a, b, c, d, e : extended; min1, min2, min : extended; fa, fb, fc : extended; p, q, r : extended; s, tol1, xm : extended; iter : integer; begin result := false; try a := x1; b := x2; fa := f(x1, params); if IsNaN(fa) then exit; fb := f(x2, params); if IsNaN(fb) then exit; if fa*fb > 0.0 then exit; fc := fb; for iter := 1 to ItMax do begin if fb*fc > 0.0 then begin c := a; fc := fa; d := b - a; e := d; end; if abs(fc) < abs(fb) then begin a := b; b := c; c := a; fa := fb; fb := fc; fc := fa; end; tol1 := 2.0 * FloatEps * abs(b) + 0.5 * tol; xm := 0.5 * (c - b); if (abs(xm) <= tol1) or (fb = 0.0) then begin x0 := b; result := true; exit; end; if (abs(xm) <= tol1) and (abs(fa) > abs(fb)) then begin s := fb / fa; if a = c then begin p := 2.0 * xm * s; q := 1.0 - s; end else begin q := fa / fc; r := fb / fc; p := s * (2 * xm * q * (q-r) - (b-a) * (r-1)); q := (q-1) * (r-1) * (s-1); end; if (p > 0.0) then q := -q; p := abs(p); min1 := 3.0 * xm * q - abs(tol1 * q); min2 := abs(e * q); if min1 < min2 then min := min1 else min := min2; if 2.0 * p < min then begin e := d; d := p / q; end else begin d := xm; e := d; end; end else begin d := xm; e := d; end; a := b; fa := fb; if abs(d) > tol1 then b := b + d else begin if xm >= 0 then b := b + abs(tol1) else b := b - abs(tol1); end; fb := f(b, params); if IsNaN(fb) then exit; end; x0 := b; result := true; except end; end; { Helper function to calculate the built-in voltage V0 of a p/n junction with linear concentration gradient. Use FindRoot to determine ther zero of this function. } function Calc_BuiltinVoltage(V0: extended; const params:array of extended): extended; var a, eps, V, T, ni : extended; arg : extended; x: extended; begin a := params[0]; eps := params[1]; V := params[2]; T := params[3]; ni := params[4]; x := 12.0 * eps * (V0 - V) * a*a / q; if x < 0 then begin Result := NaN; exit; end; arg := power(x, 1.0/3) / (2*ni); result := 2*kB*T/q * ln(arg) - V0; end; { Calculates the temperature dependence of intrinsic density, in m-3. } function Calc_ni(AMaterial: TMaterial; T: double) : double; begin case AMaterial of mSi : result := 5.29E19 * power(T/300, 2.54) * exp(-6726/T); // in 1/cm³ // Ref. www.pveducation.org/pvcdrom/pn-junction/intrinsic-carrier-concentration { mSi : result := 9.38E19 * sqr(T/300) * exp(-6884/T); // Ref. http://www.udel.edu/igert/pvcdrom/SEMICON/NI.HTM // 300 K --> 1.01E10 } else if T = 300 then result := ni[AMaterial] else raise Exception.Create(STemperatureDependenceNotSupported); end; result := result / VolumeFactor[vu_cm3]; // 1/cm³ --> 1/m3 end; function NumToStr(AValue: Extended): String; begin if AValue < 1E-4 then Result := FormatFloat(CapaExpFormat, AValue) else if AValue > 1E4 then Result := FormatFloat(CapaExpFormat, AValue) else Result := FormatFloat(CapaStdFormat, AValue); end; { TPNJunctionCapFrame } constructor TPNJunctionCapFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FIniKey := 'p/n junction'; EdDeltaConc.Top := EdNa.Top; CbDeltaConcUnits.Top := CbNaUnits.Top; LblDeltaConc.Top := LblNa.Top; LblDeltaConcPerMicron.Top := LblNa.Top; end; procedure TPNJunctionCapFrame.Calculate; var kToverQ : extended; // kT/q T : extended; // temperature ND, NA, a : extended; material : TMaterial; V0: extended; // Built-in voltage W: extended; // Junction width W0: extended; // junction width at V=0 V: extended; // applied voltage Cj0: extended; // junction capacitance at V=0 Cj: extended; // junction capacitance emax: extended; // max field deltaConc: extended; // concentration gradient fv, fa, fL, fc: extended; // unit conversion factors for volume, area, length and capa fE, fCA, fCD, fdN: extended; // ... max field, acceptor, donator concentration tmp1, tmp2 : extended; params : array of extended; begin FErrMsg := ''; try if (CbMaterial.ItemIndex = -1) then exit; if (EdTemp.Text = '') or not TryStrToFloat(EdTemp.Text, T) then exit; if T <= 0 then exit; if (CbJctType.ItemIndex = -1) then exit; if (EdVoltage.Text = '') then exit; if (EdNa.Text = '') or not TryStrToFloat(EdNa.Text, NA) then exit; if Na <= 0 then exit; if (EdNd.Text = '') or not TryStrToFloat(EdNd.Text, ND) then exit; if Nd <= 0 then exit; if (CbNaUnits.ItemIndex = -1) then exit; if (CbNdUnits.ItemIndex = -1) then exit; if CbJctType.ItemIndex = 1 then begin // graded junction if (EdDeltaConc.Text = '') or not TryStrToFloat(EdDeltaConc.Text, deltaConc) then exit; if (CbDeltaConcUnits.ItemIndex = -1) then exit; end; if CbEMaxUnits.ItemIndex = -1 then exit; if CbDepletionWidthUnits.ItemIndex = -1 then exit; fa := AreaFactor[au_cm2]; fc := CapaFactor[cu_nF]; fL := LenFactor[TLenUnits(CbDepletionWidthUnits.ItemIndex)]; fE := EFieldFactor[TEFieldUnits(CbEMaxUnits.ItemIndex)]; material := TMaterial(CbMaterial.ItemIndex); if CbTempUnits.ItemIndex = ord(tuC) then T := T + 273; kToverQ := kB * T / q; V := EdVoltage.Value; case CbJctType.ItemIndex of 0: // *** abrupt junction *** begin fCA := 1.0 / VolumeFactor[TVolumeUnits(CbNaUnits.ItemIndex)]; fCD := 1.0 / VolumeFactor[TVolumeUnits(CbNdUnits.ItemIndex)]; // Dopant concentrations (1/m3) NA := NA * fCA; ND := ND * fCD; // built-in voltage (V) V0 := kToverQ * ln( NA * ND / sqr(Calc_ni(material, T)) ); if (V > V0) then begin FErrMsg := Format(SVoltageMustBeSmallerThanBuiltIn, [V0]); ClearResults; exit; end; // jct width (m) W := sqrt (2 * MaterialEps[material]/q * (NA + ND)/(NA * ND) * (V0 - V) ); // jct capa per area (F/m2) Cj := MaterialEps[material] / W; // max field (V/m) emax := 2.0 * (V0 - V) / W; end; 1: // *** linearly graded junction *** begin // Concentration gradient dN/dx (1/m4), 1E6 because of dx = 1 micron fdN := 1.0 / VolumeFactor[TVolumeUnits(CbDeltaConcUnits.ItemIndex)]; a := deltaConc * fdN * 1E6; // Find jct width and built-in voltage. Solve nonlinear equation system // w = power(12 eps (V0 - V) / ( q a), 1/3) ( units: m) // V0 = 2 kT/q ln ( aw / (2 ni) ) ( units: V) SetLength(params, 5); params[0] := a; params[1] := MaterialEps[material]; params[2] := V; params[3] := T; params[4] := Calc_ni(material, T); if FindRoot(@Calc_BuiltinVoltage, 1E-1, 2.0, 1E-3, params, V0) then begin if (V > V0) then begin FErrMsg := Format(SVoltageMustBeSmallerThanBuiltIn, [V0]); ClearResults; exit; end; W := power(12 * MaterialEps[material] * (V0 - V) / (q * a), 1/3); end else begin // use approximate solution tmp1 := sqr(a) * MaterialEps[material] * kToverQ; tmp2 := 8 * q * power(Calc_ni(material, T), 3); V0 := 2/3 * kToverQ * ln( tmp1/tmp2); V0 := V0 + 0.075; // compensate for numerical approximation used in above eqns. if (V > V0) then begin ClearResults; FErrMsg := Format(SVoltageMustBeSmallerThanBuiltIn, [V0]); exit; end; // raise Exception.CreateFmt(SVoltageMustBeSmallerThanBuiltIn, [V0]); W := power( 12 * MaterialEps[material] * (V0 - V) / (q*a), 1/3); end; // jct capa per area (F/m2) Cj := MaterialEps[material] / W; // max field (V/m) emax := q * a * sqr(W) / (8 * MaterialEps[material]); end; end; TxtEMax.Text := NumToStr(emax / fE); TxtBuiltInVoltage.Text := NumToStr(V0); TxtDepletionWidth.Text := NumToStr(W / fL); TxtCapaPerArea.Text := NumToStr(Cj / (fc/fa)); except on E:Exception do begin ClearResults; FErrMsg := E.Message; end; end; end; procedure TPNJunctionCapFrame.CbJctTypeChange(Sender: TObject); begin DataChanged(Sender); LblNa.Visible := CbJctType.ItemIndex = 0; EdNa.Visible := CbJctType.ItemIndex = 0; CbNaUnits.Visible := CbJctType.ItemIndex = 0; LblNd.Visible := CbJctType.ItemIndex = 0; EdNd.Visible := CbJctType.ItemIndex = 0; CbNdUnits.Visible := CbJctType.ItemIndex = 0; LblDeltaConc.Visible := CbJctType.ItemIndex = 1; EdDeltaConc.Visible := CbJctType.ItemIndex = 1; CbDeltaConcUnits.Visible := CbJctType.ItemIndex = 1; LblDeltaConcPerMicron.Visible := CbJctType.ItemIndex = 1; end; procedure TPNJunctionCapFrame.ClearResults; begin TxtEMax.Clear; TxtBuiltinVoltage.Clear; TxtDepletionWidth.Clear; TxtCapaPerArea.Clear; end; procedure TPNJunctionCapFrame.ReadFromIni(ini: TCustomIniFile); var fs: TFormatSettings; value: Extended; s: String; begin fs := DefaultFormatSettings; fs.DecimalSeparator := '.'; s := ini.ReadString(FIniKey, 'Material', ''); if (s <> '') then CbMaterial.ItemIndex := CbMaterial.Items.IndexOf(s) else CbMaterial.ItemIndex := -1; s := ini.ReadString(FIniKey, 'Temperature', ''); if (s <> '') and TryStrToFloat(s, value, fs) then EdTemp.Text := FloatToStr(value) else EdTemp.Clear; s := ini.ReadString(FIniKey, 'Temperature units', ''); if (s <> '') then CbTempUnits.ItemIndex := CbTempUnits.Items.IndexOf(s) else CbTempUnits.ItemIndex := -1; s := ini.ReadString(FIniKey, 'Junction type', ''); if (s <> '') then CbJctType.ItemIndex := CbJctType.Items.IndexOf(s) else CbJcttype.ItemIndex := -1; s := ini.ReadString(FIniKey, 'Voltage', ''); if (s <> '') and TryStrToFloat(s, value, fs) then EdVoltage.Value := value else EdVoltage.Clear; s := ini.ReadString(FIniKey, 'Na', ''); if (s <> '') and TryStrToFloat(s, value, fs) then EdNa.Text := FormatFloat(ConcFormat, value) else EdNa.Clear; s := ini.Readstring(FIniKey, 'Na units', ''); if s <> '' then CbNaUnits.ItemIndex := CbNaUnits.Items.IndexOf(s) else CbNaUnits.ItemIndex := -1; s := ini.ReadString(FIniKey, 'Nd', ''); if (s <> '') and TryStrToFloat(s, value, fs) then EdNd.Text := FormatFloat(ConcFormat, value) else EdNd.Clear; s := ini.Readstring(FIniKey, 'Nd units', ''); if s <> '' then CbNdUnits.ItemIndex := CbNdUnits.Items.IndexOf(s) else CbNdUnits.ItemIndex := -1; s := ini.ReadString(FIniKey, 'Concentration change', ''); if (s <> '') and TryStrToFloat(s, value, fs) then EdDeltaConc.Text := FormatFloat(ConcFormat, value) else EdDeltaConc.Clear; s := ini.Readstring(FIniKey, 'Concentration change units', ''); if s <> '' then CbDeltaConcUnits.ItemIndex := CbDeltaConcUnits.Items.IndexOf(s) else CbDeltaConcUnits.ItemIndex := -1; s := ini.Readstring(FIniKey, 'Field units', ''); if s <> '' then CbEMaxUnits.ItemIndex := CbEMaxUnits.Items.IndexOf(s) else CbEMaxUnits.ItemIndex := -1; s := ini.Readstring(FIniKey, 'Field units', ''); if s <> '' then CbEMaxUnits.ItemIndex := CbEMaxUnits.Items.IndexOf(s) else CbEMaxUnits.ItemIndex := -1; s := ini.Readstring(FIniKey, 'Depletion width units', ''); if s <> '' then CbDepletionWidthUnits.ItemIndex := CbDepletionWidthUnits.Items.IndexOf(s) else CbDepletionWidthUnits.ItemIndex := -1; CbJctTypeChange(nil); Calculate; end; procedure TPNJunctionCapFrame.SetEditLeft(AValue: Integer); begin TxtEMax.Left := CbMaterial.Left; Panel1.Height := TxtCapaPerArea.Top + TxtCapaPerArea.Height + TxtEMax.Top; Width := CbTempUnits.Left + CbTempUnits.Width + 30; end; function TPNJunctionCapFrame.ValidData(out AMsg: String; out AControl: TWinControl): Boolean; begin Result := false; if not IsValidComboValue(CbMaterial, AMsg) then begin AControl := CbMaterial; exit; end; if not IsValidNumber(EdTemp, AMsg) then begin AControl := EdTemp; exit; end; if not IsValidComboValue(CbTempUnits, AMsg) then begin AControl := CbTempUnits; exit; end; if (StrToFloat(EdTemp.Text) <= 0) and (CbTempUnits.ItemIndex = ord(tuK)) then begin AControl := EdTemp; AMsg := STemperaturePositive; exit; end; if not IsValidComboValue(CbJctType, AMsg) then begin AControl := CbJctType; exit; end; if not IsValidPositive(EdNa, AMsg) then begin AControl := EdNa; exit; end; if not IsValidPositive(EdNd, AMsg) then begin AControl := EdNd; exit; end; if CbJctType.ItemIndex = 1 then begin if not IsValidNumber(EdDeltaConc, AMsg) then begin AControl := EdDeltaConc; exit; end; if not IsValidComboValue(CbDeltaConcUnits, AMsg) then begin AControl := CbDeltaConcUnits; exit; end; end; if not IsvalidComboValue(CbEMaxUnits, AMsg) then begin AControl := CbEMaxUnits; exit; end; if not IsValidComboValue(CbDepletionWidthUnits, AMsg) then begin AControl := CbDepletionWidthUnits; exit; end; Result := True; end; procedure TPNJunctionCapFrame.WriteToIni(ini: TCustomIniFile); var fs: TFormatSettings; value: Extended; begin fs := DefaultFormatSettings; fs.DecimalSeparator := '.'; ini.EraseSection(FIniKey); if (CbMaterial.ItemIndex >= 0) then ini.WriteString(FIniKey, 'Material', CbMaterial.Items[CbMaterial.ItemIndex]); if (EdTemp.Text <> '') and TryStrToFloat(EdTemp.Text, value) then ini.WriteString(FIniKey, 'Temperature', FloatToStr(value, fs)); if CbTempUnits.ItemIndex >= 0 then ini.WriteString(FIniKey, 'Temperature units', CbTempUnits.Items[CbTempUnits.ItemIndex]); if CbJctType.ItemIndex >= 0 then ini.WriteString(FIniKey, 'Junction type', CbJctType.Items[CbJctType.ItemIndex]); if (EdVoltage.Text <> '') then ini.WriteString(FIniKey, 'Voltage', FloatToStr(EdVoltage.Value, fs)); if (EdNa.Text <> '') and TryStrToFloat(EdNa.Text, value) then ini.WriteString(FIniKey, 'Na', FloatToStr(value, fs)); if CbNaUnits.ItemIndex >= 0 then ini.WriteString(FIniKey, 'Na units', CbNaUnits.Items[CbNaUnits.ItemIndex]); if (EdNd.Text <> '') and TryStrToFloat(EdNd.Text, value) then ini.WriteString(FIniKey, 'Nd', FloatToStr(value, fs)); if CbNdUnits.ItemIndex >= 0 then ini.WriteString(FIniKey, 'Nd units', CbNdUnits.Items[CbNdUnits.ItemIndex]); if (EdDeltaConc.Text <> '') and TryStrToFloat(EdDeltaConc.Text, value) then ini.WriteString(FIniKey, 'Concentration change', FloatToStr(value, fs)); if CbDeltaConcUnits.ItemIndex >= 0 then ini.WriteString(FIniKey, 'Concentration change units', CbDeltaConcUnits.Items[CbDeltaConcUnits.ItemIndex]); if CbEMaxUnits.ItemIndex >= 0 then ini.WriteString(FIniKey, 'Field units', CbEMaxUnits.Items[CbEMaxUnits.ItemIndex]); if CbDepletionWidthUnits.ItemIndex >= 0 then ini.WriteString(FIniKey, 'Depletion width units', CbDepletionWidthUnits.Items[CbDepletionWidthUnits.ItemIndex]); end; end.