text
stringlengths
14
6.51M
{ Algorithme d'encryptage/décryptage SEA (Stream Encoding Algorithm) } { Auteur : Bacterius (www.delphifr.com) } { Copyright : NE PAS MODIFIER CE FICHIER SANS ACCORD DE L'AUTEUR/ DO NOT MODIFY THIS FILE WITHOUT AUTHOR PERMISSION } unit SEA; interface uses Windows, LEA_Hash; type { Le type du callback : octet n°Position sur Count } { Pour éviter de massacrer le temps d'execution du code, veillez à ne traiter qu'un certain nombre de callbacks (tous les 2^16 octets par exemple) } TSEACallback = procedure (Position, Count: Longword); { Oui, c'est toujours plus lisible et ça change rien } TSEAKey = THash; const OPERATION_ENCRYPT = $1; { Pour encrypter } OPERATION_DECRYPT = $2; { Pour décrypter } OPERATION_FAST = $4; { Encryptage/Décryptage rapide } OPERATION_SECURE = $8; { Encryptage/Décryptage très lent mais plus sécurisé } function ObtainKey(Str: String): TSEAKey; function Encrypt(var Buffer; const Size: Longword; Key: TSEAKey; const Operation: Longword; Callback: TSEACallback = nil): Boolean; function EncryptFile(const FilePath: String; const Key: TSEAKey; const Operation: Longword; Callback: TSEACallback = nil): Boolean; implementation { Les fonctions de rotate-shift left (ROL) et right (ROR) sur des octets et sur double-mots } function RShlLong(A, B: Longword): Longword; begin Result := (A shl B) or (A shr ($08 - B)); end; function RShl(A, B: Byte): Byte; begin Result := (A shl B) or (A shr ($08 - B)); end; function RShr(A, B: Byte): Byte; begin Result := (A shr B) or (A shl ($08 - B)); end; { Fonction pour obtenir une clef d'encryptage 128 bits à partir d'une chaîne } function ObtainKey(Str: String): TSEAKey; begin Result := HashStr(Str); end; { La fonction d'encryptage : le Buffer sert d'entrée de données et de sortie de données } function Encrypt(var Buffer; const Size: Longword; Key: TSEAKey; const Operation: Longword; Callback: TSEACallback = nil): Boolean; Var P, E: PByte; I: Longword; H: THash; begin Result := False; { Encrypter ou décrypter, il faut choisir ! } if (OPERATION_ENCRYPT and Operation <> 0) and (OPERATION_DECRYPT and Operation <> 0) then Exit; if (OPERATION_ENCRYPT and Operation = 0) and (OPERATION_DECRYPT and Operation = 0) then Exit; { Idem pour le niveau de sécurité } if (OPERATION_FAST and Operation <> 0) and (OPERATION_SECURE and Operation <> 0) then Exit; if (OPERATION_FAST and Operation = 0) and (OPERATION_SECURE and Operation = 0) then Exit; { On refuse les données de taille 0 (après tout, ça ne changerait rien) } if Size = 0 then Exit; { On définit le début et la fin du buffer, et on met le compteur (I) à 0 } P := @Buffer; E := Ptr(Longword(@Buffer) + Size); I := 0; { On prend un hash initial } H := Hash(I, 4, nil); repeat { Si on est en décryptage, on effectue un rotate-shift RIGHT sur la clef au DEBUT } if (OPERATION_DECRYPT and Operation <> 0) then P^ := RShr(P^, (Key.B mod $08) xor (I mod $08)); { De temps en temps on modifie le hashage de la position actuelle selon le niveau de sécurité } if (Operation and OPERATION_SECURE <> 0) then H := Hash(I, 4, nil); if (Operation and OPERATION_FAST <> 0) then if Succ(I) mod $FF = 0 then H := Hash(I, 4, nil); { Rien de très compliqué, des opérations réversibles pourvu qu'on ait la clef :D } with H do begin P^ := (Key.B mod $FF) xor (P^ xor (C mod $FF)); P^ := (Key.A mod $FF) xor (P^ xor (B mod $FF)); P^ := (Key.D mod $FF) xor (P^ xor (A mod $FF)); P^ := (Key.C mod $FF) xor (P^ xor (D mod $FF)); end; { Si on est en encryptage, on effectue un rotate-shift LEFT sur la clef à la FIN } if (OPERATION_ENCRYPT and Operation <> 0) then P^ := RShl(P^, (Key.B mod $08) xor (I mod $08)); { On envoie le callback si l'application en a fourni un } if Assigned(Callback) then Callback(Succ(I), Size); { On avance dans le buffer, et on incrémente le compteur } Inc(P); Inc(I); until P = E; Result := True; end; function EncryptFile(const FilePath: String; const Key: TSEAKey; const Operation: Longword; Callback: TSEACallback = nil): Boolean; Var H, M: Longword; P: Pointer; begin Result := False; { On ouvre le fichier avec droits exclusifs } H := CreateFile(PChar(FilePath), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0); if H = INVALID_HANDLE_VALUE then Exit; { CreateFileMapping rejette les fichiers de taille 0. Notre fonction d'encryptage/décryptage les rejette également. Alors autant arrêter là plutôt que de bousiller des cycles inutiles. } if GetFileSize(H, nil) = 0 then begin CloseHandle(H); Exit; end; try { On crée une image du fichier en mémoire (lecture/écriture) } M := CreateFileMapping(H, nil, PAGE_READWRITE, 0, 0, nil); try if M = 0 then Exit; { On mappe le fichier en mémoire en lecture/écriture } P := MapViewOfFile(M, FILE_MAP_READ or FILE_MAP_WRITE, 0, 0, 0); try if P = nil then Exit; { Et on envoie le pointeur sur le fichier à la fonction. Attention, le fichier crypté/décrypté remplace l'original ! } Result := Encrypt(P^, GetFileSize(H, nil), Key, Operation, Callback); finally { On fait le ménage derrière nous ... } UnmapViewOfFile(P); end; finally CloseHandle(M); end; finally CloseHandle(H); end; end; end.
unit uManagerExplorer; interface uses Generics.Collections, System.Classes, System.SysUtils, System.SyncObjs, Vcl.Forms, uSettings, uMemory, ExplorerTypes; type TManagerExplorer = class(TObject) private FExplorers: TList<TCustomExplorerForm>; FForms: TList<TForm>; FShowPrivate: Boolean; FShowEXIF: Boolean; FSync: TCriticalSection; public constructor Create; destructor Destroy; override; function NewExplorer(GoToLastSavedPath: Boolean): TCustomExplorerForm; procedure AddExplorer(Explorer: TCustomExplorerForm); procedure RemoveExplorer(Explorer: TCustomExplorerForm); function IsExplorer(Explorer: TCustomExplorerForm): Boolean; property ShowPrivate: Boolean read FShowPrivate write FShowPrivate; end; function ExplorerManager: TManagerExplorer; implementation uses ExplorerUnit; var FExplorerManager: TManagerExplorer = nil; function ExplorerManager: TManagerExplorer; begin if FExplorerManager = nil then FExplorerManager := TManagerExplorer.Create; Result := FExplorerManager; end; { TManagerExplorer } procedure TManagerExplorer.AddExplorer(Explorer: TCustomExplorerForm); begin FShowEXIF := AppSettings.ReadBool('Options', 'ShowEXIFMarker', False); if FExplorers.IndexOf(Explorer) = -1 then FExplorers.Add(Explorer); if FForms.IndexOf(Explorer) = -1 then FForms.Add(Explorer); end; constructor TManagerExplorer.Create; begin FSync := TCriticalSection.Create; FExplorers := TList<TCustomExplorerForm>.Create; FForms := TList<TForm>.Create; FShowPrivate := False; end; destructor TManagerExplorer.Destroy; begin F(FExplorers); F(FForms); F(FSync); inherited; end; function TManagerExplorer.IsExplorer(Explorer: TCustomExplorerForm): Boolean; begin FSync.Enter; try Result := FExplorers.IndexOf(Explorer) <> -1; finally FSync.Leave; end; end; function TManagerExplorer.NewExplorer(GoToLastSavedPath: Boolean): TCustomExplorerForm; begin Result := TExplorerForm.Create(Application, GoToLastSavedPath); end; procedure TManagerExplorer.RemoveExplorer(Explorer: TCustomExplorerForm); begin FSync.Enter; try FExplorers.Remove(Explorer); FForms.Remove(Explorer); finally FSync.Leave; end; end; initialization finalization F(FExplorerManager); end.
unit VoxelBankItem; interface uses Voxel, BasicFunctions; type TVoxelBankItem = class private Counter: longword; Editable : boolean; Voxel : TVoxel; Filename: string; public // Constructor and Destructor constructor Create; overload; constructor Create(const _Filename: string); overload; constructor Create(const _Voxel: PVoxel); overload; destructor Destroy; override; // Sets procedure SetEditable(_value: boolean); procedure SetFilename(_value: string); // Gets function GetEditable: boolean; function GetFilename: string; function GetVoxel : PVoxel; // Counter function GetCount : integer; procedure IncCounter; procedure DecCounter; end; PVoxelBankItem = ^TVoxelBankItem; implementation // Constructors and Destructors // This one starts a blank voxel. constructor TVoxelBankItem.Create; begin Voxel := TVoxel.Create; Counter := 1; Filename := ''; end; constructor TVoxelBankItem.Create(const _Filename: string); begin Voxel := TVoxel.Create; Voxel.LoadFromFile(_Filename); Counter := 1; Filename := CopyString(_Filename); end; constructor TVoxelBankItem.Create(const _Voxel: PVoxel); begin Voxel := TVoxel.Create(_Voxel^); Counter := 1; Filename := CopyString(Voxel.Filename); end; destructor TVoxelBankItem.Destroy; begin Voxel.Free; Filename := ''; inherited Destroy; end; // Sets procedure TVoxelBankItem.SetEditable(_value: boolean); begin Editable := _value; end; procedure TVoxelBankItem.SetFilename(_value: string); begin Filename := CopyString(_Value); end; // Gets function TVoxelBankItem.GetEditable: boolean; begin Result := Editable; end; function TVoxelBankItem.GetFilename: string; begin Result := Filename; end; function TVoxelBankItem.GetVoxel : PVoxel; begin Result := @Voxel; end; // Counter function TVoxelBankItem.GetCount : integer; begin Result := Counter; end; procedure TVoxelBankItem.IncCounter; begin inc(Counter); end; procedure TVoxelBankItem.DecCounter; begin Dec(Counter); end; end.
{----------------------------------------------------------------------------- Unit Name: frmMessages Author: Kiriakos Vlahos Purpose: Messages Window History: -----------------------------------------------------------------------------} unit frmMessages; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Menus, JvDockControlForm, JvComponent, PythonEngine, Contnrs, frmIDEDockWin, ExtCtrls, TB2Item, TBX, TBXThemes, TBXDkPanels, VirtualTrees, TB2Dock, TB2Toolbar, ActnList, JvComponentBase; type TMessagesWindow = class(TIDEDockWindow) TBXPopupMenu: TTBXPopupMenu; mnClearall: TTBXItem; MessagesView: TVirtualStringTree; TBToolbar1: TTBToolbar; TBControlItem5: TTBControlItem; TBControlItem6: TTBControlItem; BtnPreviousMsgs: TTBXButton; BtnNextMsgs: TTBXButton; MsgsActionList: TActionList; actClearAll: TAction; actPreviousMsgs: TAction; actNextMsgs: TAction; TBXItem1: TTBXItem; TBXItem2: TTBXItem; TBXSeparatorItem1: TTBXSeparatorItem; actCopyToClipboard: TAction; TBXSeparatorItem2: TTBXSeparatorItem; TBXItem3: TTBXItem; procedure TBXPopupMenuPopup(Sender: TObject); procedure actCopyToClipboardExecute(Sender: TObject); procedure ClearAllExecute(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure MessagesViewInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure MessagesViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure MessagesViewDblClick(Sender: TObject); procedure actNextMsgsExecute(Sender: TObject); procedure actPreviousMsgsExecute(Sender: TObject); private { Private declarations } fMessageHistory : TObjectList; fHistoryIndex : integer; fHistorySize : integer; protected procedure TBMThemeChange(var Message: TMessage); message TBM_THEMECHANGE; public { Public declarations } procedure ShowWindow; procedure AddMessage(Msg: string; FileName : string = ''; Line : integer = 0; Offset : integer = 0); procedure ClearMessages; procedure ShowPythonTraceback; procedure ShowPythonSyntaxError(E: EPySyntaxError); procedure JumpToPosition(Node : PVirtualNode); procedure UpdateMsgActions; end; var MessagesWindow: TMessagesWindow; implementation uses frmPyIDEMain, uEditAppIntfs, SynEditTypes, dmCommands, uCommonFunctions, Clipbrd, JvDockGlobals; {$R *.dfm} Type TMsg = class Msg: string; FileName : string; Line : integer; Offset : integer; end; PMsgRec = ^TMsgRec; TMsgRec = record Msg : TMsg; end; { TMessagesWindow } procedure TMessagesWindow.AddMessage(Msg, FileName: string; Line, Offset : integer); Var NewMsg : TMsg; begin if fMessageHistory.Count = 0 then // Create New List fHistoryIndex := fMessageHistory.Add(TObjectList.Create(True)) else if fHistoryIndex <> fMessageHistory.Count - 1 then begin fHistoryIndex := fMessageHistory.Count - 1; MessagesView.Clear; end; NewMsg := TMsg.Create; NewMsg.Msg := Msg; NewMsg.FileName := FileName; NewMsg.Line := Line; NewMsg.Offset := Offset; TObjectList(fMessageHistory[fHistoryIndex]).Add(NewMsg); // ReInitializes the list MessagesView.RootNodeCount := TObjectList(fMessageHistory[fHistoryIndex]).Count; UpdateMsgActions; end; procedure TMessagesWindow.ClearMessages; begin MessagesView.Clear; if fMessageHistory.Count = 0 then // Create New List fHistoryIndex := fMessageHistory.Add(TObjectList.Create(True)) // Onwns objects else if TObjectList(fMessageHistory[fMessageHistory.Count-1]).Count = 0 then // Reuse last list fHistoryIndex := fMessageHistory.Count - 1 else begin // Create new list fHistoryIndex := fMessageHistory.Add(TObjectList.Create(True)); if fMessageHistory.Count > fHistorySize then begin fMessageHistory.Delete(0); fHistoryIndex := fMessageHistory.Count - 1; end; end; UpdateMsgActions; end; procedure TMessagesWindow.ClearAllExecute(Sender: TObject); begin fMessageHistory.Clear; ClearMessages; end; procedure TMessagesWindow.actCopyToClipboardExecute(Sender: TObject); begin Clipboard.AsText := MessagesView.ContentToText(tstAll, #9); end; procedure TMessagesWindow.ShowPythonTraceback; Var i : integer; begin with GetPythonEngine.TraceBack do begin if ItemCount > 0 then begin AddMessage('Traceback'); for i := 1 {don't show base frame} to ItemCount-1 do with Items[i] do AddMessage(' '+Context, FileName, LineNo); end; ShowDockForm(Self); end; end; procedure TMessagesWindow.ShowPythonSyntaxError(E: EPySyntaxError); begin AddMessage('Syntax Error'); with E do begin AddMessage(' ' + E.EValue, EFileName, ELineNumber, EOffset); ShowDockForm(Self); end; end; procedure TMessagesWindow.ShowWindow; begin ShowDockForm(Self); end; procedure TMessagesWindow.FormActivate(Sender: TObject); begin inherited; if not HasFocus then begin FGPanelEnter(Self); PostMessage(MessagesView.Handle, WM_SETFOCUS, 0, 0); end; end; procedure TMessagesWindow.JumpToPosition(Node : PVirtualNode); Var Msg : TMsg; begin if Assigned(Node) then begin MessagesView.Selected[Node] := True; Msg := PMsgRec(MessagesView.GetNodeData(Node))^.Msg; if (Msg.FileName ='') then Exit; // No FileName or LineNumber PyIDEMainForm.ShowFilePosition(Msg.FileName, Msg.Line, Msg.Offset); end; end; procedure TMessagesWindow.FormCreate(Sender: TObject); begin inherited; fMessageHistory := TObjectList.Create(True); // Onwns objects fHistoryIndex := -1; // 10 sounds reasonable // Could become user defined fHistorySize := 10; // Let the tree know how much data space we need. MessagesView.NodeDataSize := SizeOf(TMsgRec); MessagesView.OnAdvancedHeaderDraw := CommandsDataModule.VirtualStringTreeAdvancedHeaderDraw; MessagesView.OnHeaderDrawQueryElements := CommandsDataModule.VirtualStringTreeDrawQueryElements; end; procedure TMessagesWindow.FormDestroy(Sender: TObject); begin fMessageHistory.Free; inherited; end; procedure TMessagesWindow.MessagesViewInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); begin Assert(MessagesView.GetNodeLevel(Node) = 0); Assert(Integer(Node.Index) < TObjectList(fMessageHistory[fHistoryIndex]).Count); PMsgRec(MessagesView.GetNodeData(Node))^.Msg := TMsg(TObjectList(fMessageHistory[fHistoryIndex])[Node.Index]); end; procedure TMessagesWindow.MessagesViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); begin Assert(MessagesView.GetNodeLevel(Node) = 0); Assert(Integer(Node.Index) < TObjectList(fMessageHistory[fHistoryIndex]).Count); with PMsgRec(MessagesView.GetNodeData(Node))^.Msg do case Column of 0: CellText := Msg; 1: CellText := FileName; 2: if Line > 0 then CellText := IntToStr(Line) else CellText := ''; 3: if Offset > 0 then CellText := IntToStr(Offset) else CellText := ''; end; end; procedure TMessagesWindow.MessagesViewDblClick(Sender: TObject); begin if Assigned(MessagesView.GetFirstSelected()) then JumpToPosition(MessagesView.GetFirstSelected) end; procedure TMessagesWindow.TBMThemeChange(var Message: TMessage); begin inherited; if Message.WParam = TSC_VIEWCHANGE then begin MessagesView.Header.Invalidate(nil, True); MessagesView.Colors.HeaderHotColor := CurrentTheme.GetItemTextColor(GetItemInfo('active')); end; end; procedure TMessagesWindow.actNextMsgsExecute(Sender: TObject); begin if fHistoryIndex < fMessageHistory.Count - 1 then begin Inc(fHistoryIndex); MessagesView.RootNodeCount := TObjectList(fMessageHistory[fHistoryIndex]).Count; MessagesView.ReinitNode(MessagesView.RootNode, True); MessagesView.Invalidate; end; UpdateMsgActions; end; procedure TMessagesWindow.actPreviousMsgsExecute(Sender: TObject); begin if fHistoryIndex > 0 then begin Dec(fHistoryIndex); MessagesView.RootNodeCount := TObjectList(fMessageHistory[fHistoryIndex]).Count; MessagesView.ReinitNode(MessagesView.RootNode, True); MessagesView.Invalidate; end; UpdateMsgActions; end; procedure TMessagesWindow.UpdateMsgActions; begin actPreviousMsgs.Enabled := fHistoryIndex > 0 ; actNextMsgs.Enabled := fHistoryIndex < fMessageHistory.Count - 1; BtnPreviousMsgs.Enabled := actPreviousMsgs.Enabled; BtnNextMsgs.Enabled := actNextMsgs.Enabled; actClearAll.Enabled := MessagesView.RootNodeCount <> 0; actCopyToClipboard.Enabled := MessagesView.RootNodeCount <> 0; end; procedure TMessagesWindow.TBXPopupMenuPopup(Sender: TObject); begin UpdateMsgActions; end; end.
unit uClassAnamnese; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TAnamnese } TAnamnese = class private FalergiaAnestesia: string; FalergiaQualAnestesia: string; FalgumaAlergia: string; FantecedentesFamiliares: string; FapreensivoTratDentario: string; FchegouMenopausa: string; FconsumoAcucar: string; Fescovacao: string; FestaGravida: string; FfoiHospitalizado: string; FhabitosViciosos: string; FidAnamnese: integer; FidTblPaciente: integer; FobsAnatomoHisto: string; FporqueApreensivo: string; FporqueHospitalizado: string; FprevisaoParto: string; FqualAlergia: string; FqualTratMedico: string; FquandoChegouMenopausa: string; FquantosFilhos: byte; FteveQuantasGravidez: byte; FtomaMedicamento: string; FtomaQualMedicamento: string; FtratamentoMedico: string; FusoFioDental: string; public property idAnamnese: integer read FidAnamnese write FidAnamnese; property consumoAcucar: string read FconsumoAcucar write FconsumoAcucar; property escovacao: string read Fescovacao write Fescovacao; property usoFioDental: string read FusoFioDental write FusoFioDental; property obsAnatomoHisto: string read FobsAnatomoHisto write FobsAnatomoHisto; property habitosViciosos: string read FhabitosViciosos write FhabitosViciosos; property antecedentesFamiliares: string read FantecedentesFamiliares write FantecedentesFamiliares; property apreensivoTratDentario: string read FapreensivoTratDentario write FapreensivoTratDentario; property porqueApreensivo: string read FporqueApreensivo write FporqueApreensivo; property tratamentoMedico: string read FtratamentoMedico write FtratamentoMedico; property qualTratMedico: string read FqualTratMedico write FqualTratMedico; property tomaMedicamento: string read FtomaMedicamento write FtomaMedicamento; property tomaQualMedicamento: string read FtomaQualMedicamento write FtomaQualMedicamento; property alergiaAnestesia: string read FalergiaAnestesia write FalergiaAnestesia; property alergiaQualAnestesia: string read FalergiaQualAnestesia write FalergiaQualAnestesia; property algumaAlergia: string read FalgumaAlergia write FalgumaAlergia; property qualAlergia: string read FqualAlergia write FqualAlergia; property foiHospitalizado: string read FfoiHospitalizado write FfoiHospitalizado; property porqueHospitalizado: string read FporqueHospitalizado write FporqueHospitalizado; property estaGravida: string read FestaGravida write FestaGravida; property previsaoParto: string read FprevisaoParto write FprevisaoParto; property teveQuantasGravidez: byte read FteveQuantasGravidez write FteveQuantasGravidez; property quantosFilhos: byte read FquantosFilhos write FquantosFilhos; property chegouMenopausa: string read FchegouMenopausa write FchegouMenopausa; property quandoChegouMenopausa: string read FquandoChegouMenopausa write FquandoChegouMenopausa; property idTblPaciente: integer read FidTblPaciente write FidTblPaciente; end; implementation { TAnamnese } end.
unit Scheduler; interface uses RyuLibBase, SimpleThread, DynamicQueue, QueryPerformance, Windows, SysUtils, Classes, SyncObjs; const DEFAULT_INTERVAL = 10; type // TODO: TPacketProcessor, TaskQueue, TWorker, TScheduler 차이점 설명 또는 통합 // TODO: TaskQueue, TWorker, TScheduler 차이점 설명 {* 처리해야 할 작업을 큐에 넣고 차례로 실행한다. 작업의 실행은 내부의 스레드를 이용해서 비동기로 실행한다. 작업 요청이 다양한 스레드에서 진행되는데, 순차적인 동작이 필요 할 때 사용한다. 요청 된 작업이 요청한 스레드와 별개의 스레드에서 실행되어야 할 때 사용한다. (비동기 실행) TaskQueue 와 다른 점은 TTimer와 같이 주기적인 시간에도 이벤트가 발생한다는 것이다. } TScheduler = class private FCS : TCriticalSection; FTasks : TDynamicQueue; procedure do_Tasks; function get_Task:TObject; private TickCount, OldTick, Tick : Cardinal; procedure do_Timer; private FSimpleThread : TSimpleThread; procedure on_FSimpleThread_Execute(ASimpleThread:TSimpleThread); private FOnTask: TDataAndTagEvent; FOnTerminate: TNotifyEvent; FOnTimer: TNotifyEvent; FInterval: integer; FIsStarted: boolean; FOnStop: TNotifyEvent; FOnStart: TNotifyEvent; procedure SetInterval(const Value: integer); public constructor Create; destructor Destroy; override; procedure Clear; procedure Start; procedure Stop; procedure Add(AData:pointer; ASize:integer); overload; procedure Add(AData:pointer; ASize:integer; ATag:pointer); overload; procedure Add(ATag:pointer); overload; public property IsStarted : boolean read FIsStarted; property Interval : integer read FInterval write SetInterval; public property OnStart : TNotifyEvent read FOnStart write FOnStart; property OnStop : TNotifyEvent read FOnStop write FOnStop; property OnTimer : TNotifyEvent read FOnTimer write FOnTimer; property OnTask : TDataAndTagEvent read FOnTask write FOnTask; property OnTerminate : TNotifyEvent read FOnTerminate write FOnTerminate; end; implementation type TTaskType = (ttData, ttStart, ttStop); TTask = class private FTaskType : TTaskType; FData : pointer; FSize : integer; FTag : pointer; public constructor Create(ATaskType:TTaskType); reintroduce; overload; constructor Create(AData:pointer; ASize:integer; ATag:pointer); reintroduce; overload; destructor Destroy; override; end; { TTask } constructor TTask.Create(AData: pointer; ASize: integer; ATag: pointer); begin inherited Create; FTaskType := ttData; FSize := ASize; if FSize <= 0 then begin FData := nil; end else begin GetMem(FData, FSize); Move(AData^, FData^, FSize); end; FTag := ATag; end; constructor TTask.Create(ATaskType: TTaskType); begin inherited Create; FTaskType := ATaskType; FData := nil; FSize := 0; FTag := 0; end; destructor TTask.Destroy; begin if FData <> nil then FreeMem(FData); inherited; end; { TScheduler } procedure TScheduler.Add(AData: pointer; ASize: integer); begin FCS.Acquire; try FTasks.Push( TTask.Create(AData, ASize, nil) ); FSimpleThread.WakeUp; finally FCS.Release; end; end; procedure TScheduler.Add(AData: pointer; ASize: integer; ATag: pointer); begin FCS.Acquire; try FTasks.Push( TTask.Create(AData, ASize, ATag) ); FSimpleThread.WakeUp; finally FCS.Release; end; end; procedure TScheduler.Add(ATag: pointer); begin FCS.Acquire; try FTasks.Push( TTask.Create(nil, 0, ATag) ); FSimpleThread.WakeUp; finally FCS.Release; end; end; procedure TScheduler.Clear; var Task : TTask; begin FCS.Acquire; try while FTasks.Pop(Pointer(Task)) do Task.Free; finally FCS.Release; end; end; constructor TScheduler.Create; begin inherited; FIsStarted := false; FInterval := DEFAULT_INTERVAL; FCS := TCriticalSection.Create; FTasks := TDynamicQueue.Create(false); FSimpleThread := TSimpleThread.Create('', on_FSimpleThread_Execute); end; destructor TScheduler.Destroy; begin Clear; FSimpleThread.Terminate; inherited; end; procedure TScheduler.do_Tasks; var Task : TTask; begin Task := Pointer( get_Task ); while Task <> nil do begin try case Task.FTaskType of ttData: if Assigned(FOnTask) then FOnTask(Self, Task.FData, Task.FSize, Task.FTag); ttStart: begin FIsStarted := true; if Assigned(FOnStart) then FOnStart(Self); end; ttStop: begin FIsStarted := false; if Assigned(FOnStop) then FOnStop(Self); end; end; finally Task.Free; end; Task := Pointer( get_Task ); end; end; procedure TScheduler.do_Timer; begin Tick := GetTick; if FIsStarted = false then begin OldTick := Tick; TickCount := 0; Exit; end; if Tick > OldTick then begin TickCount := TickCount + (Tick-OldTick); if TickCount >= FInterval then begin TickCount := 0; if Assigned(FOnTimer) then FOnTimer(Self); end; end; OldTick := Tick; end; function TScheduler.get_Task: TObject; begin Result := nil; FCS.Acquire; try FTasks.Pop(Pointer(Result)); finally FCS.Release; end; end; procedure TScheduler.on_FSimpleThread_Execute(ASimpleThread:TSimpleThread); begin TickCount := 0; OldTick := GetTick; while not ASimpleThread.Terminated do begin do_Tasks; do_Timer; ASimpleThread.Sleep(1); end; Clear; if Assigned(FOnTerminate) then FOnTerminate(Self); // FreeAndNil(FCS); // FreeAndNil(FTasks); end; procedure TScheduler.SetInterval(const Value: integer); begin FInterval := Value; end; procedure TScheduler.Start; begin FCS.Acquire; try FTasks.Push( TTask.Create(ttStart) ); FSimpleThread.WakeUp; finally FCS.Release; end; end; procedure TScheduler.Stop; begin // TODO: 실행되면 바로 모든 스케쥴 처리가 종료되도록 (플래그 설정) FCS.Acquire; try FTasks.Push( TTask.Create(ttStop) ); FSimpleThread.WakeUp; finally FCS.Release; end; end; end.
unit MVVM.Core; interface uses System.SysUtils, System.Classes, System.SyncObjs, Spring, Spring.Container, MVVM.Bindings, MVVM.Interfaces, MVVM.Interfaces.Architectural, MVVM.ViewFactory, MVVM.Types; type TContainerHelper = class helper for TContainer public function ViewModelProvider<T: IViewModel>: T; procedure RegisterViewModel(AClass, AInterface: PTypeInfo; const AIsSingleton: Boolean); end; MVVMCore = record private class var FPlatformServicesClass: TPlatformServicesClass; FContainer: TContainer; FDefaultBindingStrategyName: String; FDefaultViewPlatform: string; FSynchronizer: TLightweightMREW; class constructor CreateC; class destructor DestroyC; class function GetDefaultBindingStrategyName: String; static; class procedure SetDefaultBindingStrategyName(const AStrategyName: String); static; class function GetDefaultViewPlatform: String; static; class procedure SetDefaultViewPlatform(const APlatform: String); static; class procedure AutoRegister; static; public class procedure RegisterPlatformServices(AServicioClass: TPlatformServicesClass); static; class function PlatformServices: IPlatformServices; static; class function IoC: TContainer; static; class function EnableBinding(AObject: TObject): Boolean; static; class function DisableBinding(AObject: TObject): Boolean; static; class procedure InitializationDone; static; class function ViewsProvider: TViewFactoryClass; static; //class procedure DetectCommandsAndPrepare(AView: TComponent); static; class procedure DelegateExecution(AProc: TProc; AExecutionMode: EDelegatedExecutionMode); overload; static; class procedure DelegateExecution<T>(AData: T; AProc: TProc<T>; AExecutionMode: EDelegatedExecutionMode); overload; static; class function DefaultBindingStrategy: IBindingStrategy; static; class property DefaultBindingStrategyName: String read GetDefaultBindingStrategyName write SetDefaultBindingStrategyName; class property DefaultViewPlatform: String read GetDefaultViewPlatform write SetDefaultViewPlatform; end; implementation uses System.Threading, System.RTTI, System.Actions, System.TypInfo, MVVM.CommandFactory, MVVM.Attributes, MVVM.Utils; { TContainerHelper } procedure TContainerHelper.RegisterViewModel(AClass, AInterface: PTypeInfo; const AIsSingleton: Boolean); begin case AIsSingleton of True: begin RegisterType(AClass).Implements(AInterface).AsSingleton; end; False: begin RegisterType(AClass).Implements(AInterface); end; end; end; function TContainerHelper.ViewModelProvider<T>: T; begin Result := Resolve<T>; end; { MVVM } class procedure MVVMCore.AutoRegister; var Ctx: TRttiContext; Typ: TRttiType; LMethod: TRttiMethod; LAttr: TCustomAttribute; LVMA: View_For_ViewModel; LVMI: ViewModel_Implements; LInstanceType: TRttiInstanceType; LInterfaces: TArray<TRttiInterfaceType>; I: Integer; begin Ctx := TRttiContext.Create; try for Typ in Ctx.GetTypes do begin // Loop for class attributes for LAttr in Typ.GetAttributes do begin // Utils.IdeDebugMsg('Atributo: ' + LAttr.QualifiedClassName); case Utils.AttributeToCaseSelect(LAttr, [View_For_ViewModel, ViewModel_Implements]) of 0: // View_For_ViewModel begin LVMA := LAttr as View_For_ViewModel; if not Typ.IsInstance then Continue; LInstanceType := Typ.AsInstance; TViewFactory.Register(LInstanceType, LVMA.ViewAlias, LVMA.Platform); end; 1: // ViewModel_Implements begin LVMI := LAttr as ViewModel_Implements; if Typ.IsInstance then begin LInstanceType := Typ.AsInstance; LInterfaces := LInstanceType.GetImplementedInterfaces; if Length(LInterfaces) > 0 then begin for I := Low(LInterfaces) to High(LInterfaces) do begin if LInterfaces[I].GUID = LVMI.VMInterface then begin case LVMI.InstanceType of EInstanceType.itSingleton: begin MVVMCore.IoC.RegisterViewModel(LInstanceType.Handle, LInterfaces[I].Handle, True); //MVVMCore.IoC.RegisterType(LInstanceType.Handle).Implements(LInterfaces[I].Handle).AsSingleton; end; EInstanceType.itNewInstance: begin MVVMCore.IoC.RegisterViewModel(LInstanceType.Handle, LInterfaces[I].Handle, False); //MVVMCore.IoC.RegisterType(LInstanceType.Handle).Implements(LInterfaces[I].Handle); end; end; Break; end; end; end; end; end; end; end; end; finally Ctx.Free; end; end; //class procedure MVVMCore.DetectCommandsAndPrepare(AView: TComponent); //var // Ctx: TRttiContext; // Typ: TRttiType; // LAttr: TCustomAttribute; // LVMA: View_For_ViewModel; // LVMI: ViewModel_Implements; // LInstanceType: TRttiInstanceType; // LInterfaces: TArray<TRttiInterfaceType>; // I: Integer; // LField: TRttiField; // LCommand: Command; // LTypeData: PTypeData; // LExecute: RActionMember; // LCanExecute: RActionMember; // LParams: RActionMember; // LBindable: IBindableAction; //begin // if not Supports(AView, IBindableAction, LBindable) then // Exit; // Ctx := TRttiContext.Create; // try // Typ := ctx.GetType(AView.ClassType); // LInstanceType := ctx.GetType(AView.ClassType) as TRttiInstanceType; // // Loop the Fields // for LField in Typ.GetFields do // begin // if (LField.FieldType.TypeKind = tkClass) then // begin // LTypeData := GetTypeData(LField.FieldType.Handle); // if (not LTypeData^.ClassType.InheritsFrom(TContainedAction)) then //only an action is allowed // Continue; // // Loop for attributes // for LAttr in Typ.GetAttributes do // begin // case Utils.AttributeToCaseSelect(LAttr, [Command]) of // 0: // begin // LCommand := LAttr as Command; // LExecute := TCommandsFactory.GetActionMember(LCommand.ExecuteName); // //LBindable.Bind(LExecute.Method.Invoke(AView, []) as TExecuteMethod); // end; // end; // end; // end; // end; // finally // // end; //end; class function MVVMCore.IoC: TContainer; begin Result := FContainer; end; class constructor MVVMCore.CreateC; begin FContainer := TContainer.Create; FDefaultBindingStrategyName := ''; FDefaultViewPlatform := ''; end; class function MVVMCore.GetDefaultBindingStrategyName: String; begin FSynchronizer.BeginRead; try Result := FDefaultBindingStrategyName; finally FSynchronizer.EndRead; end; end; class function MVVMCore.GetDefaultViewPlatform: String; begin FSynchronizer.BeginRead; try Result := FDefaultViewPlatform; finally FSynchronizer.EndRead; end; end; class function MVVMCore.DefaultBindingStrategy: IBindingStrategy; begin Result := TBindingManager.GetDefaultRegisteredBindingStrategy end; class procedure MVVMCore.DelegateExecution(AProc: TProc; AExecutionMode: EDelegatedExecutionMode); begin case AExecutionMode of medQueue: begin TThread.Queue(TThread.CurrentThread, procedure begin AProc; end); end; medSynchronize: begin TThread.Synchronize(TThread.CurrentThread, procedure begin AProc end); end; medNewTask: begin TTask.Create( procedure begin AProc end).Start; end; medNormal: begin AProc; end; end; end; class procedure MVVMCore.DelegateExecution<T>(AData: T; AProc: TProc<T>; AExecutionMode: EDelegatedExecutionMode); begin case AExecutionMode of medQueue: begin TThread.Queue(TThread.CurrentThread, procedure begin AProc(AData); end); end; medSynchronize: begin TThread.Synchronize(TThread.CurrentThread, procedure begin AProc(AData) end); end; medNewTask: begin TTask.Create( procedure begin AProc(AData) end).Start; end; medNormal: begin AProc(AData); end; end; end; class destructor MVVMCore.DestroyC; begin FContainer.Free; end; class function MVVMCore.DisableBinding(AObject: TObject): Boolean; var [weak] LBinding: IBindable; begin Result := False; if Supports(AObject, IBindable, LBinding) then begin LBinding.Binding.Enabled := False; Result := True; end; end; class function MVVMCore.EnableBinding(AObject: TObject): Boolean; var [weak] LBinding: IBindable; begin Result := False; if Supports(AObject, IBindable, LBinding) then begin LBinding.Binding.Enabled := True; Result := True; end; end; class procedure MVVMCore.InitializationDone; begin AutoRegister; FContainer.Build; end; class procedure MVVMCore.RegisterPlatformServices(AServicioClass: TPlatformServicesClass); begin FPlatformServicesClass := AServicioClass; end; class procedure MVVMCore.SetDefaultBindingStrategyName(const AStrategyName: String); begin FSynchronizer.BeginWrite; try FDefaultBindingStrategyName := AStrategyName; finally FSynchronizer.EndWrite; end; end; class procedure MVVMCore.SetDefaultViewPlatform(const APlatform: String); begin FSynchronizer.BeginWrite; try FDefaultViewPlatform := APlatform; finally FSynchronizer.EndWrite; end; end; class function MVVMCore.PlatformServices: IPlatformServices; begin Spring.Guard.CheckNotNull(FPlatformServicesClass, 'No hay registrado ningun servicio para la plataforma'); Result := FPlatformServicesClass.Create; end; class function MVVMCore.ViewsProvider: TViewFactoryClass; begin Result := TViewFactory; end; end.
unit XLSXML; {- ******************************************************************************** ******* XLSReadWriteII V3.00 ******* ******* ******* ******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} {$H+} {$R-} {$I XLSRWII2.inc} interface uses Classes, SysUtils, XLSHTMLDecode; type TTagType = (ttUnknown,ttBegin,ttEnd,ttSingle,ttXmlId); {$WARNINGS OFF} type TXMLValueList = class(TStringList) private FValueParts: TStringList; function GetAsFloat(Index: integer): double; function GetAsInteger(Index: integer): integer; function GetElement(Index: integer): string; function GetValue(Index: integer): string; function GetIsFloat(Index: integer): boolean; public constructor Create; destructor Destroy; override; procedure SplitValue(Index: integer); procedure Add(S: string); // reintroduce; function FindElement(E: string): integer; function FindStrElement(E: string): WideString; function FindIntElement(E: string; Default: integer): integer; property Element[Index: integer]: string read GetElement; property Value[Index: integer]: string read GetValue; property ValueParts: TStringList read FValueParts; property AsInteger[Index: integer]: integer read GetAsInteger; property AsFloat[Index: integer]: double read GetAsFloat; property IsFloat[Index: integer]: boolean read GetIsFloat; end; {$WARNINGS ON} type TXLSReadXML = class(TObject) private function GetFullTag: string; protected FValues: TXMLValueList; FTagType: TTagType; FTagClass,FTagName: string; FText: WideString; function GetChar(var C: char): boolean; virtual; abstract; procedure UnGetChar; virtual; abstract; function ReadTag: boolean; public constructor Create; destructor Destroy; override; function GetTagNext: boolean; procedure Seek(Offset: integer); virtual; abstract; function Position: integer; virtual; abstract; property TagType: TTagType read FTagType; property TagClass: string read FTagClass; property TagName: string read FTagName; property FullTag: string read GetFullTag; property Text: WideString read FText; property Values: TXMLValueList read FValues; end; type TXLSReadXMLStream = class(TXLSReadXML) private FStream: TStream; protected procedure UnGetChar; override; function GetChar(var C: char): boolean; override; public constructor Create(Stream: TStream); procedure Seek(Offset: integer); override; function Position: integer; override; end; type TXLSReadXMLMemory = class(TXLSReadXML) private FBuf: PByteArray; FBufSize,FBufPos: integer; protected function GetChar(var C: char): boolean; override; procedure UnGetChar; override; public constructor Create(Buf: PByteArray; BufSize: integer); procedure Seek(Offset: integer); override; function Position: integer; override; function FindTag(Tag: string): boolean; end; function GetNextWord(var S: string; Sep: char): string; function HexStrToInt(S: string): integer; implementation function CPos(C: char; S: string): integer; begin for Result := 1 to Length(S) do begin if S[Result] = C then Exit; end; Result := -1; end; function CPosSkipQuotes(C: char; S: string): integer; var InQuote: boolean; begin InQuote := False; for Result := 1 to Length(S) do begin if S[Result] = '"' then InQuote := not InQuote; if not InQuote and (S[Result] = C) then Exit; end; Result := -1; end; function GetNextWordSkipQuotes(var S: string; Sep: char): string; var p: integer; begin p := CPosSkipQuotes(Sep,S); if p > 0 then begin Result := Trim(Copy(S,1,p - 1)); S := Trim(Copy(S,p + 1,MAXINT)); end else begin Result := Trim(S); S := ''; end; end; function GetNextWord(var S: string; Sep: char): string; var p: integer; begin p := CPos(Sep,S); if p > 0 then begin Result := Trim(Copy(S,1,p - 1)); S := Trim(Copy(S,p + 1,MAXINT)); end else begin Result := Trim(S); S := ''; end; end; procedure SplitStr(S: string; var Left,Right: string; Sep: char); var p: integer; begin p := CPos(Sep,S); if p > 0 then begin Left := Trim(Copy(S,1,p - 1)); Right := Trim(Copy(S,p + 1,MAXINT)); end else Left := S; end; procedure RemoveQuotes(var S: string); begin if (S <> '') and (S[1] in ['"','''']) then S := Copy(S,2,MAXINT); if (S <> '') and (S[Length(S)] in ['"','''']) then S := Copy(S,1,Length(S) - 1); end; function HexStrToInt(S: string): integer; var i: integer; C: char; begin Result := 0; for i := 1 to Length(S) do begin C := S[i]; case C of '0'..'9': Result := (Result shl 4) + (Ord(C) - $30); 'A'..'F': Result := (Result shl 4) + (Ord(C) - $37); 'a'..'f': Result := (Result shl 4) + (Ord(C) - $57); end; end; end; { TXMLValueList } procedure TXMLValueList.Add(S: string); var S2: string; begin S2 := GetNextWord(S,'='); if S <> '' then begin RemoveQuotes(S); S2 := S2 + '=' + S; end; inherited Add(S2); end; constructor TXMLValueList.Create; begin FValueParts := TStringList.Create; end; destructor TXMLValueList.Destroy; begin FValueParts.Free; inherited; end; function TXMLValueList.FindElement(E: string): integer; begin for Result := 0 to Count - 1 do begin if GetElement(Result) = E then Exit; end; Result := -1; end; function TXMLValueList.FindIntElement(E: string; Default: integer): integer; var i: integer; S: string; begin for i := 0 to Count - 1 do begin if GetElement(i) = E then begin S := GetValue(i); if Copy(S,1,1) = '#' then Result := HexStrToInt(S) else Result := StrToIntDef(S,Default); Exit; end; end; Result := Default; end; function TXMLValueList.FindStrElement(E: string): WideString; var i: integer; begin for i := 0 to Count - 1 do begin if GetElement(i) = E then begin Result := DecodeHTMLText(UTF8ToWideString(GetValue(i))); Exit; end; end; Result := ''; end; function TXMLValueList.GetAsFloat(Index: integer): double; var tempDS: char; i: integer; S: string; begin tempDS := DecimalSeparator; DecimalSeparator := '.'; try S := GetValue(Index); i := 1; while (i <= Length(S)) and (S[i] in ['0'..'9','.']) do Inc(i); if i < Length(S) then S := Copy(S,1,i - 1); Result := StrToFloat(S); finally DecimalSeparator := tempDS; end; end; function TXMLValueList.GetAsInteger(Index: integer): integer; var S: string; begin S := GetValue(Index); if Copy(S,1,1) = '#' then Result := HexStrToInt(S) else Result := StrToIntDef(S,0); end; function TXMLValueList.GetElement(Index: integer): string; var S: string; p: integer; begin S := Strings[Index]; p := CPos('=',S); if p > 0 then Result := Copy(S,1,p - 1) else Result := S; end; function TXMLValueList.GetIsFloat(Index: integer): boolean; var i: integer; S: string; begin S := GetValue(Index); i := 1; while (i <= Length(S)) and (S[i] in ['0'..'9','.']) do Inc(i); Result := i > Length(S); end; function TXMLValueList.GetValue(Index: integer): string; var S: string; p: integer; begin S := Strings[Index]; p := CPos('=',S); if p > 0 then Result := Copy(S,p + 1,MAXINT) else Result := ''; end; procedure TXMLValueList.SplitValue(Index: integer); var S: string; begin FValueParts.Clear; S := GetValue(Index); while S <> '' do FValueParts.Add(GetNextWord(S,' ')); end; { TXLSReadXML } constructor TXLSReadXML.Create; begin FValues := TXMLValueList.Create; end; destructor TXLSReadXML.Destroy; begin FValues.Free; inherited; end; function TXLSReadXML.GetFullTag: string; begin Result := FTagClass + ':' + FTagName; end; function TXLSReadXML.GetTagNext: boolean; begin Result := ReadTag; end; function TXLSReadXML.ReadTag: boolean; var C: char; S,S2: string; Slash: boolean; InString: boolean; begin Result := False; InString := False; Slash := False; FTagType := ttUnknown; while GetChar(C) do begin if C = '<' then begin if GetChar(C) and (C = '/') then FTagType := ttEnd else S := S + C; while GetChar(C) do begin if C = '"' then InString := not InString; if InString then begin S := S + C; Continue; end; if C = '>' then begin if (S <> '') and (S[1] = '?') and (Copy(S,1,4) = '?xml') then begin FTagType := ttXmlId; Result := True; Exit; end; if Slash then FTagType := ttSingle else if FTagType = ttUnknown then FTagType := ttBegin; S2 := S; FTagClass := GetNextWord(S,' '); SplitStr(FTagClass,FTagClass,FTagName,':'); FValues.Clear; while S <> '' do begin FValues.Add(GetNextWordSkipQuotes(S,' ')); end; S2 := ''; while GetChar(C) do begin if C = '<' then begin unGetChar; Break; end; S2 := S2 + C; end; FText := DecodeHTMLText(UTF8ToWideString(Trim(S2))); Result := True; Exit; end else begin Slash := C = '/'; if not Slash then S := S + C; end; end; end; end; end; { TXLSReadXMLStream } constructor TXLSReadXMLStream.Create(Stream: TStream); begin inherited Create; FStream := Stream; end; function TXLSReadXMLStream.GetChar(var C: char): boolean; begin Result := FStream.Read(C,1) = 1; end; function TXLSReadXMLStream.Position: integer; begin Result := FStream.Position; end; procedure TXLSReadXMLStream.Seek(Offset: integer); begin FStream.Seek(Offset,soFromBeginning); end; procedure TXLSReadXMLStream.UnGetChar; begin FStream.Seek(-1,soFromCurrent); end; { TXLSReadXMLMemory } constructor TXLSReadXMLMemory.Create(Buf: PByteArray; BufSize: integer); begin inherited Create; FBuf := Buf; FBufSize := BufSize; FBufPos := 0; end; function TXLSReadXMLMemory.FindTag(Tag: string): boolean; var i,j,L: integer; begin Result := False; if Tag = '' then Exit; L := Length(Tag); i := FBufPos; while i < FBufSize do begin j := 1; while (Char(FBuf[i]) = Tag[j]) and (j <= L) and (i < FBufSize) do begin Inc(i); Inc(j); end; Result := j = (L + 1); if Result then begin FBufPos := i - j; Result := ReadTag; Exit; end; Inc(i); end; end; function TXLSReadXMLMemory.GetChar(var C: char): boolean; begin Result := FBufPos < FBufSize; if Result then begin C := Char(FBuf[FBufPos]); Inc(FBufPos); end; end; function TXLSReadXMLMemory.Position: integer; begin Result := FBufPos; end; procedure TXLSReadXMLMemory.Seek(Offset: integer); begin FBufPos := Offset; end; procedure TXLSReadXMLMemory.UnGetChar; begin if FBufPos > 0 then Dec(FBufPos); end; end.
{----------------------------------------------------------------------------- Unit Name: frmVariables Author: Kiriakos Vlahos Date: 09-Mar-2005 Purpose: Variables Window History: -----------------------------------------------------------------------------} unit frmVariables; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, ImgList, JvDockControlForm, JvComponent, Menus, VTHeaderPopup, VirtualTrees, frmIDEDockWin, TBX, TBXThemes, JvExExtCtrls, JvNetscapeSplitter, JvExControls, JvLinkLabel, TBXDkPanels, JvComponentBase, cPyBaseDebugger; type TVariablesWindow = class(TIDEDockWindow) VTHeaderPopupMenu: TVTHeaderPopupMenu; VariablesTree: TVirtualStringTree; Splitter: TJvNetscapeSplitter; TBXPageScroller: TTBXPageScroller; HTMLLabel: TJvLinkLabel; procedure VariablesTreeChange(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure FormCreate(Sender: TObject); procedure VariablesTreeInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure VariablesTreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure VariablesTreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure FormActivate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure VariablesTreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); private { Private declarations } CurrentFrame : TBaseFrameInfo; CurrentFileName, CurrentFunctionName : string; GlobalsNameSpace, LocalsNameSpace : TBaseNameSpaceItem; protected procedure TBMThemeChange(var Message: TMessage); message TBM_THEMECHANGE; public { Public declarations } procedure ClearAll; procedure UpdateWindow; end; var VariablesWindow: TVariablesWindow = nil; implementation uses frmPyIDEMain, frmCallStack, PythonEngine, VarPyth, dmCommands, uCommonFunctions, JclFileUtils, StringResources, frmPythonII, JvDockGlobals, cPyDebugger; {$R *.dfm} Type PPyObjRec = ^TPyObjRec; TPyObjRec = record NameSpaceItem : TBaseNameSpaceItem; end; procedure TVariablesWindow.FormCreate(Sender: TObject); begin inherited; // Let the tree know how much data space we need. VariablesTree.NodeDataSize := SizeOf(TPyObjRec); VariablesTree.OnAdvancedHeaderDraw := CommandsDataModule.VirtualStringTreeAdvancedHeaderDraw; VariablesTree.OnHeaderDrawQueryElements := CommandsDataModule.VirtualStringTreeDrawQueryElements; HTMLLabel.Color := clWindow; TBXPageScroller.Color := clWindow; end; procedure TVariablesWindow.VariablesTreeInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var Data, ParentData: PPyObjRec; begin Data := VariablesTree.GetNodeData(Node); if VariablesTree.GetNodeLevel(Node) = 0 then begin Assert(Node.Index <= 1); if Assigned(CurrentFrame) then begin if Node.Index = 0 then begin Assert(Assigned(GlobalsNameSpace)); Data.NameSpaceItem := GlobalsNameSpace; InitialStates := [ivsHasChildren]; end else if Node.Index = 1 then begin Assert(Assigned(LocalsNameSpace)); Data.NameSpaceItem := LocalsNameSpace; InitialStates := [ivsExpanded, ivsHasChildren]; end; end else begin Assert(Node.Index = 0); Assert(Assigned(GlobalsNameSpace)); Data.NameSpaceItem := GlobalsNameSpace; InitialStates := [ivsExpanded, ivsHasChildren]; end; VariablesTree.ChildCount[Node] := Data.NameSpaceItem.ChildCount; end else begin ParentData := VariablesTree.GetNodeData(ParentNode); Data.NameSpaceItem := ParentData.NameSpaceItem.ChildNode[Node.Index]; VariablesTree.ChildCount[Node] := Data.NameSpaceItem.ChildCount; if Data.NameSpaceItem.ChildCount > 0 then InitialStates := [ivsHasChildren] else InitialStates := []; end; end; procedure TVariablesWindow.VariablesTreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); var Data : PPyObjRec; begin Data := VariablesTree.GetNodeData(Node); if Assigned(Data) then if nsaChanged in Data.NameSpaceItem.Attributes then TargetCanvas.Font.Color := clRed else if nsaNew in Data.NameSpaceItem.Attributes then TargetCanvas.Font.Color := clBlue; end; procedure TVariablesWindow.VariablesTreeGetImageIndex( Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var Data : PPyObjRec; begin if (Column = 0) and (Kind in [ikNormal, ikSelected]) then begin Data := VariablesTree.GetNodeData(Node); with GetPythonEngine do begin if Data.NameSpaceItem.IsDict then begin if vsExpanded in Node.States then ImageIndex := 9 else ImageIndex := 10; end else if Data.NameSpaceItem.IsModule then ImageIndex := 18 else if Data.NameSpaceItem.IsMethod then ImageIndex := 11 else if Data.NameSpaceItem.IsFunction then ImageIndex := 14 else if Data.NameSpaceItem.Has__dict__ then begin if (Data.NameSpaceItem.ChildCount > 0) and (vsExpanded in Node.States) then ImageIndex := 12 else ImageIndex := 13; end else ImageIndex := 1 end end else ImageIndex := -1; end; procedure TVariablesWindow.VariablesTreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var Data : PPyObjRec; begin Data := VariablesTree.GetNodeData(Node); CellText := ''; case Column of 0 : CellText := Data.NameSpaceItem.Name; 1 : with GetPythonEngine do CellText := Data.NameSpaceItem.ObjectType; 2 : begin try CellText := Data.NameSpaceItem.Value; except CellText := ''; end; end; end; end; Type // to help us access protected methods TCrackedVirtualStringTree = class(TVirtualStringTree) end; procedure TVariablesWindow.UpdateWindow; procedure ReinitNode(Node: PVirtualNode; Recursive: Boolean); forward; procedure ReinitChildren(Node: PVirtualNode; Recursive: Boolean); // Forces all child nodes of Node to be reinitialized. // If Recursive is True then also the grandchildren are reinitialized. // Modified version to reinitialize only when the node is already initialized var Run: PVirtualNode; begin if Assigned(Node) then begin TCrackedVirtualStringTree(VariablesTree).InitChildren(Node); Run := Node.FirstChild; end else begin TCrackedVirtualStringTree(VariablesTree).InitChildren(VariablesTree.RootNode); Run := VariablesTree.RootNode.FirstChild; end; while Assigned(Run) do begin if vsInitialized in Run.States then ReinitNode(Run, Recursive); Run := Run.NextSibling; end; end; //---------------------------------------------------------------------------------------------------------------------- procedure ReinitNode(Node: PVirtualNode; Recursive: Boolean); // Forces the given node and all its children (if recursive is True) to be initialized again without // modifying any data in the nodes nor deleting children (unless the application requests a different amount). begin if Assigned(Node) and (Node <> VariablesTree.RootNode) then begin // Remove dynamic styles. Node.States := Node.States - [vsChecking, vsCutOrCopy, vsDeleting, vsHeightMeasured]; TCrackedVirtualStringTree(VariablesTree).InitNode(Node); end; if Recursive then ReinitChildren(Node, True); end; Var SameFrame : boolean; RootNodeCount : Cardinal; OldGlobalsNameSpace, OldLocalsNamespace : TBaseNameSpaceItem; begin if not Assigned(CallStackWindow) then begin // Should not happen! ClearAll; Exit; end; // Get the selected frame CurrentFrame := CallStackWindow.GetSelectedStackFrame; SameFrame := (not Assigned(CurrentFrame) and (CurrentFileName = '') and (CurrentFunctionName = '')) or (Assigned(CurrentFrame) and (CurrentFileName = CurrentFrame.FileName) and (CurrentFunctionName = CurrentFrame.FunctionName)); OldGlobalsNameSpace := GlobalsNameSpace; OldLocalsNamespace := LocalsNameSpace; GlobalsNameSpace := nil; LocalsNameSpace := nil; // Turn off Animation to speed things up VariablesTree.TreeOptions.AnimationOptions := VariablesTree.TreeOptions.AnimationOptions - [toAnimatedToggle]; if Assigned(CurrentFrame) then begin CurrentFileName := CurrentFrame.FileName; CurrentFunctionName := CurrentFrame.FunctionName; // Set the initial number of nodes. GlobalsNameSpace := PyIDEMainForm.PyDebugger.GetFrameGlobals(CurrentFrame); LocalsNameSpace := PyIDEMainForm.PyDebugger.GetFrameLocals(CurrentFrame); if Assigned(GlobalsNameSpace) and Assigned(LocalsNameSpace) then RootNodeCount := 2 else RootNodeCount := 0; end else begin CurrentFileName := ''; CurrentFunctionName := ''; GlobalsNameSpace := TNameSpaceItem.Create('globals', VarPythonEval('globals()')); RootNodeCount := 1; end; if SameFrame and (RootNodeCount = VariablesTree.RootNodeCount) then begin if Assigned(GlobalsNameSpace) and Assigned(OldGlobalsNameSpace) then GlobalsNameSpace.CompareToOldItem(OldGlobalsNameSpace); if Assigned(LocalsNameSpace) and Assigned(OldLocalsNameSpace) then LocalsNameSpace.CompareToOldItem(OldLocalsNameSpace); VariablesTree.BeginUpdate; try ReinitChildren(VariablesTree.RootNode, True); VariablesTree.InvalidateToBottom(VariablesTree.GetFirstVisible); finally VariablesTree.EndUpdate; end; end else begin VariablesTree.Clear; VariablesTree.RootNodeCount := RootNodeCount; end; FreeAndNil(OldGlobalsNameSpace); FreeAndNil(OldLocalsNameSpace); VariablesTree.TreeOptions.AnimationOptions := VariablesTree.TreeOptions.AnimationOptions + [toAnimatedToggle]; VariablesTreeChange(VariablesTree, nil); end; procedure TVariablesWindow.ClearAll; begin CurrentFrame := nil; VariablesTree.Clear; FreeAndNil(GlobalsNameSpace); FreeAndNil(LocalsNameSpace); end; procedure TVariablesWindow.FormActivate(Sender: TObject); begin inherited; if not HasFocus then begin FGPanelEnter(Self); PostMessage(VariablesTree.Handle, WM_SETFOCUS, 0, 0); end; end; procedure TVariablesWindow.TBMThemeChange(var Message: TMessage); begin inherited; if Message.WParam = TSC_VIEWCHANGE then begin VariablesTree.Header.Invalidate(nil, True); VariablesTree.Colors.HeaderHotColor := CurrentTheme.GetItemTextColor(GetItemInfo('active')); FGPanel.Color := CurrentTheme.GetItemColor(GetItemInfo('inactive')); Splitter.ButtonColor := CurrentTheme.GetItemColor(GetItemInfo('inactive')); Splitter.ButtonHighlightColor := CurrentTheme.GetItemColor(GetItemInfo('active')); end; end; procedure TVariablesWindow.FormDestroy(Sender: TObject); begin VariablesWindow := nil; ClearAll; inherited; end; procedure TVariablesWindow.VariablesTreeChange(Sender: TBaseVirtualTree; Node: PVirtualNode); Var FunctionName, ModuleName, NameSpace, ObjectName, ObjectType, ObjectValue, DocString : string; LineNo : integer; Data : PPyObjRec; begin // Get the selected frame if Assigned(CurrentFrame) then begin FunctionName := CurrentFrame.FunctionName; ModuleName := PathRemoveExtension(ExtractFileName(CurrentFrame.FileName)); LineNo := CurrentFrame.Line; NameSpace := Format(SNamespaceFormat, [FunctionName, ModuleName, LineNo]); end else NameSpace := 'Interpreter globals'; if Assigned(Node) and (vsSelected in Node.States) then begin Data := VariablesTree.GetNodeData(Node); ObjectName := Data.NameSpaceItem.Name; ObjectType := Data.NameSpaceItem.ObjectType; ObjectValue := HTMLSafe(Data.NameSpaceItem.Value); DocString := HTMLSafe(Data.NameSpaceItem.DocString); HTMLLabel.Caption := Format(SVariablesDocSelected, [NameSpace, ObjectName, ObjectType, ObjectValue, Docstring]); end else HTMLLabel.Caption := Format(SVariablesDocNotSelected, [NameSpace]); end; end.
unit Odontologia.Controlador.Agenda.Interfaces; interface uses Data.DB, Odontologia.Controlador.Estado.Cita.Interfaces, Odontologia.Controlador.Medico.Interfaces, Odontologia.Controlador.Paciente.Interfaces, Odontologia.Modelo.Entidades.Agenda; type iControllerAgenda = interface ['{CF622183-1258-4B6E-B4A1-A3D28F5CC81E}'] function DataSource (aDataSource : TDataSource) : iControllerAgenda; function Buscar (aFecha : String) : iControllerAgenda; overload; function Buscar (aFecha, aMedico, aPaciente : String) : iControllerAgenda; overload; function Buscar (aFecha, aMedico, aPaciente, aEstado : String) : iControllerAgenda; overload; function Buscar : iControllerAgenda; overload; function Insertar : iControllerAgenda; function Modificar : iControllerAgenda; function Eliminar : iControllerAgenda; function Entidad : TDAGENDA; function Medico : iControllerMedico; function Paciente : iControllerPaciente; function EstadoCita : iControllerEstadoCita; end; implementation end.
unit tables; interface procedure DrawTable; procedure DrawLTable; procedure DrawTest; procedure DrawLTest; procedure SetSizes(newP, newM, newN, newLen:word); procedure SetAlgo(newAlgo:word); procedure SetSortingType(newType:word); procedure DrawMenuBar; var algoTypes:array [1..3] of string [24]; implementation uses crt, algos; type ALGOFUNC=function:longint; FORMPROC=procedure; var linId, id, testId, lTestId, M, N, P, Len, sorting, algo:word; algFuncs:array [1..3] of ALGOFUNC; formProcs:array[1..3] of FORMPROC; busy:boolean; menuStrs:array [1..5, 1..4] of string [24]; var sortTypes:array [1..3] of string [16]; function Bigger(x, y:longint):longint; begin if x > y then Bigger:=x else Bigger:=y; end; procedure SetSizes(newP, newM, newN, newLen:word); begin M:=newM; N:=newN; P:=newP; Len:=newLen; SetDimensions(P, M, N, Len); DrawMenuBar; end; procedure DrawTest; var tm:longint; begin busy:=true; DrawMenuBar; testId:=testId+1; formProcs[sorting]; writeln(' Тест №', testId, 'для масива A[P, M, N]; P=', P, ' M=', M, ' N=', N, '.'); writeln(' Алгоритм обходу: ', algoTypes[algo], '. Тип упорядкованстi:', sortTypes[sorting], '.'); write('Час сортування : ', algFuncs[algo], '.'); writeln; busy:=false; algFuncs[algo]; DrawMenuBar; end; procedure SetAlgo(newAlgo:word); begin algo:=newAlgo; DrawMenuBar; end; procedure SetSortingType(newType:word); begin sorting:=newType; DrawMenuBar; end; procedure DrawLTest; var tm:longint; begin busy:=true; DrawMenuBar; lTestId:=lTestId+1; formProcs[sorting]; tm:=SortLinear; writeln(' Тест №', lTestId, ' для вектора C[N]; N=', Len, '.'); writeln(' Алгоритм обходу: ', algoTypes[algo], '. Тип упорядкованстi: ', sortTypes[sorting], '.'); write('Час сортування: ', tm, '.'); writeln; busy:=false; SortLinear; DrawMenuBar; end; procedure DrawTable; var cellStrs:array [1..4, 1..4] of string [32]; colWids:array [1..4] of word; max, tabWid:word; i, j, k:word; begin busy:=true; DrawMenuBar; id:=id+1; cellStrs[1, 1]:=''; cellStrs[1, 2]:='Вiдсорт.'; cellStrs[1, 3]:='Невiдсорт.'; cellStrs[1, 4]:='Оберн. вiдсорт.'; cellStrs[2, 1]:='Дод. масив'; cellStrs[3, 1]:='Перетв. коорд.'; cellStrs[4, 1]:='Прямий обхiд'; for j:=1 to 3 do for i:=1 to 3 do begin formProcs[j]; str(longint(algFuncs[i]), cellStrs[i+1, j+1]); end; tabWid:=0; for j:=1 to 4 do begin max:=0; for i:=1 to 4 do if length(cellStrs[i, j]) > max then max:=length(cellStrs[i, j]); colWids[j]:=max+2; tabWid:=tabWid+colWids[j]; end; writeln(' Таблиця №', id, ' для масива A[P, M, N]; P=', P, ' M=', M, ' N=', N, '.'); tabWid:=tabWid+5; for i:=1 to 4 do begin for j:=1 to tabWid do write('-'); writeln; write('|'); for j:=1 to 4 do begin for k:=1 to (colWids[j]-length(cellStrs[i, j])-1) do write(' '); write(cellStrs[i, j]); write(' |'); end; writeln; end; for i:=1 to tabWid do write('-'); writeln; busy:=false; DrawMenuBar; end; procedure DrawLTable; var cellStrs:array [1..2, 1..3] of string [32]; colWids:array [1..3] of word; max, tabWid:word; i, j, k:word; begin busy:=true; DrawMenuBar; linId:=linId+1; cellStrs[1, 1]:='Вiдсорт.'; cellStrs[1, 3]:='Оберн. вiдсорт.'; cellStrs[1, 2]:='Невiдсорт.'; for i:=1 to 3 do begin formProcs[i]; str(SortLinear, cellStrs[2, i]); end; writeln(' Таблиця №', linId, ' для вектора C[N]; N=', Len, '.'); tabWid:=0; for i:=1 to 3 do begin colWids[i]:=Bigger(length(cellStrs[1, i]), length(cellStrs[2, i]))+2; tabWid:=tabWid+colWids[i]; end; tabWid:=tabWid+4; for i:=1 to 2 do begin for j:=1 to tabWid do write('-'); writeln; write('|'); for j:=1 to 3 do begin for k:=1 to (colWids[j]-length(cellStrs[i, j])-1) do write(' '); write(cellStrs[i, j], ' |'); end; writeln; end; for i:=1 to tabWid do write('-'); writeln; busy:=false; DrawMenuBar; end; procedure DrawMenuBar; var i, j, k, tabWid, max:word; colWids:array [1..4] of word; x, y:word; begin x:=WhereX; y:=WhereY; if y < 8 then y:=8; for i:=1 to 8 do begin GotoXY(1, i); for j:=1 to 80 do write(' '); end; GotoXY(1, 1); str(P, menuStrs[1, 3]); menuStrs[1, 3]:='P='+menuStrs[1, 3]; str(M, menuStrs[2, 3]); menuStrs[2, 3]:='M='+menuStrs[2, 3]; str(N, menuStrs[3, 3]); menuStrs[3, 3]:='N='+menuStrs[3, 3]; menuStrs[4, 3]:=''; str(Len, menuStrs[5, 3]); menuStrs[5, 3]:='Len='+menuStrs[5, 3]; menuStrs[1, 4]:='Упорядк.: '+sortTypes[sorting]; menuStrs[2, 4]:='Обхiд: '+algoTypes[algo]; menuStrs[3, 4]:=''; if busy = true then menuStrs[4, 4]:='Працюю...' else menuStrs[4, 4]:='Вiльний'; menuStrs[4, 4]:='Статус: '+menuStrs[4, 4]; menuStrs[5, 4]:=''; tabWid:=0; for j:=1 to 4 do begin max:=0; for i:=1 to 5 do if length(menuStrs[i, j]) > max then max:=length(menuStrs[i, j]); colWids[j]:=max+2; tabWid:=tabWid+colWids[j]; end; tabWid:=tabWid+3; for i:=1 to tabWid do write('='); writeln; for i:=1 to 5 do begin write('| '); for j:= 1 to 4 do begin write(menuStrs[i, j]); for k:=1 to (colWids[j]-length(menuStrs[i, j])-1) do write(' '); if (j=2) or (j=4) then write('|'); write(' '); end; writeln; end; for i:=1 to tabWid do write('='); GotoXY(x, y); end; begin algFuncs[1]:=Algo_1; algFuncs[2]:=Algo_2; algFuncs[3]:=Algo_3; formProcs[1]:=FormStraightSorted; formProcs[2]:=FormRandom; formProcs[3]:=FormBackSorted; menuStrs[1, 1]:='1-Розмiри'; menuStrs[2, 1]:='2-Алг. обходу'; menuStrs[3, 1]:='3-Вiдсорт.'; menuStrs[4, 1]:='4-Невiдсорт.'; menuStrs[5, 1]:='5-Оберн. вiдсорт.'; menuStrs[1, 2]:='6-Тест. масив'; menuStrs[2, 2]:='7-Тест. вектор'; menuStrs[3, 2]:='8-Пак. режим (масив)'; menuStrs[4, 2]:='9-Пак. режим (вектор)'; menuStrs[5, 2]:='0-Вихiд'; sortTypes[1]:='Вiдсорт.'; sortTypes[2]:='Невiдсорт.'; sortTypes[3]:='Оберн.'; algoTypes[1]:='Дод. масив'; algoTypes[2]:='Перет. Коорд.'; algoTypes[3]:='Прямий обхiд'; id:=0; linId:=0; testId:=0; lTestId:=0; busy:=false; algo:=1; sorting:=2; SetSizes(1, 1, 1, 1); end.
{ Delphi Application Unit by Aphex http://iamaphex.cjb.net unremote@knology.net } unit ApplicationUnit; interface uses Windows, StrList; type TProcedure = procedure; TApplication = class(TObject) private FStartup: TProcedure; FMain: TProcedure; FShutdown: TProcedure; FTerminated: boolean; function ProcessMessage(var Msg: TMsg): Boolean; protected public property Startup: TProcedure read FStartup write FStartup; property Main: TProcedure read FMain write FMain; property Shutdown: TProcedure read FShutdown write FShutdown; property Terminated: boolean read FTerminated write FTerminated; procedure StayResident; procedure Terminate; procedure ProcessMessages; end; implementation function TApplication.ProcessMessage(var Msg: TMsg): Boolean; begin Result := False; if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin Result := True; if Msg.Message <> $0012 then begin TranslateMessage(Msg); DispatchMessage(Msg); end else begin FTerminated := True; end; end; end; procedure TApplication.ProcessMessages; var Msg: TMsg; begin while ProcessMessage(Msg) do; end; procedure TApplication.Terminate; begin FTerminated := True; end; procedure TApplication.StayResident; var Msg: TMsg; begin if Assigned(FStartup) then FStartup; while not FTerminated do begin while ProcessMessage(Msg) do; Sleep(100); if Assigned(FMain) then FMain; end; if Assigned(FShutdown) then FShutdown; end; end.
unit ConverterClassIndex; interface type TTemperatureScale = (tsCelsius, tsFahrenheit, tsKelvin); const cTemperatureString: array[TTemperatureScale] of String = ('Celsius', 'Fahrenheit', 'Kelvin'); type TTemperature = class private FCelsius : Extended; protected procedure Assign(AValue: TTemperature); function GetTemperature(AIndex: TTemperatureScale): Extended; procedure SetTemperature(AIndex: TTemperatureScale; AValue : Extended); public constructor Create; property Temperature : TTemperature write Assign; class function StringToScale(AValue: String): TTemperatureScale; class function ScaleToString(AValue: TTemperatureScale): String; property Value[Index : TTemperatureScale]: Extended read GetTemperature write SetTemperature; default; property Celsius : Extended index tsCelsius read GetTemperature write SetTemperature; property Fahrenheit : Extended index tsFahrenheit read GetTemperature write SetTemperature; property Kelvin: Extended index tsKelvin read GetTemperature write SetTemperature; end; implementation uses ConvUtils; // from Celsius to Celsius // Fahrenheit [F] = [C] x 9/5 + 32 [C] = ([F] - 32) x 5/9 // Kelvin [K] = [C] + 273.15 [C] = [K] - 273.15 // Rankine [R] = ([C] + 273.15) x 9/5 [C] = ([R] - 491.67) x 5/9 constructor TTemperature.Create; begin FCelsius := 0; end; function TTemperature.GetTemperature(AIndex: TTemperatureScale): Extended; begin case AIndex of tsCelsius : Result := FCelsius; tsFahrenheit : Result := FCelsius * 9 / 5 + 32; tsKelvin : Result := FCelsius + 273.15; else raise EConversionError.Create('Unknown scale!'); end end; procedure TTemperature.SetTemperature(AIndex: TTemperatureScale; AValue: Extended); begin case AIndex of tsCelsius : FCelsius := AValue; tsFahrenheit : FCelsius := (AValue - 32) * 5 / 9; tsKelvin : FCelsius := AValue - 273.15; else raise EConversionError.Create('Unknown scale!'); end end; procedure TTemperature.Assign(AValue: TTemperature); begin FCelsius := AValue.FCelsius; end; class function TTemperature.StringToScale(AValue: String): TTemperatureScale; var i : TTemperatureScale; begin for i := low(TTemperatureScale) to high(TTemperatureScale) do if AValue = cTemperatureString[i] then begin Result := i; exit; end; raise EConversionError.Create('Unknown scale!'); end; class function TTemperature.ScaleToString(AValue: TTemperatureScale): String; begin Result := cTemperatureString[AValue]; end; end.
{$I vp.inc} unit VpZeosDs; interface uses SysUtils, Classes, DB, VpBaseDS, VpDBDS, ZCompatibility, ZConnection, ZDataset; type TVpZeosDatastore = class(TVpCustomDBDatastore) private FConnection: TZConnection; FContactsTable: TZTable; FEventsTable: TZTable; FResourceTable: TZTable; FTasksTable: TZTable; procedure SetConnection(const AValue: TZConnection); protected procedure CreateTable(const ATableName: String); procedure CreateAllTables; function GetContactsTable: TDataset; override; function GetEventsTable: TDataset; override; function GetResourceTable: TDataset; override; function GetTasksTable: TDataset; override; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetConnected(const AValue: Boolean); override; public constructor Create(AOwner: TComponent); override; procedure CreateTables; function GetNextID(TableName: string): integer; override; property ResourceTable; property EventsTable; property ContactsTable; property TasksTable; published property Connection: TZConnection read FConnection write SetConnection; // inherited property AutoConnect default false; property AutoCreate default false; property Daybuffer; end; implementation uses LazFileUtils, VpConst; { TVpZeosDatastore } constructor TVpZeosDatastore.Create(AOwner: TComponent); begin inherited; FContactsTable := TZTable.Create(self); FContactsTable.TableName := 'Contacts'; FEventsTable := TZTable.Create(Self); FEventsTable.TableName := 'Events'; FResourceTable := TZTable.Create(self); FResourceTable.TableName := 'Resources'; FTasksTable := TZTable.Create(self); FTasksTable.TableName := 'Tasks'; end; procedure TVpZeosDatastore.CreateAllTables; begin if not FContactsTable.Exists then CreateTable(ContactsTableName); if not FEventsTable.Exists then CreateTable(EventsTableName); if not FResourceTable.Exists then CreateTable(ResourceTableName); if not FTasksTable.Exists then CreateTable(TasksTableName); end; procedure TVpZeosDatastore.CreateTable(const ATableName: String); begin if ATableName = ContactsTableName then begin FConnection.ExecuteDirect( 'CREATE TABLE Contacts ('+ 'RecordID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '+ 'ResourceID INTEGER,' + 'FirstName VARCHAR(50) ,'+ 'LastName VARCHAR(50) , '+ 'Birthdate DATE, '+ 'Anniversary DATE, '+ 'Title VARCHAR(50) ,'+ 'Company VARCHAR(50) ,'+ 'Job_Position VARCHAR(30), '+ 'Address VARCHAR(100), '+ 'City VARCHAR(50), '+ 'State VARCHAR(25), '+ 'Zip VARCHAR(10), '+ 'Country VARCHAR(25), '+ 'Notes VARCHAR(1024), '+ 'Phone1 VARCHAR(25), '+ 'Phone2 VARCHAR(25), '+ 'Phone3 VARCHAR(25), '+ 'Phone4 VARCHAR(25), '+ 'Phone5 VARCHAR(25), '+ 'PhoneType1 INTEGER, '+ 'PhoneType2 INTEGER, '+ 'PhoneType3 INTEGER, '+ 'PhoneType4 INTEGER, '+ 'PhoneType5 INTEGER, '+ 'Category INTEGER, '+ 'EMail VARCHAR(100), '+ 'Custom1 VARCHAR(100), '+ 'Custom2 VARCHAR(100),'+ 'Custom3 VARCHAR(100), '+ 'Custom4 VARCHAR(100), '+ 'UserField0 VARCHAR(100), '+ 'UserField1 VARCHAR(100), '+ 'UserField2 VARCHAR(100), '+ 'UserField3 VARCHAR(100), '+ 'UserField4 VARCHAR(100), '+ 'UserField5 VARCHAR(100), '+ 'UserField6 VARCHAR(100), '+ 'UserField7 VARCHAR(100), '+ 'UserField8 VARCHAR(100), '+ 'UserField9 VARCHAR(100) )' ); FConnection.ExecuteDirect( 'CREATE INDEX ContactsResourceID_idx ON Contacts(ResourceID)' ); FConnection.ExecuteDirect( 'CREATE INDEX ContactsName_idx ON Contacts(LastName, FirstName)' ); FConnection.ExecuteDirect( 'CREATE INDEX ContactsCompany_idx ON Contacts(Company)' ); end else if ATableName = EventsTableName then begin FConnection.ExecuteDirect( 'CREATE TABLE Events ('+ 'RecordID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '+ 'StartTime TIMESTAMP, '+ 'EndTime TIMESTAMP, '+ 'ResourceID INTEGER, '+ 'Description VARCHAR(255), '+ 'Location VARCHAR(255), '+ 'Notes VARCHAR(1024), ' + 'Category INTEGER, '+ 'AllDayEvent BOOL, '+ 'DingPath VARCHAR(255), '+ 'AlarmSet BOOL, '+ 'AlarmAdvance INTEGER, '+ 'AlarmAdvanceType INTEGER, '+ 'SnoozeTime TIMESTAMP, '+ 'RepeatCode INTEGER, '+ 'RepeatRangeEnd TIMESTAMP, '+ 'CustomInterval INTEGER, '+ 'UserField0 VARCHAR(100), '+ 'UserField1 VARCHAR(100), '+ 'UserField2 VARCHAR(100), '+ 'UserField3 VARCHAR(100), '+ 'UserField4 VARCHAR(100), '+ 'UserField5 VARCHAR(100), '+ 'UserField6 VARCHAR(100), '+ 'UserField7 VARCHAR(100), '+ 'UserField8 VARCHAR(100), '+ 'UserField9 VARCHAR(100) )' ); FConnection.ExecuteDirect( 'CREATE INDEX EventsResourceID_idx ON Events(ResourceID)' ); FConnection.ExecuteDirect( 'CREATE INDEX EventsStartTime_idx ON Events(StartTime)' ); FConnection.ExecuteDirect( 'CREATE INDEX EventsEndTime_idx ON Events(EndTime)' ); end else if ATableName = ResourceTableName then begin FConnection.ExecuteDirect( 'CREATE TABLE Resources ( '+ 'ResourceID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '+ 'Description VARCHAR(255), '+ 'Notes VARCHAR(1024), '+ 'ImageIndex INTEGER, '+ 'ResourceActive BOOL, '+ 'UserField0 VARCHAR(100), '+ 'UserField1 VARCHAR(100), '+ 'UserField2 VARCHAR(100), '+ 'UserField3 VARCHAR(100), '+ 'UserField4 VARCHAR(100), '+ 'UserField5 VARCHAR(100), '+ 'UserField6 VARCHAR(100), '+ 'UserField7 VARCHAR(100), '+ 'UserField8 VARCHAR(100), '+ 'UserField9 VARCHAR(100) )' ); end else if ATableName = TasksTableName then begin FConnection.ExecuteDirect( 'CREATE TABLE Tasks ('+ 'RecordID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '+ 'ResourceID INTEGER, '+ 'Complete BOOL, '+ 'Description VARCHAR(255), '+ 'Details VARCHAR(1024), '+ 'CreatedOn TIMESTAMP, '+ 'Priority INTEGER, '+ 'Category INTEGER, '+ 'CompletedOn TIMESTAMP, '+ 'DueDate TIMESTAMP, '+ 'UserField0 VARCHAR(100), '+ 'UserField1 VARCHAR(100), '+ 'UserField2 VARCHAR(100), '+ 'UserField3 VARCHAR(100), '+ 'UserField4 VARCHAR(100), '+ 'UserField5 VARCHAR(100), '+ 'UserField6 VARCHAR(100), '+ 'UserField7 VARCHAR(100), '+ 'UserField8 VARCHAR(100), '+ 'UserField9 VARCHAR(100) )' ); FConnection.ExecuteDirect( 'CREATE INDEX TasksResourceID_idx ON Tasks(ResourceID)' ); FConnection.ExecuteDirect( 'CREATE INDEX TasksDueDate_idx ON Tasks(DueDate)' ); FConnection.ExecuteDirect( 'CREATE INDEX TasksCompletedOn_idx ON Tasks(CompletedOn)' ); end; end; procedure TVpZeosDatastore.CreateTables; var wasConnected: Boolean; begin wasConnected := FConnection.Connected; FConnection.Connected := true; CreateAllTables; SetConnected(wasConnected or AutoConnect); end; function TVpZeosDatastore.GetContactsTable: TDataset; begin Result := FContactsTable; end; function TVpZeosDatastore.GetEventsTable: TDataset; begin Result := FEventsTable; end; function TVpZeosDataStore.GetNextID(TableName: string): integer; begin { This is not needed in the ZEOS datastore as these tables use autoincrement fields. } result := -1; end; function TVpZeosDatastore.GetResourceTable : TDataset; begin Result := FResourceTable; end; function TVpZeosDatastore.GetTasksTable : TDataset; begin Result := FTasksTable; end; procedure TVpZeosDatastore.Loaded; begin inherited; if not (csDesigning in ComponentState) then Connected := AutoConnect and ( AutoCreate or (FContactsTable.Exists and FEventsTable.Exists and FResourceTable.Exists and FTasksTable.Exists) ); end; procedure TVpZeosDatastore.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FConnection) then FConnection := nil; end; procedure TVpZeosDatastore.SetConnected(const AValue: Boolean); begin if (AValue = Connected) or (FConnection = nil) then exit; if AValue and AutoCreate then CreateTables; FConnection.Connected := AValue; if FConnection.Connected then begin FContactsTable.Open; FEventsTable.Open; FResourceTable.Open; FTasksTable.Open; end; inherited SetConnected(AValue); if FConnection.Connected then Load; end; procedure TVpZeosDatastore.SetConnection(const AValue: TZConnection); var wasConnected: Boolean; begin if AValue = FConnection then exit; // To do: clear planit lists... if FConnection <> nil then begin wasConnected := FConnection.Connected; Connected := false; end else wasConnected := false; FConnection := AValue; FContactsTable.Connection := FConnection; FEventsTable.Connection := FConnection; FResourceTable.Connection := FConnection; FTasksTable.Connection := FConnection; if wasConnected then Connected := true; end; end.
unit IntDataSet; interface uses AbstractDataSet; type TIntDataSet = class (TAbstractDataSet) private // Gets function GetData(_pos: integer): integer; reintroduce; // Sets procedure SetData(_pos: integer; _data: integer); reintroduce; protected FData : packed array of integer; // Gets function GetDataLength: integer; override; function GetLast: integer; override; // Sets procedure SetLength(_size: integer); override; public // copies procedure Assign(const _Source: TAbstractDataSet); override; // properties property Data[_pos: integer]:integer read GetData write SetData; end; implementation // Gets function TIntDataSet.GetData(_pos: integer): integer; begin Result := FData[_pos]; end; function TIntDataSet.GetDataLength: integer; begin Result := High(FData) + 1; end; function TIntDataSet.GetLast: integer; begin Result := High(FData); end; // Sets procedure TIntDataSet.SetData(_pos: integer; _data: integer); begin FData[_pos] := _data; end; procedure TIntDataSet.SetLength(_size: Integer); begin System.SetLength(FData,_size); end; // copies procedure TIntDataSet.Assign(const _Source: TAbstractDataSet); var maxData,i: integer; begin Length := _Source.Length; maxData := GetDataLength() - 1; for i := 0 to maxData do begin Data[i] := (_Source as TIntDataSet).Data[i]; end; end; end.
unit E_Utils; //------------------------------------------------------------------------------ // Модуль маленьких полезных подпрограмм //------------------------------------------------------------------------------ // Содержит процедуры и функции, выполняющие сервисную работу //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, T_Common; //------------------------------------------------------------------------------ //! атомарные OR 1/2/4-байтовые //------------------------------------------------------------------------------ procedure LockedOr8( AResult: Pointer; AArg: Pointer ); register; procedure LockedOr16( AResult: Pointer; AArg: Pointer ); register; procedure LockedOr32( AResult: Pointer; AArg: Pointer ); register; //------------------------------------------------------------------------------ //! зеркально перевернуть байты в 8/4/2-байтном числе //------------------------------------------------------------------------------ function Swap64( const AArg: UInt64 ): UInt64; register; function Swap32( const AArg: Cardinal ): Cardinal; register; function Swap16( const AArg: Word ): Word; register; //------------------------------------------------------------------------------ //! вернуть массив чисел из строки чисел с разделителями //! ТОЛЬКО целые неотрицательные числа //! возвращает True, если строка успешно преобразована //------------------------------------------------------------------------------ function ConvertStr2IntArray( const AStr: string; const ADelimiter: Char; var RArray: TMyIntegerArray ): Boolean; //------------------------------------------------------------------------------ //! выдать индекс строки в массиве строк //! возвращает -1 если строка не найдена //------------------------------------------------------------------------------ function IsStrInArray( const AStrArray: TMyStringArray; const AStr: string ): Integer; //------------------------------------------------------------------------------ //! выдать индекс числа в массиве чисел //! возвращает -1 если число не найдено //------------------------------------------------------------------------------ function IsIntInArray( const AIntArray: TMyIntegerArray; const AInt: Integer ): Integer; //------------------------------------------------------------------------------ //! вернуть строку даты в формате MS SQL сервера //------------------------------------------------------------------------------ function SQLDate( const ADate: TDateTime ): string; //------------------------------------------------------------------------------ //! вернуть строку времени в формате MS SQL сервера //------------------------------------------------------------------------------ function SQLTime( const ATime: TDateTime ): string; //------------------------------------------------------------------------------ //! вернуть строку даты и времени в формате MS SQL сервера //------------------------------------------------------------------------------ function SQLDateTime( const ADateTime: TDateTime ): string; //------------------------------------------------------------------------------ //! вернуть сформированную строку функции CONVERT даты для выполнения MS SQL сервером //------------------------------------------------------------------------------ function SQLDateConvert( const ADate: TDateTime ): string; //------------------------------------------------------------------------------ //! вернуть сформированную строку функции CONVERT времени для выполнения MS SQL сервером //------------------------------------------------------------------------------ function SQLTimeConvert( const ATime: TDateTime ): string; //------------------------------------------------------------------------------ //! вернуть сформированную строку функции CONVERT даты и времени для выполнения MS SQL сервером //------------------------------------------------------------------------------ function SQLDateTimeConvert( const ADateTime: TDateTime ): string; //------------------------------------------------------------------------------ //! изменить порядок байт в слове с я321 на я123 //------------------------------------------------------------------------------ function TransformColor( const AColor: Cardinal ): Cardinal; register; //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ const //------------------------------------------------------------------------------ //! строковые константы преобразования для SQL-сервера //------------------------------------------------------------------------------ CSQLDate: string = 'yyyymmdd'; CSQLTime: string = 'hh":"nn":"ss'; CSQLDateTime: string = 'yyyymmdd hh:nn:ss'; CSQLCDate: string = 'CONVERT(datetime, ''%s'', 112)'; CSQLCTime: string = 'CONVERT(datetime, ''%s'', 108)'; CSQLCDateTime: string = 'CONVERT(datetime, ''%s'', 120)'; procedure LockedOr8( AResult: Pointer; AArg: Pointer ); asm mov cl,[edx]; lock or [eax],cl; end; procedure LockedOr16( AResult: Pointer; AArg: Pointer ); asm mov cx,[edx]; lock or [eax],cx; end; procedure LockedOr32( AResult: Pointer; AArg: Pointer ); asm mov ecx,[edx]; lock or [eax],ecx; end; function Swap64( const AArg: UInt64 ): UInt64; asm lea ecx,AArg; mov edx,[ecx]; mov eax,[ecx + 4]; bswap edx; bswap eax; end; function Swap32( const AArg: Cardinal ): Cardinal; asm bswap eax; end; function Swap16( const AArg: Word ): Word; asm xchg ah, al; end; function ConvertStr2IntArray( const AStr: string; const ADelimiter: Char; var RArray: TMyIntegerArray ): Boolean; var //! WorkStr: string; //! CurPos: Integer; //! CifNum: Integer; //! WorkChar: Char; //------------------------------------------------------------------------------ begin Result := True; WorkStr := AStr + ADelimiter; CifNum := 0; CurPos := 1; while ( CurPos <= Length( WorkStr ) ) do begin WorkChar := WorkStr[CurPos]; if ( WorkChar >= '0' ) and ( WorkChar <= '9' ) then begin // цифра Inc( CifNum ); end else if ( WorkChar = ADelimiter ) then begin // разделитель if ( CifNum <> 0 ) then begin // были цифры SetLength( RArray, Length( RArray ) + 1 ); RArray[High( RArray )] := StrToInt( Copy( WorkStr, CurPos - CifNum, CifNum ) ); CifNum := 0; end; end else begin // что-то другое Exit( False ); end; Inc( CurPos ); end; end; function IsStrInArray( const AStrArray: TMyStringArray; const AStr: string ): Integer; begin for Result := Low( AStrArray ) to High( AStrArray ) do begin if ( AStrArray[Result] = AStr ) then Exit; end; Result := -1; end; function IsIntInArray( const AIntArray: TMyIntegerArray; const AInt: Integer ): Integer; begin for Result := Low( AIntArray ) to High( AIntArray ) do begin if ( AIntArray[Result] = AInt ) then Exit; end; Result := -1; end; function SQLDate( const ADate: TDateTime ): string; begin // формат: yyyymmdd // использовать с: CONVERT(datetime, 'SQLDate', 112) Result := FormatDateTime( cSQLDate, ADate ); end; function SQLTime( const ATime: TDateTime ): string; begin // формат: hh:mi:ss // использовать с: CONVERT(datetime, 'SQLTime', 108) Result := FormatDateTime( cSQLTime, ATime ); end; function SQLDateTime( const ADateTime: TDateTime ): string; begin // формат: yyyy-mm-dd hh:mi:ss // использовать с: CONVERT(datetime, 'SQLDateTime', 120) Result := FormatDateTime( cSQLDateTime, ADateTime ); end; function SQLDateConvert( const ADate: TDateTime ): string; begin Result := SQLDate( ADate ); Result := Format( cSQLCDate, [Result] ); end; function SQLTimeConvert( const ATime: TDateTime ): string; begin Result := SQLTime( ATime ); Result := Format( cSQLCTime, [Result] ); end; function SQLDateTimeConvert( const ADateTime: TDateTime ): string; begin Result := SQLDateTime( ADateTime ); Result := Format( cSQLCDateTime, [Result] ); end; function TransformColor( const AColor: Cardinal ): Cardinal; asm bswap eax; shr eax,8; end; end.
program twexe; {$mode objfpc}{$H+} {$define UseCThreads} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp { twexe units } ,logger, twexemain, exedata, fileops ; type { TTwexeApp } TTwexeApp = class(TCustomApplication) private FileArgs: array of string; OrigExeFile: string; OutDir: string; protected procedure DoRun; override; procedure ProcessOptions(); public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { TTwexeApp } procedure TTwexeApp.ProcessOptions(); Var CmdLOpts: TStrings; NonOpts: TStrings; i: Integer; ErrorMsg: string; begin //Default values Opts.Flags := [toOpenBrowser]; // parse options try CmdLOpts := TStringList.Create; NonOpts := TStringList.Create; // check parameters ErrorMsg:=CheckOptions('epvo:sz:hk::r::t:',[],CmdLOpts,NonOpts); if ErrorMsg<>'' then begin PrintHeader(); logger.Error(ErrorMsg); logger.Error('Aborting.'); Terminate; end; //Process z option - internal option for original exe path i:=CmdLOpts.IndexOfName('z'); If i <> -1 then begin OrigExeFile:=CmdLOpts.ValueFromIndex[i]; exedata.OriginalExeFile:=OrigExeFile; //FIXME: this is lousy end; //Process o option - output directory for conversion i:=CmdLOpts.IndexOfName('o'); If i <> -1 then Opts.ConversionOutDir:=CmdLOpts.ValueFromIndex[i]; //Process k option - extract tiddlywiki in optional directory //OutDir is used to call HandleExtractData i:=CmdLOpts.IndexOfName('k'); If i <> -1 then OutDir := CmdLOpts.ValueFromIndex[i] else OutDir := GetEXEPath(); //Process t option - port number to listen for http server i:=CmdLOpts.IndexOfName('t'); If i <> -1 then begin Opts.ServerPort := StrToInt(CmdLOpts.ValueFromIndex[i]); LogFmt('User specified port: %d',[Opts.ServerPort]); end else Opts.ServerPort := 0; //Try different ports //Process h option if HasOption('h','help') then begin PrintHeader(); WriteHelp; Terminate; Exit; end; //Process s option - no browser if HasOption('s') then Opts.Flags := Opts.Flags - [toOpenBrowser]; //Process p option - programatic run from program/script if HasOption('p') then begin Opts.Flags := Opts.Flags + [toProgramaticRun] - [toOpenBrowser]; end; //Process r option - bind to 0.0.0.0 or specified address //to allow remote clients i:=CmdLOpts.IndexOfName('r'); if HasOption('r') then begin Opts.Flags := Opts.Flags + [toAllowRemoteClients]; If i <> -1 then //Remote address specified Opts.ServerBindAddress := CmdLOpts.ValueFromIndex[i] else Opts.ServerBindAddress := '' //same as 0.0.0.0, listen on all ifaces end else //Listen only locally Opts.ServerBindAddress := '127.0.0.1'; finally SetLength(FileArgs,NonOpts.Count); For i:=0 to NonOpts.Count - 1 do FileArgs[i] := NonOpts[i]; If Assigned(CmdLOpts) then FreeAndNil(CmdLOpts); If Assigned(NonOpts) then FreeAndNil(NonOpts); end; end; procedure TTwexeApp.DoRun; begin try //Handle cmdline args, and set values in twexemain.Opts ProcessOptions(); If Terminated then Exit; //Write html tiddlywiki file If HasOption('k','') then begin PrintHeader(); Show('Extracting tiddlywiki5 html file.'); //OutDir is set by ProcessOptions() HandleExtractData(OutDir); Show('Tiddlywiki written in directory ''' + OutDir + '''.'); Terminate; Exit; end; //Print header (includes version number) If HasOption('v','') then begin PrintHeader(); Terminate; Exit; end; //End already running server If HasOption('e') then begin PrintHeader(); twexemain.StopRunningServer(); Terminate; Exit; end; { Run main function - options have been written to twexemain.Opts } Twexemain.TwexeMain(OrigExeFile, FileArgs); // stop program loop Terminate; except on E:Exception do begin Error('Unhandled exception: ' + E.ToString); CleanupOnExit(); WaitForUser(); Terminate; end; end; end; constructor TTwexeApp.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TTwexeApp.Destroy; begin inherited Destroy; end; procedure TTwexeApp.WriteHelp; begin Write('Usage: '); TextColor(Blue); Write(FileNameNoExt(ExeName)); TextColor(Yellow);Writeln(' [options] [file]'); ResetColors(); Writeln(); Writeln(' This file is a twixie, a single file tiddlywiki5 executable.'); Writeln(); Writeln(' If you run it with no file specified, it will open the browser'); Writeln(' and serve the tiddlywiki5 file.'); Writeln(); Writeln(' If a file is specified, and it is a TiddlyWiki5 file, then'); Writeln(' convert it into a twixie with the same file name as the '); Writeln(' specified file.'); Writeln(); TextColor(Blue); writeln('OPTIONS:'); writeln(#9,'-h'); TextColor(DarkGray); writeln(#9,#9,'Print this help information.'); TextColor(Blue); writeln(#9,'-s'); TextColor(DarkGray); writeln(#9,#9,'Do not open browser.'); ResetColors(); TextColor(Blue); writeln(#9,'-k [dir]'); TextColor(DarkGray); writeln(#9,#9,'Write html wiki file in the specified directory or '); writeln(#9,#9,'in the directory of this twixie if no directory is specified.'); TextColor(Blue); writeln(#9,'-v'); TextColor(DarkGray); writeln(#9,#9,'Print version number and exit.'); TextColor(Blue); writeln(#9,'-e'); TextColor(DarkGray); writeln(#9,#9,'Terminate running server.'); ResetColors(); end; var Application: TTwexeApp; {$R *.res} begin Application:=TTwexeApp.Create(nil); Application.Run; Application.Free; end.
unit UnitPackSystem; interface uses SysUtils, Classes, Zlib; procedure CompressFiles(Files: TStrings; const Filename: String); function DecompressStream(Stream: TMemoryStream; DestDirectory: String; const Source: Boolean): Boolean; function AttachToFile(const AFileName: string; MemoryStream: TMemoryStream; Version: String): Boolean; function LoadFromFile(const AFileName: string; MemoryStream: TMemoryStream): Boolean; function Unpack(const Source: Boolean): Boolean; function GetVersion: String; implementation uses UnitfrmMain; procedure CompressFiles(Files : TStrings; const Filename : String); var infile, outfile, tmpFile : TFileStream; compr : TCompressionStream; i,l : Integer; s : String; begin if Files.Count > 0 then begin outFile := TFileStream.Create(Filename,fmCreate); try { the number of files } l := Files.Count; outfile.Write(l,SizeOf(l)); for i := 0 to Files.Count-1 do begin infile := TFileStream.Create(Files[i],fmOpenRead); try { the original filename } s := ExtractFilename(Files[i]); l := Length(s); outfile.Write(l,SizeOf(l)); outfile.Write(s[1],l); { the original filesize } l := infile.Size; outfile.Write(l,SizeOf(l)); { compress and store the file temporary} tmpFile := TFileStream.Create('tmp',fmCreate); compr := TCompressionStream.Create(clMax,tmpfile); try compr.CopyFrom(infile,l); finally compr.Free; tmpFile.Free; end; { append the compressed file to the destination file } tmpFile := TFileStream.Create('tmp',fmOpenRead); try l := tmpFile.Size; outfile.WriteBuffer(l, SizeOf(l)); outfile.CopyFrom(tmpFile,0); finally tmpFile.Free; end; finally infile.Free; end; end; finally outfile.Free; end; DeleteFile('tmp'); end; end; function DecompressStream(Stream : TMemoryStream; DestDirectory : String; const Source: Boolean): Boolean; var dest,s : String; decompr : TDecompressionStream; outfile : TFilestream; i,l,lr,c : Integer; begin // IncludeTrailingPathDelimiter (D6/D7 only) dest := IncludeTrailingPathDelimiter(DestDirectory); Result := False; try { number of files } Stream.Read(c,SizeOf(c)); for i := 1 to c do begin { read filename } Stream.Read(l,SizeOf(l)); SetLength(s,l); Stream.Read(s[1],l); Stream.Read(l,SizeOf(l)); Stream.Read(lr,SizeOf(lr)); { check if this is the right file } if (s = 'hl2launch.exe') or ((Pos('.source', s) <> 0) and (Source)) or ((Pos('.orangebox', s) <> 0) and (not Source)) then begin { remove extension and read filesize } if (s <> 'hl2launch.exe') then s := ChangeFileExt(s, ''); { decompress the files and store it } s := dest+s; //include the path outfile := TFileStream.Create(s,fmCreate); decompr := TDecompressionStream.Create(Stream); try outfile.CopyFrom(decompr,l); finally outfile.Free; decompr.Free; end; end else Stream.Position := Stream.Position + lr; end; finally Result := True; end; end; function AttachToFile(const AFileName: string; MemoryStream: TMemoryStream; Version: String): Boolean; var aStream: TFileStream; iSize: Integer; begin Result := False; if not FileExists(AFileName) then Exit; try aStream := TFileStream.Create(AFileName, fmOpenWrite or fmShareDenyWrite); MemoryStream.Seek(0, soFromBeginning); // seek to end of File // ans Ende der Datei Seeken aStream.Seek(0, soFromEnd); // copy data from MemoryStream // Daten vom MemoryStream kopieren aStream.CopyFrom(MemoryStream, 0); // save Stream-Size // die Streamgr÷▀e speichern iSize := MemoryStream.Size + SizeOf(Integer); aStream.Write(iSize, SizeOf(iSize)); // save version number+length iSize := aStream.Position; aStream.Write(Version[1], Length(Version)); aStream.Write(iSize, SizeOf(iSize)); finally aStream.Free; end; Result := True; end; function LoadFromFile(const AFileName: string; MemoryStream: TMemoryStream): Boolean; var aStream: TMemoryStream; iSize: Integer; EndPos: Integer; begin Result := False; if not FileExists(AFileName) then Exit; try aStream := TMemoryStream.Create; aStream.LoadFromFile(AFileName); // drop version part aStream.Seek(-SizeOf(Integer), soFromEnd); aStream.Read(EndPos, SizeOf(Integer)); aStream.SetSize(EndPos); // seek to position where Stream-Size is saved // zur Position seeken wo Streamgr÷▀e gespeichert aStream.Seek(-SizeOf(Integer), soFromEnd); aStream.Read(iSize, SizeOf(iSize)); if iSize > aStream.Size then begin aStream.Free; Exit; end; // seek to position where data is saved // zur Position seeken an der die Daten abgelegt sind aStream.Seek(-iSize, soFromEnd); MemoryStream.SetSize(iSize - SizeOf(Integer)); MemoryStream.CopyFrom(aStream, iSize - SizeOf(iSize)); MemoryStream.Seek(0, soFromBeginning); finally aStream.Free; end; Result := True; end; { Unpack function } function Unpack(const Source: Boolean): Boolean; var eStream: TMemoryStream; begin eStream := TMemoryStream.Create; try // Get ZIP LoadFromFile(ParamStr(0), eStream); DecompressStream(eStream, ExtractFilePath(ParamStr(0)), Source); // Unpack files Result := True; except Result := False; end; eStream.Free; end; function GetVersion: String; var FileStream: TFileStream; EndPos, Size: Integer; Version: String; begin FileStream := TFileStream.Create(ParamStr(0), fmOpenRead or fmShareDenyWrite); FileStream.Seek(-SizeOf(Integer), soFromEnd); FileStream.Read(EndPos, SizeOf(EndPos)); FileStream.Position := EndPos; Size := FileStream.Size - EndPos - SizeOf(Integer); SetString(Result, nil, Size); FileStream.Read(Pointer(Result)^, Size); // YAMS FileStream.Free; end; end.
unit sgDriverNetworkingSDL2; interface uses sgShared, sgNamedIndexCollection, sgTypes; //TCP Connection function CreateTCPHostProcedure (const aPort : LongInt) : Boolean; function CreateTCPConnectionProcedure (const aDestIP : String; const aDestPort : LongInt; aprotocol : ConnectionType) : Connection; function AcceptTCPConnectionProcedure () : LongInt; //TCP Message procedure BroadcastTCPMessageProcedure (const aMsg : String); function SendTCPMessageProcedure (const aMsg : String; const aConnection : Connection) : Connection; function TCPMessageReceivedProcedure () : Boolean; //HTTP Message function SendHTTPRequestProcedure (const aReq : HTTPRequest; const aConnection : Connection) : Connection; //UDP function CreateUDPHostProcedure (const aPort : LongInt) : LongInt; function CreateUDPConnectionProcedure (const aDestIP : String; const aDestPort, aInPort : LongInt) : Connection; //UDP Message procedure BroadcastUDPMessageProcedure (const aMsg : String); function SendUDPMessageProcedure (const aMsg : String; const aConnection : Connection) : Boolean; function UDPMessageReceivedProcedure () : Boolean; //Close Sockets function CloseTCPHostSocketProcedure (const aPort: LongInt) : Boolean; function CloseConnectionProcedure (var aConnection : Connection; const aCloseUDPSocket : Boolean) : Boolean; function CloseUDPSocketProcedure (const aPort : LongInt) : Boolean; procedure CloseAllTCPHostSocketProcedure (); procedure CloseAllConnectionsProcedure (const aCloseUDPSockets : Boolean); procedure CloseAllUDPSocketProcedure (); function MyIPProcedure () : String; function ConnectionCountProcedure () : LongInt; function RetreiveConnectionProcedure (const aConnectionAt : LongInt) : Connection; procedure FreeAllNetworkingResourcesProcedure (); //Initialisation procedure LoadSDLNetworkingDriver (); implementation uses SysUtils, sgUtils, sgNetworking, sgDriverNetworking, StrUtils; type TCPSocketArray = Array of PTCPSocket; ConnectionArray = Array of Connection; UDPSocketArray = Array of PUDPSocket; TCPListenSocket = record socket : PTCPSocket; port : LongInt; end; PacketData = array [0..511] of Char; BytePtr = ^Byte; var _ListenSockets : Array of TCPListenSocket; _Connections : ConnectionArray; _Socketset : PSDLNet_SocketSet; _UDPListenSockets : UDPSocketArray; _UDPSocketIDs : NamedIndexCollection; _UDPConnectionIDs : NamedIndexCollection; _UDPSendPacket : PUDPPacket = nil; _UDPReceivePacket : PUDPPacket = nil; //---------------------------------------------------------------------------- // Internal Functions //---------------------------------------------------------------------------- function CreateConnection() : Connection; begin New(result); result^.socket := nil; result^.ip := 0; result^.stringIP := ''; result^.port := 0; result^.firstmsg := nil; result^.lastMsg := nil; result^.msgCount := 0; result^.protocol := TCP; result^.partMsgData := ''; result^.msgLen := -1; end; function GetConnectionWithID(const aIP : LongWord; const aPort : LongInt; aprotocol : ConnectionType) : Connection; var i : LongInt; begin result := nil; for i := Low(_Connections) to High(_Connections) do begin if (_Connections[i]^.ip = aIP) and (_Connections[i]^.port = aPort) and (_Connections[i]^.protocol = aprotocol) then begin result := _Connections[i]; end; end; end; procedure ExtractData(const buffer: PacketData; aReceivedCount: LongInt; const aConnection : Connection); // var // msgLen : Byte = 0; // bufIdx : LongInt = 0; // Index of current data in the buffer // msg : String; begin // while bufIdx < aReceivedCount do // Loop until all messages are extracted from the buffer // begin // if aConnection^.msgLen > 0 then // Size of the message is based on the data in the connection, or from packet // begin // msg := aConnection^.partMsgData; // msgLen := aConnection^.msgLen - Length(msg); // Adjusted length for previous read // aConnection^.msgLen := -1; // aConnection^.partMsgData := ''; // end // else // begin // msg := ''; // msgLen := Byte(buffer[bufIdx]); // Get the length of the next message // // WriteLn('msglen: ', msgLen); // bufIdx += 1; // end; // for bufIdx := bufIdx to bufIdx + msgLen - 1 do // begin // if (bufIdx >= aReceivedCount) or (bufIdx > Length(buffer)) then // begin // aConnection^.partMsgData := msg; // aConnection^.msgLen := msgLen; // // WriteLn('Message: ', msg, ' '); // // WriteLn('Part message: ', msg); // exit; // Exit... end of buffer, but not end of message // end; // msg += buffer[bufIdx]; // end; // EnqueueMessage(msg, aConnection); // // WriteLn('Receive message: ', msg, ' '); // bufIdx += 1; // Advance to start of next message // end; end; function TCPIP(aNewSocket : PTCPSocket) : LongWord; var lRemoteIP : PIPAddress; begin lRemoteIP := SDLNet_TCP_GetPeerAddress(aNewSocket); result := SDLNet_Read32(@lRemoteIP^.host); end; function TCPPort(aNewSocket : PTCPSocket) : LongInt; var lRemoteIP : PIPAddress; begin lRemoteIP := SDLNet_TCP_GetPeerAddress(aNewSocket); result := SDLNet_Read16(@lRemoteIP^.port); end; //---------------------------------------------------------------------------- // Misc Function //---------------------------------------------------------------------------- function MyIPProcedure() : String; begin result := '127.0.0.1'; end; function ConnectionCountProcedure() : LongInt; begin result := Length(_Connections); end; function RetreiveConnectionProcedure(const aConnectionAt : LongInt) : Connection; begin result := nil; if (aConnectionAt < 0) or (aConnectionAt > High(_Connections)) then exit; result := _Connections[aConnectionAt]; end; //---------------------------------------------------------------------------- // TCP Connection Handling //---------------------------------------------------------------------------- function OpenTCPConnection(aIP : PChar; aPort : LongInt) : PTCPSocket; var lIPAddress : TIPAddress; begin result := nil; if (SDLNet_ResolveHost(lIPAddress, aIP, aPort) < 0) then exit; result := SDLNet_TCP_Open(lIPAddress); end; function CreateTCPHostProcedure(const aPort : LongInt) : Boolean; var lTempSocket : PTCPSocket = nil; begin lTempSocket := OpenTCPConnection(nil, aPort); if Assigned(lTempSocket) then begin SetLength(_ListenSockets, Length(_ListenSockets) + 1); _ListenSockets[High(_ListenSockets)].socket := lTempSocket; _ListenSockets[High(_ListenSockets)].port := aPort; end; result := Assigned(lTempSocket); end; function CreateTCPConnectionProcedure(const aDestIP : String; const aDestPort : LongInt; aprotocol : ConnectionType) : Connection; var lTempSocket : PTCPSocket = nil; begin result := nil; lTempSocket := OpenTCPConnection(PChar(aDestIP), aDestPort); if Assigned(lTempSocket) then begin result := CreateConnection(); result^.IP := TCPIP(lTempSocket); result^.port := aDestPort; result^.socket := lTempSocket; result^.protocol := aprotocol; result^.stringIP := aDestIP; SetLength(_Connections, Length(_Connections) + 1); _Connections[High(_Connections)] := result; SDLNet_AddSocket(_SocketSet, PSDLNet_GenericSocket(lTempSocket)); end; end; function AcceptTCPConnectionProcedure() : LongInt; var lTempSocket : PTCPSocket = nil; lNewConnection : Connection; i : LongInt; begin result := 0; for i := Low(_ListenSockets) to High(_ListenSockets) do begin lTempSocket := SDLNet_TCP_Accept(_ListenSockets[i].socket); if Assigned(lTempSocket) then begin lNewConnection := CreateConnection(); lNewConnection^.IP := TCPIP(lTempSocket); lNewConnection^.socket := lTempSocket; lNewConnection^.port := _ListenSockets[i].port; SetLength(_Connections, Length(_Connections) + 1); _Connections[High(_Connections)] := lNewConnection; SDLNet_AddSocket(_SocketSet, PSDLNet_GenericSocket(lTempSocket)); // EnqueueNewConnection(lNewConnection); result += 1; end; end; end; //---------------------------------------------------------------------------- // TCP Message Handling //---------------------------------------------------------------------------- function TCPMessageReceivedProcedure() : Boolean; var i, lReceived : LongInt; buffer: PacketData; begin result := False; if SDLNet_CheckSockets(_SocketSet, 0) < 1 then exit; for i := Low(_Connections) to High(_Connections) do begin if SDLNET_SocketReady(PSDLNet_GenericSocket(_Connections[i]^.socket)) then begin if (_Connections[i]^.protocol = TCP) then begin lReceived := SDLNet_TCP_Recv(_Connections[i]^.socket, @buffer, 512); if (lReceived <= 0) then continue; ExtractData(buffer, lReceived, _Connections[i]) end else if (_Connections[i]^.protocol = HTTP) then begin WriteLn('ERROR -- ExtractHTTPData'); // ExtractHTTPData(_Connections[i]); end; result := True; end; end; end; function SendHTTPRequestProcedure(const aReq: HTTPRequest; const aConnection : Connection) : Connection; var lLen, i : LongInt; buffer : Array of Char; lMsg : String = ''; begin result := nil; if (aConnection = nil) or (aConnection^.socket = nil) or (aConnection^.protocol <> HTTP) then begin RaiseWarning('SDL 1.2 SendTCPMessageProcedure Illegal Connection Arguement (nil or not HTTP)'); exit; end; lMsg := HTTPRequestToString(aReq) + #13#10#13#10; SetLength(buffer, Length(lMsg)); for i := 0 to Length(lMsg) - 1 do buffer[i] := lMsg[i + 1]; lLen := Length(lMsg); // WriteLn(lMsg); if (SDLNet_TCP_Send(aConnection^.socket, @buffer[0], lLen) < lLen) then begin result := aConnection; RaiseWarning('Error sending message: SDLNet_TCP_Send: ' + SDLNet_GetError() + ' HTTP Connection may have been refused.'); end; end; function SendTCPMessageProcedure(const aMsg : String; const aConnection : Connection) : Connection; var lLen, i : LongInt; buffer: PacketData; begin result := nil; if (aConnection = nil) or (aConnection^.socket = nil) then begin RaiseWarning('SDL 1.2 SendTCPMessageProcedure Illegal Connection Arguement'); exit; end; if Length(aMsg) > 255 then begin RaiseWarning('SwinGame messages must be less than 256 characters in length'); exit; end; for i := 0 to Length(aMsg) + 1 do begin if i = 0 then buffer[i] := Char(Length(aMsg)) else if i < Length(aMsg) + 1 then buffer[i] := aMsg[i]; end; lLen := Length(aMsg) + 1; if (SDLNet_TCP_Send(aConnection^.socket, @buffer, lLen) < lLen) then begin result := aConnection; RaiseWarning('Error sending message: SDLNet_TCP_Send: ' + SDLNet_GetError()); end; end; procedure BroadcastTCPMessageProcedure(const aMsg : String); var lLen, i : LongInt; buffer: PacketData; begin if Length(aMsg) > 255 then begin RaiseWarning('SwinGame messages must be less than 256 characters in length'); exit; end; for i := 0 to Length(aMsg) + 1 do begin if i = 0 then buffer[i] := Char(Length(aMsg)) else if i < Length(aMsg) + 1 then buffer[i] := aMsg[i]; end; lLen := Length(aMsg) + 1; for i := Low(_Connections) to High(_Connections) do begin if (SDLNet_TCP_Send(_Connections[i]^.socket, @buffer[0], lLen) < lLen) then begin RaiseWarning('Error broadcasting message: SDLNet_TCP_Send: ' + SDLNet_GetError()); end; end; end; //---------------------------------------------------------------------------- // UDP Connections //---------------------------------------------------------------------------- procedure CreatePackets(); begin if _UDPSendPacket = nil then _UDPSendPacket := SDLNet_AllocPacket(512); if _UDPReceivePacket = nil then _UDPReceivePacket := SDLNet_AllocPacket(512); end; function CreateUDPHostProcedure(const aPort : LongInt) : LongInt; var lTempSocket : PUDPSocket = nil; lPortID : String; begin lPortID := IntToStr(aPort); result := -1; if HasName(_UDPSocketIDs, lPortID) then begin result := IndexOf(_UDPSocketIDs, lPortID); exit; end; lTempSocket := SDLNet_UDP_Open(aPort); if Assigned(lTempSocket) then begin SetLength(_UDPListenSockets, Length(_UDPListenSockets) + 1); _UDPListenSockets[High(_UDPListenSockets)] := lTempSocket; AddName(_UDPSocketIDs, lPortID); result := High(_UDPListenSockets); end; CreatePackets(); if result = -1 then RaiseWarning('OpenUDPListenerPort: ' + SDLNET_GetError()); end; function CreateUDPConnectionProcedure(const aDestIP : String; const aDestPort, aInPort : LongInt) : Connection; var lIdx : LongInt; lDecDestIP : LongWord; lDecIPStr : String; begin result := nil; lDecDestIP := IPv4ToDec(aDestIP); lDecIPStr := IntToStr(lDecDestIP); if HasName(_UDPConnectionIDs, lDecIPStr + ':' + IntToStr(aDestPort)) then exit; lIdx := CreateUDPHostProcedure(aInPort); if (lIdx = -1) then begin RaiseWarning('SDL 1.2 - CreateUDPConnectionProcedure: Could not Bind Socket.'); exit; end; AddName(_UDPConnectionIDs, lDecIPStr + ':' + IntToStr(aDestPort)); result := CreateConnection(); result^.ip := lDecDestIP; result^.port := aDestPort; result^.protocol := UDP; result^.stringIP := lDecIPStr; lIdx := CreateUDPHostProcedure(aInPort); result^.socket := _UDPListenSockets[lIdx]; SetLength(_Connections, Length(_Connections) + 1); _Connections[High(_Connections)] := result; CreatePackets(); if not Assigned(result^.socket) then RaiseWarning('OpenUDPSendPort: ' + SDLNET_GetError()); end; //---------------------------------------------------------------------------- // UDP Message //---------------------------------------------------------------------------- function UDPMessageReceivedProcedure() : Boolean; var i, j : LongInt; lMsg : String = ''; lConnection : Connection; lSrcIPString : String; // lNewConnection: Boolean = False; lSrcPort : LongInt; lSrcIP : LongWord; begin result := False; for i := Low(_UDPListenSockets) to High(_UDPListenSockets) do begin if SDLNet_UDP_Recv(_UDPListenSockets[i], _UDPReceivePacket) > 0 then begin lSrcIP := SDLNet_Read32(@_UDPReceivePacket^.address.host); lSrcPort := SDLNet_Read16(@_UDPReceivePacket^.address.port); lConnection := GetConnectionWithID(lSrcIP, lSrcPort, UDP); if not Assigned(lConnection) then begin lSrcIPString := HexStrToIPv4(DecToHex(lSrcIP)); lConnection := CreateUDPConnectionProcedure(lSrcIPString, lSrcPort, StrToInt(NameAt(_UDPSocketIDs, i))); // lNewConnection := True; end; if not Assigned(lConnection) then begin RaiseWarning('SDL 1.2 - UDPMessageReceivedProcedure: Could Not Create Connection.'); exit; end; for j := 0 to _UDPReceivePacket^.len - 1 do lMsg += Char((_UDPReceivePacket^.data)[j]); // if lNewConnection then // EnqueueNewConnection(lConnection); // EnqueueMessage(lMsg, lConnection); result := True; end; end; end; function SendUDPMessageProcedure(const aMsg : String; const aConnection : Connection) : Boolean; var lIPAddress : TIPaddress; begin result := False; if not Assigned(aConnection) then begin RaiseWarning('SDL 1.2 - SendUDPMessageProcedure: Unassigned Connection.'); exit; end; SDLNet_ResolveHost(lIPAddress, PChar(HexStrToIPv4(DecToHex(aConnection^.ip))), aConnection^.port); _UDPSendPacket^.address.host := lIPAddress.host; _UDPSendPacket^.address.port := lIPAddress.port; _UDPSendPacket^.len := Length(aMsg); _UDPSendPacket^.data := @(aMsg[1]); SDLNet_UDP_Send(aConnection^.socket, -1, _UDPSendPacket); result := True; end; procedure BroadcastUDPMessageProcedure(const aMsg : String); var lIPAddress : TIPaddress; i : LongInt; begin for i := Low(_Connections) to High(_Connections) do begin SDLNet_ResolveHost(lIPAddress, PChar(HexStrToIPv4(DecToHex(_Connections[i]^.ip))), _Connections[i]^.port); _UDPSendPacket^.address.host := lIPAddress.host; _UDPSendPacket^.address.port := lIPAddress.port; _UDPSendPacket^.len := Length(aMsg); _UDPSendPacket^.data := @(aMsg[1]); SDLNet_UDP_Send(_Connections[i]^.socket, -1, _UDPSendPacket); end; end; //---------------------------------------------------------------------------- // Close Single //---------------------------------------------------------------------------- function CloseUDPSocket(var aSocket : PUDPSocket) : Boolean; var lTmpSockets : Array of PUDPSocket; i, j, lOffset : LongInt; begin result := False; if (Length(_UDPListenSockets) = 0) or not Assigned(aSocket) then begin RaiseWarning('SDL 1.2 - CloseUDPListenSocketProcedure: Could Not Close UDP Socket.'); exit; end; lOffset := 0; SetLength(lTmpSockets, Length(_UDPListenSockets) - 1); for i := Low(_UDPListenSockets) to High(_UDPListenSockets) do begin if aSocket = _UDPListenSockets[i] then begin lOffset := 1; for j := Low(_Connections) to High(_Connections) do if _Connections[j]^.socket = _UDPListenSockets[i] then _Connections[j]^.socket := nil; SDLNet_UDP_Close(_UDPListenSockets[i]); RemoveName(_UDPSocketIDs, i); end else lTmpSockets[i - lOffset] := _UDPListenSockets[i]; end; _UDPListenSockets := lTmpSockets; result := True; end; function CloseTCPHostSocketProcedure(const aPort : LongInt) : Boolean; var lTmpListenArray : Array of TCPListenSocket; offSet: LongInt = 0; i : LongInt; begin result := False; if Length(_ListenSockets) = 0 then begin RaiseWarning('SDL 1.2 - CloseUDPListenSocketProcedure: Could Not Close TCP Socket.'); exit; end; SetLength(lTmpListenArray, Length(_ListenSockets)); for i := Low(_ListenSockets) to High(_ListenSockets) do begin if (_ListenSockets[i].port = aPort) then begin offSet := 1; if Assigned(_ListenSockets[i].socket) then begin SDLNet_TCP_Close(_ListenSockets[i].socket); result := True; end; end else lTmpListenArray[i - offset] := _ListenSockets[i]; end; if (result) then begin _ListenSockets := lTmpListenArray; SetLength(_ListenSockets, Length(_ListenSockets) - 1); end; end; function CloseConnectionProcedure(var aConnection : Connection; const aCloseUDPSocket : Boolean) : Boolean; // var // lTmpConnectionArray : ConnectionArray; // offSet: LongInt = 0; // i : LongInt; begin result := False; // if (Length(_Connections) = 0) or (not Assigned(aConnection)) then begin RaiseWarning('SDL 1.2 - CloseConnectionProcedure: Could Not Close Connection.'); exit; end; // SetLength(lTmpConnectionArray, Length(_Connections) - 1); // for i := Low(_Connections) to High(_Connections) do // begin // if (_Connections[i] = aConnection) then // begin // offSet := 1; // if (aConnection^.protocol <> UDP) and Assigned(aConnection^.socket) then // begin // SDLNet_TCP_DelSocket(_Socketset, aConnection^.socket); // SDLNet_TCP_Close(aConnection^.socket); // end else if (aConnection^.protocol = UDP) then // RemoveName(_UDPConnectionIDs, IntToStr(aConnection^.ip) + ':' + IntToStr(aConnection^.port)); // result := True; // end else begin // lTmpConnectionArray[i - offset] := _Connections[i]; // end; // end; // if aCloseUDPSocket and Assigned(aConnection^.socket) then // CloseUDPSocket(aConnection^.socket); // ClearMessageQueue(aConnection); // FreeConnection(aConnection); // if (result) then // _Connections := lTmpConnectionArray; end; function CloseUDPSocketProcedure(const aPort : LongInt) : Boolean; var lTmpSockets : Array of PUDPSocket; i, j, lOffset, lIdx : LongInt; begin result := False; if Length(_UDPListenSockets) = 0 then begin RaiseWarning('SDL 1.2 - CloseUDPListenSocketProcedure: Could Not Close UDP Socket.'); exit; end; lIdx := IndexOf(_UDPSocketIDs, IntToStr(aPort)); if lIdx = -1 then exit; RemoveName(_UDPSocketIDs, lIdx); lOffset := 0; SetLength(lTmpSockets, Length(_UDPListenSockets) - 1); for i := Low(_UDPListenSockets) to High(_UDPListenSockets) do begin if i = lIdx then begin lOffset := 1; for j := Low(_Connections) to High(_Connections) do if _Connections[j]^.socket = _UDPListenSockets[i] then _Connections[j]^.socket := nil; SDLNet_UDP_Close(_UDPListenSockets[i]) end else lTmpSockets[i - lOffset] := _UDPListenSockets[i]; end; _UDPListenSockets := lTmpSockets; result := True; end; //---------------------------------------------------------------------------- // Close All //---------------------------------------------------------------------------- procedure CloseAllTCPHostSocketProcedure(); var i : LongInt; begin for i := Low(_ListenSockets) to High(_ListenSockets) do SDLNet_TCP_Close(_ListenSockets[i].socket); SetLength(_ListenSockets, 0); end; procedure CloseAllConnectionsProcedure(const aCloseUDPSockets : Boolean); begin while (Length(_Connections) <> 0) do CloseConnectionProcedure(_Connections[High(_Connections)], aCloseUDPSockets); { for i := Low(_Connections) to High(_Connections) do begin if (_Connections[i]^.isTCP) and Assigned(_Connections[i]^.socket) then begin SDLNet_DelSocket(_SocketSet, _Connections[i]^.socket); SDLNet_TCP_Close(_Connections[i]^.socket); end else begin RemoveAllNamesInCollection(_UDPConnectionIDs); if Assigned(_Connections[i]^.socket) and aCloseUDPSocket then SDLNet_UDP_Close(_Connections[i]^.socket); end; ClearMessageQueue(_Connections[i]); FreeConnection(_Connections[i]); end; SetLength(_Connections, 0);} end; procedure CloseAllUDPSocketProcedure(); var i : LongInt; begin for i := Low(_UDPListenSockets) to High(_UDPListenSockets) do SDLNet_UDP_Close(_UDPListenSockets[i]); SetLength(_UDPListenSockets, 0); end; procedure FreeAllNetworkingResourcesProcedure(); begin CloseAllConnectionsProcedure(False); CloseAllTCPHostSocketProcedure(); CloseAllUDPSocketProcedure(); if Assigned(_UDPReceivePacket) then begin SDLNet_FreePacket(_UDPReceivePacket); _UDPReceivePacket := nil; end; if Assigned(_SocketSet) then begin SDLNet_FreeSocketSet(_SocketSet); _SocketSet := nil; end; // _UDPSendPacket is not Allocated // if Assigned(_UDPSendPacket) then // SDLNet_FreePacket(_UDPSendPacket); FreeNamedIndexCollection(_UDPSocketIDs); FreeNamedIndexCollection(_UDPConnectionIDs); end; //---------------------------------------------------------------------------- // Init //---------------------------------------------------------------------------- procedure LoadSDLNetworkingDriver(); begin NetworkingDriver.CreateTCPHost := @CreateTCPHostProcedure; NetworkingDriver.CreateTCPConnection := @CreateTCPConnectionProcedure; NetworkingDriver.AcceptTCPConnection := @AcceptTCPConnectionProcedure; NetworkingDriver.TCPMessageReceived := @TCPMessageReceivedProcedure; NetworkingDriver.BroadcastTCPMessage := @BroadcastTCPMessageProcedure; NetworkingDriver.SendTCPMessage := @SendTCPMessageProcedure; NetworkingDriver.SendHTTPRequest := @SendHTTPRequestProcedure; NetworkingDriver.CreateUDPHost := @CreateUDPHostProcedure; NetworkingDriver.CreateUDPConnection := @CreateUDPConnectionProcedure; NetworkingDriver.UDPMessageReceived := @UDPMessageReceivedProcedure; NetworkingDriver.SendUDPMessage := @SendUDPMessageProcedure; NetworkingDriver.BroadcastUDPMessage := @BroadcastUDPMessageProcedure; NetworkingDriver.CloseTCPHostSocket := @CloseTCPHostSocketProcedure; NetworkingDriver.CloseConnection := @CloseConnectionProcedure; NetworkingDriver.CloseUDPSocket := @CloseUDPSocketProcedure; NetworkingDriver.MyIP := @MyIPProcedure; NetworkingDriver.ConnectionCount := @ConnectionCountProcedure; NetworkingDriver.RetreiveConnection := @RetreiveConnectionProcedure; NetworkingDriver.CloseAllTCPHostSocket := @CloseAllTCPHostSocketProcedure; NetworkingDriver.CloseAllConnections := @CloseAllConnectionsProcedure; NetworkingDriver.CloseAllUDPSocket := @CloseAllUDPSocketProcedure; NetworkingDriver.FreeAllNetworkingResources := @FreeAllNetworkingResourcesProcedure; end; initialization begin // if (SDLNet_Init() < 0) then // RaiseWarning('SDLNet_Init: ' + SDLNet_GetError()); _SocketSet := SDLNET_AllocSocketSet(16); InitNamedIndexCollection(_UDPSocketIDs); InitNamedIndexCollection(_UDPConnectionIDs); end; finalization begin FreeAllNetworkingResourcesProcedure(); // SDLNet_Quit(); end; end.
{*******************************************************} { } { Cards Report } { } { Copyright (c) 2018 - 2021 Sergey Lubkov } { } {*******************************************************} unit CR.Application; interface uses System.Classes, System.SysUtils, System.Variants, App.Constants, App.Options, App.DB.Options, App.DB.Application, CR.Options, App.DB.Connection, App.MSSQL.Connection; type TCRApplication = class(TCLDBApplication) private function GetDBConnection: TCLMSConnection; function GetOptions: TCROptions; function GetLogicDate: TDate; protected function OptionsClass(): TCLOptionsClass; override; function DBConnectionClass(): TCLDBConnectionClass; override; function GetApplicationName(): string; override; public constructor Create(Owner: TComponent); override; destructor Destroy(); override; procedure ApplyConnectionParams; property Options: TCROptions read GetOptions; property DBConnection: TCLMSConnection read GetDBConnection; property LogicDate: TDate read GetLogicDate; end; var CRApplication: TCRApplication; implementation { TCRApplication } constructor TCRApplication.Create(Owner: TComponent); begin inherited; AppVersion := '1.0.0'; end; destructor TCRApplication.Destroy; begin inherited; end; function TCRApplication.GetDBConnection: TCLMSConnection; begin Result := TCLMSConnection(FDBConnection); end; function TCRApplication.GetOptions: TCROptions; begin Result := TCROptions(FOptions); end; function TCRApplication.GetLogicDate: TDate; begin Result := Options.LogicDate; end; function TCRApplication.OptionsClass: TCLOptionsClass; begin Result := TCROptions; end; function TCRApplication.DBConnectionClass: TCLDBConnectionClass; begin Result := TCLMSConnection; end; function TCRApplication.GetApplicationName: string; begin Result := 'Card Reports'; end; procedure TCRApplication.ApplyConnectionParams; begin DBConnection.Server := Options.Server; DBConnection.UserName := Options.UserName; DBConnection.Password := Options.Password; DBConnection.Database := Options.Database; DBConnection.Port := Options.Port; end; end.
unit risocas; interface uses SysUtils, Dialogs; implementation uses Math, GestionDesErreurs, Main, ModelsManage, Riz; // ----------------------------------------------------------------------------- // On calcule la vitesse moyenne de développement en considérant qu'elle est // linéaire croissante de 0 à 1 entre Tbase et Topt1, puis constante et égale à // 1 entre Topt1 et Topt2 puis décroissante de 1 à 0 entre Topt2 et Tlethale. // Puis on calcule la température équivalente comprise entre Tbase et Topt1 // donnant la même vitesse de développement. // On calcule les degrés jours à partir de cette température équivalente // // In order to get a stress-corrected term for degree-days (DegreDuJourCor), // multiply the daily DegresDuJour by (cstr ^ DEVcstr); DEVcstr is a new parameter // that slows down development rate under stress, assuming values between 0 // (no effect) and 1 (proportional effect of cstr). // ----------------------------------------------------------------------------- procedure RS_EvalDegresJourVitMoy(const TMax, TMin, TBase, TOpt1, TOpt2, TL, cstr, DEVcstr: double; var DegresDuJour, DegresDuJourCor: Double); var v, v1, v2: Double; begin try v1 := ((Max(TMin, TBase) + Min(TOpt1, Min(TL, TMax))) / 2 - TBase) / (TOpt1 - TBase); v2 := (TL - (max(TMax, TOpt2) + TOpt2) / 2) / (TL - TOpt2); v := (v1 * (min(Min(TL, TMax), TOpt1) - TMin) + (min(TOpt2, max(TOpt1, Min(TL, TMax))) - TOpt1) + v2 * (max(TOpt2, Min(TL, TMax)) - TOpt2)) / (Min(TL, TMax) - Max(TMin, TBase)); DegresDuJour := v * (TOpt1 - TBase); DegresDuJourCor := DegresDuJour / Power(Max(cstr, 0.00000001), DEVcstr); except AfficheMessageErreur('RS_EvalDegresJourVitMoy | TMax=' + FloatToStr(TMax) + ' TMin=' + FloatToStr(TMin) + 'TBase=' + FloatToStr(TBase) + ' TOpt1=' + FloatToStr(TOpt1) + ' TOpt2=' + FloatToStr(TOpt2) + ' TL=' + FloatToStr(TL) + ' DegresDuJour=' + FloatToStr(DegresDuJour) + ' DegreDuJourCor=' + FloatToStr(DegresDuJourCor), URisocas); end; end; procedure RS_EvalDegresJourVitMoy_V2(const NumPhase, TMax, TMin, TBase, TOpt1, TOpt2, TLet, cstr, DEVcstr, StressCold : Double; var DegresDuJour, DegresDuJourCor: Double); var v, v1, v3 : Double; S1, S2, S3 : Double; Tn, Tx : Double; begin try if (TMax <> TMin) then begin if ((TMax <= Tbase) or (TMin >= TLet)) then begin V := 0; end else begin Tn := Max(TMin, Tbase); Tx := Min(TMax, TLet); V1 := ((Tn + Min(TOpt1, Tx)) / 2 - Tbase) / (TOpt1 - Tbase); S1 := V1 * Max(0, min(TOpt1, Tx) - Tn); S2 := 1 * Max(0, min(Tx, TOpt2) - Max(Tn, TOpt1)); V3 := (TLet - (Max(Tx, TOpt2) + Max(TOpt2, Tn)) / 2) / (TLet - TOpt2); S3 := V3 * Max(0, Tx - Max(TOpt2, Tn)); V := (S1 + S2 + S3) / (TMax - TMin); end end else begin if (TMax < TOpt1) then begin V := (TMax - Tbase) / (TOpt1 - Tbase); end else begin if (TMax < TOpt2) then begin V := 1 end else begin V := (TLet - TMax) / (Tlet - TOpt2); end; end; end; DegresDuJour := V * (TOpt1 - TBase); if (NumPhase > 1) and (NumPhase < 5) then begin DegresDuJourCor := DegresDuJour * Power(Max(cstr, 0.00000001), DEVcstr); end else begin DegresDuJourCor := DegresDuJour; end; DegresDuJourCor := DegresDuJourCor * StressCold; except AfficheMessageErreur('RS_EvalDegresJourVitMoy | TMax=' + FloatToStr(TMax) + ' TMin=' + FloatToStr(TMin) + 'TBase=' + FloatToStr(TBase) + ' TOpt1=' + FloatToStr(TOpt1) + ' TOpt2=' + FloatToStr(TOpt2) + ' TL=' + FloatToStr(TLet) + ' DegresDuJour=' + FloatToStr(DegresDuJour) + ' DegreDuJourCor=' + FloatToStr(DegresDuJourCor), URisocas); end; end; // ----------------------------------------------------------------------------- // This new module serves to simulate the number of leaves produced on the main // stem, needed to estimate upper limits to LAI and demand for assimilates. // The basis is cumulation of DegresDuJourCor, with the introduction of a new // variable called HaunIndex, which indicates the number of leaves already // produced. The new parameter Phyllo (in degree days, typical varietal values // between 20 and 60) sets the rhythm of leaf development. // ----------------------------------------------------------------------------- procedure RS_Phyllochron(const NumPhase, DegresDuJourCor, Phyllo, RelPhylloPhaseStemElong: Double; var PhaseStemElongation, HaunGain, HaunIndex: Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin if (((NumPhase > 3) or (HaunIndex > 20)) and (NumPhase < 5)) then begin PhaseStemElongation := 1; end else begin PhaseStemElongation := 0; end; if (PhaseStemElongation = 0) then begin HaunGain := DegresDuJourCor / Phyllo; if (HaunIndex < 3) then begin HaunGain := HaunGain * 2; end; end else begin if (PhaseStemElongation = 1) then begin HaunGain := RelPhylloPhaseStemElong * (DegresDuJourCor / Phyllo); end; end; HaunIndex := HaunIndex + HaunGain; end else begin HaunGain := 0; PhaseStemElongation := 0; end; except AfficheMessageErreur('RS_Phyllochron', URisocas); end; end; // ----------------------------------------------------------------------------- // Calcul de la hauteur du couvert en fonction de DJ et cstr // We introduce the new state variables ApexHeight and PlantHeight, which are // also output variables. ApexHeight is the sum of Internode lengths on the main // culm. PlantHeight is (ApexHeight + fn(HaunIndex)) because the leaves // contribute to plant height. We introduce as new parameters InternodeLengthMax // and LeafLengthMax. // ----------------------------------------------------------------------------- procedure RS_EvolHauteur_SDJ_cstr(const PhaseStemElongation, CoeffInternodeNum, HaunGain, cstr, InternodeLengthMax, RelPotLeafLength, LeafLengthMax, CulmsPerHill, IcMean, Kdf, Ic, WtRatioLeafSheath, StressCold, CstrMean : Double; var ApexHeightGain, ApexHeight, PlantHeight, PlantWidth : Double); var CorrectedCstrMean: Double; begin try if (PhaseStemElongation = 1) then begin ApexHeightGain := HaunGain * Min(Power(Min(Ic, 1), 0.5), cstr) * StressCold * InternodeLengthMax; ApexHeightGain := ApexHeightGain * CoeffInternodeNum; end else begin ApexHeightGain := 0; end; ApexHeight := ApexHeight + ApexHeightGain; if (CstrMean <= 0) then begin CorrectedCstrMean := 1; end else begin CorrectedCstrMean := CstrMean; end; PlantHeight := ApexHeight + (1.5 * (1 - Kdf) * RelPotLeafLength * LeafLengthMax * Sqrt(IcMean) * CorrectedCstrMean * (1 + 1 / WtRatioLeafSheath)); PlantWidth := power(Kdf,1.5) * 2 * Sqrt(IcMean) * RelPotLeafLength * LeafLengthMax ;{DELETED LB} {* Min(1.4, (1 + 0.1 * (CulmsPerHill - 1)));} except AfficheMessageErreur('RS_EvolHauteur_SDJ_cstr', URisocas); end; end; // ----------------------------------------------------------------------------- // PAR intercepté journalier (fonction de LTRkdfcl) // ----------------------------------------------------------------------------- procedure RS_EvalParIntercepte(const PAR, {SHIFTED LB} {LIRkdfcl ,}{/SHIFTED LB} LAI , Kdf: Double; var PARIntercepte , LIRkdfcl : Double); begin try {NEW LB} if (LAI > 0) and (LIRkdfcl = 0) then LIRkdfcl := ( 1 - exp(-kdf * LAI)); // right after germination there is a problem with module sequence, like chicken and egg; this overcomes it {NEW LB} PARIntercepte := PAR * LIRkdfcl; except AfficheMessageErreur('RS_EvalParIntercepte | PAR: ' + FloatToStr(PAR) + ' LIRkdfcl: ' + FloatToStr(LIRkdfcl), URisocas); end; end; // ----------------------------------------------------------------------------- // Assim is less sensitive than transpiration to cstr, but currently cstrassim = // assim. // ASScstr is a new parameter that slows attenuates cstr effect on assimilation // relative to transpiration, assuming values between 1 (same effect on // transpiration and assimilation) and ca. 0.5 (assim less sensitive than // transpiration, leasing to increased transpiration efficiency TE). // ----------------------------------------------------------------------------- procedure RS_EvalCstrAssim(const cstr, ASScstr : Double; var cstrassim : Double); begin try cstrassim := Power(Max(cstr, 0.00000001), ASScstr); except AfficheMessageErreur('RS_EvalCstrAssim', URisocas); end; end; // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- procedure RS_EvalRespMaint(const kRespMaintLeaf, kRespMaintSheath, kRespMaintRoot, kRespInternode, kRespPanicle: Double; const DryMatStructLeafPop, DryMatStructSheathPop, DryMatStructRootPop, DryMatStructInternodePop, DryMatStructPaniclePop: Double; const TMoyCalc, kTempMaint, CoefficientQ10: Double; var RespMaintTot: Double); var RespMaintLeafPop: Double; RespMaintSheathPop: Double; RespMaintRootPop: Double; RespMaintInternodePop: Double; RespMaintPaniclePop: Double; CoeffQ10: Double; begin try CoeffQ10 := Power(CoefficientQ10, (TMoyCalc - kTempMaint) / 10); RespMaintLeafPop := kRespMaintLeaf * DryMatStructLeafPop * CoeffQ10; RespMaintSheathPop := kRespMaintSheath * DryMatStructSheathPop * CoeffQ10; RespMaintRootPop := kRespMaintRoot * DryMatStructRootPop * CoeffQ10; RespMaintInternodePop := kRespInternode * DryMatStructInternodePop * CoeffQ10; RespMaintPaniclePop := kRespPanicle * DryMatStructPaniclePop * CoeffQ10; RespMaintTot := RespMaintLeafPop + RespMaintSheathPop + RespMaintRootPop + RespMaintInternodePop + RespMaintPaniclePop; except AfficheMessageErreur('RS_EvalRespMaint', URisocas); end; end; procedure RS_EvolPlantTilNumTot(const NumPhase, ChangePhase, PlantsPerHill, TilAbility, Density, Ic, IcTillering, cstr, HaunIndex, HaunCritTillering: Double; var CulmsPerHill, CulmsPerPlant, CulmsPop: Double); var TilNewPlant: Double; begin try if ((NumPhase = 1) and (ChangePhase = 1)) then begin CulmsPerHill := PlantsPerHill; end else begin if ((NumPhase = 2) and (ChangePhase = 1)) then begin CulmsPerPlant := 1; CulmsPop := CulmsPerPlant * Density * PlantsPerHill; end else begin if ((NumPhase > 1) and (NumPhase < 4) and (HaunIndex > HaunCritTillering)) then begin TilNewPlant := cstr * Min(Max(0, (Ic - IcTillering) * TilAbility), 2); CulmsPerHill := CulmsPerHill + TilNewPlant; CulmsPerPlant := CulmsPerHill / PlantsPerHill; CulmsPop := CulmsPerHill * Density; end else begin CulmsPerPlant := CulmsPerPlant; CulmsPop := CulmsPop; CulmsPerHill := CulmsPerHill; end; end; end; except AfficheMessageErreur('RS_EvolPlantTilNumTot', URisocas); end; end; procedure RS_EvolPlantTilNumTot_V2(const NumPhase, ChangePhase, PlantsPerHill, TilAbility, Density, Ic, IcTillering, cstr, HaunIndex, HaunCritTillering, LtrKdfcl: Double; var CulmsPerHill, CulmsPerPlant, CulmsPop: Double); var TilNewPlant: Double; begin try if ((NumPhase = 1) and (ChangePhase = 1)) then begin CulmsPerHill := PlantsPerHill; end else begin if ((NumPhase = 2) and (ChangePhase = 1)) then begin CulmsPerPlant := 1; CulmsPop := CulmsPerPlant * Density * PlantsPerHill; end else begin if ((NumPhase > 1) and (NumPhase < 4) and (HaunIndex > HaunCritTillering)) then begin TilNewPlant := cstr * Min(Max(0, (Ic - IcTillering) * TilAbility) * Sqrt(LtrKdfcl), 2); CulmsPerPlant := CulmsPerPlant + TilNewPlant; CulmsPerHill := CulmsPerPlant * PlantsPerHill; CulmsPop := CulmsPerHill * Density; end else begin CulmsPerPlant := CulmsPerPlant; CulmsPop := CulmsPop; CulmsPerHill := CulmsPerHill; end; end; end; except AfficheMessageErreur('RS_EvolPlantTilNumTot_V2', URisocas); end; end; procedure RS_EvolPlantLeafNumTot(const NumPhase, CulmsPerHill, HaunGain: Double; var PlantLeafNumNew, PlantLeafNumTot: Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin PlantLeafNumNew := HaunGain * CulmsPerHill; PlantLeafNumTot := PlantLeafNumTot + PlantLeafNumNew; end else begin PlantLeafNumNew := PlantLeafNumNew; PlantLeafNumTot := PlantLeafNumTot; end; except AfficheMessageErreur('RS_EvolPlantLeafNumTot', URisocas); end; end; procedure RS_EvolMobiliTillerDeath(const NumPhase, SDJPhase4, SeuilTempRPR, CoeffTillerDeath, Density, Ic, PlantsPerHill: Double; var TillerDeathPop, CulmsPop, CulmsPerPlant, CulmsPerHill: Double); begin try if ((NumPhase = 3) or ((NumPhase = 4) and (SDJPhase4 <= 0.67 * SeuilTempRPR)) and (CulmsPerPlant >= 1)) then begin TillerDeathPop := (1 - (Min(Ic, 1))) * CulmsPop * CoeffTillerDeath; CulmsPop := CulmsPop - TillerDeathPop; CulmsPerPlant := CulmsPop / (Density * PlantsPerHill); CulmsPerHill := CulmsPerPlant * PlantsPerHill; end; except AfficheMessageErreur('RS_EvolMobiliTillerDeath', URisocas); end; end; procedure RS_EvolMobiliTillerDeath_V2(const NumPhase, SDJPhase4, SeuilTempRPR, CoeffTillerDeath, Density, Ic, PlantsPerHill: Double; var TillerDeathPop, CulmsPop, CulmsPerPlant, CulmsPerHill, DryMatStructPaniclePop: Double); begin try if ((NumPhase = 3) or ((NumPhase = 4) and (SDJPhase4 <= {NEW} 0.7 * SeuilTempRPR)) and (CulmsPerPlant >= 1)) then begin TillerDeathPop := (1 - (Min(Ic, 1))) * CulmsPop * CoeffTillerDeath; CulmsPop := CulmsPop - TillerDeathPop; CulmsPerPlant := CulmsPop / (Density * PlantsPerHill); CulmsPerHill := CulmsPerPlant * PlantsPerHill; DryMatStructPaniclePop := DryMatStructPaniclePop * Max(0, CulmsPop) / (CulmsPop + TillerDeathPop); end; except AfficheMessageErreur('RS_EvolMobiliTillerDeath_V2', URisocas); end; end; procedure RS_EvolMobiliLeafDeath(const NumPhase, Ic, CoeffLeafDeath, sla: Double; var LeafDeathPop, DryMatStructLeafPop, MobiliLeafDeath, DeadLeafDrywtPop, LaiDead: Double); begin try if (NumPhase > 1) then begin LeafDeathPop := (1 - (Min(Ic, 1))) * DryMatStructLeafPop * CoeffLeafDeath; DryMatStructLeafPop := DryMatStructLeafPop - LeafDeathPop; MobiliLeafDeath := 0.25 {NEW} * LeafDeathPop; DeadLeafDrywtPop := DeadLeafDrywtPop + (0.75 {NEW} * LeafDeathPop); LaiDead := DeadLeafDrywtPop * sla; end; except AfficheMessageErreur('RS_EvolMobiliLeafDeath', URisocas); end; end; procedure RS_EvalSupplyTot(const NumPhase, PhaseStemElongation, Assim, MobiliLeafDeath, RespMaintTot: Double; var RespMaintDebt, AssimNotUsed, AssimNotUsedCum, AssimSurplus, SupplyTot , CumSupplyTot: Double); begin try SupplyTot := Assim + MobiliLeafDeath - RespMaintTot - Max(0, RespMaintDebt); {NEW} if NumPhase < 7 then CumSupplyTot := CumSupplyTot + SupplyTot {NEW R} - MobiliLeafDeath // Output Test variable for source for dry matter production (consider also AssimNotUsed!) else CumSupplyTot := 0; if (SupplyTot <= 0) then begin RespMaintDebt := 0 - SupplyTot; SupplyTot := 0; end else begin RespMaintDebt := 0; end; {DELETED} { if ((NumPhase < 5) and (PhaseStemElongation = 0)) then begin AssimNotUsed := AssimSurplus; AssimNotUsedCum := AssimNotUsedCum + AssimNotUsed; end else begin AssimNotUsed := 0; AssimNotUsedCum := AssimNotUsedCum + AssimNotUsed; end; } // These commands seem redundant and in the wrong place. Denete? except AfficheMessageErreur('RS_EvalSupplyTot', URisocas); end; end; procedure RS_EvalRelPotLeafLength(const NumPhase, HaunIndex, RankLongestLeaf: Double; var RelPotLeafLength: Double); begin try if (NumPhase > 1) then begin RelPotLeafLength := Min((0.1 + 0.9 * HaunIndex / RankLongestLeaf), 1); end; except AfficheMessageErreur('RS_EvalRelPotLeafLength', URisocas); end; end; procedure RS_EvalDemandStructLeaf(const NumPhase, PlantLeafNumNew, sla, SlaMax, RelPotLeafLength, Density, LeafLengthMax, CoeffLeafWLRatio, cstr: Double; var DemLeafAreaPlant, DemStructLeafPlant, DemStructLeafPop: Double); var CorrectedSla: Double; begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin DemLeafAreaPlant := (Power((RelPotLeafLength * LeafLengthMax), 2) * CoeffLeafWLRatio * 0.725 * PlantLeafNumNew / 1000000) * cstr; if (sla = 0) then begin CorrectedSla := SlaMax; end else begin CorrectedSla := sla; end; DemStructLeafPlant := DemLeafAreaPlant * 0.1 / CorrectedSla; DemStructLeafPop := DemStructLeafPlant * Density / 1000; end; except AfficheMessageErreur('RS_EvalDemandStructLeaf', URisocas); end; end; procedure RS_EvalDemandStructLeaf_V2(const NumPhase, PlantLeafNumNew, SlaNew, SlaMax, RelPotLeafLength, Density, LeafLengthMax, CoeffLeafWLRatio, cstr, StressCold: Double; var DemLeafAreaPlant, DemStructLeafPlant, DemStructLeafPop, A_DemStructLeaf: Double); var CorrectedSla: Double; begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin DemLeafAreaPlant := (Power((RelPotLeafLength * LeafLengthMax), 2) * CoeffLeafWLRatio * 0.725 * PlantLeafNumNew / 1000000) * Min(cstr, StressCold); if (SlaNew = 0) then begin CorrectedSla := SlaMax; end else begin CorrectedSla := SlaNew; end; DemStructLeafPlant := DemLeafAreaPlant * 0.1 / CorrectedSla; DemStructLeafPop := DemStructLeafPlant * Density / 1000; A_DemStructLeaf := DemStructLeafPlant * Density / 1000; end; except AfficheMessageErreur('RS_EvalDemandStructLeaf_V2', URisocas); end; end; procedure RS_EvalDemandStructSheath(const NumPhase, DemStructLeafPop, WtRatioLeafSheath, SlaMin, SlaMax, Sla, StressCold: Double; var DemStructSheathPop {TEST}{, A_DemStructSheath}: Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin DemStructSheathPop := (1 + ((SlaMax - Sla) / (SlaMax - SlaMin))) * 0.5 * DemStructLeafPop / WtRatioLeafSheath * Max(0.00001, StressCold); //A_DemStructSheath := DemStructSheathPop; end; except AfficheMessageErreur('RS_EvalDemandStructSheath', URisocas); end; end; procedure RS_EvalDemandStructRoot(const NumPhase, Density: Double; CoeffRootMassPerVolMax, RootPartitMax, GrowthStructTotPop, RootFront, SupplyTot: Double; var RootSystSoilSurfPop, RootSoilSurfPop, RootSystVolPop, GainRootSystVolPop, GainRootSoilSurfPop, DemStructRootPop, RootSystSoilSurfPopOld, RootFrontOld, DemStructRootPlant: Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin RootSystSoilSurfPop := Min(RootFront * RootFront * Density / 1000000, 10000); RootSystVolPop := RootSystSoilSurfPop * RootFront / 1000; GainRootSoilSurfPop := RootSystSoilSurfPop - RootSystSoilSurfPopOld; GainRootSystVolPop := (RootSystSoilSurfPop + GainRootSoilSurfPop) * (RootFront - RootFrontOld); DemStructRootPop := Min(CoeffRootMassPerVolMax * GainRootSystVolPop, SupplyTot * RootPartitMax); DemStructRootPlant := DemStructRootPop * 1000 / density; RootSystSoilSurfPopOld := RootSystSoilSurfPop; RootFrontOld := RootFront; end; except AfficheMessageErreur('RS_EvalDemandStructRoot', URisocas); end; end; procedure RS_EvalDemandStructRoot_V2(const NumPhase, Density: Double; CoeffRootMassPerVolMax, RootPartitMax, GrowthStructTotPop, RootFront, SupplyTot, DemStructLeafPop, DemStructSheathPop, DryMatStructRootPop: Double; var RootSystSoilSurfPop, RootSystVolPop, GainRootSystVolPop, GainRootSystSoilSurfPop, DemStructRootPop, RootSystSoilSurfPopOld, RootFrontOld, RootSystVolPopOld, DemStructRootPlant{TEST}{, GrowthView}: Double); begin try RootSystSoilSurfPop := Min(RootFront * RootFront * Density / 1000000, 10000); RootSystVolPop := RootSystSoilSurfPop * RootFront / 1000; if ((NumPhase > 1) and (NumPhase < 5)) then begin GainRootSystSoilSurfPop := RootSystSoilSurfPop - RootSystSoilSurfPopOld; GainRootSystVolPop := RootSystVolPop - RootSystVolPopOld; DemStructRootPop := Min((DemStructLeafPop + DemStructSheathPop) * RootPartitMax, Max(0, CoeffRootMassPerVolMax * RootSystVolPop - DryMatStructRootPop)); //GrowthView := DemStructRootPop; DemStructRootPlant := DemStructRootPop * 1000 / density; RootSystSoilSurfPopOld := RootSystSoilSurfPop; RootFrontOld := RootFront; RootSystVolPopOld := RootSystVolPop; end; except AfficheMessageErreur('RS_EvalDemandStructRoot_V2', URisocas); end; end; procedure RS_EvalDemandStructInternode(const PhaseElongation, ApexHeightGain, CulmsPerHill, CoeffInternodeMass, Density, Ic: Double; var DemStructInternodePlant, DemStructInternodePop: Double); begin try if (PhaseElongation = 1) then begin DemStructInternodePlant := Power(Min(Ic, 1), 0.5) * ApexHeightGain * CulmsPerHill * CoeffInternodeMass; DemStructInternodePop := DemStructInternodePlant * Density / 1000; end; except AfficheMessageErreur('RS_EvalDemandStructInternode', URisocas); end; end; procedure RS_EvalDemandStructIN_V2(const PhaseElongation, ApexHeightGain, CulmsPerHill, CoeffInternodeMass, Density, Ic , ResCapacityInternodePop , DryMatResInternodePop, {NEW G} CoeffReserveSink , {NEW LB} NumPhase : Double; var DemStructInternodePlant, DemStructInternodePop , {NEW G}DemResInternodePop: Double); begin try if (PhaseElongation = 1) then begin DemStructInternodePlant := Power(Min(Ic, 1), 0.5) * ApexHeightGain * CulmsPerHill * CoeffInternodeMass; DemStructInternodePop := DemStructInternodePlant * Density / 1000; end; {NEW LB} if (NumPhase > 1) and (NumPhase < 5) then {NEW G} DemResInternodePop := (ResCapacityInternodePop - DryMatResInternodePop) * CoeffReserveSink; // CoeffReserveSink is a crop para 0…1 that sets daily reserve sink as fraction of deficit {/NEW G} {/NEW LB} except AfficheMessageErreur('RS_EvalDemandStructIN_V2', URisocas); end; end; procedure RS_EvalDemandStructPanicle(const NumPhase, CoeffPanicleMass, CulmsPerHill, Ic, DryMatStructPaniclePop, Density, PanStructMassMax: Double; var DemStructPaniclePlant, PanStructMass, DemStructPaniclePop: Double); begin try if (NumPhase = 4) then begin DemStructPaniclePlant := CoeffPanicleMass * CulmsPerHill * Ic; PanStructMass := 1000 * DryMatStructPaniclePop / (Density * CulmsPerHill); if (PanStructMass > PanStructMassMax) then begin DemStructPaniclePlant := 0; end; DemStructPaniclePop := DemStructPaniclePlant * Density / 1000; end; except AfficheMessageErreur('RS_EvalDemandStructPanicle', URisocas); end; end; procedure RS_EvalDemandStructPanicle_V2(const NumPhase, CoeffPanicleMass, CulmsPerHill, Ic, DryMatStructPaniclePop, Density, PanStructMassMax, StressCold: Double; var DemStructPaniclePlant, PanStructMass, DemStructPaniclePop: Double); begin try if (NumPhase = 4) then begin DemStructPaniclePlant := CoeffPanicleMass * CulmsPerHill * Sqrt(Min(Ic, 1)) * Sqrt(Max(0.00001, StressCold)); PanStructMass := 1000 * DryMatStructPaniclePop / (Density * CulmsPerHill); if (PanStructMass > PanStructMassMax) then begin DemStructPaniclePlant := 0; end; DemStructPaniclePop := DemStructPaniclePlant * Density / 1000; end; except AfficheMessageErreur('RS_EvalDemandStructPanicle_V2', URisocas); end; end; procedure RS_EvalDemandTotAndIcPreFlow(const NumPhase, RespMaintTot, DemStructLeafPop, DemStructSheathPop, DemStructRootPop, DemStructInternodePop, DemStructPaniclePop, SupplyTot, NbDaysSinceGermination, PlantHeight, Cstr, DemResInternodePop: Double; var DemStructTotPop, Ic, IcCumul, IcMean, CstrCumul, CstrMean , A_DemStructTot: Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin DemStructTotPop := DemStructLeafPop + DemStructSheathPop + DemStructRootPop + DemStructInternodePop + DemStructPaniclePop {NEW G} + DemResInternodePop; A_DemStructTot := DemStructLeafPop + DemStructSheathPop + DemStructRootPop + DemStructInternodePop + DemStructPaniclePop {NEW G} + DemResInternodePop; Ic := SupplyTot / DemStructTotPop; if (Ic <= 0) then begin Ic := 0; end; if (PlantHeight = 0) then begin Ic := 1; end; IcCumul := IcCumul + Min(Ic, 1); IcMean := IcCumul / NbDaysSinceGermination; CstrCumul := CstrCumul + Cstr; CstrMean := CstrCumul / NbDaysSinceGermination; end; if ((NumPhase = 5) or (NumPhase = 6)) then begin IcCumul := IcCumul + Min(Ic, 1); IcMean := IcCumul / NbDaysSinceGermination; CstrCumul := CstrCumul + Cstr; CstrMean := CstrCumul / NbDaysSinceGermination; end; except AfficheMessageErreur('RS_EvalDemandTotAndIcPreFlow', URisocas); end; end; procedure RS_EvolGrowthStructLeafPop(const NumPhase, Ic, SupplyTot, DemStructLeafPop, DemStructTotPop: Double; var GrowthStructLeafPop {, GrowthView}, A_GrowthStructLeaf : Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin if (Ic < 1) then begin {YIELD ERROR 34.5} GrowthStructLeafPop := SupplyTot * (DemStructLeafPop / DemStructTotPop); A_GrowthStructLeaf := SupplyTot * (DemStructLeafPop / DemStructTotPop); end else begin GrowthStructLeafPop := DemStructLeafPop; A_GrowthStructLeaf := DemStructLeafPop; //showMessage('DEM:_'+ floattostr(DemStructLeafPop)+' A_G: _' +floattostr(A_GrowthStructLeaf)); end; end; {GrowthView := GrowthStructLeafPop;} except AfficheMessageErreur('RS_EvolGrowthStructLeafPop', URisocas); end; end; procedure RS_EvolGrowthStructSheathPop(const NumPhase, Ic, SupplyTot, DemStructSheathPop, DemStructTotPop: Double; var GrowthStructSheathPop: Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin if (Ic < 1) then begin GrowthStructSheathPop := SupplyTot * (DemStructSheathPop / DemStructTotPop); end else begin GrowthStructSheathPop := DemStructSheathPop; end; end; except AfficheMessageErreur('RS_EvolGrowthStructSheathPop', URisocas); end; end; procedure RS_EvolGrowthStructRootPop(const NumPhase, Ic, SupplyTot, DemStructRootPop, DemStructTotPop: Double; var GrowthStructRootPop: Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin if (Ic < 1) then begin GrowthStructRootPop := SupplyTot * (DemStructRootPop / DemStructTotPop); end else begin GrowthStructRootPop := DemStructRootPop; end; end; except AfficheMessageErreur('RS_EvolGrowthStructRootPop', URisocas); end; end; procedure RS_EvolGrowthStructINPop(const NumPhase, Ic, SupplyTot, DemStructInternodePop, DemStructTotPop , DemResInternodePop: Double; var GrowthStructInternodePop, {NEW G} GrowthResInternodePop: Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin if (Ic < 1) then begin GrowthStructInternodePop := SupplyTot * (DemStructInternodePop / DemStructTotPop); {NEW G} GrowthResInternodePop := SupplyTot * (DemResInternodePop / DemStructTotPop); {/NEW G} end else begin GrowthStructInternodePop := DemStructInternodePop; {NEW G} GrowthResInternodePop := DemResInternodePop; {/NEW G} end; end; except AfficheMessageErreur('RS_EvolGrowthStructInternodePop', URisocas); end; end; procedure RS_EvolGrowthStructPanPop(const NumPhase, Ic, SupplyTot, DemStructPaniclePop, DemStructTotPop: Double; var GrowthStructPaniclePop: Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin if (Ic < 1) then begin GrowthStructPaniclePop := SupplyTot * (DemStructPaniclePop / DemStructTotPop); end else begin GrowthStructPaniclePop := DemStructPaniclePop; end; end; except AfficheMessageErreur('RS_EvolGrowthStructPaniclePop', URisocas); end; end; procedure RS_AddResToGrowthStructPop(const NumPhase, Ic, PhaseStemElongation, DryMatResInternodePop, DemStructTotPop, DemStructLeafPop, DemStructSheathPop, DemStructRootPop, DemStructInternodePop, DemStructPaniclePop, RelMobiliInternodeMax, GrowthResInternodePop: Double; var ResInternodeMobiliDayPot, GrowthStructDeficit, GrowthStructLeafPop, GrowthStructSheathPop, GrowthStructRootPop, GrowthStructInternodePop, GrowthStructPaniclePop, GrowthStructTotPop, ResInternodeMobiliDay , A_GrowthStructLeaf , A_GrowthStructTot, A_ResInternodeMobiliDay : Double); begin try if (NumPhase > 1) then begin //if (PhaseStemElongation = 1) then {DELETED may 06}{if (NumPhase > 2) then begin ResInternodeMobiliDayPot := RelMobiliInternodeMax * DryMatResInternodePop; GrowthStructDeficit := Max((DemStructTotPop - GrowthStructTotPop }{NEW LB}{ - GrowthResInternodePop), 0);} {DELETED may 06} {end;} if ((Ic < 1) and (DemStructTotPop > 0)) then begin ResInternodeMobiliDay := Min(ResInternodeMobiliDayPot, GrowthStructDeficit); A_ResInternodeMobiliDay := Min(ResInternodeMobiliDayPot, GrowthStructDeficit); {DELETED} { GrowthStructTotPop := GrowthStructLeafPop + GrowthStructSheathPop + GrowthStructRootPop + GrowthStructInternodePop + GrowthStructPaniclePop + GrowthResInternodePop; } {/DELETED} GrowthStructLeafPop := GrowthStructLeafPop + ResInternodeMobiliDay * (DemStructLeafPop / DemStructTotPop); A_GrowthStructLeaf := GrowthStructLeafPop; GrowthStructSheathPop := GrowthStructSheathPop + ResInternodeMobiliDay * (DemStructSheathPop / DemStructTotPop); GrowthStructRootPop := GrowthStructRootPop + ResInternodeMobiliDay * (DemStructRootPop / DemStructTotPop); GrowthStructInternodePop := GrowthStructInternodePop + ResInternodeMobiliDay * (DemStructInternodePop / DemStructTotPop); GrowthStructPaniclePop := GrowthStructPaniclePop + ResInternodeMobiliDay * (DemStructPaniclePop / DemStructTotPop); // The following is an update on total growth including mobilization from reserves. Storage does not benefit from mobilization so GrowthResInternodePop is unaltered since module 65, but is included in total growth GrowthStructTotPop := GrowthStructLeafPop + GrowthStructSheathPop + GrowthStructRootPop + GrowthStructInternodePop + GrowthStructPaniclePop {NEW P} + GrowthResInternodePop; A_GrowthStructTot := GrowthStructTotPop; end; end; except AfficheMessageErreur('RS_AddResToGrowthStructPop' + ' GrowthStrucTotPop : ' + floattostr(GrowthStructTotPop), URisocas); end; end; procedure RS_EvolDemPanFilPopAndIcPFlow(const NumPhase, DryMatStructPaniclePop, CoeffPanSinkPop, SterilityTot, DegresDuJourCor, DegresNumPhase5, SupplyTot, Assim, RespMaintTot, StressCold: Double; var PanicleSinkPop, DemPanicleFillPop, AssimSurplus , Ic , A_AssimSurplus: Double); begin try if (NumPhase = 5) then begin PanicleSinkPop := DryMatStructPaniclePop * CoeffPanSinkPop * (1 - SterilityTot); DemPanicleFillPop := (DegresDuJourCor / DegresNumPhase5) * PanicleSinkPop * Sqrt(Max(0.00001, StressCold)); Ic := SupplyTot / Max(DemPanicleFillPop, 0.0000001); if (Ic <= 0) then begin Ic := 0; end; end; if (NumPhase = 6) then begin Ic := Assim / RespMaintTot; if (Ic >= 1) then begin AssimSurplus := Max(0, Assim - RespMaintTot); A_AssimSurplus := Max(0, Assim - RespMaintTot); end else begin AssimSurplus := 0; A_AssimSurplus := 0; end; if (Ic < 0) then begin Ic := 0; end; end; except AfficheMessageErreur('RS_EvolDemPanFilPopAndIcPFlow', URisocas); end; end; procedure RS_EvolPanicleFilPop(const NumPhase, Ic, DryMatResInternodePop, DemPanicleFilPop, SupplyTot, RelMobiliInternodeMax, RespMaintTot, Assim: Double; var ResInternodeMobiliDayPot, AssimSurplus, PanicleFilDeficit, ResInternodeMobiliDay, PanicleFilPop, GrainYieldPop, A_AssimSurplus , A_ResInternodeMobiliDay: Double); begin try if (NumPhase = 5) then begin ResInternodeMobiliDayPot := RelMobiliInternodeMax * DryMatResInternodePop; if (Ic > 1) then begin PanicleFilPop := Max(DemPanicleFilPop, 0); PanicleFilDeficit := 0; AssimSurplus := SupplyTot - PanicleFilPop; A_AssimSurplus := SupplyTot - PanicleFilPop; end else begin if (Ic <= 1) then begin PanicleFilDeficit := Max((DemPanicleFilPop - Max(SupplyTot, 0)), 0); ResInternodeMobiliDay := Max(Min(ResInternodeMobiliDayPot, 0.5 * PanicleFilDeficit), 0); A_ResInternodeMobiliDay := Max(Min(ResInternodeMobiliDayPot, 0.5 * PanicleFilDeficit), 0); PanicleFilPop := Max((SupplyTot + ResInternodeMobiliDay), 0); AssimSurplus := 0; A_AssimSurplus := 0; end; end; GrainYieldPop := GrainYieldPop + PanicleFilPop; end else begin if (NumPhase = 6) then begin AssimSurplus := Assim - RespMaintTot; A_AssimSurplus := Assim - RespMaintTot; ResInternodeMobiliDay := Min(Max(0, RespMaintTot - Assim), DryMatResInternodePop); A_ResInternodeMobiliDay := Min(Max(0, RespMaintTot - Assim), DryMatResInternodePop); end else begin if (NumPhase > 6) then begin ResInternodeMobiliDay := 0; A_ResInternodeMobiliDay := 0; end; end; end; except AfficheMessageErreur('RS_EvolPanicleFilPop', URisocas); end; end; procedure RS_EvolGrowthReserveInternode(const NumPhase, PhaseStemElongation, DryMatStructInternodePop, DryMatStructSheathPop, CoeffResCapacityInternode, AssimSurplus, ResInternodeMobiliDay: Double; var ResCapacityInternodePop, IncreaseResInternodePop, DryMatResInternodePop, AssimNotUsed, AssimNotUsedCum, GrowthResInternodePop, {NEW LB} DryMatResInternodePopOld , A_IncreaseResInternodePop: Double); begin try //if ((PhaseStemElongation = 1) or (NumPhase >= 5)) then if (NumPhase >= 2) then begin {NEW LB} DryMatResInternodePopOld := DryMatResInternodePop; // Needed to calculate reservesaccumulation for the day which happens in 2 steps {/NEW LB} ResCapacityInternodePop := (DryMatStructInternodePop + DryMatStructSheathPop) * CoeffResCapacityInternode; //growthView := GrowthResInternodePop; {NEW G} DryMatResInternodePop := DryMatResInternodePop + GrowthResInternodePop; // Demand-driven growth of reserve pool {/NEW G} IncreaseResInternodePop := Min(Max(AssimSurplus, 0), Max((ResCapacityInternodePop - DryMatResInternodePop), 0)); A_IncreaseResInternodePop := Min(Max(AssimSurplus, 0), Max((ResCapacityInternodePop - DryMatResInternodePop), 0)); GrowthResInternodePop := IncreaseResInternodePop - ResInternodeMobiliDay; //showmessage(floatToStr(DryMatResInternodePop)+' '+floatToStr(IncreaseResInternodePop)+' '+floatToStr(GrowthResInternodePop)); DryMatResInternodePop := DryMatResInternodePop + GrowthResInternodePop; // Surplus- and mobilization-driven growth of reserve pool //growthView := GrowthResInternodePop; AssimNotUsed := Max((AssimSurplus - IncreaseResInternodePop), 0); AssimNotUsedCum := AssimNotUsedCum + AssimNotUsed; end; except AfficheMessageErreur('RS_EvolGrowthReserveInternode', URisocas); end; end; procedure RS_EvolGrowthTot(const NumPhase, GrowthStructLeafPop, GrowthStructSheathPop, GrowthStructRootPop, GrowthStructInternodePop, GrowthStructPaniclePop, GrowthResInternodePop, PanicleFilPop , DryMatResInternodePop , DryMatResInternodePopOld: Double; var GrowthStructTotPop, GrowthDryMatPop , A_GrowthStructTot : Double); begin try if (NumPhase < 5) then begin GrowthStructTotPop := GrowthStructLeafPop + GrowthStructSheathPop + GrowthStructRootPop + GrowthStructInternodePop + GrowthStructPaniclePop; A_GrowthStructTot := GrowthStructTotPop; end else begin GrowthStructTotPop := 0; A_GrowthStructTot := GrowthStructTotPop; end; GrowthDryMatPop := GrowthStructTotPop + {NEW LB} (DryMatResInternodePop - DryMatResInternodePopOld) {/NEW LB}{DELETED} {GrowthResInternodePop} + PanicleFilPop; except AfficheMessageErreur('RS_EvolGrowthTot', URisocas); end; end; procedure RS_EvalLai(const NumPhase, ChangePhase, DryMatStructLeafPop, sla, SlaMax, {NEW P} LeafLengthMax, RelPotLeafLength, GrowthStructTotPop, GrowthStructLeafPop {/NEW P} , DemStructLeafPop: Double; var Lai , {NEW P} LastLeafLengthPot , LastLeafLength {/NEW P}: Double); var CorrectedSla: Double; begin try //showMessage(floattostr(NumPhase)); if ((NumPhase = 2) and (ChangePhase = 1)) then begin CorrectedSla := SlaMax; end else begin CorrectedSla := sla; {NEW} LastLeafLengthPot := RelPotLeafLength * LeafLengthMax; if GrowthStructTotPop > 0 then LastLeafLength := LastLeafLengthPot * sqrt(GrowthStructLeafPop / DemStructLeafPop); {/NEW} end; Lai := DryMatStructLeafPop * CorrectedSla; except AfficheMessageErreur('RS_EvalLai', URisocas); end; end; procedure RS_EvalClumpAndLightInter(const NumPhase, KRolling, Density, PlantWidth, PlantHeight, Kdf, Lai, CoeffClump: Double; var Kcl, Kdfcl, LIRkdf, LIRkdfcl, LTRkdf, LTRkdfcl: Double); var PlantDistance: Double; PlantLeafAreaGreen: Double; ClumpDens: Double; ClumpIsol: Double; CorrectedPlantWidth: Double; CorrectedPlantHeight: Double; RolledLai: Double; begin try if (NumPhase > 1) then begin RolledLai := Lai * KRolling; PlantDistance := Sqrt(10000 / Density); PlantLeafAreaGreen := Power(PlantDistance, 2) * RolledLai; if (PlantWidth = 0) then begin CorrectedPlantWidth := 1; end else begin CorrectedPlantWidth := PlantWidth; end; if (PlantHeight = 0) then begin CorrectedPlantHeight := 1; end else begin CorrectedPlantHeight := PlantHeight; end; ClumpDens := Sqrt(Max(PlantLeafAreaGreen / (Power(0.5 * CorrectedPlantWidth / 2000, 2) * PI) - 1, 0)); ClumpIsol := Sqrt(Max(Power(PlantDistance, 2) / (Power(0.5 * CorrectedPlantWidth / 2000, 2) * PI) - 1, 0)) / (CorrectedPlantHeight / 1000); Kcl := ClumpDens * ClumpIsol; Kdfcl := Kdf - Min(CoeffClump * Kcl, 0.4 * Kdf); LIRkdf := 1 - Exp(-Kdf * RolledLai); LIRkdfcl := 1 - Exp(-Kdfcl * RolledLai); LTRkdf := Exp(-Kdf * RolledLai); LTRkdfcl := Exp(-Kdfcl * RolledLai); end; except AfficheMessageErreur('RS_EvalClumpingAndLightInter', URisocas); end; end; procedure RS_EvalClumpAndLightInter_V2(const NumPhase, KRolling, Density, PlantWidth, PlantHeight, Kdf, Lai, FractionPlantHeightSubmer: Double; var LIRkdf, LIRkdfcl, LTRkdf, LTRkdfcl: Double); var RolledLai: Double; begin try if (NumPhase > 1) and (PlantWidth > 0) then begin RolledLai := Lai * KRolling * {MODIFIED JUNE 20}{Sqrt}power((1 - FractionPlantHeightSubmer), 0.3); LIRkdf := 1 - Exp(-Kdf * RolledLai); LIRkdfcl := (1 - Exp(-Kdf * RolledLai * 10000 / Min(10000, Density * pi * Power(PlantWidth / 2000, 2)))) * (Min(10000, Density * pi * Power(PlantWidth / 2000, 2)) / 10000); LTRkdf := 1 - LIRkdf; LTRkdfcl := 1 - LIRkdfcl; end; except AfficheMessageErreur('RS_EvalClumpingAndLightInter_V2', URisocas); end; end; procedure RS_EvalSlaMitch(const SlaMax, SlaMin, AttenMitch, SDJ, SDJLevee, NumPhase, DegresDuJour, TOpt1, TBase, TempSla, DryMatStructLeafPop, GrowthStructLeafPop: Double; var SlaMitch, SlaNew, Sla: Double); begin try if (NumPhase > 1) then begin SlaMitch := SlaMin + (SlaMax - SlaMin) * Power(AttenMitch, (SDJ - SDJLevee)); SlaNew := SlaMin + (SlaMitch - SlaMin) * Power(DegresDuJour / (TOpt1 - TBase), TempSla); Sla := ((Sla * DryMatStructLeafPop) + (SlaNew * GrowthStructLeafPop)) / (DryMatStructLeafPop + GrowthStructLeafPop); end else begin SlaMitch := 0; SlaNew := 0; Sla := SlaMax; end; except AfficheMessageErreur('RS_EvalSlaMitch', URisocas); end; end; procedure RS_EvalRUE(const NumPhase, ChangePhase, ParIntercepte, DryMatTotPop, DeadLeafDrywtPop , DryMatStructRootPop, Tr, Evap, Dr, Lr, SupplyTot, AssimNotUsed, Irrigation, IrrigAutoDay, Pluie, Assim, AssimPot, Conversion, NbJas , Transplanting , NurseryStatus, //NEW Density , DensityNursery, DryMatAboveGroundTotPop : Double; var RUE, CumPar, CumTr, CumEt, CumWUse, CumWReceived, CumIrrig, CumDr, CumLr, TrEffInst, TrEff, WueEt, WueTot, ConversionEff{, growthView}: Double); var CorrectedIrrigation: Double; begin try if ((NumPhase < 1) or ((NumPhase = 1) and (ChangePhase = 1))) {NEW G}or (Density = DensityNursery){/NEW G} then begin CumPar := 0; RUE := 0; CumTr := 0.00001; CumEt := 0.00001; CumWUse := 0.00001; CumWReceived := 0; CumIrrig := 0; CumDr := 0; CumLr := 0; end else begin {NEW Y} If (Transplanting = 0) or (NurseryStatus = 1) then begin CumPar := CumPar + ParIntercepte; CumTr := CumTr + Tr; CumEt := CumEt + Tr + Evap; CumWUse := CumWUse + Tr + Evap + Dr + Lr; end; {/NEW Y} if (Irrigation = NullValue) then begin CorrectedIrrigation := 0; end else begin CorrectedIrrigation := Irrigation; end; {NEW Y} If (Transplanting = 0) or (NurseryStatus = 1) then begin CumWReceived := CumWReceived + Pluie + CorrectedIrrigation + IrrigAutoDay; CumIrrig := CumIrrig + CorrectedIrrigation + IrrigAutoDay; CumDr := CumDr + Dr; CumLr := CumLr + Lr; end; {/NEW Y} if (AssimPot <> 0) then begin ConversionEff := Conversion * Assim / {NEW JUNE} (ParIntercepte * Conversion * 10){AssimPot}; end; if ((Tr > 0) and (NbJas > {NEW G}20{/NEW G}) and (NumPhase > 1)) then begin TrEffInst := (SupplyTot - AssimNotUsed) / (Tr * 10000); TrEff := DryMatTotPop / (CumTr * 10000); WueEt := DryMatTotPop / (CumEt * 10000); WueTot := DryMatTotPop / (CumWuse * 10000); {DELETED G} //RUE := ((DryMatTotPop + DeadLeafDrywtPop - DryMatStructRootPop) / Max(CumPar, 0.00001)) / 10; //(Please delete this grey line and replace with the following one in green) {/DELETED G} {NEW G} RUE := ( DryMatAboveGroundTotPop / Max(CumPar, 0.00001)) / 10; {/NEW G} end; end; //growthView := cumPar ; except AfficheMessageErreur('RS_EvalRUE', URisocas); end; end; procedure RS_EvolKcpKceBilhy(const LTRkdfcl, KcMax, Mulch: Double; var Kcp, Kce, KcTot: Double); begin try Kcp := Min((1 - LTRkdfcl) * KcMax, KcMax); Kcp := Min(Kcp, KcMax); Kce := LTRkdfcl * 1 * (Mulch / 100); KcTot := Kcp + Kce; except AfficheMessageErreur('RS_BilhyEvolKcpLai', URisocas); end; end; procedure RS_EvolEvapSurfRFE_RDE(const Kce, EvapPot, CapaREvap, CapaRDE, StRurMax, RuSurf: Double; var Evap, ValRSurf, ValRFE, ValRDE, StRur, StRu, Kr, KceReal: Double); var ValRSurfPrec, EvapRU: Double; Evap1, Evap2: Double; begin try ValRSurfPrec := ValRSurf; // ValRSurf est l'eau contenue dans les réservoirs Revap (non transpirable) et RDE (transpirable et évaporable if (ValRFE > 0) then begin if (ValRFE < EvapPot) then begin Evap1 := ValRFE; Evap2 := Max(0, Min(ValRSurf, ((EvapPot - ValRFE) * ValRSurf) / (CapaREvap + CapaRDE))); // borné à 0 et ValRSurf le 27/04/05 end else begin Evap1 := EvapPot; Evap2 := 0; end; end else begin Evap1 := 0; Evap2 := Max(0, Min(ValRSurf, EvapPot * ValRSurf / (CapaREvap + CapaRDE))); // borné à 0 et ValRSurf le 27/04/05 end; Evap := Evap1 + Evap2; ValRFE := ValRFE - Evap1; ValRSurf := ValRSurf - Evap2; ValRDE := Max(0, ValRSurf - CapaREvap); if (EvapPot = 0) then begin Kr := 0; end else begin Kr := Evap / EvapPot; end; // part de l'évaporation prélevée dans les réservoirs RFE et RDE if (ValRSurf >= CapaREvap) then begin EvapRU := Evap; end else begin if (ValRSurfPrec <= CapaREvap) then begin EvapRU := Evap1; end else begin EvapRU := evap1 + ValRSurfPrec - CapaREvap; end; end; //Evaporation de Ru et Rur, MAJ if (StRurMax <= RuSurf) then begin // quand les racines n'ont pas dépassé la première couche StRur := Max(0, StRur - EvapRU * StRurMax / RuSurf); end else begin StRur := Max(0, StRur - EvapRU); end; StRu := StRu - EvapRU; // Ajout JCS 29/06/2009 KceReal := Kce * Kr; except AfficheMessageErreur('RS_EvolEvapSurfRFE_RDE', URisocas); end; end; procedure RS_EvolEvapSurfRFE_RDE_V2(const NumPhase, Kce, EvapPot, CapaREvap, CapaRDE, CapaRFE, RuRac, RuSurf, {FloodwaterDepth,} BundHeight, EpaisseurSurf, EpaisseurProf, {StockMacropores,} RootFront, ResUtil: Double; var Evap, ValRSurf, ValRFE, ValRDE, StockRac, StockTotal, StockSurface, Kr, KceReal{NEW JUNE 19}, FloodwaterDepth, StockMacropores: Double); var ValRSurfPrec, EvapRU: Double; Evap1, Evap2: Double; begin try // Evaporation in absence of surface water if ((StockMacropores + FloodwaterDepth) = 0) {DELETED JUNE 19}{or (NumPhase = 0)} then begin ValRSurfPrec := ValRSurf; // ValRSurf est l'eau contenue dans les réservoirs Revap (non transpirable) et RDE (transpirable et évaporable if (ValRFE > 0) then begin if (ValRFE < EvapPot) then begin Evap1 := ValRFE; Evap2 := Max(0, Min(ValRSurf, ((EvapPot - ValRFE) * ValRSurf) / (CapaREvap + CapaRDE))); // borné à 0 et ValRSurf le 27/04/05 end else begin Evap1 := EvapPot; Evap2 := 0; end; end else begin Evap1 := 0; Evap2 := Max(0, Min(ValRSurf, EvapPot * ValRSurf / (CapaREvap + CapaRDE))); // borné à 0 et ValRSurf le 27/04/05 end; Evap := Evap1 + Evap2; ValRFE := ValRFE - Evap1; ValRSurf := ValRSurf - Evap2; ValRDE := Max(0, ValRSurf - CapaREvap); if (EvapPot = 0) then begin Kr := 0; end else begin Kr := Evap / EvapPot; end; // part de l'évaporation prélevée dans les réservoirs RFE et RDE if (ValRSurf >= CapaREvap) then begin EvapRU := Evap; end else begin if (ValRSurfPrec <= CapaREvap) then begin EvapRU := Evap1; end else begin EvapRU := evap1 + ValRSurfPrec - CapaREvap; end; end; //Evaporation de Ru et Rur, MAJ if (RuRac <= RuSurf) then begin // quand les racines n'ont pas dépassé la première couche StockRac := Max(0, StockRac - EvapRU * RuRac / RuSurf); end else begin StockRac := Max(0, StockRac - EvapRU); end; StockTotal := StockTotal - EvapRU; StockRac := Min(StockRac, StockTotal); // Ajout JCS 29/06/2009 KceReal := Kce * Kr; end; // Surface water evaporation during crop cycle if (StockMacropores + FloodwaterDepth > 0) and (NumPhase > 0) then begin Evap := EvapPot; ValRSurf := CapaREvap + StockMacropores * (EpaisseurSurf / (EpaisseurSurf + EpaisseurProf)); ValRFE := CapaRFE + StockMacropores * (EpaisseurSurf / (EpaisseurSurf + EpaisseurProf)); ValRDE := CapaRDE; StockRac := RuRac + StockMacropores * (RootFront / (EpaisseurSurf + EpaisseurProf)); StockSurface := RuSurf + StockMacropores * (EpaisseurSurf / (EpaisseurSurf + EpaisseurProf)); StockTotal := (EpaisseurSurf + EpaisseurProf) * ResUtil / 1000 + StockMacropores; StockRac := Min(StockRac, StockTotal); Kr := 1; KceReal := Kce; end; {NEW JUNE 19} // Surface water evaporation before and after crop cycle if (StockMacropores + FloodwaterDepth > 0) and (NumPhase = 0) then begin Evap := EvapPot; FloodwaterDepth := FloodwaterDepth - Evap; If (FloodwaterDepth < 0) then Begin StockMacropores := StockMacropores + FloodwaterDepth; FloodwaterDepth := 0; StockMacropores := Max(StockMacropores, 0); End; ValRSurf := CapaREvap + StockMacropores * (EpaisseurSurf / (EpaisseurSurf + EpaisseurProf)); ValRFE := CapaRFE + StockMacropores * (EpaisseurSurf / (EpaisseurSurf + EpaisseurProf)); ValRDE := CapaRDE; StockSurface := RuSurf + StockMacropores * (EpaisseurSurf / (EpaisseurSurf + EpaisseurProf)); StockTotal := (EpaisseurSurf + EpaisseurProf) * ResUtil / 1000 + StockMacropores; Kr := 1; KceReal := Kce; end; except AfficheMessageErreur('RS_EvolEvapSurfRFE_RDE_V2', URisocas); end; end; procedure RS_EvolConsRes_Flood_V2(const NumPhase, RuRac, RuSurf, CapaREvap, Tr, Evap, CapaRDE, CapaRFE, EpaisseurSurf, EpaisseurProf, ResUtil: Double; var StockRac, StockSurface, StockTotal, ValRFE, ValRDE, ValRSurf, FloodwaterDepth, StockMacropores: Double); var TrSurf: Double; WaterDeficit: Double; begin try TrSurf := 0; StockSurface := ValRFE + ValRDE; if (FloodwaterDepth + StockMacropores = 0) or (NumPhase = 0) then begin // le calcul de cstr et de Tr doit intervenir après l'évaporation // calcul de la part de transpiration affectée aux réservoirs de surface if (RuRac <> 0) then begin if (RuRac <= RuSurf) then //correction JCC le 21/08/02 de stRurMax<=RuSurf/stRurMax begin TrSurf := Tr; end else begin //TrSurf:=Tr*RuSurf/stRurMax;// on peut pondérer ici pour tenir compte du % racines dans chaque couche if (StockRac <> 0) then begin TrSurf := Tr * StockSurface / StockRac; // modif du 15/04/05 pondération par les stocks et non les capacités, sinon on n'extrait pas Tr si stock nul end; end; end else begin TrSurf := 0; end; // MAJ des réservoirs de surface en répartissant TrSurf entre RFE et RDE ValRDE := Max(0, ValRSurf - CapaREvap); if (ValRDE + ValRFE < TrSurf) then begin ValRFE := 0; ValRSurf := ValRSurf - ValRDE; ValRDE := 0; end else begin if (ValRFE > TrSurf) then begin ValRFE := ValRFE - TrSurf; // priorité à la RFU end else begin ValRSurf := ValRSurf - (TrSurf - ValRFE); ValRDE := ValRDE - (TrSurf - ValRFE); ValRFE := 0; end; end; StockSurface := ValRFE + ValRDE; StockRac := Max(0, StockRac - Tr); // 18/04/05 déplacé en fin de procédure, car utilisé pour le calcul de Trsurf StockTotal := Max(0, StockTotal - Tr); StockRac := Min(StockRac, StockTotal); end; if ((StockMacropores + FloodwaterDepth) > 0) and ((StockMacropores + FloodwaterDepth) <= (Tr + Evap)) and (NumPhase > 0) then begin WaterDeficit := (Tr + Evap) - (StockMacropores + FloodwaterDepth); StockMacropores := 0; FloodwaterDepth := 0; StockTotal := (EpaisseurSurf + EpaisseurProf) * ResUtil / 1000 - WaterDeficit; StockRac := RuRac - WaterDeficit; StockRac := Min(StockRac, StockTotal); StockSurface := Max(EpaisseurSurf * ResUtil / 1000 - WaterDeficit, 0); ValRFE := Max(StockSurface - ValRDE - Waterdeficit, 0); ValRDE := ValRDE; ValRSurf := ValRFE + ValRDE; end else begin if ((StockMacropores + FloodwaterDepth) > (Tr + Evap)) and (NumPhase > 0) then begin FloodwaterDepth := FloodwaterDepth - (Tr + Evap); StockMacropores := StockMacropores + Min(0, FloodwaterDepth); FloodwaterDepth := Max(FloodwaterDepth, 0); StockTotal := (EpaisseurSurf + EpaisseurProf) * ResUtil / 1000 + StockMacropores; StockRac := RuRac + StockMacropores; StockRac := Min(StockRac, StockTotal); StockSurface := Max(EpaisseurSurf * ResUtil / 1000 + StockMacropores * (EpaisseurSurf / (EpaisseurSurf + EpaisseurProf)), 0); ValRFE := Max(StockSurface - ValRDE, 0); ValRDE := ValRDE; end; end; except AfficheMessageErreur('RS_EvolConsRes_Flood_V2', URisocas); end; end; procedure RS_EvalConversion(const NumPhase, EpsiB, AssimBVP, SommeDegresJourCor, SommeDegresJourPhasePrecedente, AssimMatu1, AssimMatu2, SeuilTempPhaseSuivante: Double; var Conversion: Double); var KAssim: Double; begin try { Modif JCC du 21/04/05 en phase BVP KAssim est toujours = 1, sinon autant modifier Tx Conversion. Ensuite Kdf augmente et on ne sait pas simuler cette variation. On va jouer sur AssimBVP, que l'on pourra d'ailleurs renommer AssimRPR} case trunc(NumPhase) of 2: KAssim := 1; 3..4: KAssim := AssimBVP; 5: KAssim := AssimBVP + (SommeDegresJourCor - SommeDegresJourPhasePrecedente) * (AssimMatu1 - AssimBVP) / (SeuilTempPhaseSuivante - SommeDegresJourPhasePrecedente); 6: KAssim := AssimMatu1 + (SommeDegresJourCor - SommeDegresJourPhasePrecedente) * (AssimMatu2 - AssimMatu1) / (SeuilTempPhaseSuivante - SommeDegresJourPhasePrecedente); else KAssim := 0; end; Conversion := KAssim * EpsiB; //if Conversion < 0 then //Conversion := 0; except AfficheMessageErreur('RS_EvalConversion | NumPhase: ' + FloatToStr(NumPhase) + ' SommeDegresJourCor: ' + FloatToStr(SommeDegresJourCor), URisocas); end; end; procedure RS_EvolPSPMVMD(const Numphase, ChangePhase, SomDegresJourCor, DegresDuJourCor, SeuilPP, PPCrit, DureeDuJour, PPExp: Double; var SumPP, SeuilTempPhasePrec, SeuilTempPhaseSuivante: Double); var SDJPSP: Double; {Procedure speciale Vaksman Dingkuhn valable pour tous types de sensibilite photoperiodique et pour les varietes non photoperiodique. PPsens varie de 0,4 a 1,2. Pour PPsens > 2,5 = variété non photoperiodique. SeuilPP = 13.5 PPcrit = 12 SumPP est dans ce cas une variable quotidienne (et non un cumul) testee dans EvolPhenoPhotoperStress} begin try if (NumPhase = 3) then begin if (ChangePhase = 1) then begin SumPP := 100; //valeur arbitraire d'initialisation >2.5 SDJPSP := Max(0.01, DegresDuJourCor); end else begin SDJPSP := SomDegresJourCor - SeuilTempPhasePrec + Max(0.01, DegresDuJourCor); end; SumPP := Power((1000 / SDJPSP), PPExp) * Max(0, (DureeDuJour - PPCrit)) / (SeuilPP - PPCrit); SeuilTempPhaseSuivante := SeuilTempPhasePrec + SDJPSP; end; except AfficheMessageErreur('RS_EvolPSPMVMD', URisocas); end; end; procedure RS_EvolSomDegresJourCor(const DegresDuJourCor, NumPhase: Double; var SommeDegresJourCor: Double); begin try if (NumPhase >= 1) then // on ne cumule qu'après la germination begin SommeDegresJourCor := SommeDegresJourCor + DegresDuJourCor; end else begin SommeDegresJourCor := 0; end; except AfficheMessageErreur('RS_EvolSomDegresJourCor', URisocas); end; end; procedure RS_EvalMaximumLai(const NumPhase, ChangePhase, Lai: Double; var TempLai, MaximumLai: Double); begin try if (Lai > TempLai) then begin TempLai := Lai; end; if (NumPhase <> 7) then begin MaximumLai := 0; end else if (NumPhase = 7) and (ChangePhase = 1) then begin MaximumLai := TempLai; end; except AfficheMessageErreur('RS_EvalMaximumLai', URisocas); end; end; procedure RS_EvalVitesseRacinaire(const VRacLevee, RootSpeedBVP, RootSpeedRPR, RootSpeedPSP, RootSpeedMatu1, RootSpeedMatu2, RootCstr, cstr, NumPhase, DegreDuJourCor: Double; //DegreDuJour ou DegreDuJourCor? var VitesseRacinaire, VitesseRacinaireDay: Double); //Modif JCC du 15/03/2005 pour inclure VracLevée différente de VRacBVP begin try case Trunc(NumPhase) of 1: VitesseRacinaire := VRacLevee; 2: VitesseRacinaire := RootSpeedBVP; 3: VitesseRacinaire := RootSpeedPSP; 4: VitesseRacinaire := RootSpeedRPR; 5: VitesseRacinaire := RootSpeedMatu1; { TODO : attention en cas de gestion du champ vide... } 6: VitesseRacinaire := RootSpeedMatu2; else VitesseRacinaire := 0 end; VitesseRacinaireDay := VitesseRacinaire * DegreDuJourCor * Power(cstr, RootCstr); except AfficheMessageErreur('EvalVitesseRacinaire | NumPhase: ' + FloatToStr(NumPhase), URisocas); end; end; procedure RS_EvolDryMatTot(const NumPhase, ChangePhase, PlantsPerHill, TxResGrain, PoidsSecGrain, Densite, GrowthStructLeafPop, GrowthStructSheathPop, GrowthStructRootPop, GrowthStructInternodePop, GrowthStructPaniclePop, GrowthStructTotPop, GrowthResInternodePop, GrainYieldPop, ResCapacityInternodePop, CulmsPerPlant, CoeffPanSinkPop, SterilityTot: Double; var DryMatStructLeafPop, DryMatStructSheathPop, DryMatStructRootPop, DryMatStructInternodePop, DryMatStructPaniclePop, DryMatStructStemPop, DryMatStructTotPop, DryMatResInternodePop, DryMatVegeTotPop, DryMatPanicleTotPop, DryMatAboveGroundPop, DryMatTotPop, HarvestIndex, InternodeResStatus, PanicleNumPop, PanicleNumPlant, GrainYieldPanicle, SpikeNumPop, SpikeNumPanicle, FertSpikeNumPop, GrainFillingStatus, RootShootRatio: Double); begin try if ((NumPhase = 2) and (ChangePhase = 1)) then begin DryMatTotPop := Densite * PlantsPerHill * TxResGrain * PoidsSecGrain / 1000; DryMatStructLeafPop := DryMatTotPop * 0.5; end else begin if (NumPhase > 1) then begin DryMatStructLeafPop := DryMatStructLeafPop + GrowthStructLeafPop; DryMatStructSheathPop := DryMatStructSheathPop + GrowthStructSheathPop; DryMatStructRootPop := DryMatStructRootPop + GrowthStructRootPop; DryMatStructInternodePop := DryMatStructInternodePop + GrowthStructInternodePop; DryMatStructPaniclePop := DryMatStructPaniclePop + GrowthStructPaniclePop; DryMatStructStemPop := DryMatStructSheathPop + DryMatStructInternodePop + DryMatResInternodePop; DryMatStructTotPop := DryMatStructLeafPop + DryMatStructSheathPop + DryMatStructRootPop + DryMatStructInternodePop + DryMatStructPaniclePop; DryMatVegeTotPop := DryMatStructTotPop + DryMatResInternodePop - DryMatStructPaniclePop; DryMatPanicleTotPop := DryMatStructPaniclePop + GrainYieldPop; DryMatTotPop := DryMatVegeTotPop + GrainYieldPop; DryMatAboveGroundPop := DryMatTotPop - DryMatStructRootPop; RootShootRatio := DryMatStructRootPop / DryMatAboveGroundPop; if (ResCapacityInternodePop = 0) then begin InternodeResStatus := 0; end else begin InternodeResStatus := DryMatResInternodePop / ResCapacityInternodePop; end; end; if (NumPhase > 4) then begin HarvestIndex := GrainYieldPop / DryMatAboveGroundPop; PanicleNumPlant := CulmsPerPlant; PanicleNumPop := CulmsPerPlant * Densite * PlantsPerHill; GrainYieldPanicle := 1000 * GrainYieldPop / PanicleNumPop; SpikeNumPop := 1000000 * DryMatStructPaniclePop * CoeffPanSinkPop / PoidsSecGrain; SpikeNumPanicle := SpikeNumPop / PanicleNumPop; FertSpikeNumPop := SpikeNumPop * (1 - SterilityTot); GrainFillingStatus := 1000000 * (GrainYieldPop / FertSpikeNumPop) / PoidsSecGrain; end; end; except AfficheMessageErreur('RS_EvolDryMatTot', URisocas); end; end; procedure RS_EvolDryMatTot_V2(const NumPhase, ChangePhase, PlantsPerHill, TxResGrain, PoidsSecGrain, Densite, GrowthStructLeafPop, GrowthStructSheathPop, GrowthStructRootPop, GrowthStructInternodePop, GrowthStructPaniclePop, GrowthStructTotPop, GrowthResInternodePop, GrainYieldPop, ResCapacityInternodePop, CulmsPerPlant, CoeffPanSinkPop, SterilityTot, DeadLeafdrywtPop {NEW LB}, DryMatResInternodePopOld, PanicleFilPop , AssimNotUsedCum {NEW R} , MobiliLeafDeath: Double; var DryMatStructLeafPop, DryMatStructSheathPop, DryMatStructRootPop, DryMatStructInternodePop, DryMatStructPaniclePop, {NEW LB} DryMatStemPop {/NEW LB}, DryMatStructTotPop, DryMatResInternodePop, DryMatVegeTotPop, DryMatPanicleTotPop, DryMatAboveGroundPop, DryMatTotPop, HarvestIndex, InternodeResStatus, PanicleNumPop, PanicleNumPlant, GrainYieldPanicle, SpikeNumPop, SpikeNumPanicle, FertSpikeNumPop, GrainFillingStatus, RootShootRatio , DryMatAboveGroundTotPop , {NEW LB} CumGrowthPop, GrowthPop , CumCarbonUsedPop : Double); begin try {NEW LB} CumGrowthPop := CumGrowthPop + GrowthStructLeafPop + GrowthStructSheathPop + GrowthStructInternodepop + GrowthStructRootPop + GrowthStructPaniclePop + (DryMatResInternodePop - DryMatResInternodePopOld) + PanicleFilPop {NEW R} - MobiliLeafDeath; GrowthPop := GrowthStructLeafPop + GrowthStructSheathPop + GrowthStructInternodepop + GrowthStructRootPop + GrowthStructPaniclePop + (DryMatResInternodePop - DryMatResInternodePopOld) + PanicleFilPop {NEW R} - MobiliLeafDeath; // Output Test variable for carbon balance (consider also AssimNotUsedCum) {/NEW LB} if ((NumPhase = 2) and (ChangePhase = 1)) then begin DryMatTotPop := Densite * PlantsPerHill * TxResGrain * PoidsSecGrain / 1000; DryMatStructLeafPop := DryMatTotPop * 0.5; end else begin if (NumPhase > 1) then begin DryMatStructLeafPop := DryMatStructLeafPop + GrowthStructLeafPop; DryMatStructSheathPop := DryMatStructSheathPop + GrowthStructSheathPop; DryMatStructRootPop := DryMatStructRootPop + GrowthStructRootPop; DryMatStructInternodePop := DryMatStructInternodePop + GrowthStructInternodePop; DryMatStructPaniclePop := DryMatStructPaniclePop + GrowthStructPaniclePop; DryMatStemPop := DryMatStructSheathPop + DryMatStructInternodePop + DryMatResInternodePop; DryMatStructTotPop := DryMatStructLeafPop + DryMatStructSheathPop + DryMatStructRootPop + DryMatStructInternodePop + DryMatStructPaniclePop; DryMatVegeTotPop := DryMatStemPop + DryMatStructLeafPop + DryMatStructRootPop {DELETED LB} {+ DryMatResInternodePop} + DeadLeafDryWtPop;{DELETED LB}{DryMatStructTotPop + DryMatResInternodePop - DryMatStructPaniclePop;} DryMatPanicleTotPop := DryMatStructPaniclePop + GrainYieldPop; DryMatTotPop := DryMatVegeTotPop {NEW LB}+ DrymatPanicleTotPop{/NEW LB};{DELETED LB} {+ GrainYieldPop} {NEW Y}{+ DryMatStructPaniclePop }{/NEW Y}{NEW G}{+ DeadLeafDryWtPop}{/NEW G}{;} DryMatAboveGroundPop := DryMatTotPop - DryMatStructRootPop {NEW LB} - DeadLeafDryWtPop; {NEW Y} DryMatAboveGroundTotPop := DryMatAboveGroundPop + DeadLeafDrywtPop; {/NEW Y} {NEW LB} CumCarbonUsedPop := DryMatTotPop + AssimNotUsedCum; // This should be equal to CumSupplyTot! {/NEW LB} RootShootRatio := DryMatStructRootPop / DryMatAboveGroundPop; if (ResCapacityInternodePop = 0) then begin InternodeResStatus := 0; end else begin InternodeResStatus := DryMatResInternodePop / ResCapacityInternodePop; end; end; if (NumPhase > 4) then begin HarvestIndex := GrainYieldPop / {NEW LB}DryMatAboveGroundTotPop; // This includes dead leaves PanicleNumPlant := CulmsPerPlant; PanicleNumPop := CulmsPerPlant * Densite * PlantsPerHill; GrainYieldPanicle := 1000 * GrainYieldPop / PanicleNumPop; SpikeNumPop := 1000 * DryMatStructPaniclePop * CoeffPanSinkPop / PoidsSecGrain; SpikeNumPanicle := SpikeNumPop / PanicleNumPop; FertSpikeNumPop := SpikeNumPop * (1 - SterilityTot); GrainFillingStatus := 1000 * (GrainYieldPop / FertSpikeNumPop) / PoidsSecGrain; end; end; except on E : Exception do AfficheMessageErreur('RS_EvolDryMatTot_V2 '+E.message, URisocas); end; end; procedure RS_InitiationCulture(const SeuilTempLevee, SeuilTempBVP, SeuilTempRPR, SeuilTempMatu1, SeuilTempMatu2: Double; var SommeDegresJourMaximale, NumPhase, SommeDegresJour, SeuilTempPhaseSuivante, Lai, IcCumul, FTSW, cstr, DurPhase1, DurPhase2, DurPhase3, DurPhase4, DurPhase5, DurPhase6, TempLai, ApexHeightGain, ChangeNurseryStatus, ChangePhase, ChangeSsPhase, CstrPhase2, CstrPhase3, CstrPhase4, CstrPhase5, CstrPhase6, CumCstrPhase2, CumCstrPhase3, CumCstrPhase4, CumCstrPhase5, CumCstrPhase6, CumFTSWPhase2, CumFTSWPhase3, CumFTSWPhase4, CumFTSWPhase5, CumFTSWPhase6, CumIcPhase2, CumIcPhase3, CumIcPhase4, CumIcPhase5, CumIcPhase6, DAF, DemLeafAreaPlant, DemPanicleFillPop, DemStructInternodePlant, DemStructInternodePop, DemStructLeafPlant, DemStructLeafPop, DemStructPaniclePlant, DemStructPaniclePop, DemStructRootPlant, DemStructRootPop, DemStructSheathPop, DemStructTotPop, FloodWaterGain, FtswPhase2, FtswPhase3, FtswPhase4, FtswPhase5, FtswPhase6, GainRootSystSoilSurfPop, GainRootSystVolPop, GrowthDryMatPop, GrowthResInternodePop, GrowthStructDeficit, GrowthStructInternodePop, GrowthStructLeafPop, GrowthStructPaniclePop, GrowthStructRootPop, GrowthStructSheathPop, GrowthStructTotPop, HaunGain, IcPhase2, IcPhase3, IcPhase4, IcPhase5, IcPhase6, IncreaseResInternodePop, Kcl, Kr, MobiliLeafDeath, NbDaysSinceGermination, NurseryStatus, PanicleFilDeficit, PanicleFilPop, PanicleSinkPop, PanStructMass, PlantLeafNumNew, ResInternodeMobiliDay, ResInternodeMobiliDayPot, RootFrontOld, RootSystSoilSurfPop, RootSystSoilSurfPopOld, RootSystVolPop, RootSysVolPopOld, SDJCorPhase4 : Double); begin try NumPhase := 0; SommeDegresJourMaximale := SeuilTempLevee + SeuilTempBVP + SeuilTempRPR + SeuilTempMatu1 + SeuilTempMatu2; SommeDegresJour := 0; SeuilTempPhaseSuivante := 0; Lai := 0; IcCumul := 0; FTSW := 1; cstr := 1; DurPhase1 := 0; DurPhase2 := 0; DurPhase3 := 0; DurPhase4 := 0; DurPhase5 := 0; DurPhase6 := 0; TempLai := 0; ApexHeightGain := 0; ChangeNurseryStatus := 0; ChangePhase := 0; ChangeSsPhase := 0; CstrPhase2 := 0; CstrPhase3 := 0; CstrPhase4 := 0; CstrPhase5 := 0; CstrPhase6 := 0; CumCstrPhase2 := 0; CumCstrPhase3 := 0; CumCstrPhase4 := 0; CumCstrPhase5 := 0; CumCstrPhase6 := 0; CumFTSWPhase2 := 0; CumFTSWPhase3 := 0; CumFTSWPhase4 := 0; CumFTSWPhase5 := 0; CumFTSWPhase6 := 0; CumIcPhase2 := 0; CumIcPhase3 := 0; CumIcPhase4 := 0; CumIcPhase5 := 0; CumIcPhase6 := 0; DAF := 0; DemLeafAreaPlant := 0; DemPanicleFillPop := 0; DemStructInternodePlant := 0; DemStructInternodePop := 0; DemStructLeafPlant := 0; DemStructLeafPop := 0; DemStructPaniclePlant := 0; DemStructPaniclePop := 0; DemStructRootPlant := 0; DemStructRootPop := 0; DemStructSheathPop := 0; DemStructTotPop := 0; FloodWaterGain := 0; FtswPhase2 := 0; FtswPhase3 := 0; FtswPhase4 := 0; FtswPhase5 := 0; FtswPhase6 := 0; GainRootSystSoilSurfPop := 0; GainRootSystVolPop := 0; GrowthDryMatPop := 0; GrowthResInternodePop := 0; GrowthStructDeficit := 0; GrowthStructInternodePop := 0; GrowthStructLeafPop := 0; GrowthStructPaniclePop := 0; GrowthStructRootPop := 0; GrowthStructSheathPop := 0; GrowthStructTotPop := 0; HaunGain := 0; IcPhase2 := 0; IcPhase3 := 0; IcPhase4 := 0; IcPhase5 := 0; IcPhase6 := 0; IncreaseResInternodePop := 0; Kcl := 0; Kr := 0; MobiliLeafDeath := 0; NbDaysSinceGermination := 0; NurseryStatus := 0; PanicleFilDeficit := 0; PanicleFilPop := 0; PanicleSinkPop := 0; PanStructMass := 0; PlantLeafNumNew := 0; ResInternodeMobiliDay := 0; ResInternodeMobiliDayPot := 0; RootFrontOld := 0; RootSystSoilSurfPop := 0; RootSystSoilSurfPopOld := 0; RootSystVolPop := 0; RootSysVolPopOld := 0; SDJCorPhase4 := 0; except AfficheMessageErreur('RS_InitiationCulture', URisocas); end; end; procedure RS_InitiationCulture_V2(const SeuilTempLevee, SeuilTempBVP, SeuilTempRPR, SeuilTempMatu1, SeuilTempMatu2, EpaisseurSurf, EpaisseurProf, VolRelMacropores: Double; var SommeDegresJourMaximale, NumPhase, SommeDegresJour, SeuilTempPhaseSuivante, Lai, IcCumul, VolMacropores: Double); begin try NumPhase := 0; SommeDegresJourMaximale := SeuilTempLevee + SeuilTempBVP + SeuilTempRPR + SeuilTempMatu1 + SeuilTempMatu2; SommeDegresJour := 0; SeuilTempPhaseSuivante := 0; Lai := 0; IcCumul := 0; VolMacropores := VolRelMacropores * (EpaisseurSurf + EpaisseurProf) / 100; except AfficheMessageErreur('RS_InitiationCulture_V2', URisocas); end; end; procedure RS_EvolGrowthStructTot(const NumPhase {SHIFTED LB}{, GrowthStructLeafPop, GrowthStructSheathPop, GrowthStructRootPop, GrowthStructInternodePop, GrowthStructPaniclePop } {/SHIFTED LB}, SupplyTot, GrowthResInternodePop: Double; var GrowthStructTotPop, AssimSurplus {SHIFTED LB} , GrowthStructLeafPop, GrowthStructSheathPop, GrowthStructRootPop, GrowthStructInternodePop, GrowthStructPaniclePop {/SHIFTED LB} ,A_GrowthStructLeaf, A_GrowthStructTot, A_AssimSurplus : Double); begin try if ((NumPhase > 1) and (NumPhase < 5)) then begin GrowthStructTotPop := GrowthStructLeafPop + GrowthStructSheathPop + GrowthStructRootPop + GrowthStructInternodePop + GrowthStructPaniclePop {NEW P}+ GrowthResInternodePop; A_GrowthStructTot := GrowthStructTotPop; AssimSurplus := Max((SupplyTot - GrowthStructTotPop {DELETED}{- GrowthResInternodePop}), 0); A_AssimSurplus := Max((SupplyTot - GrowthStructTotPop {DELETED}{- GrowthResInternodePop}), 0); end {NEW LB} else begin GrowthStructLeafPop := 0; A_GrowthStructLeaf := GrowthStructLeafPop; GrowthStructSheathPop := 0; GrowthStructInternodePop := 0; GrowthStructRootPop := 0; GrowthStructPaniclePop := 0; GrowthStructTotPop := 0; A_GrowthStructTot := GrowthStructTotPop; end; {/NEW LB} except AfficheMessageErreur('RS_EvolGrowthStructTot', URisocas); end; end; procedure RS_LeafRolling(const NumPhase, RollingBase, RollingSens, FTSW, Eto: Double; var KRolling: Double); begin try if (NumPhase > 1) then begin KRolling := RollingBase + (1 - RollingBase) * Power(FTSW, Max(0.0000001, Eto * RollingSens)); if KRolling > 1 then KRolling := 1; end; except AfficheMessageErreur('RS_LeafRolling', URisocas); end; end; procedure RS_EvalRootFront(const NumPhase, RuRac, ResUtil: Double; var RootFront: Double); begin try if (NumPhase > 0) then begin RootFront := ((1 / ResUtil) * RuRac) * 1000; end; except AfficheMessageErreur('RS_EvalRootFront', URisocas); end; end; procedure RS_EvalSDJPhase4(const NumPhase, DegreDuJourCor: Double; var SDJPhase4: Double); begin try if (NumPhase = 4) then begin SDJPhase4 := SDJPhase4 + DegreDuJourCor; end; except AfficheMessageErreur('RS_EvalSDJPhase4', URisocas); end; end; procedure RS_EvalDateGermination(const NumPhase, ChangePhase: Double; var NbDaysSinceGermination: double); begin try if ((NumPhase < 1) or ((NumPhase = 1) and (ChangePhase = 1))) then begin NbDaysSinceGermination := 0; end else begin NbDaysSinceGermination := NbDaysSinceGermination + 1; end; except AfficheMessageErreur('RS_EvalDateGermination', URisocas); end; end; procedure RS_EvalSterility(const Numphase, ChangePhase, KCritSterCold1, KCritSterCold2, KCritSterHeat1, KCritSterHeat2, KCritSterFtsw1, KCritSterFtsw2, TMinMoy, TMaxMoy, FtswMoy: Double; var SterilityCold, SterilityHeat, SterilityDrought, SterilityTot: Double); begin try if ((NumPhase = 5) and (ChangePhase = 1)) then begin SterilityCold := Max(0, (Min(1, KCritSterCold1 / (KCritSterCold1 - KCritSterCold2) - TMinMoy / (KCritSterCold1 - KCritSterCold2)))); SterilityHeat := 1 - Max(0, (Min(1, KCritSterHeat2 / (KCritSterHeat2 - KCritSterHeat1) - TMaxMoy / (KCritSterHeat2 - KCritSterHeat1)))); SterilityDrought := Max(0, (Min(1, KCritSterFtsw1 / (KCritSterFtsw1 - KCritSterFtsw2) - FtswMoy / (KCritSterFtsw1 - KCritSterFtsw2)))); end else begin SterilityCold := SterilityCold; SterilityHeat := SterilityHeat; SterilityDrought := SterilityDrought; end; SterilityTot := Min(0.999, 1 - ((1 - SterilityCold) * (1 - SterilityHeat) * (1 - SterilityDrought))); except AfficheMessageErreur('RS_EvalSterility', URisocas); end; end; procedure RS_ResetVariablesToZero(const NumPhase, ChangePhase: Double; var CulmsPerPlant, CulmsPerHill, CulmsPop, GrainYieldPop, DryMatStructLeafPop, DryMatStructSheathPop, DryMatStructRootPop, DryMatStructInternodePop, DryMatResInternodePop, DryMatStructPaniclePop, DryMatStructStemPop, DryMatStructTotPop, DryMatVegeTotPop, DryMatPanicleTotPop, DryMatAboveGroundPop, DryMatTotPop, HarvestIndex, PanicleNumPop, PanicleNumPlant, GrainYieldPanicle, SpikeNumPop, SpikeNumPanicle, FertSpikePop, GrainFillingStatus, PhaseStemElongation, Sla, HaunIndex, ApexHeight, PlantHeight, PlantWidth, VitesseRacinaireDay, Kcl, KRolling, LIRKdfcl, LtrKdfcl, AssimPot, Assim, RespMaintTot, SupplyTot, AssimSurplus, AssimNotUsed, AssimNotUsedCum, TillerDeathPop, DeadLeafDryWtPop, ResCapacityInternodePop, InternodeResStatus, cstr, FTSW , DryMatAboveGroundTotPop: Double); begin try if ((NumPhase = 7) and (ChangePhase = 1)) then begin CulmsPerPlant := 0; CulmsPerHill := 0; CulmsPop := 0; GrainYieldPop := 0; DryMatStructLeafPop := 0; DryMatStructSheathPop := 0; DryMatStructRootPop := 0; DryMatStructInternodePop := 0; DryMatResInternodePop := 0; DryMatStructPaniclePop := 0; DryMatStructStemPop := 0; DryMatStructTotPop := 0; DryMatVegeTotPop := 0; DryMatPanicleTotPop := 0; DryMatAboveGroundPop := 0; DryMatTotPop := 0; HarvestIndex := 0; PanicleNumPop := 0; PanicleNumPlant := 0; GrainYieldPanicle := 0; SpikeNumPop := 0; SpikeNumPanicle := 0; FertSpikePop := 0; GrainFillingStatus := 0; PhaseStemElongation := 0; Sla := 0; HaunIndex := 0; ApexHeight := 0; PlantHeight := 0; PlantWidth := 0; VitesseRacinaireDay := 0; Kcl := 0; KRolling := 0; LIRKdfcl := 0; LTRKdfcl := 1; AssimPot := 0; Assim := 0; RespMaintTot := 0; SupplyTot := 0; AssimSurplus := 0; AssimNotUsed := 0; AssimNotUsedCum := 0; TillerDeathPop := 0; DeadLeafDryWtPop := 0; ResCapacityInternodePop := 0; InternodeResStatus := 0; cstr := 0; FTSW := 0; DryMatAboveGroundTotPop := 0; end; except AfficheMessageErreur('RS_ResetVariablesToZero', URisocas); end; end; procedure RS_InitParcelle(const StockIniSurf, StockIniProf, Ru, EpaisseurSurf, EpaisseurProf, HumPF, PEvap, DateSemis: Double; var StTot, LTRkdfcl, Hum, RuSurf, ProfRU, StRuMax, CapaREvap, CapaRFE, CapaRDE, ValRSurf, ValRDE, ValRFE, StockSurface: Double); var Stockini2: Double; Stockini1: Double; begin try ProfRU := EpaisseurSurf + EpaisseurProf; // à supprimer ultérieurement dans les différents modules RuSurf := Ru * EpaisseurSurf / 1000; CapaREvap := 0.5 * EpaisseurSurf * HumPF; CapaRFE := PEvap * (CapaREvap + RuSurf); CapaRDE := RuSurf - CapaRFE; StRuMax := Ru * ProfRu / 1000; Stockini1 := Min(StockIniSurf, CapaREvap + RuSurf); Stockini2 := Min(StockIniProf, Ru * EpaisseurProf / 1000); ValRSurf := Min(Stockini1, CapaREvap + CapaRDE); ValRDE := Max(0, ValRSurf - CapaREvap); ValRFE := Max(0, Stockini1 - (CapaREvap + CapaRDE)); StockSurface := ValRDE + ValRFE; StTot := StockSurface + Stockini2; //transpirable Hum := StTot; LTRkdfcl := 1; except AfficheMessageErreur('RS_InitParcelle', URisocas); end; end; procedure RS_InitParcelle_V2(const StockIniSurf, StockIniProf, EpaisseurSurf, EpaisseurProf, HumPF, HumFC, HumSat, PEvap, DateSemis : Double; var ResUtil, StockTotal, LTRkdfcl, Hum, RuSurf, ProfRU, StRuMax, CapaREvap, CapaRFE, CapaRDE, ValRSurf, ValRDE, ValRFE, StockSurface, CounterNursery, VolRelMacropores, VolMacropores, LIRkdf, LTRkdf: Double); var Stockini2: Double; Stockini1: Double; begin try VolRelMacropores := 100 * (HumSat - HumFC); ResUtil := (HumFC - HumPF) * 1000; ProfRU := EpaisseurSurf + EpaisseurProf; // à supprimer ultérieurement dans les différents modules RuSurf := ResUtil * EpaisseurSurf / 1000; CapaREvap := 0.5 * EpaisseurSurf * HumPF; CapaRFE := PEvap * (CapaREvap + RuSurf); CapaRDE := RuSurf - CapaRFE; StRuMax := ResUtil * ProfRu / 1000; Stockini1 := Min(StockIniSurf, CapaREvap + RuSurf); Stockini2 := Min(StockIniProf, ResUtil * EpaisseurProf / 1000); ValRSurf := Min(Stockini1, CapaREvap + CapaRDE); ValRDE := Max(0, ValRSurf - CapaREvap); ValRFE := Max(0, Stockini1 - (CapaREvap + CapaRDE)); StockSurface := ValRDE + ValRFE; StockTotal := StockSurface + Stockini2; //transpirable Hum := StockTotal; LTRkdfcl := 1; LIRkdf := 0; LTRkdf := 0; CounterNursery := 0; VolMacropores := VolRelMacropores * (EpaisseurSurf + EpaisseurProf) / 100; except AfficheMessageErreur('RS_InitParcelle_V2', URisocas); end; end; procedure RS_EvalAssimPot(const PARIntercepte, PAR, Conversion, Tmax, Tmin, Tbase, Topt1, DayLength, StressCold, CO2Exp, Ca , CO2Cp {NEW Y}, SlaMin , Sla , CoeffAssimSla : Double; var AssimPot, CoeffCO2Assim: Double); begin try begin if (-CO2Exp <> 0) and (CO2Cp <> 0) then CoeffCO2Assim := (1 - exp(-CO2Exp * (Ca - CO2Cp))) / (1 - exp(-CO2Exp * (400 - CO2Cp))); // This coefficient always equals 1 at 400ppm CO2 and describes AssimPot response to Ca AssimPot := PARIntercepte * Conversion * 10 * CoeffCO2Assim; // Ordinary linear effect on intercepted light on canopy assimulation , multiplied by CO2 effect AssimPot := AssimPot * Min(((3 * Tmax + Tmin) / 4 - Tbase) / (Topt1 - Tbase), 1); // Reduction of assimilation at diurnal temperatures < Topt1 AssimPot := AssimPot * Sqrt(Max(0.00001, StressCold)); // Cold stress effect on AssimPot (affects also organ demands and grain filling) if ((PARIntercepte <> 0) and (DayLength <> 0)) then begin AssimPot := AssimPot * Power( (PAR / DayLength), 0.667) / (PAR / DayLength); // De-linearization of PAR response of AssimPot. At 1 MJ/h (cloudless) effect is zero {NEW Y} AssimPot := AssimPot * Power((SlaMin / Max(Sla, SlaMin)), CoeffAssimSla); // Effect of SLA on AssimPot ; AssimPot is reduced if Sla>SlaMin; For no effect set parameter CoeffAssimSla=0, for proportional effect set CoeffAssimSla=1. Intermediate values are OK. end; end; except on E : Exception do begin AfficheMessageErreur('RS_EvalAssimPot ', URisocas); end; end; end; procedure RS_EvalEvapPot(const Etp, Kce: Double; var EvapPot: Double); begin try EvapPot := Kce * Etp; except AfficheMessageErreur('RS_EvalEvapPot', URisocas); end; end; procedure RS_Transplanting_V2(const NumPhase, DensityNursery, DensityField, DurationNursery, PlantsPerHill, Transplanting: Double; var NurseryStatus, ChangeNurseryStatus, CounterNursery, Density, DryMatStructLeafPop, DryMatStructSheathPop, DryMatStructRootPop, DryMatStructInternodePop, DryMatStructPaniclePop, DryMatResInternodePop: Double); var DensityChange: Double; begin try DensityChange := DensityField / (DensityNursery / PlantsPerHill); if ((Transplanting = 1) and (NumPhase >= 1)) then begin CounterNursery := CounterNursery + 1; end; if ((Transplanting = 1) and (CounterNursery < DurationNursery) and (ChangeNurseryStatus = 0)) then begin NurseryStatus := 0; ChangeNurseryStatus := 0; end else begin if ((Transplanting = 1) and (CounterNursery >= DurationNursery) and (ChangeNurseryStatus = 0) and (NurseryStatus = 0)) then begin NurseryStatus := 1; ChangeNurseryStatus := 1; end else begin NurseryStatus := 1; ChangeNurseryStatus := 0; end; end; if (NurseryStatus = 1) then begin Density := DensityField; end else begin Density := DensityNursery / PlantsPerHill; end; if (ChangeNurseryStatus = 1) then begin DryMatStructLeafPop := DryMatStructLeafPop * DensityChange; DryMatStructSheathPop := DryMatStructSheathPop * DensityChange; DryMatStructRootPop := DryMatStructRootPop * DensityChange; DryMatStructInternodePop := DryMatStructInternodePop * DensityChange; DryMatStructPaniclePop := DryMatStructPaniclePop * DensityChange; DryMatResInternodePop := DryMatResInternodePop * DensityChange; end; except AfficheMessageErreur('RS_Transplanting_V2', URisocas); end; end; procedure RS_TransplantingShock_V2(const CounterNursery, CoeffTransplantingShock: Double; var Assim: Double); begin try if ((CounterNursery > 0) and (CounterNursery < 8)) then begin Assim := Assim * CoeffTransplantingShock; end else begin Assim := Assim; end; except AfficheMessageErreur('RS_TransplantingShock_V2', URisocas); end; end; procedure RS_EvalRuiss_FloodDyna_V2(const NumPhase, Rain, SeuilRuiss, PourcRuiss, BundHeight, Irrigation, PlantHeight, LifeSavingDrainage, PlotDrainageDAF, VolMacropores, SuilRuiss, PercolationMax, DAF: Double; var StockMacropores, FloodwaterDepth, EauDispo, Lr: Double); var CorrectedIrrigation: Double; CorrectedBundheight: Double; begin try Lr := 0; CorrectedBundheight := Bundheight; // implement lifesaving drainage if (LifeSavingDrainage = 1) and (FloodwaterDepth > (0.5 * PlantHeight)) and (PlantHeight > 0) and (NumPhase > 1) and (BundHeight > 0) then begin CorrectedBundheight := 0.5 * PlantHeight; Lr := Lr + Max(0, FloodwaterDepth - (0.5 * PlantHeight)); FloodwaterDepth := Min(FloodwaterDepth, (0.5 * PlantHeight)); if (FloodwaterDepth + StockMacropores > 0) then begin EauDispo := FloodwaterDepth + StockMacropores; end; end; // implement terminal drainage if (NumPhase > 4) and (NumPhase < 7) and (DAF > PlotDrainageDAF) and (BundHeight > 0) then begin CorrectedBundHeight := 0; Lr := Lr + FloodwaterDepth; FloodWaterDepth := 0; if ((FloodwaterDepth + StockMacropores) > 0) then begin EauDispo := StockMacropores; end else begin EauDispo := Rain; end; end; // define corrected irrigation if (Irrigation = NullValue) then begin CorrectedIrrigation := 0; end else begin CorrectedIrrigation := Irrigation; end; // implement runoff and EauDispo under terminal drainage if (CorrectedBundHeight = 0) and (BundHeight <> CorrectedBundHeight) then begin if ((StockMacropores + FloodwaterDepth) = 0) then begin EauDispo := Rain + CorrectedIrrigation; end else begin StockMacropores := StockMacropores + Rain + CorrectedIrrigation; Lr := Lr + Max(0, StockMacropores - VolMacropores); StockMacropores := StockMacropores - Max(0, StockMacropores - VolMacropores); EauDispo := StockMacropores; end; end; // implement classical upland runoff (SARRAH) if (BundHeight = 0) then begin if (Rain > SuilRuiss) then begin Lr := Lr + (Rain + CorrectedIrrigation - SeuilRuiss) * PourcRuiss / 100; EauDispo := Rain + CorrectedIrrigation - Lr; end else begin EauDispo := Rain + CorrectedIrrigation; end; end; // implement bunded-plot style water ponding and runoff, regular situation w/o drainage if (CorrectedBundHeight > 0) then begin if ((StockMacropores + FloodwaterDepth) = 0) then begin Lr := Lr + Max((Rain + CorrectedIrrigation - BundHeight - VolMacropores), 0); EauDispo := Min(Rain + CorrectedIrrigation, BundHeight + VolMacropores); end else begin StockMacropores := StockMacropores + Rain + CorrectedIrrigation; FloodwaterDepth := FloodwaterDepth + Max(0, StockMacropores - VolMacropores); StockMacropores := Min(VolMacropores, StockMacropores); Lr := Lr + Max(0, FloodwaterDepth - CorrectedBundHeight); FloodwaterDepth := Min(FloodwaterDepth, CorrectedBundHeight); EauDispo := StockMacropores + FloodwaterDepth; end; end; except AfficheMessageErreur('RS_EvalRuiss_FloodDyna_V2', URisocas); end; end; procedure RS_EvolRempliResRFE_RDE_V2(const NumPhase, RuSurf, EauDispo, RuRac, CapaRFE, CapaREvap, CapaRDE, StRuMax, PercolationMax, BundHeight, EpaisseurSurf, EpaisseurProf, VolMacropores: Double; var FloodwaterDepth, StockTotal, StockRac, Hum, StockSurface, Dr, ValRDE, ValRFE, ValRSurf, FloodwaterGain, StockMacropores: Double); var EauReste, ValRSurfPrec, EauTranspi: Double; begin try Dr := 0; EauTranspi := 0; if (StockMacropores + FloodwaterDepth = 0) then begin EauReste := 0; ValRFE := ValRFE + EauDispo; if (ValRFE > CapaRFE) then begin EauReste := ValRFE - CapaRFE; ValRFE := CapaRFE; end; ValRSurfPrec := ValRSurf; ValRSurf := ValRSurf + EauReste; if (ValRSurfPrec < CapaREvap) then begin EauTranspi := EauDispo - (Min(CapaREvap, ValRSurf) - ValRSurfPrec); end else begin EauTranspi := EauDispo; end; if (ValRSurf > (CapaREvap + CapaRDE)) then begin ValRSurf := CapaREvap + CapaRDE; ValRDE := CapaRDE; end else begin if (ValRSurf <= CapaREvap) then begin ValRDE := 0; end else begin ValRDE := ValRSurf - CapaREvap; end; end; StockSurface := ValRFE + ValRDE; StockTotal := StockTotal + EauTranspi; if (StockTotal > StRuMax) then begin Dr := StockTotal - StRuMax; StockTotal := StRuMax; end else begin Dr := 0; end; if Hum < (CapaRFE + CapaRDE) then begin Hum := StockSurface; end else begin Hum := Max(Hum, StockTotal); end; end; StockRac := Min(StockRac + EauTranspi, RuRac); // Shifting non-percolating Dr back to macropores & floodwater if plot is bunded if (BundHeight > 0) then begin // Shifting non-percolating Dr to Floodwater StockMacropores := StockMacropores + Max(0, Dr - PercolationMax); Dr := Min(Dr, PercolationMax); if (StockMacropores > VolMacropores) then begin FloodWaterDepth := FloodWaterDepth + (StockMacropores - VolMacropores); StockMacropores := VolMacropores; end; // Implementing Dr if (FloodwaterDepth >= PercolationMax) then begin Dr := PercolationMax; FloodwaterDepth := FloodwaterDepth - Dr; StockMacropores := VolMacropores; end else begin if (FloodwaterDepth < PercolationMax) and ((FloodwaterDepth + StockMacropores) >= PercolationMax) then begin Dr := PercolationMax; FloodwaterDepth := FloodwaterDepth - Dr; StockMacropores := StockMacropores + FloodwaterDepth; FloodwaterDepth := 0; end else begin Dr := Min(PercolationMax, (FloodwaterDepth + StockMacropores + Dr)); FloodwaterDepth := 0; StockMacropores := 0; end; end; end; except AfficheMessageErreur('RS_EvolRempliResRFE_RDE_V2', URisocas); end; end; procedure RS_AutomaticIrrigation_V2(const NumPhase, IrrigAuto, IrrigAutoTarget, BundHeight, PlantHeight, Irrigation, PlotDrainageDAF, DAF, VolMacropores, VolRelMacropores, Rain {NEW Y} , FTSWIrrig, IrrigAutoStop, IrrigAutoResume, ChangeNurseryStatus, PercolationMax, NbJas {, Ftsw }, RuSurf , {Ru}ResUtil, RootFront, EpaisseurSurf, EpaisseurProf {NEW JUNE 19}, ProfRacIni: Double; var FloodwaterDepth, IrrigAutoDay, IrrigTotDay, StockMacropores, EauDispo , RuRac, StockRac, Ftsw {NEW JUNE 18}, Lr : Double); var IrrigAutoTargetCor: Double; CorrectedIrrigation: Double; CorrectedBundHeight: Double; StressPeriod : Double; begin try CorrectedBundHeight := BundHeight; {StressPeriod := 0; } if (Irrigation = NullValue) then begin CorrectedIrrigation := 0; end else begin CorrectedIrrigation := Irrigation; end; if (NumPhase > 4) and (NumPhase < 7) and (DAF > PlotDrainageDAF) then begin CorrectedBundHeight := 0; end; {NEW Y} if (NbJas >= IrrigAutoStop) and (NbJas < IrrigAutoResume) then StressPeriod := 1 else StressPeriod := 0; {/NEW Y} {NEW JUNE 18} // Enable interruption of irrigation for user defined period If (StressPeriod=1) and (FloodwaterDepth>0) then begin Lr := Lr + FloodwaterDepth; FloodwaterDepth := 0; // Drain off floodwater during user-defined stressperiod End; if (NumPhase < 7) and (DAF <= PlotDrainageDaf) and (IrrigAuto = 1) and (NumPhase > 0) and (CorrectedBundHeight > 0) {NEW Y} and (Ftsw <= FTSWIrrig) and (StressPeriod = 0){/NEW Y} then begin // FtswIrrig is a management parameter making irrigation conditional on Ftsw IrrigAutoTargetCor := Min((IrrigAutoTarget * BundHeight), (0.5 * PlantHeight)); // Provide initial water flush for infiltration if (NumPhase = 1) then begin IrrigAutoTargetCor := Max(IrrigAutoTargetCor, BundHeight / 2); end; // dimension irrigation on day i to replenish the floodwater, macropores and RuRac {DELETED JUNE 18} {IrrigAutoDay := Max(0, (IrrigAutoTargetCor - FloodwaterDepth + Min((VolMacropores - StockMacropores) / 2, VolRelMacropores * 200 / 100))); // The sense of the last part of this equation is not clear} {NEW JUNE 18} IrrigAutoDay := Max(0,(IrrigAutoTargetCor - FloodwaterDepth)) + + (VolMacropores - StockMacropores) + RuRac * (1-(min(Ftsw, 1))); // Pre-irrigation at transplanting, in mm {NEW Y} If ChangeNurseryStatus = 1 then IrrigAutoDay := (IrrigAutoTarget * BundHeight) + VolMacropores + RuSurf + PercolationMax; {/NEW Y} if (StockMacropores + FloodwaterDepth) = 0 then begin EauDispo := Rain + CorrectedIrrigation + IrrigAutoDay; end else begin FloodwaterDepth := FloodwaterDepth + IrrigAutoDay; // make sure Macropores is fully filled before floodwater can build up! if (VolMacropores > 0) and (StockMacropores < VolMacropores) and (FloodwaterDepth > 0) then begin StockMacropores := StockMacropores + FloodwaterDepth; FloodwaterDepth := max(0, StockMacropores - VolMacropores); StockMacropores := StockMacropores - FloodwaterDepth; {NEW P} {NEW JUNE 18} {Provision is introduced where RootFront is not evaluated yet, we take the value of ProfRacIni} if RootFront = 0 then RuRac := {NEW JUNE 18}{Ru}ResUtil * ProfRacIni / 1000 else RuRac := {NEW JUNE 18}{Ru}ResUtil * RootFront / 1000; //showMessage(floattostr(ResUtil)+' * '+floattostr(ProfRacIni)+' NbJas:'+floattostr(NbJas)+' NumPhase:'+floattostr(NumPhase)); if RootFront = 0 then StockRac := RuRac + StockMacropores * ProfRacIni / (EpaisseurSurf + EpaisseurProf) else StockRac := RuRac + StockMacropores * RootFront / (EpaisseurSurf + EpaisseurProf); Ftsw := StockRac / RuRac; {NEW P} end; EauDispo := StockMacropores + FloodwaterDepth; end; end else begin if (NumPhase < 7) and (DAF <= PlotDrainageDaf) and (IrrigAuto = 1) and (NumPhase > 0) and (CorrectedBundHeight = 0) then begin FloodwaterDepth := 0; {DELETED JUNE 18}{StockMacropores := 0;} end; end; IrrigTotDay := CorrectedIrrigation + IrrigAutoDay; except AfficheMessageErreur('RS_AutomaticIrrigation_V2', URisocas); end; end; procedure RS_FloodwaterDynamic_V2(const FloodwaterDepth, PlantHeight: Double; var FractionPlantHeightSubmer: Double); begin try if (PlantHeight > 0) then begin FractionPlantHeightSubmer := Min(Max(0, FloodwaterDepth / PlantHeight), 1); end; except AfficheMessageErreur('RS_FloodwaterDynamic_V2', URisocas); end; end; procedure RS_EvolRurRFE_RDE_V2(const VitesseRacinaire, Hum, ResUtil, StockSurface, RuSurf, ProfRacIni, EpaisseurSurf, EpaisseurProf, ValRDE, ValRFE, NumPhase, ChangePhase, FloodwaterDepth, StockMacropores, {NEW Y}RootFrontMax , ChangeNurseryStatus, Transplanting, TransplantingDepth {/NEW Y} : Double; var RuRac, StockRac, StockTotal, FloodwaterGain, RootFront: Double); var DeltaRur: Double; begin try if (NumPhase = 0) then begin RuRac := 0; StockRac := 0; end else begin if ((NumPhase = 1) and (ChangePhase = 1)) then // les conditions de germination sont atteinte et nous sommes le jour même begin RuRac := ResUtil * Min(ProfRacIni, (EpaisseurSurf + EpaisseurProf)) / 1000; if (ProfRacIni <= EpaisseurSurf) then begin StockRac := (ValRDE + ValRFE) * ProfRacIni / EpaisseurSurf; end else begin StockRac := StockTotal * Min(ProfRacIni / (EpaisseurSurf + EpaisseurProf), 1); end; end else begin if (Hum - StockMacropores - RuRac) < (VitesseRacinaire / 1000 * ResUtil) then begin DeltaRur := Max(0, Hum - StockMacropores - RuRac); {NEW P} If (RootFront >= (EpaisseurSurf + EpaisseurProf)) or (RootFront >= RootFrontMax) then DeltaRur := 0; // limit root front progression to RootFrontMax and soil depth {/NEW P} end else begin DeltaRur := VitesseRacinaire / 1000 * ResUtil; {NEW Y} If {NEW P}(RootFront >= (EpaisseurSurf + EpaisseurProf)) or {/NEW P}(RootFront >= RootFrontMax) then DeltaRur := 0; // limit root front progression to RootFrontMax and soil depth {/NEW Y} end; RuRac := RuRac + DeltaRur; if (RuRac > RuSurf) then begin StockRac := StockRac + DeltaRur; end else begin StockRac := (ValRDE + ValRFE) * (RuRac / RuSurf); end; end; end; // The following is needed to have the correct basis for calculating FTSW under // supersaturated soil condition (macropores filled) if (NumPhase <> 0) then begin RootFront := ((1 / ResUtil) * RuRac) * 1000; {NEW Y} if(ChangeNurseryStatus = 1) and (Transplanting = 1) then begin RootFront := TransplantingDepth; if (RootFront < 40) then RootFront := 40 else if (RootFront > 200) then RootFront := 200; // Security: avoid aberrant values for transplanting depth // set new root front to depth of transplanting RuRac := RootFront * ResUtil / 1000; end {/NEW Y} end; if ((StockMacropores + FloodwaterDepth) > 0) then begin StockRac := RootFront * ResUtil / 1000 + (RootFront / (EpaisseurSurf + EpaisseurProf)) * StockMacropores; StockRac := Min(StockRac, StockTotal); end; except AfficheMessageErreur('RS_EvolRurRFE_RDE_V2', URisocas); end; end; procedure RS_PlantSubmergence_V2(const PlantHeight, FloodwaterDepth: Double; var FractionPlantHeightSubmer: Double); begin try FractionPlantHeightSubmer := Min(Max(0, FloodwaterDepth / Max(PlantHeight, 0.1)), 1); except AfficheMessageErreur('RS_PlantSubmergence_V2', URisocas); end; end; procedure RS_ExcessAssimilToRoot_V2(const NumPhase, ExcessAssimToRoot, DryMatStructRootPop, RootSystVolPop, CoeffRootMassPerVolMax: Double; var RootMassPerVol, GrowthStructRootPop, AssimNotUsed: Double); begin try if (NumPhase > 1) then begin RootMassPerVol := DryMatStructRootPop / RootSystVolPop; end; if (ExcessAssimToRoot = 1) then begin if (NumPhase < 5) and (NumPhase > 1) and (AssimNotUsed > 0) then begin if (RootMassPerVol < CoeffRootMassPerVolMax) then begin GrowthStructRootPop := GrowthStructRootPop + AssimNotUsed; AssimNotUsed := 0; end; end; end; except AfficheMessageErreur('RS_ExcessAssimilToRoot_V2', URisocas); end; end; procedure RS_EvolRempliMacropores_V2(const NumPhase, EpaisseurSurf, EpaisseurProf, ResUtil, StockMacropores, RootFront, CapaRDE, CapaRFE, FloodwaterDepth: Double; var StockTotal, Hum, StockSurface, StockRac, ValRDE, ValRFE, ValRSurf: Double); begin try if ((StockMacropores + FloodwaterDepth) > 0) then begin StockTotal := (EpaisseurSurf + EpaisseurProf) * ResUtil / 1000 + StockMacropores; Hum := StockTotal; StockSurface := EpaisseurSurf * ResUtil / 1000 + (EpaisseurSurf / (EpaisseurSurf + EpaisseurProf)) * StockMacropores; StockRac := RootFront * ResUtil / 1000 + (RootFront / (EpaisseurSurf + EpaisseurProf)) * StockMacropores; ValRDE := CapaRDE; ValRFE := CapaRFE; ValRSurf := EpaisseurSurf * ResUtil / 1000; end; except AfficheMessageErreur('RS_EvolRempliMacropores_V2', URisocas); end; end; procedure RS_EvalFTSW_V2(const RuRac, StockTotal, StockMacropores, StRuMax: Double; var StockRac, ftsw: Double); begin try StockRac := Min(StockRac, (RuRac + (StockMacropores * RuRac / StRuMax))); StockRac := Min(StockRac, StockTotal); if (RuRac > 0) then begin ftsw := StockRac / RuRac; end else begin ftsw := 0; end; except AfficheMessageErreur('EvalFTSW | StRurMax: ' + FloatToStr(RuRac) + ' StRur: ' + FloatToStr(StockRac) + ' ftsw: ' + FloatToStr(ftsw), URisocas); end; end; procedure RS_EvalDAF_V2(const NumPhase: Double; var DAF: Double); begin try if (NumPhase > 4) then begin DAF := DAF + 1; end else begin DAF := DAF; end; except AfficheMessageErreur('RS_EvalDAF_V2', URisocas); end; end; procedure RS_EvalSimStartGermin(const NumPhase, ChangePhase, NbJas: Double; var SimStartGermin: Double); begin try if (NumPhase = 1) and (ChangePhase = 1) then begin SimStartGermin := NbJas end; except AfficheMessageErreur('RS_EvalSimStartGermin', URisocas); end; end; procedure RS_EvalSimEmergence(const NumPhase, ChangePhase, NbJas: Double; var SimEmergence: Double); begin try if (NumPhase = 2) and (ChangePhase = 1) then begin SimEmergence := NbJas end; except AfficheMessageErreur('RS_EvalSimEmergence', URisocas); end; end; procedure RS_EvalSimStartPSP(const NumPhase, ChangePhase, NbJas: Double; var SimStartPSP: Double); begin try if (NumPhase = 3) and (ChangePhase = 1) then begin SimStartPSP := NbJas end; except AfficheMessageErreur('RS_EvalSimStartPSP', URisocas); end; end; procedure RS_EvalSimPanIni(const NumPhase, ChangePhase, NbJas: Double; var SimPanIni: Double); begin try if (NumPhase = 4) and (ChangePhase = 1) then begin SimPanIni := NbJas end; except AfficheMessageErreur('RS_EvalSimPanIni', URisocas); end; end; procedure RS_EvalSimAnthesis50(const NumPhase, ChangePhase, NbJas: Double; var SimAnthesis50: Double); begin try if (NumPhase = 5) and (ChangePhase = 1) then begin SimAnthesis50 := NbJas end; except AfficheMessageErreur('RS_EvalSimAnthesis50', URisocas); end; end; procedure RS_EvalSimStartMatu2(const NumPhase, ChangePhase, NbJas: Double; var SimStartMatu2: Double); begin try if (NumPhase = 6) and (ChangePhase = 1) then begin SimStartMatu2 := NbJas end; except AfficheMessageErreur('RS_EvalSimStartMatu2', URisocas); end; end; procedure RS_EvalSimEndCycle(const NumPhase, ChangePhase, NbJas: Double; var SimEndCycle: Double); begin try if (NumPhase = 7) and (ChangePhase = 1) then begin SimEndCycle := NbJas; end; except AfficheMessageErreur('RS_EvalSimEndCycle ', URisocas); end; end; procedure RS_EvalColdStress(const KCritStressCold1, KCritStressCold2, TMin: Double; var StressCold: Double); begin try StressCold := 1 - Max(0, Min(1, KCritStressCold1 / (KCritStressCold1 - KCritStressCold2) - TMin / (KCritStressCold1 - KCritStressCold2))); StressCold := Max(0.00001, StressCold); except AfficheMessageErreur('RS_EvalColdStress', URisocas); end; end; procedure RS_EvalAssim(const AssimPot, CstrAssim: Double; var Assim: Double); begin try Assim := Max(AssimPot * CstrAssim, 0); except AfficheMessageErreur('EvalAssim | AssimPot: ' + FloatToStr(AssimPot) + ' CstrAssim: ' + FloatToStr(CstrAssim) + ' StressCold: ', URisocas); end; end; procedure RS_Priority2GrowthPanStrctPop(const PriorityPan, DemStructPaniclePop , {NEW LB} NumPhase, GrowthStructTotPop, DemStructInternodePop, DemStructTotPop, DemStructLeafPop, DemStructSheathPop, DemStructRootPop, DemResInternodePop : Double; var GrowthStructPaniclePop, GrowthStructInternodePop {NEW LB} , GrowthStructLeafPop, GrowthStructSheathPop, GrowthStructRootPop, GrowthResInternodePop: Double); var GrowthPanDeficit: Double; GrowthStructPaniclePlus : Double; begin try if (GrowthStructPaniclePop < DemStructPaniclePop) {NEW LB} and (NumPhase = 4){NEW LB} then begin GrowthPanDeficit := DemStructPaniclePop - GrowthStructPaniclePop; {NEW LB} GrowthStructPaniclePlus := Min(PriorityPan * GrowthPanDeficit, GrowthStructTotPop - GrowthStructPaniclePop); {/NEW LB} GrowthStructPaniclePop := GrowthStructPaniclePop {NEW LB}+ GrowthStructPaniclePlus; GrowthStructInternodePop := GrowthStructInternodePop - GrowthStructPaniclePlus * (DemStructInternodePop / DemStructTotPop); GrowthStructLeafPop := GrowthStructLeafPop - GrowthStructPaniclePlus * (DemStructLeafPop / DemStructTotPop); GrowthStructSheathPop := GrowthStructSheathPop - GrowthStructPaniclePlus * (DemStructSheathPop / DemStructTotPop); GrowthStructRootPop := GrowthStructRootPop - GrowthStructPaniclePlus * (DemStructRootPop / DemStructTotPop); GrowthResInternodePop := GrowthResInternodePop - GrowthStructPaniclePlus * (DemResInternodePop / DemStructTotPop); {/NEW LB} {DELETED LB} {GrowthStructInternodePop := Max(0, GrowthStructInternodePop - PriorityPan * GrowthPanDeficit);} end; except AfficheMessageErreur('RS_Priority2GrowthPanStrctPop', URisocas); end; end; procedure RS_KeyResults_V2(const NumPhase, CulmsPerPlant, CulmsPerHill, Cstr, FTSW, Ic, Lai, GrainYieldPop, DryMatAboveGroundPop, DryMatResInternodePop ,{NEW LB} DryMatTotPop , GrainFillingStatus , SterilityTot , CumIrrig, CumWUse: Double; var CulmsPerPlantMax, CulmsPerHillMax, DurPhase1, DurPhase2, DurPhase3, DurPhase4, DurPhase5, DurPhase6, CumCstrPhase2, CumCstrPhase3, CumCstrPhase4, CumCstrPhase5, CumCstrPhase6, CumFTSWPhase2, CumFTSWPhase3, CumFTSWPhase4, CumFTSWPhase5, CumFTSWPhase6, CumIcPhase2, CumIcPhase3, CumIcPhase4, CumIcPhase5, CumIcPhase6, IcPhase2, IcPhase3, IcPhase4, IcPhase5, IcPhase6, FtswPhase2, FtswPhase3, FtswPhase4, FtswPhase5, FtswPhase6, CstrPhase2, CstrPhase3, CstrPhase4, CstrPhase5, CstrPhase6, DurGermFlow, DurGermMat, LaiFin, CulmsPerHillFin, CulmsPerPlantFin, GrainYieldPopFin, DryMatAboveGroundPopFin, ReservePopFin, {NEW LB} DryMatTotPopFin , GrainFillingStatusFin , SterilityTotFin, CumIrrigFin, CumWUseFin : Double); begin try if (NumPhase > 1) and (NumPhase < 7) then begin CulmsPerPlantMax := Max(CulmsPerPlant, CulmsPerPlantMax); CulmsPerHillMax := Max(CulmsPerHill, CulmsPerHillMax); end; if (NumPhase = 1) then begin DurPhase1 := DurPhase1 + 1; end; if (NumPhase = 2) then begin DurPhase2 := DurPhase2 + 1; CumCstrPhase2 := CumCstrPhase2 + Cstr; CumFTSWPhase2 := CumFTSWPhase2 + FTSW; CumIcPhase2 := CumIcPhase2 + Ic; end; if (NumPhase = 3) then begin DurPhase3 := DurPhase3 + 1; CumCstrPhase3 := CumCstrPhase3 + Cstr; CumFTSWPhase3 := CumFTSWPhase3 + FTSW; CumIcPhase3 := CumIcPhase3 + Ic; end; if (NumPhase = 4) then begin DurPhase4 := DurPhase4 + 1; CumCstrPhase4 := CumCstrPhase4 + Cstr; CumFTSWPhase4 := CumFTSWPhase4 + FTSW; CumIcPhase4 := CumIcPhase4 + Ic; end; if (NumPhase = 5) then begin DurPhase5 := DurPhase5 + 1; CumCstrPhase5 := CumCstrPhase5 + Cstr; CumFTSWPhase5 := CumFTSWPhase5 + FTSW; CumIcPhase5 := CumIcPhase5 + Ic; end; if (NumPhase = 6) then begin DurPhase6 := DurPhase6 + 1; CumCstrPhase6 := CumCstrPhase6 + Cstr; CumFTSWPhase6 := CumFTSWPhase6 + FTSW; CumIcPhase6 := CumIcPhase6 + Ic; end; if (NumPhase = 7) then begin IcPhase2 := CumIcPhase2 / Max(DurPhase2, 0.1); IcPhase3 := CumIcPhase3 / Max(DurPhase3, 0.1); IcPhase4 := CumIcPhase4 / Max(DurPhase4, 0.1); IcPhase5 := CumIcPhase5 / Max(DurPhase5, 0.1); IcPhase6 := CumIcPhase6 / Max(DurPhase6, 0.1); FtswPhase2 := CumFtswPhase2 / Max(DurPhase2, 0.1); FtswPhase3 := CumFtswPhase3 / Max(DurPhase3, 0.1); FtswPhase4 := CumFtswPhase4 / Max(DurPhase4, 0.1); FtswPhase5 := CumFtswPhase5 / Max(DurPhase5, 0.1); FtswPhase6 := CumFtswPhase6 / Max(DurPhase6, 0.1); CstrPhase2 := CumCstrPhase2 / Max(DurPhase2, 0.1); CstrPhase3 := CumCstrPhase3 / Max(DurPhase3, 0.1); CstrPhase4 := CumCstrPhase4 / Max(DurPhase4, 0.1); CstrPhase5 := CumCstrPhase5 / Max(DurPhase5, 0.1); CstrPhase6 := CumCstrPhase6 / Max(DurPhase6, 0.1); DurGermFlow := DurPhase2 + DurPhase3 + DurPhase4; DurGermMat := DurPhase2 + DurPhase3 + DurPhase4 + DurPhase5 + DurPhase6; LaiFin := Lai; CulmsPerHillFin := CulmsPerHill; CulmsPerPlantFin := CulmsPerPlant; GrainYieldPopFin := GrainYieldPop; DryMatAboveGroundPopFin := DryMatAboveGroundPop; ReservePopFin := DryMatResInternodePop; {NEW LB} DryMatTotPopFin := DryMatTotPop; GrainFillingStatusFin := GrainFillingStatus; SterilityTotFin := SterilityTot; CumIrrigFin := CumIrrig; CumWUseFin := CumWUse; {/NEW LB} end; except AfficheMessageErreur('RS_KeyResults_V2', URisocas); end; end; procedure RS_EvolWaterLoggingUpland_V2(const PercolationMax, BundHeight, VolMacropores: Double; var Dr, Lr, StockMacropores: Double); begin try if (Dr > PercolationMax) and (BundHeight = 0) then begin StockMacropores := StockMacropores + (Dr - PercolationMax); Lr := Lr + Max(0, StockMacropores - VolMacropores); Dr := PercolationMax; StockMacropores := Min(StockMacropores, VolMacropores); end; except AfficheMessageErreur('RS_EvolWaterLoggingUpland_V2', URisocas); end; end; procedure RS_EvalStressWaterLogging_V2(const StockMacropores, VolMacropores, RootFront, EpaisseurSurf, EpaisseurProf, WaterLoggingSens: Double; var FractionRootsLogged, CoeffStressLogging: Double); begin try if (StockMacropores > 0) and (RootFront > 0) then begin FractionRootsLogged := (Max(0, RootFront - ((VolMacropores - StockMacropores) / VolMacropores) * (EpaisseurSurf + EpaisseurProf))) / RootFront; CoeffStressLogging := 1 - (FractionRootsLogged * Min(1, WaterLoggingSens)); end; except AfficheMessageErreur('RS_EvalStressWaterLogging_V2', URisocas); end; end; procedure RS_EvalCstrPFactorFAO_V2(const PFactor, FTSW, ETo, KcTot, StockMacropores, CoeffStressLogging: Double; var cstr: Double); var pFact: Extended; begin try pFact := PFactor + 0.04 * (5 - KcTot * ETo); pFact := Max(0, pFact); pFact := Min(0.8, pFact); cstr := Min((FTSW / (1 - pFact)), 1); cstr := Max(0, cstr); if (StockMacropores > 0) then begin cstr := cstr * CoeffStressLogging; end; except AfficheMessageErreur('RS_EvalCstrPFactorFAO_V2', URisocas); end; end; procedure RS_BindAgronomicResults(const numphase: double); var part_1 : TextFile; part_2 : TextFile; complete_file : TextFile; content_of_1 : string; content_of_2 : string; begin try if fileexists('D:\Projets Cirad\SarraH\DBEcosys\DBResult\Requetes\Agronomic results short.txt') then begin AssignFile(part_1,'D:\Projets Cirad\SarraH\DBEcosys\DBResult\Requetes\Agronomic results short.txt'); AssignFile(part_2,'D:\Projets Cirad\SarraH\DBEcosys\DBResult\Requetes\Agronomic results short part 2.txt'); AssignFile(complete_file ,'D:\Projets Cirad\SarraH\DBEcosys\DBResult\Requetes\Agronomic results short FULL.txt'); reset(part_1); reset(part_2); reWrite(complete_file); while not eof(part_1) do begin readln(part_1, content_of_1); readln(part_2, content_of_2); writeLn(complete_file, 'test');//content_of_1 + content_of_2); end; closeFile(part_1); closeFile(part_2); closeFile(complete_file); end; except AfficheMessageErreur('RS_BindAgronomicResults', URisocas); end; end; // ----------------------------------------------------------------------------- // Méthodes dynamiques // ----------------------------------------------------------------------------- procedure RS_EvalDegresJourVitMoyDyn(var T: TPointeurProcParam); begin RS_EvalDegresJourVitMoy(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]); end; procedure RS_EvalDegresJourVitMoy_V2Dyn(var T: TPointeurProcParam); begin RS_EvalDegresJourVitMoy_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11]); end; procedure RS_PhyllochronDyn(var T: TPointeurProcParam); begin RS_Phyllochron(T[0], T[1], T[2], T[3], T[4], T[5], T[6]); end; procedure RS_EvolHauteur_SDJ_cstrDyn(var T: TPointeurProcParam); begin RS_EvolHauteur_SDJ_cstr(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17]); end; procedure RS_EvalParIntercepteDyn(var T: TPointeurProcParam); begin RS_EvalParIntercepte(T[0], T[1], T[2] , T[3] , T[4]); end; procedure RS_EvalCstrAssimDyn(var T: TPointeurProcParam); begin RS_EvalCstrAssim(T[0], T[1], T[2]); end; procedure RS_EvalRespMaintDyn(var T: TPointeurProcParam); begin RS_EvalRespMaint(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13]); end; procedure RS_EvolPlantTilNumTotDyn(var T: TPointeurProcParam); begin RS_EvolPlantTilNumTot(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12]); end; procedure RS_EvolPlantTilNumTot_V2Dyn(var T: TPointeurProcParam); begin RS_EvolPlantTilNumTot_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13]); end; procedure RS_EvolPlantLeafNumTotDyn(var T: TPointeurProcParam); begin RS_EvolPlantLeafNumTot(T[0], T[1], T[2], T[3], T[4]); end; procedure RS_EvolMobiliTillerDeathDyn(var T: TPointeurProcParam); begin RS_EvolMobiliTillerDeath(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10]); end; procedure RS_EvolMobiliTillerDeath_V2Dyn(var T: TPointeurProcParam); begin RS_EvolMobiliTillerDeath_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11]); end; procedure RS_EvolMobiliLeafDeathDyn(var T: TPointeurProcParam); begin RS_EvolMobiliLeafDeath(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]); end; procedure RS_EvalSupplyTotDyn(var T: TPointeurProcParam); begin RS_EvalSupplyTot(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10]); end; procedure RS_EvalRelPotLeafLengthDyn(var T: TPointeurProcParam); begin RS_EvalRelPotLeafLength(T[0], T[1], T[2], T[3]); end; procedure RS_EvalDemandStructLeafDyn(var T: TPointeurProcParam); begin RS_EvalDemandStructLeaf(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11]); end; procedure RS_EvalDemandStructLeaf_V2Dyn(var T: TPointeurProcParam); begin RS_EvalDemandStructLeaf_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13]); end; procedure RS_EvalDemandStructSheathDyn(var T: TPointeurProcParam); begin RS_EvalDemandStructSheath(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]); end; procedure RS_EvalDemandStructRootDyn(var T: TPointeurProcParam); begin RS_EvalDemandStructRoot(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15]); end; procedure RS_EvalDemandStructRoot_V2Dyn(var T: TPointeurProcParam); begin RS_EvalDemandStructRoot_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18]); end; procedure RS_EvalDemandStructInternodeDyn(var T: TPointeurProcParam); begin RS_EvalDemandStructInternode(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]); end; procedure RS_EvalDemandStructIN_V2Dyn(var T: TPointeurProcParam); begin RS_EvalDemandStructIN_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8],T[9],T[10],T[11], T[12]); end; procedure RS_EvalDemandStructPanicleDyn(var T: TPointeurProcParam); begin RS_EvalDemandStructPanicle(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]); end; procedure RS_EvalDemandStructPanicle_V2Dyn(var T: TPointeurProcParam); begin RS_EvalDemandStructPanicle_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10]); end; procedure RS_EvalDemandTotAndIcPreFlowDyn(var T: TPointeurProcParam); begin RS_EvalDemandTotAndIcPreFlow(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17] , T[18]); end; procedure RS_EvolGrowthStructLeafPopDyn(var T: TPointeurProcParam); begin RS_EvolGrowthStructLeafPop(T[0], T[1], T[2], T[3], T[4], T[5], T[6]); end; procedure RS_EvolGrowthStructSheathPopDyn(var T: TPointeurProcParam); begin RS_EvolGrowthStructSheathPop(T[0], T[1], T[2], T[3], T[4], T[5]); end; procedure RS_EvolGrowthStructRootPopDyn(var T: TPointeurProcParam); begin RS_EvolGrowthStructRootPop(T[0], T[1], T[2], T[3], T[4], T[5]); end; procedure RS_EvolGrowthStructINPopDyn(var T: TPointeurProcParam); begin RS_EvolGrowthStructINPop(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]); end; procedure RS_EvolGrowthStructPanPopDyn(var T: TPointeurProcParam); begin RS_EvolGrowthStructPanPop(T[0], T[1], T[2], T[3], T[4], T[5]); end; procedure RS_EvolGrowthStructTotDyn(var T: TPointeurProcParam); begin RS_EvolGrowthStructTot(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10] , T[11], T[12]); end; procedure RS_AddResToGrowthStructPopDyn(var T: TPointeurProcParam); begin RS_AddResToGrowthStructPop(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9],T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21], T[22], T[23]); end; procedure RS_EvolDemPanFilPopAndIcPFlowDyn(var T: TPointeurProcParam); begin RS_EvolDemPanFilPopAndIcPFlow(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14]); end; procedure RS_EvolPanicleFilPopDyn(var T: TPointeurProcParam); begin RS_EvolPanicleFilPop(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15]); end; procedure RS_EvolGrowthReserveInternodeDyn(var T: TPointeurProcParam); begin RS_EvolGrowthReserveInternode(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12] , T[13], T[14]); end; procedure RS_EvolGrowthTotDyn(var T: TPointeurProcParam); begin RS_EvolGrowthTot(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11] , T[12]); end; procedure RS_EvalLaiDyn(var T: TPointeurProcParam); begin RS_EvalLai(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12]); end; procedure RS_EvalClumpAndLightInterDyn(var T: TPointeurProcParam); begin RS_EvalClumpAndLightInter(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13]); end; procedure RS_EvalClumpAndLightInter_V2Dyn(var T: TPointeurProcParam); begin RS_EvalClumpAndLightInter_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11]); end; procedure RS_EvalSlaMitchDyn(var T: TPointeurProcParam); begin RS_EvalSlaMitch(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14]); end; procedure RS_EvalRUEDyn(var T: TPointeurProcParam); begin RS_EvalRUE(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21], T[22], T[23], T[24], T[25], T[26], T[27], T[28], T[29], T[30], T[31] , T[32], T[33], T[34] , T[35] , T[36] , T[37]); end; procedure RS_EvolKcpKceBilhyDyn(var T: TPointeurProcParam); begin RS_EvolKcpKceBilhy(T[0], T[1], T[2], T[3], T[4], T[5]); end; procedure RS_EvolEvapSurfRFE_RDEDyn(var T: TPointeurProcParam); begin RS_EvolEvapSurfRFE_RDE(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13]); end; procedure RS_EvolEvapSurfRFE_RDE_V2Dyn(var T: TPointeurProcParam); begin RS_EvolEvapSurfRFE_RDE_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21], T[22], T[23]); end; procedure RS_EvalConversionDyn(var T: TPointeurProcParam); begin RS_EvalConversion(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]); end; procedure RS_EvolPSPMVMDDyn(var T: TPointeurProcParam); begin RS_EvolPSPMVMD(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10]); end; procedure RS_EvolSomDegresJourCorDyn(var T: TPointeurProcParam); begin RS_EvolSomDegresJourCor(T[0], T[1], T[2]); end; procedure RS_EvalMaximumLaiDyn(var T: TPointeurProcParam); begin RS_EvalMaximumLai(T[0], T[1], T[2], T[3], T[4]); end; procedure RS_EvalVitesseRacinaireDyn(var T: TPointeurProcParam); begin RS_EvalVitesseRacinaire(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11]); end; procedure RS_EvolDryMatTotDyn(var T: TPointeurProcParam); begin RS_EvolDryMatTot(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21], T[22], T[23], T[24], T[25], T[26], T[27], T[28], T[29], T[30], T[31], T[32], T[33], T[34], T[35], T[36], T[37], T[38], T[39]); end; procedure RS_EvolDryMatTot_V2Dyn(var T: TPointeurProcParam); begin RS_EvolDryMatTot_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21], T[22], T[23], T[24], T[25], T[26], T[27], T[28], T[29], T[30], T[31], T[32], T[33], T[34], T[35], T[36], T[37], T[38], T[39], T[40], T[41], T[42], T[43] , T[44] , T[45] , T[46] , T[47] , T[48]); end; procedure RS_InitiationCultureDyn(var T: TPointeurProcParam); begin RS_InitiationCulture(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21], T[22], T[23], T[24], T[25], T[26], T[27], T[28], T[29], T[30], T[31], T[32], T[33], T[34], T[35], T[36], T[37], T[38], T[39], T[40], T[41], T[42], T[43], T[44], T[45], T[46], T[47], T[48], T[49], T[50], T[51], T[52], T[53], T[54], T[55], T[56], T[57], T[58], T[59], T[60], T[61], T[62], T[63], T[64], T[65], T[66], T[67], T[68], T[69], T[70], T[71], T[72], T[73], T[74], T[75], T[76], T[77], T[78], T[79], T[80], T[81], T[82], T[83], T[84], T[85], T[86], T[87], T[88], T[89], T[90], T[91], T[92], T[93], T[94], T[95], T[96], T[97], T[98]); end; procedure RS_InitiationCulture_V2Dyn(var T: TPointeurProcParam); begin RS_InitiationCulture_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14]); end; procedure RS_LeafRollingDyn(var T: TPointeurProcParam); begin RS_LeafRolling(T[0], T[1], T[2], T[3], T[4], T[5]); end; procedure RS_EvalRootFrontDyn(var T: TPointeurProcParam); begin RS_EvalRootFront(T[0], T[1], T[2], T[3]); end; procedure RS_EvalSDJPhase4Dyn(var T: TPointeurProcParam); begin RS_EvalSDJPhase4(T[0], T[1], T[2]); end; procedure RS_EvalDateGerminationDyn(var T: TPointeurProcParam); begin RS_EvalDateGermination(T[0], T[1], T[2]); end; procedure RS_EvalSterilityDyn(var T: TPointeurProcParam); begin RS_EvalSterility(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14]); end; procedure RS_ResetVariablesToZeroDyn(var T: TPointeurProcParam); begin RS_ResetVariablesToZero(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21], T[22], T[23], T[24], T[25], T[26], T[27], T[28], T[29], T[30], T[31], T[32], T[33], T[34], T[35], T[36], T[37], T[38], T[39], T[40], T[41], T[42], T[43], T[44], T[45], T[46], T[47], T[48], T[49], T[50]); end; procedure RS_EvalAssimPotDyn(var T: TPointeurProcParam); begin RS_EvalAssimPot(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8] , T[9], T[10], T[11], T[12] , T[13] , T[14] , T[15], T[16]); end; procedure RS_InitParcelleDyn(var T: TPointeurProcParam); begin RS_InitParcelle(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20]); end; procedure RS_InitParcelle_V2Dyn(var T: TPointeurProcParam); begin RS_InitParcelle_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21], T[22], T[23], T[24], T[25], T[26], T[27]); end; procedure RS_EvalEvapPotDyn(var T: TPointeurProcParam); begin RS_EvalEvapPot(T[0], T[1], T[2]); end; procedure RS_Transplanting_V2Dyn(var T: TPointeurProcParam); begin RS_Transplanting_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15]); end; procedure RS_TransplantingShock_V2Dyn(var T: TPointeurProcParam); begin RS_TransplantingShock_V2(T[0], T[1], T[2]); end; procedure RS_EvalRuiss_FloodDyna_V2Dyn(var T: TPointeurProcParam); begin RS_EvalRuiss_FloodDyna_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16]); end; procedure RS_EvolRempliResRFE_RDE_V2Dyn(var T: TPointeurProcParam); begin RS_EvolRempliResRFE_RDE_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21], T[22], T[23]); end; procedure RS_AutomaticIrrigation_V2Dyn(var T: TPointeurProcParam); begin RS_AutomaticIrrigation_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15] //NEW , T[16],T[17],T[18],T[19], T[20],T[21],T[22],T[23], T[24],T[25],T[26],T[27], T[28],T[29],T[30], T[31]); end; procedure RS_FloodwaterDynamic_V2Dyn(var T: TPointeurProcParam); begin RS_FloodwaterDynamic_V2(T[0], T[1], T[2]); end; procedure RS_EvolRurRFE_RDE_V2Dyn(var T: TPointeurProcParam); begin RS_EvolRurRFE_RDE_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21] , T[22]); end; procedure RS_EvolConsRes_Flood_V2Dyn(var T: TPointeurProcParam); begin RS_EvolConsRes_Flood_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18]); end; procedure RS_PlantSubmergence_V2Dyn(var T: TPointeurProcParam); begin RS_PlantSubmergence_V2(T[0], T[1], T[2]); end; procedure RS_ExcessAssimilToRoot_V2Dyn(var T: TPointeurProcParam); begin RS_ExcessAssimilToRoot_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]); end; procedure RS_EvolRempliMacropores_V2Dyn(var T: TPointeurProcParam); begin RS_EvolRempliMacropores_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15]); end; procedure RS_EvalFTSW_V2Dyn(var T: TPointeurProcParam); begin RS_EvalFTSW_V2(T[0], T[1], T[2], T[3], T[4], T[5]); end; procedure RS_EvalDAF_V2Dyn(var T: TPointeurProcParam); begin RS_EvalDAF_V2(T[0], T[1]); end; procedure RS_EvalSimStartGerminDyn(var T: TPointeurProcParam); begin RS_EvalSimStartGermin(T[0], T[1], T[2], T[3]); end; procedure RS_EvalSimEmergenceDyn(var T: TPointeurProcParam); begin RS_EvalSimEmergence(T[0], T[1], T[2], T[3]); end; procedure RS_EvalSimStartPSPDyn(var T: TPointeurProcParam); begin RS_EvalSimStartPSP(T[0], T[1], T[2], T[3]); end; procedure RS_EvalSimPanIniDyn(var T: TPointeurProcParam); begin RS_EvalSimPanIni(T[0], T[1], T[2], T[3]); end; procedure RS_EvalSimAnthesis50Dyn(var T: TPointeurProcParam); begin RS_EvalSimAnthesis50(T[0], T[1], T[2], T[3]); end; procedure RS_EvalSimStartMatu2Dyn(var T: TPointeurProcParam); begin RS_EvalSimStartMatu2(T[0], T[1], T[2], T[3]); end; procedure RS_EvalSimEndCycleDyn(var T: TPointeurProcParam); begin RS_EvalSimEndCycle(T[0], T[1], T[2], T[3]); end; procedure RS_EvalColdStressDyn(var T: TPointeurProcParam); begin RS_EvalColdStress(T[0], T[1], T[2], T[3]); end; procedure RS_EvalAssimDyn(var T: TPointeurProcParam); begin RS_EvalAssim(T[0], T[1], T[2]); end; procedure RS_Priority2GrowthPanStrctPopDyn(var T: TPointeurProcParam); begin RS_Priority2GrowthPanStrctPop(T[0], T[1], T[2], T[3] , T[4], T[5], T[6], T[7] ,T[8], T[9], T[10], T[11],T[12], T[13], T[14], T[15]); end; procedure RS_KeyResults_V2Dyn(var T: TPointeurProcParam); begin RS_KeyResults_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10], T[11], T[12], T[13], T[14], T[15], T[16], T[17], T[18], T[19], T[20], T[21], T[22], T[23], T[24], T[25], T[26], T[27], T[28], T[29], T[30], T[31], T[32], T[33], T[34], T[35], T[36], T[37], T[38], T[39], T[40], T[41], T[42], T[43], T[44], T[45], T[46], T[47], T[48], T[49], T[50], T[51], T[52], T[53], T[54], T[55], T[56], T[57], T[58], T[59], T[60], T[61], T[62], T[63], T[64], T[65]); end; procedure RS_EvolWaterLoggingUpland_V2Dyn(var T: TPointeurProcParam); begin RS_EvolWaterLoggingUpland_V2(T[0], T[1], T[2], T[3], T[4], T[5]); end; procedure RS_EvalStressWaterLogging_V2Dyn(var T: TPointeurProcParam); begin RS_EvalStressWaterLogging_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]); end; procedure RS_EvalCstrPFactorFAO_V2Dyn(var T: TPointeurProcParam); begin RS_EvalCstrPFactorFAO_V2(T[0], T[1], T[2], T[3], T[4], T[5], T[6]); end; procedure RS_BindAgronomicResultsDyn(var T: TPointeurProcParam); begin RS_BindAgronomicResults(T[0]); end; initialization TabProc.AjoutProc('RS_EvalDegresJourVitMoy', RS_EvalDegresJourVitMoyDyn); TabProc.AjoutProc('RS_EvalDegresJourVitMoy_V2', RS_EvalDegresJourVitMoy_V2Dyn); TabProc.AjoutProc('RS_Phyllochron', RS_PhyllochronDyn); TabProc.AjoutProc('RS_EvolHauteur_SDJ_cstr', RS_EvolHauteur_SDJ_cstrDyn); TabProc.AjoutProc('RS_EvalParIntercepte', RS_EvalParIntercepteDyn); TabProc.AjoutProc('RS_EvalCstrAssim', RS_EvalCstrAssimDyn); TabProc.AjoutProc('RS_EvalRespMaint', RS_EvalRespMaintDyn); TabProc.AjoutProc('RS_EvolPlantTilNumTot', RS_EvolPlantTilNumTotDyn); TabProc.AjoutProc('RS_EvolPlantTilNumTot_V2', RS_EvolPlantTilNumTot_V2Dyn); TabProc.AjoutProc('RS_EvolPlantLeafNumTot', RS_EvolPlantLeafNumTotDyn); TabProc.AjoutProc('RS_EvolMobiliTillerDeath', RS_EvolMobiliTillerDeathDyn); TabProc.AjoutProc('RS_EvolMobiliTillerDeath_V2', RS_EvolMobiliTillerDeath_V2Dyn); TabProc.AjoutProc('RS_EvolMobiliLeafDeath', RS_EvolMobiliLeafDeathDyn); TabProc.AjoutProc('RS_EvalSupplyTot', RS_EvalSupplyTotDyn); TabProc.AjoutProc('RS_EvalRelPotLeafLength', RS_EvalRelPotLeafLengthDyn); TabProc.AjoutProc('RS_EvalDemandStructLeaf', RS_EvalDemandStructLeafDyn); TabProc.AjoutProc('RS_EvalDemandStructLeaf_V2', RS_EvalDemandStructLeaf_V2Dyn); TabProc.AjoutProc('RS_EvalDemandStructSheath', RS_EvalDemandStructSheathDyn); TabProc.AjoutProc('RS_EvalDemandStructRoot', RS_EvalDemandStructRootDyn); TabProc.AjoutProc('RS_EvalDemandStructRoot_V2', RS_EvalDemandStructRoot_V2Dyn); TabProc.AjoutProc('RS_EvalDemandStructInternode', RS_EvalDemandStructInternodeDyn); TabProc.AjoutProc('RS_EvalDemandStructIN_V2', RS_EvalDemandStructIN_V2Dyn); TabProc.AjoutProc('RS_EvalDemandStructPanicle', RS_EvalDemandStructPanicleDyn); TabProc.AjoutProc('RS_EvalDemandStructPanicle_V2', RS_EvalDemandStructPanicle_V2Dyn); TabProc.AjoutProc('RS_EvalDemandTotAndIcPreFlow', RS_EvalDemandTotAndIcPreFlowDyn); TabProc.AjoutProc('RS_EvolGrowthStructLeafPop', RS_EvolGrowthStructLeafPopDyn); TabProc.AjoutProc('RS_EvolGrowthStructSheathPop', RS_EvolGrowthStructSheathPopDyn); TabProc.AjoutProc('RS_EvolGrowthStructRootPop', RS_EvolGrowthStructRootPopDyn); TabProc.AjoutProc('RS_EvolGrowthStructINPop', RS_EvolGrowthStructINPopDyn); TabProc.AjoutProc('RS_EvolGrowthStructPanPop', RS_EvolGrowthStructPanPopDyn); TabProc.AjoutProc('RS_EvolGrowthStructTot', RS_EvolGrowthStructTotDyn); TabProc.AjoutProc('RS_AddResToGrowthStructPop', RS_AddResToGrowthStructPopDyn); TabProc.AjoutProc('RS_EvolDemPanFilPopAndIcPFlow', RS_EvolDemPanFilPopAndIcPFlowDyn); TabProc.AjoutProc('RS_EvolPanicleFilPop', RS_EvolPanicleFilPopDyn); TabProc.AjoutProc('RS_EvolGrowthReserveInternode', RS_EvolGrowthReserveInternodeDyn); TabProc.AjoutProc('RS_EvolGrowthTot', RS_EvolGrowthTotDyn); TabProc.AjoutProc('RS_EvalLai', RS_EvalLaiDyn); TabProc.AjoutProc('RS_EvalClumpAndLightInter', RS_EvalClumpAndLightInterDyn); TabProc.AjoutProc('RS_EvalClumpAndLightInter_V2', RS_EvalClumpAndLightInter_V2Dyn); TabProc.AjoutProc('RS_EvalSlaMitch', RS_EvalSlaMitchDyn); TabProc.AjoutProc('RS_EvalRUE', RS_EvalRUEDyn); TabProc.AjoutProc('RS_EvolKcpKceBilhy', RS_EvolKcpKceBilhyDyn); TabProc.AjoutProc('RS_EvolEvapSurfRFE_RDE', RS_EvolEvapSurfRFE_RDEDyn); TabProc.AjoutProc('RS_EvolEvapSurfRFE_RDE_V2', RS_EvolEvapSurfRFE_RDE_V2Dyn); TabProc.AjoutProc('RS_EvalConversion', RS_EvalConversionDyn); TabProc.AjoutProc('RS_EvolPSPMVMD', RS_EvolPSPMVMDDyn); TabProc.AjoutProc('RS_EvolSomDegresJourCor', RS_EvolSomDegresJourCorDyn); TabProc.AjoutProc('RS_EvalMaximumLai', RS_EvalMaximumLaiDyn); TabProc.AjoutProc('RS_EvalVitesseRacinaire', RS_EvalVitesseRacinaireDyn); TabProc.AjoutProc('RS_EvolDryMatTot', RS_EvolDryMatTotDyn); TabProc.AjoutProc('RS_EvolDryMatTot_V2', RS_EvolDryMatTot_V2Dyn); TabProc.AjoutProc('RS_InitiationCulture', RS_InitiationCultureDyn); TabProc.AjoutProc('RS_LeafRolling', RS_LeafRollingDyn); TabProc.AjoutProc('RS_EvalRootFront', RS_EvalRootFrontDyn); TabProc.AjoutProc('RS_EvalSDJPhase4', RS_EvalSDJPhase4Dyn); TabProc.AjoutProc('RS_EvalDateGermination', RS_EvalDateGerminationDyn); TabProc.AjoutProc('RS_EvalSterility', RS_EvalSterilityDyn); TabProc.AjoutProc('RS_ResetVariablesToZero', RS_ResetVariablesToZeroDyn); TabProc.AjoutProc('RS_EvalAssimPot', RS_EvalAssimPotDyn); TabProc.AjoutProc('RS_InitParcelle', RS_InitParcelleDyn); TabProc.AjoutProc('RS_InitParcelle_V2', RS_InitParcelle_V2Dyn); TabProc.AjoutProc('RS_EvalEvapPot', RS_EvalEvapPotDyn); TabProc.AjoutProc('RS_Transplanting_V2', RS_Transplanting_V2Dyn); TabProc.AjoutProc('RS_TransplantingShock_V2', RS_TransplantingShock_V2Dyn); TabProc.AjoutProc('RS_EvalRuiss_FloodDyna_V2', RS_EvalRuiss_FloodDyna_V2Dyn); TabProc.AjoutProc('RS_EvolRempliResRFE_RDE_V2', RS_EvolRempliResRFE_RDE_V2Dyn); TabProc.AjoutProc('RS_AutomaticIrrigation_V2', RS_AutomaticIrrigation_V2Dyn); TabProc.AjoutProc('RS_FloodwaterDynamic_V2', RS_FloodwaterDynamic_V2Dyn); TabProc.AjoutProc('RS_EvolRurRFE_RDE_V2', RS_EvolRurRFE_RDE_V2Dyn); TabProc.AjoutProc('RS_EvolConsRes_Flood_V2', RS_EvolConsRes_Flood_V2Dyn); TabProc.AjoutProc('RS_PlantSubmergence_V2', RS_PlantSubmergence_V2Dyn); TabProc.AjoutProc('RS_ExcessAssimilToRoot_V2', RS_ExcessAssimilToRoot_V2Dyn); TabProc.AjoutProc('RS_EvolRempliMacropores_V2', RS_EvolRempliMacropores_V2Dyn); TabProc.AjoutProc('RS_EvalFTSW_V2', RS_EvalFTSW_V2Dyn); TabProc.AjoutProc('RS_InitiationCulture_V2', RS_InitiationCulture_V2Dyn); TabProc.AjoutProc('RS_EvalDAF_V2', RS_EvalDAF_V2Dyn); TabProc.AjoutProc('RS_EvalSimStartGermin', RS_EvalSimStartGerminDyn); TabProc.AjoutProc('RS_EvalSimEmergence', RS_EvalSimEmergenceDyn); TabProc.AjoutProc('RS_EvalSimStartPSP', RS_EvalSimStartPSPDyn); TabProc.AjoutProc('RS_EvalSimPanIni', RS_EvalSimPanIniDyn); TabProc.AjoutProc('RS_EvalSimAnthesis50', RS_EvalSimAnthesis50Dyn); TabProc.AjoutProc('RS_EvalSimStartMatu2', RS_EvalSimStartMatu2Dyn); TabProc.AjoutProc('RS_EvalSimEndCycle', RS_EvalSimEndCycleDyn); TabProc.AjoutProc('RS_EvalColdStress', RS_EvalColdStressDyn); TabProc.AjoutProc('RS_EvalAssim', RS_EvalAssimDyn); TabProc.AjoutProc('RS_Priority2GrowthPanStrctPop', RS_Priority2GrowthPanStrctPopDyn); TabProc.AjoutProc('RS_KeyResults_V2', RS_KeyResults_V2Dyn); TabProc.AjoutProc('RS_EvolWaterLoggingUpland_V2', RS_EvolWaterLoggingUpland_V2Dyn); TabProc.AjoutProc('RS_EvalStressWaterLogging_V2', RS_EvalStressWaterLogging_V2Dyn); TabProc.AjoutProc('RS_EvalCstrPFactorFAO_V2', RS_EvalCstrPFactorFAO_V2Dyn); TabProc.AjoutProc('RS_BindAgronomicResults', RS_BindAgronomicResultsDyn ); end.
{ *************************************************************************** Copyright (c) 2016-2018 Kike Pérez Unit : Quick.Logger.Provider.SysLog Description : Log to SysLog server Author : Kike Pérez Version : 1.22 Created : 15/06/2018 Modified : 14/09/2019 This file is part of QuickLogger: https://github.com/exilon/QuickLogger *************************************************************************** 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. *************************************************************************** } unit Quick.Logger.Provider.SysLog; {$i QuickLib.inc} interface uses Classes, SysUtils, IdSysLog, IdSysLogMessage, Quick.Commons, Quick.Logger; type TSyslogFacility = TIdSyslogFacility; TLogSysLogProvider = class (TLogProviderBase) private fHost : string; fPort : Integer; fSysLog : TIdSysLog; fFacility : TSyslogFacility; public constructor Create; override; destructor Destroy; override; property Host : string read fHost write fHost; property Port : Integer read fPort write fPort; property Facility : TSyslogFacility read fFacility write fFacility; procedure Init; override; procedure Restart; override; procedure WriteLog(cLogItem : TLogItem); override; end; var GlobalLogSysLogProvider : TLogSysLogProvider; implementation constructor TLogSysLogProvider.Create; begin inherited; LogLevel := LOG_ALL; fHost := '127.0.0.1'; fPort := 514; fFacility := TSyslogFacility.sfUserLevel; end; destructor TLogSysLogProvider.Destroy; begin if Assigned(fSysLog) then begin try if fSysLog.Connected then fSysLog.Disconnect; except //hide disconnection excepts end; fSysLog.Free; end; inherited; end; procedure TLogSysLogProvider.Init; begin inherited; fSysLog := TIdSysLog.Create(nil); fSysLog.Host := fHost; fSysLog.Port := fPort; try fSysLog.Connect; except on E : Exception do raise Exception.CreateFmt('SysLogProvider: %s',[e.message]); end; end; procedure TLogSysLogProvider.Restart; begin Stop; if Assigned(fSysLog) then begin if fSysLog.Connected then fSysLog.Disconnect; fSysLog.Free; end; Init; end; procedure TLogSysLogProvider.WriteLog(cLogItem : TLogItem); var msg : TIdSysLogMessage; begin if not fSysLog.Connected then fSysLog.Connect; msg := TIdSysLogMessage.Create(nil); try msg.TimeStamp := cLogItem.EventDate; msg.Hostname := SystemInfo.HostName; msg.Facility := fFacility; msg.Msg.Process := SystemInfo.AppName; case cLogItem.EventType of etHeader: msg.Severity := TIdSyslogSeverity.slInformational; etInfo: msg.Severity := TIdSyslogSeverity.slInformational; etSuccess: msg.Severity := TIdSyslogSeverity.slNotice; etWarning: msg.Severity := TIdSyslogSeverity.slWarning; etError: msg.Severity := TIdSyslogSeverity.slError; etCritical: msg.Severity := TIdSyslogSeverity.slCritical; etException: msg.Severity := TIdSyslogSeverity.slAlert; etDebug: msg.Severity := TIdSyslogSeverity.slDebug; etTrace: msg.Severity := TIdSyslogSeverity.slInformational; etDone: msg.Severity := TIdSyslogSeverity.slNotice; etCustom1: msg.Severity := TIdSyslogSeverity.slEmergency; etCustom2: msg.Severity := TIdSyslogSeverity.slInformational; end; if CustomMsgOutput then msg.Msg.Text := cLogItem.Msg else msg.Msg.Text := LogItemToLine(cLogItem,False,True); fSysLog.SendLogMessage(msg,False); finally msg.Free; end; end; initialization GlobalLogSysLogProvider := TLogSysLogProvider.Create; finalization if Assigned(GlobalLogSysLogProvider) and (GlobalLogSysLogProvider.RefCount = 0) then GlobalLogSysLogProvider.Free; end.
unit ClassClockyWidget; {$mode objfpc}{$H+} interface uses Classes, Graphics, SysUtils, httpsend, superobject, inifiles, clockyutils ,bgrabitmap, bgrabitmaptypes ; const CLOCKY_CHECK_INTERVAL = 15 * 60; const CLOCKY_PROFILE_COUNT = 8; const CLOCKY_PROVIDER_OPENWEATHER = 0; const CLOCKY_PROVIDER_YAHOO = 1; {$ifdef Windows} const CLOCKY_FONT = 'Arial'; {$endif} {$ifdef Linux} const CLOCKY_FONT ='sans-serif'; {$endif} type TClockyWeatherConditions = record CurrentTemp: integer; Description: string; Icon: string; Code: integer; end; { TClockyWidget } TClockyWidget = class( TObject) ProfileID: integer; ExePath: string; TickCount: int64; LastMove: int64; LastConditionsCheck: int64; LocalTimeZone: double; //ie, time zone where computer is LocationTimeZone: double; //location of where we're checking weather LocationTitle: string; Location: string; //whats passed to the api TimeFormat: string; DateFormat: string; TempUnit: string; //F or C BackgroundColor: integer; Flat: boolean; DefaultFontName: string; FontName: string; // Top: integer; Left: integer; // Conditions: TClockyWeatherConditions; //resources //Shiny: TPortableNetworkGraphic; //ShinyBottom: TPortableNetworkGraphic; Shiny: TBGRABitmap; ShinyBottom: TBGRABitmap; //Icons: array[0..100] of TPortableNetworkGraphic; Icons: array[0..100] of TBGRABitmap; WeatherProvider: integer; //API Keys OpenWeatherMapAPIKey: string; constructor create( sPath: string); function GetProfileName(n: integer): string; function GetTimeStr(): string; function GetDateStr(): string; procedure Render( c: TCanvas; width: integer; height: integer); procedure UpdateWeatherConditions; procedure UpdateWeatherConditionsOpenWeather; procedure UpdateWeatherConditionsYahoo; function iconOpenWeatherToVCloud( sOW: string): integer; function yahooCodeToVCloud( nCode: integer): integer; procedure Load; procedure Save; function isProfileAutolaunch( nProfile: integer): boolean; end; implementation { TClockyWidget } constructor TClockyWidget.create( sPath: string); var i: integer; begin ExePath := sPath; ProfileID := 1; LocationTitle := 'State College'; Location := 'State College,PA'; TimeFormat := 'hh:nnam/pm'; DateFormat := 'ddd, mmm dd, yyyy'; BackgroundColor := $600000; DefaultFontName := CLOCKY_FONT; WeatherProvider := CLOCKY_PROVIDER_YAHOO; //OPENWEATHER; Conditions.Code := 100; { Shiny := TPortableNetworkGraphic.Create; Shiny.LoadFromFile( ExePath + 'graphics/shiny-top.png'); ShinyBottom := TPortableNetworkGraphic.Create; ShinyBottom.LoadFromFile( ExePath + 'graphics/shiny-bottom.png'); } Shiny := TBGRABitmap.Create( ExePath + 'graphics/shiny-top.png'); ShinyBottom := TBGRABitmap.Create( ExePath + 'graphics/shiny-bottom.png'); for i := 0 to 100 do begin icons[i] := nil; end; end; function TClockyWidget.GetProfileName(n: integer): string; var ini: TIniFile; sFile: string; begin sFile := GetAppConfigFile( false, true); ini := TIniFile.Create( sFile); result := ini.ReadString( 'Prof_' + IntToStr( n), 'LocationTitle', '(Unassigned)'); ini.Free; end; function TClockyWidget.GetTimeStr: string; begin result := FormatDateTime( TimeFormat, clockyTimeAtZone( LocalTimeZone, LocationTimeZone)); end; function TClockyWidget.GetDateStr: string; begin result := FormatDateTime( DateFormat, clockyTimeAtZone( LocalTimeZone, LocationTimeZone)); end; procedure TClockyWidget.Render(c: TCanvas; width: integer; height: integer); var tw: integer; x: integer; y: integer; s: string; png: TPortableNetworkGraphic; nIcon: integer; sIcon: string; tmppng: TBGRABitmap; begin //background c.Brush.Style := bsSolid; c.Brush.Color := BackgroundColor; //RGBToColor( 0, 0, 24); c.FillRect( 0, 0, width, height); //c.Rectangle( 0, 0, width, height); //draw glassy edge if not Flat then begin //c.Draw(0, 0, Shiny); //c.Draw(0, height - ShinyBottom.Height, ShinyBottom); Shiny.Draw( c, 0, 0, False); ShinyBottom.Draw( c, 0, height - ShinyBottom.Height, false); end; //Location Header c.Font.Name := FontName; // 'Utah'; c.Font.Color := clWhite; c.Font.Height := 20; c.Brush.Style := bsClear; tw := c.GetTextWidth( LocationTitle); x := round( (width/2) - (tw/2)); c.TextOut( x, 10, LocationTitle); //Time c.Font.Height := 40; s := GetTimeStr; tw := c.GetTextWidth( s); x := round( (width/2) - (tw/2)); c.TextOut( x, 30, s); //date c.Font.Height := 20; s := GetDateStr; tw := c.GetTextWidth( s); x := round( (width/2) - (tw/2)); c.TextOut( x, 70, s); //temp c.Font.Height := 40; s := IntToStr( Conditions.CurrentTemp) + '°'; tw := c.GetTextWidth( s); //x := round( (width/4) - (tw/2) + (width/2)); x := round((width /2) + 5); c.TextOut( x, 110, s); //icon case WeatherProvider of CLOCKY_PROVIDER_YAHOO: begin nIcon := yahooCodeToVCloud( Conditions.Code); end; else nIcon := iconOpenWeatherToVCloud( Conditions.Icon); end; if Icons[nIcon] = nil then begin //Icons[nIcon] := TPortableNetworkGraphic.Create; //Icons[nIcon].LoadFromFile( ExePath + 'icons/VClouds/' +IntToStr( nIcon) + '.png'); tmppng := TBGRABitmap.Create( ExePath + 'icons/VClouds/' +IntToStr( nIcon) + '.png'); tmppng.ResampleFilter:= rfBicubic; Icons[nIcon] := tmppng.Resample(82, 60) as TBGRABitmap; tmppng.Free; //Icons[nIcon] := TBGRABitmap.Create( ExePath + 'icons/VClouds/' +IntToStr( nIcon) + '.png'); end; if Icons[nIcon] <> nil then begin //c.Draw( 0, 100, Icons[nIcon]); //x := round( (width / 4) - 30); x := round((width / 2) - 82 - 5); //c.StretchDraw( rect( x, 100, x+82, 160), Icons[nIcon]); Icons[nIcon].draw( c, x, 100, false); end; //conditions c.Font.Height := 20; s := Conditions.Description; tw := c.GetTextWidth( s); x := round( (width/2) - (tw/2)); c.TextOut( x, 160, s); end; procedure TClockyWidget.UpdateWeatherConditions; begin case WeatherProvider of CLOCKY_PROVIDER_YAHOO: UpdateWeatherConditionsYahoo; else UpdateWeatherConditionsOpenWeather; end; end; procedure TClockyWidget.UpdateWeatherConditionsOpenWeather; var sURL: string; sj: string; rs: TStringList; j: ISuperObject; sa: TSuperArray; p: string; n: integer; begin sURL := 'http://api.openweathermap.org/data/2.5/weather?q=' + Location + '&units=imperial&APPID=' + OpenWeatherMapAPIKey; rs := TStringList.Create; try if HTTPGetText( sURL, rs) then begin sj := rs.Text; p := copy( sj, 1, 1); if (length( sj) > 0) and (p = '{') then begin j := so( sj); if assigned( j) then begin try n := j['main'].i['temp']; if (TempUnit = 'C') then begin Conditions.CurrentTemp:= clockyFtoC( n); end else begin Conditions.CurrentTemp:= n; end; sa := j.A['weather']; if sa.Length > 0 then begin Conditions.Description:= sa[0].s['main']; Conditions.Icon:= sa[0].s['icon']; end; except end; end; end; end; finally rs.Free; end; end; procedure TClockyWidget.UpdateWeatherConditionsYahoo; var sURL: string; sj: string; rs: TStringList; j: ISuperObject; sa: TSuperArray; p: string; n: integer; yql: string; begin sURL := 'http://query.yahooapis.com/v1/public/yql?q='; yql := 'select item.condition from weather.forecast where woeid in (select woeid from geo.places(1) where text="' + Location + '")'; yql := StringReplace( yql, ' ', '%20', [rfReplaceAll]); yql := StringReplace( yql, '=', '%3D', [rfReplaceAll]); yql := StringReplace( yql, '"', '%22', [rfReplaceAll]); yql := StringReplace( yql, ',', '%2C', [rfReplaceAll]); sURL := sURL + yql + '&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys'; rs := TStringList.Create; try if HTTPGetText( sURL, rs) then begin sj := rs.Text; p := copy( sj, 1, 1); if (length( sj) > 0) and (p = '{') then begin j := so( sj); if assigned( j) then begin try p := j['query'].o['results'].o['channel'].o['item'].o['condition'].S['temp']; if TryStrToInt( p, n) then begin if uppercase( TempUnit) = 'C' then begin Conditions.CurrentTemp := clockyFtoC(n); end else begin Conditions.CurrentTemp := n; end; end; p := j['query'].o['results'].o['channel'].o['item'].o['condition'].S['code']; if TryStrToInt( p, n) then begin Conditions.Code := n; end; Conditions.Description := j['query'].o['results'].o['channel'].o['item'].o['condition'].S['text']; except end; end; end; end; finally rs.Free; end; end; function TClockyWidget.iconOpenWeatherToVCloud(sOW: string): integer; begin if sOW = '01d' then result := 32 else if sOW = '01n' then result := 31 else if sOW = '02d' then result := 30 else if sOW = '02n' then result := 33 else if sOW = '03d' then result := 28 else if sOW = '03n' then result := 27 else if sOW = '04d' then result := 26 else if sOW = '04n' then result := 26 else if sOW = '09d' then result := 9 else if sOW = '09n' then result := 9 else if sOW = '10d' then result := 0 else if sOW = '10n' then result := 0 else if sOW = '11d' then result := 4 else if sOW = '11n' then result := 4 else if sOW = '13d' then result := 14 else if sOW = '13n' then result := 14 else if sOW = '50d' then result := 20 else if sOW = '50n' then result := 20 else result := 100; end; function TClockyWidget.yahooCodeToVCloud(nCode: integer): integer; begin //vcloud image set is already mapped to yahoo codes if (nCode >= 0) and (nCode <= 47) then begin result := nCode end else begin result := 100; end; end; procedure TClockyWidget.Load; var sPath, sFile, sSect, sColor: string; ini: TIniFile; p: string; begin sFile := GetAppConfigFile( false, true); sPath := ExtractFilePath( sFile); ForceDirectories( sPath); ini := TIniFile.Create( sFile); //global settings WeatherProvider := CLOCKY_PROVIDER_YAHOO; //OPENWEATHER; p := ini.ReadString( 'clocky', 'WeatherProvider', ''); if (lowercase(p) = 'yahoo') then begin WeatherProvider := CLOCKY_PROVIDER_YAHOO; end; LocalTimeZone := ini.ReadFloat( 'clocky', 'LocalTimeZone', 0); OpenWeatherMapAPIKey := ini.ReadString( 'clocky', 'OpenWeatherMapAPIKey', ''); DefaultFontName := ini.ReadString( 'clocky', 'DefaultFontName', CLOCKY_FONT); //profile specific settings sSect := 'Prof_' + IntToStr( ProfileID); p := ini.ReadString( sSect, 'WeatherProvider', ''); //to override global if (lowercase(p) = 'yahoo') then begin WeatherProvider := CLOCKY_PROVIDER_YAHOO; end; if (lowercase(p) = 'openweather') then begin WeatherProvider := CLOCKY_PROVIDER_OPENWEATHER; end; LocationTitle := ini.ReadString( sSect, 'LocationTitle', 'State College'); Location := ini.ReadString( sSect, 'Location', 'State College, PA'); LocationTimeZone := ini.ReadFloat( sSect, 'LocationTimeZone', LocalTimeZone); TempUnit := ini.ReadString( sSect, 'Unit', 'F'); Left := ini.ReadInteger( sSect, 'Left', 200); Top := ini.ReadInteger( sSect, 'Top', 200); sColor := ini.ReadString( sSect, 'BackgroundColor', '$00000000'); try BackgroundColor := StringToColor( sColor); except end; Flat := ini.ReadBool( sSect, 'Flat', false); FontName := ini.ReadString( sSect, 'FontName', DefaultFontName); ini.Free; end; procedure TClockyWidget.Save; var sPath, sFile, sSect, sColor: string; ini: TIniFile; begin sFile := GetAppConfigFile( false, true); sPath := ExtractFilePath( sFile); ForceDirectories( sPath); ini := TIniFile.Create( sFile); sSect := 'Prof_' + IntToStr( ProfileID); ini.WriteString( sSect, 'LocationTitle', LocationTitle); ini.WriteString( sSect, 'Location', Location); ini.WriteInteger( sSect, 'Left', Left); ini.WriteInteger( sSect, 'Top', Top); sColor := ColorToString( BackgroundColor); ini.WriteString( sSect, 'BackgroundColor', sColor); ini.WriteBool( sSect, 'Flat', Flat); ini.WriteString( sSect, 'FontName', FontName); ini.Free; end; function TClockyWidget.isProfileAutolaunch(nProfile: integer): boolean; var sFile: string; sSect: string; ini: TIniFile; begin result := false; sFile := GetAppConfigFile( false, true); if not FileExists( sFile) then exit; sSect := 'Prof_' + IntToStr( nProfile); ini := TIniFile.Create( sFile); result := ini.ReadBool( sSect, 'AutoLaunch', false); ini.Free; end; end.
unit uClassItemPreVenda; interface type TItemPreVenda = class private FIdItemPreVenda: Integer; FPreco: Real; FCodigoProduto: Integer; FTotal: Real; FQuantidade: integer; FIdPreVenda: Integer; FidProduto: Integer; procedure SetCodigoProduto(const Value: Integer); procedure SetIdItemPreVenda(const Value: Integer); procedure SetPreco(const Value: Real); procedure SetQuantidade(const Value: integer); procedure SetTotal(const Value: Real); procedure SetIdPreVenda(const Value: Integer); procedure SetidProduto(const Value: Integer); public property IdItemPreVenda : Integer read FIdItemPreVenda write SetIdItemPreVenda; property CodigoProduto : Integer read FCodigoProduto write SetCodigoProduto; property Quantidade : integer read FQuantidade write SetQuantidade; property Preco : Real read FPreco write SetPreco; property Total : Real read FTotal write SetTotal; property IdPreVenda : Integer read FIdPreVenda write SetIdPreVenda; property idProduto : Integer read FidProduto write SetidProduto; end; implementation { TItemPreVenda } procedure TItemPreVenda.SetCodigoProduto(const Value: Integer); begin FCodigoProduto := Value; end; procedure TItemPreVenda.SetIdItemPreVenda(const Value: Integer); begin FIdItemPreVenda := Value; end; procedure TItemPreVenda.SetIdPreVenda(const Value: Integer); begin FIdPreVenda := Value; end; procedure TItemPreVenda.SetidProduto(const Value: Integer); begin FidProduto := Value; end; procedure TItemPreVenda.SetPreco(const Value: Real); begin FPreco := Value; end; procedure TItemPreVenda.SetQuantidade(const Value: integer); begin FQuantidade := Value; end; procedure TItemPreVenda.SetTotal(const Value: Real); begin FTotal := Value; end; end.
unit tpEdit; interface uses tpString, StdCtrls, Graphics, Classes, Controls, Windows, Messages, SysUtils, Forms, tpClasses; type TtpEdit = class(TEdit) private fColorFocus: TColor; fColorNoFocus: TColor; fCheck: TCheck; fAlignment: TAlignment; fCaracter: TCaracters; FUf: string; FNull: boolean; FQtdeCsasDecimais: Integer; procedure SetAlignment(const Value: TAlignment); procedure CreateParams(var Params: TCreateParams); override; procedure SetCheck(Value: TCheck); procedure SetCaracter(Value: TCaracters); procedure SetAcceptNull(Value: boolean); procedure FormatarTpReal; procedure SetCsasDecimais(const Value: Integer); protected procedure DoEnter; override; procedure DoExit; override; public constructor Create(AOwner: TComponent); override; procedure KeyPress(var Key: Char); override; procedure Clear; override; published property ColorFocus: TColor read fColorFocus write fColorFocus default clWindow; property Check: TCheck read fCheck write SetCheck default ckNone; property Caracter: TCaracters read fCaracter write SetCaracter default tcAlfanumeric; property Alignment:TAlignment read FAlignment write SetAlignment; property UF: string read FUf write FUf; property AcceptNull: boolean read FNull write SetAcceptNull default true; property CasasDecimais: Integer read FQtdeCsasDecimais write SetCsasDecimais default 2; end; procedure Register; implementation uses tpValidar; var vet_valido: array [0..35] of string = ('0','1','2','3','4','5','6','7', '8','9','a','b','c','d','e','f', 'g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v', 'w','x','y','z'); procedure Register; begin RegisterComponents('WaibComponent', [TtpEdit]); end; { TWaibEdit } constructor TtpEdit.Create(AOwner: TComponent); begin inherited; Ctl3D := False; Height := 21; fColorFocus := clWindow; FNull := true; FQtdeCsasDecimais := 2; self.CharCase := ecUpperCase; end; procedure TtpEdit.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); case Alignment of taLeftJustify: Params.Style := Params.Style or LongWord(ES_Left); taRightJustify: Params.Style := Params.Style or LongWord(ES_Right); taCenter: Params.Style := Params.Style or LongWord(ES_Center); end; end; procedure TtpEdit.DoEnter; begin if Color <> clInfoBk then begin if fColorNoFocus <> Color then fColorNoFocus := Color; if Color <> ColorFocus then Color := ColorFocus; end; if ((fCheck = ckCpfCnpj) or (fCheck = ckCEP) or ((fCheck = ckIE) and (Text <> 'ISENTO')) or (fCheck = ckDate) or (fCheck = ckTelefone) or (fCheck = ckPis) or (fCheck = ckTitulo)) and (Text <> '') then Text := RemoverCaracters(Text); if FCaracter = tcReal then self.Text := BuscaTroca(self.Text,'.',''); SelectAll; inherited; end; procedure TtpEdit.DoExit; begin if Color <> clInfoBk then if Color <> fColorNoFocus then Color := fColorNoFocus; if (Trim(Text) <> '') or (fCheck = ckDate) then begin if (fCheck = ckCEP) then if not ValidarCep(Text) then begin Perform(WM_SETFOCUS,0,0); raise Exception.Create(' " ' + Text + ' " não é um CEP válido'); end else Text := FormatarCEP(Text); if (fCheck = ckCpfCnpj) then if not ValidarCpfCnpj(Text) then begin Perform(WM_SETFOCUS,0,0); if Length(Text) = 11 then raise Exception.Create(' " ' + Text + ' " não é um CPF válido') else raise Exception.Create(' " ' + Text + ' " não é um CNPJ válido'); end else Text:=FormatarCpfCnpj(Text); if (fCheck = ckDate) then begin if not ValidarData(Text) then begin Perform(WM_SETFOCUS,0,0); //Esse exception não está sendo levandado raise Exception.Create(' " ' + Text + ' " Não é uma data válida'); end else Text := FormatarData(Text); if (Trim(Text) = EmptyStr) and (not FNull) then Text := FormatarData(DateToStr(Now)); end; if (fCheck = ckEmail) then if not ValidarEmail(Text) then begin Perform(WM_SETFOCUS,0,0); raise Exception.Create(' " ' + Text + ' " Formato de E-mail não aceitável'); end; if (fCheck = ckIE) then if not ValidarIE(Text, FUf) then begin Perform(WM_SETFOCUS,0,0); raise Exception.Create(' " ' + Text + ' " não é uma IE válido para UF: '+FUf); end else Text := FormatarIE(RemoverCaracters(Text),FUf); if (fCheck = ckPis) then if not ValidarPis(Text) then begin Perform(WM_SETFOCUS,0,0); raise Exception.Create(' " ' + Text + ' " Não é um PIS válida'); end else Text := FormatarPis(Text); if (fCheck = ckTelefone) then if not ValidarTelefone(Text) then begin Perform(WM_SETFOCUS,0,0); raise Exception.Create(' " ' + Text + ' " não é um número de telefone válido'); end else Text := FormatarTelefone(Text); if (fCheck = ckTitulo) then if not ValidarTitulo(Text) then begin Perform(WM_SETFOCUS,0,0); raise Exception.Create(' " ' + Text + ' " Não é um título válida'); end else if Text <> '' then Text := FormatarTitulo(FormatFloat('0000000000000', StrToFloat(Text))); if (fCheck = ckUF) then if not ValidarUF(Text) then begin Perform(WM_SETFOCUS,0,0); raise Exception.Create(' " ' + Text + ' " Não é uma UF válida'); end; if (fCheck = ckURL) then if not ValidarUrl(Text) then begin Perform(WM_SETFOCUS,0,0); raise Exception.Create(' " ' + Text + ' " Não é endereço WEB aceitável'); end; if fCaracter = tcReal then begin FormatarTpReal; end; if (not FNull) and ((Text = '') or ((fCaracter = tcReal) and (StringToFloat(Text) = 0)) or ((FCheck = ckTelefone) and (length(trim(Text)) = 2))) then begin Perform(WM_SETFOCUS,0,0); raise Exception.Create('Informação necessária'); end; end; inherited; end; procedure TtpEdit.KeyPress(var Key: Char); const teclasLetras = ['A'..'Z', 'a'..'z', #8]; teclasNum = ['0'..'9', #8]; teclasAlfan = ['A'..'Z', 'a'..'z', '0'..'9', '~', '"', '''', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')' , '_', '-', '+', '=', '|', '/', '\', '{', '}', '[', ']', ':', ';', ',', '.', '<', '>', '´', '`', '³', '£', '¢', '¬', '§', 'ª', 'º', '°', '?', '²', '¹', #8]; teclasNumSymb = ['0'..'9', '~', '"', '''', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')' , '_', '-', '+', '=', '|', '/', '\', '{', '}', '[', ']', ':', ';', ',', '.', '<', '>', '´', '`', '³', '£', '¢', '¬', '§', 'ª', 'º', '°', '?', #8]; teclasReal = ['0'..'9','-', ',', #8]; teclasIE = ['I', 'S', 'E', 'N', 'T', 'O', 'i', 's', 'e', 'n', 't', 'o', '0'..'9', #8]; begin if (key in teclasAlfan) then begin if fCaracter = tcNumeric then if not (key in teclasNum) then key := #0; if fCaracter = tcAlfanumeric then if not (key in teclasAlfan) then key := #0; if fCaracter = tcNumericSymbol then if not (key in teclasNumSymb) then key := #0; if fCaracter = tcReal then if not (key in teclasReal) then key := #0; if fCaracter = tcIE then if not (key in teclasIE) then key := #0; if fCheck = ckUF then if not (key in teclasLetras) then key := #0; end; inherited KeyPress(Key); end; procedure TtpEdit.SetAlignment(const Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; RecreateWnd; end; end; procedure TtpEdit.SetCheck(Value: TCheck); begin if Value <> fCheck then fCheck := Value; self.CharCase := ecUpperCase; if fCheck = ckCep then begin self.MaxLength := 8; self.Caracter := tcNumeric; self.AcceptNull := true; end; if fCheck = ckCpfCnpj then begin self.MaxLength := 14; self.Caracter := tcNumeric; //self.AcceptNull := false; end; if fCheck = ckDate then begin self.MaxLength := 8; self.Caracter := tcNumeric; self.AcceptNull := true; end; if fCheck = ckEmail then begin self.MaxLength := 0; self.Caracter := tcAlfanumeric; self.AcceptNull := true; self.CharCase := ecLowerCase; end; if fCheck = ckIe then begin self.UF := 'MA'; self.MaxLength := 14; self.Caracter := tcIE; self.AcceptNull := false; end; if fCheck = ckNone then begin self.MaxLength := 0; self.AcceptNull := true; end; if fCheck = ckPIS then begin self.MaxLength := 11; self.Caracter := tcNumeric; self.AcceptNull := true; end; if fCheck = ckTelefone then begin self.MaxLength := 10; self.Caracter := tcNumeric; self.AcceptNull := true; end; if fCheck = ckTitulo then begin self.MaxLength := 13; self.Caracter := tcNumeric; self.AcceptNull := true; end; if fCheck = ckUf then begin self.MaxLength := 2; self.Caracter := tcAlfanumeric; self.AcceptNull := true; end; if fCheck = ckURL then begin self.MaxLength := 0; self.Caracter := tcAlfanumeric; self.AcceptNull := true; self.CharCase := ecLowerCase; end; end; procedure TtpEdit.SetCaracter(Value: TCaracters); begin if Value <> fCaracter then fCaracter := Value; if (FCheck = ckCpfCnpj) or (FCheck = ckCep) or (FCheck = ckTelefone) or (FCheck = ckDate) or (FCheck = ckPIS) or (FCheck = ckTitulo) then fCaracter := tcNumeric; if (FCheck = ckEmail) or (FCheck = ckURL) or (FCheck = ckUF) then fCaracter := tcAlfanumeric; if (FCheck = ckIE) then fCaracter := tcIE; if (fCaracter = tcAlfanumeric) or (fCaracter = tcNumeric) or (fCaracter = tcNumericSymbol) or (fCaracter = tcIE) then self.Text := '' else begin self.Text := ''; FormatarTpReal; SetAlignment(taRightJustify); end; end; procedure TtpEdit.SetAcceptNull(Value: boolean); begin if Value <> FNull then FNull := Value; //if (FCheck = ckCpfCnpj) or (FCheck = ckIE) then FNull := false; end; procedure TtpEdit.SetCsasDecimais(const Value: Integer); var QtdeKsas: Integer; begin QtdeKsas := Value; if Value < 2 then QtdeKsas := 2; if Value > 6 then QtdeKsas := 6; FQtdeCsasDecimais := QtdeKsas; if fCaracter = tcReal then FormatarTpReal; end; procedure TtpEdit.FormatarTpReal; begin if RemoverCaracters(self.Text) = '' then self.Text := ''; if Trim(self.Text) = '' then begin case CasasDecimais of 2: Text := '0,00'; 3: Text := '0,000'; 4: Text := '0,0000'; 5: Text := '0,00000'; 6: Text := '0,000000'; end; end; case CasasDecimais of 2: self.Text := FormatCurr('###,###,##0.00', StringToFloat(self.Text)); 3: self.Text := FormatCurr('###,###,##0.000', StringToFloat(self.Text)); 4: self.Text := FormatCurr('###,###,##0.0000', StringToFloat(self.Text)); 5: self.Text := FormatCurr('###,###,##0.00000', StringToFloat(self.Text)); 6: self.Text := FormatCurr('###,###,##0.000000', StringToFloat(self.Text)); end; end; procedure TtpEdit.Clear; begin inherited; if fCaracter = tcReal then FormatarTpReal; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Lens flare object. } unit VXS.LensFlare; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, System.Math, VXS.OpenGL, VXS.PersistentClasses, VXS.Scene, VXS.VectorGeometry, VXS.Objects, VXS.PipelineTransformation, VXS.Context, VXS.Color, VXS.BaseClasses, VXS.RenderContextInfo, VXS.State, VXS.VectorTypes, VXS.Utils, VXS.TextureFormat; type TFlareElement = (feGlow, feRing, feStreaks, feRays, feSecondaries); TFlareElements = set of TFlareElement; { The actual gradients between two colors are, of course, calculated by OpenGL. The start and end colors of a gradient are stored to represent the color of lens flare elements. } TVXFlareGradient = class(TVXUpdateAbleObject) private FFromColor: TVXColor; FToColor: TVXColor; protected procedure SetFromColor(const val: TVXColor); procedure SetToColor(const val: TVXColor); public constructor Create(AOwner: TPersistent); override; constructor CreateInitialized(AOwner: TPersistent; const fromColor, toColor: TColorVector); destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property fromColor: TVXColor read FFromColor write SetFromColor; property toColor: TVXColor read FToColor write SetToColor; end; const cDefaultFlareElements = [feGlow, feRing, feStreaks, feRays, feSecondaries]; type TVXLensFlare = class(TVXBaseSceneObject) private FSize: Integer; FDeltaTime: Single; FCurrSize: Single; FSeed: Integer; FSqueeze: Single; FNumStreaks: Integer; FStreakWidth, FStreakAngle: Single; FNumSecs: Integer; FResolution: Integer; FAutoZTest: Boolean; FElements: TFlareElements; FSin20Res, FCos20Res: array of Single; FSinRes, FCosRes: array of Single; FTexRays: TVXTextureHandle; FFlareIsNotOccluded: Boolean; FOcclusionQuery: TVXOcclusionQueryHandle; FGlowGradient: TVXFlareGradient; FRingGradient: TVXFlareGradient; FStreaksGradient: TVXFlareGradient; FRaysGradient: TVXFlareGradient; FSecondariesGradient: TVXFlareGradient; FDynamic: Boolean; FPreRenderPoint: TVXRenderPoint; protected procedure SetGlowGradient(const val: TVXFlareGradient); procedure SetRingGradient(const val: TVXFlareGradient); procedure SetStreaksGradient(const val: TVXFlareGradient); procedure SetRaysGradient(const val: TVXFlareGradient); procedure SetSecondariesGradient(const val: TVXFlareGradient); procedure SetSize(aValue: Integer); procedure SetSeed(aValue: Integer); procedure SetSqueeze(aValue: Single); function StoreSqueeze: Boolean; procedure SetNumStreaks(aValue: Integer); procedure SetStreakWidth(aValue: Single); function StoreStreakWidth: Boolean; procedure SetStreakAngle(aValue: Single); procedure SetNumSecs(aValue: Integer); procedure SetResolution(aValue: Integer); procedure SetAutoZTest(aValue: Boolean); procedure SetElements(aValue: TFlareElements); procedure SetDynamic(aValue: Boolean); procedure SetPreRenderPoint(const val: TVXRenderPoint); procedure PreRenderEvent(Sender: TObject; var rci: TVXRenderContextInfo); procedure PreRenderPointFreed(Sender: TObject); // These are quite unusual in that they don't use an RCI, since // PreRender is done before proper rendering starts, but we do know // which RC is being used, so we can use this state cache procedure SetupRenderingOptions(StateCache: TVXStateCache); procedure RenderRays(StateCache: TVXStateCache; const size: Single); procedure RenderStreaks(StateCache: TVXStateCache); procedure RenderRing; procedure RenderSecondaries(const posVector: TAffineVector); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure BuildList(var rci: TVXRenderContextInfo); override; procedure DoProgress(const progressTime: TVXProgressTimes); override; { Prepares pre-rendered texture to speed up actual rendering. Will use the currently active context as scratch space, and will automatically do nothing if things have already been prepared, thus you can invoke it systematically in a Viewer.BeforeRender event f.i. } procedure PreRender(activeBuffer: TVXSceneBuffer); { Access to the Flare's current size. Flares decay or grow back over several frames, depending on their occlusion status, and this property allows to track or manually alter this instantaneous size. } property FlareInstantaneousSize: Single read FCurrSize write FCurrSize; published property GlowGradient: TVXFlareGradient read FGlowGradient write SetGlowGradient; property RingGradient: TVXFlareGradient read FRingGradient; property StreaksGradient: TVXFlareGradient read FStreaksGradient; property RaysGradient: TVXFlareGradient read FRaysGradient; property SecondariesGradient: TVXFlareGradient read FSecondariesGradient; // MaxRadius of the flare. property size: Integer read FSize write SetSize default 50; // Random seed property Seed: Integer read FSeed write SetSeed; // To create elliptic flares. property Squeeze: Single read FSqueeze write SetSqueeze stored StoreSqueeze; // Number of streaks. property NumStreaks: Integer read FNumStreaks write SetNumStreaks default 4; // Width of the streaks. property StreakWidth: Single read FStreakWidth write SetStreakWidth stored StoreStreakWidth; // Angle of the streaks (in degrees) property StreakAngle: Single read FStreakAngle write SetStreakAngle; // Number of secondary flares. property NumSecs: Integer read FNumSecs write SetNumSecs default 8; // Number of segments used when rendering circles. property Resolution: Integer read FResolution write SetResolution default 64; { Automatically computes FlareIsNotOccluded depending on ZBuffer test. Not that the automated test may use test result from the previous frame into the next (to avoid a rendering stall). } property AutoZTest: Boolean read FAutoZTest write SetAutoZTest default True; { Is the LensFlare not occluded?. If false the flare will fade away, if true, it will fade in and stay. This value is automatically updated if AutoZTest is set. } property FlareIsNotOccluded: Boolean read FFlareIsNotOccluded write FFlareIsNotOccluded; // Which elements should be rendered? property Elements: TFlareElements read FElements write SetElements default cDefaultFlareElements; { Is the flare size adjusted dynamically? If true, the flare size will be grown and reduced over a few frames when it switches between occluded and non-occluded states. This requires animation to be active, but results in a smoother appearance. When false, flare will either be at full size or hidden. The flare is always considered non-dynamic at design-time. } property Dynamic: Boolean read FDynamic write FDynamic default True; { PreRender point for pre-rendered flare textures. See PreRender method for more details. } property PreRenderPoint: TVXRenderPoint read FPreRenderPoint write SetPreRenderPoint; property ObjectsSorting; property Position; property Visible; property OnProgress; property Behaviours; property Effects; end; // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------ // ------------------ TVXFlareGradient ------------------ // ------------------ constructor TVXFlareGradient.Create(AOwner: TPersistent); begin inherited; FFromColor := TVXColor.Create(Self); FToColor := TVXColor.Create(Self); end; constructor TVXFlareGradient.CreateInitialized(AOwner: TPersistent; const fromColor, toColor: TColorVector); begin Create(AOwner); FFromColor.Initialize(fromColor); FToColor.Initialize(toColor); end; destructor TVXFlareGradient.Destroy; begin FToColor.Free; FFromColor.Free; inherited; end; procedure TVXFlareGradient.Assign(Source: TPersistent); begin if Source is TVXFlareGradient then begin fromColor := TVXFlareGradient(Source).fromColor; toColor := TVXFlareGradient(Source).toColor; end; inherited; end; procedure TVXFlareGradient.SetFromColor(const val: TVXColor); begin FFromColor.Assign(val); end; procedure TVXFlareGradient.SetToColor(const val: TVXColor); begin FToColor.Assign(val); end; // ------------------ // ------------------ TVXLensFlare ------------------ // ------------------ constructor TVXLensFlare.Create(AOwner: TComponent); begin inherited; // Set default parameters: ObjectStyle := ObjectStyle + [osDirectDraw, osNoVisibilityCulling]; FSize := 50; FSeed := 1465; FSqueeze := 1; FNumStreaks := 4; FStreakWidth := 2; FNumSecs := 8; FAutoZTest := True; FlareIsNotOccluded := True; FDynamic := True; SetResolution(64); // Render all elements by default. FElements := [feGlow, feRing, feStreaks, feRays, feSecondaries]; // Setup default gradients: FGlowGradient := TVXFlareGradient.CreateInitialized(Self, VectorMake(1, 1, 0.8, 0.3), VectorMake(1, 0.2, 0, 0)); FRingGradient := TVXFlareGradient.CreateInitialized(Self, VectorMake(0.5, 0.2, 0, 0.1), VectorMake(0.5, 0.4, 0, 0.1)); FStreaksGradient := TVXFlareGradient.CreateInitialized(Self, VectorMake(1, 1, 1, 0.2), VectorMake(0.2, 0, 1, 0)); FRaysGradient := TVXFlareGradient.CreateInitialized(Self, VectorMake(1, 0.8, 0.5, 0.05), VectorMake(0.5, 0.2, 0, 0)); FSecondariesGradient := TVXFlareGradient.CreateInitialized(Self, VectorMake(0, 0.2, 1, 0), VectorMake(0, 0.8, 0.2, 0.15)); FTexRays := TVXTextureHandle.Create; end; destructor TVXLensFlare.Destroy; begin PreRenderPoint := nil; FGlowGradient.Free; FRingGradient.Free; FStreaksGradient.Free; FRaysGradient.Free; FSecondariesGradient.Free; FOcclusionQuery.Free; FTexRays.Free; inherited; end; procedure TVXLensFlare.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent = FPreRenderPoint) then PreRenderPoint := nil; inherited; end; procedure TVXLensFlare.SetupRenderingOptions(StateCache: TVXStateCache); begin with StateCache do begin Disable(stLighting); Disable(stDepthTest); Disable(stFog); Disable(stColorMaterial); Disable(stCullFace); DepthWriteMask := False; Enable(stBlend); SetBlendFunc(bfSrcAlpha, bfOne); Disable(stAlphaTest); PolygonMode := pmFill; end; end; procedure TVXLensFlare.RenderRays(StateCache: TVXStateCache; const size: Single); var i: Integer; rnd: Single; begin {$IFDEF USE_OPENGL_DEBUG} if GL.GREMEDY_string_marker then GL.StringMarkerGREMEDY(14, 'LensFlare.Rays'); {$ENDIF} with StateCache do begin LineWidth := 1; Disable(stLineSmooth); Disable(stLineStipple); end; glBegin(GL_LINES); for i := 0 to Resolution * 20 - 1 do begin if (i and 1) <> 0 then rnd := 1.5 * Random * size else rnd := Random * size; glColor4fv(RaysGradient.fromColor.AsAddress); glVertex2f(0, 0); glColor4fv(RaysGradient.toColor.AsAddress); glVertex2f(rnd * FCos20Res[i], rnd * FSin20Res[i] * Squeeze); end; glEnd; end; procedure TVXLensFlare.RenderStreaks(StateCache: TVXStateCache); var i: Integer; a, f, s, c: Single; begin {$IFDEF USE_OPENGL_DEBUG} if GL.GREMEDY_string_marker then GL.StringMarkerGREMEDY(17, 'LensFlare.Streaks'); {$ENDIF} StateCache.Enable(stLineSmooth); StateCache.LineWidth := StreakWidth; a := c2PI / NumStreaks; f := 1.5 * FCurrSize; glBegin(GL_LINES); for i := 0 to NumStreaks - 1 do begin SinCosine(StreakAngle * cPIdiv180 + a * i, f, s, c); glColor4fv(StreaksGradient.fromColor.AsAddress); glVertex3fv(@NullVector); glColor4fv(StreaksGradient.toColor.AsAddress); glVertex2f(c, Squeeze * s); end; glEnd; StateCache.Disable(stLineSmooth); end; procedure TVXLensFlare.RenderRing; var i: Integer; rW, s0, c0, s, c: Single; begin {$IFDEF USE_OPENGL_DEBUG} if GL.GREMEDY_string_marker then GL.StringMarkerGREMEDY(14, 'LensFlare.Ring'); {$ENDIF} rW := FCurrSize * (1 / 15); // Ring width glBegin(GL_QUADS); s0 := 0; c0 := 0.6; for i := 0 to Resolution - 1 do begin s := s0; c := c0; s0 := FSinRes[i] * 0.6 * Squeeze; c0 := FCosRes[i] * 0.6; glColor4fv(GlowGradient.toColor.AsAddress); glVertex2f((FCurrSize - rW) * c, (FCurrSize - rW) * s); glColor4fv(RingGradient.fromColor.AsAddress); glVertex2f(FCurrSize * c, Squeeze * FCurrSize * s); glVertex2f(FCurrSize * c0, FCurrSize * s0); glColor4fv(GlowGradient.toColor.AsAddress); glVertex2f((FCurrSize - rW) * c0, (FCurrSize - rW) * s0); glColor4fv(RingGradient.fromColor.AsAddress); glVertex2f(FCurrSize * c, FCurrSize * s); glVertex2f(FCurrSize * c0, FCurrSize * s0); glColor4fv(GlowGradient.toColor.AsAddress); glVertex2f((FCurrSize + rW) * c0, (FCurrSize + rW) * s0); glVertex2f((FCurrSize + rW) * c, (FCurrSize + rW) * s); end; glEnd; end; procedure TVXLensFlare.RenderSecondaries(const posVector: TAffineVector); var i, j: Integer; rnd: Single; v: TAffineVector; grad: TVXFlareGradient; begin {$IFDEF USE_OPENGL_DEBUG} if GL.GREMEDY_string_marker then GL.StringMarkerGREMEDY(21, 'LensFlare.Secondaries'); {$ENDIF} // Other secondaries (plain gradiented circles, like the glow): for j := 1 to NumSecs do begin rnd := 2 * Random - 1; // If rnd < 0 then the secondary glow will end up on the other side // of the origin. In this case, we can push it really far away from // the flare. If the secondary is on the flare's side, we pull it // slightly towards the origin to avoid it winding up in the middle // of the flare. if rnd < 0 then v := VectorScale(posVector, rnd) else v := VectorScale(posVector, 0.8 * rnd); if j mod 3 = 0 then grad := GlowGradient else grad := SecondariesGradient; rnd := (Random + 0.1) * FCurrSize * 0.25; glBegin(GL_TRIANGLE_FAN); glColor4fv(grad.fromColor.AsAddress); glVertex2f(v.X, v.Y); glColor4fv(grad.toColor.AsAddress); for i := 0 to Resolution - 1 do glVertex2f(FCosRes[i] * rnd + v.X, FSinRes[i] * rnd + v.Y); glEnd; end; end; procedure TVXLensFlare.BuildList(var rci: TVXRenderContextInfo); var i: Integer; depth, dist: Single; posVector, v, rv: TAffineVector; screenPos: TAffineVector; flareInViewPort, dynamicSize: Boolean; oldSeed: LongInt; projMatrix: TMatrix; CurrentBuffer: TVXSceneBuffer; begin if (rci.drawState = dsPicking) then begin if Count <> 0 then Self.RenderChildren(0, Count - 1, rci); Exit; end; CurrentBuffer := TVXSceneBuffer(rci.buffer); SetVector(v, AbsolutePosition); // are we looking towards the flare? rv := VectorSubtract(v, PAffineVector(@rci.cameraPosition)^); if VectorDotProduct(rci.cameraDirection, rv) > 0 then begin // find out where it is on the screen. screenPos := CurrentBuffer.WorldToScreen(v); flareInViewPort := (screenPos.X < rci.viewPortSize.cx) and (screenPos.X >= 0) and (screenPos.Y < rci.viewPortSize.cy) and (screenPos.Y >= 0); end else flareInViewPort := False; dynamicSize := FDynamic and not(csDesigning in ComponentState); if dynamicSize then begin // make the glow appear/disappear progressively if flareInViewPort and FlareIsNotOccluded then begin FCurrSize := FCurrSize + FDeltaTime * 10 * size; if FCurrSize > size then FCurrSize := size; end else begin FCurrSize := FCurrSize - FDeltaTime * 10 * size; if FCurrSize < 0 then FCurrSize := 0; end; end else begin if flareInViewPort and FlareIsNotOccluded then FCurrSize := size else FCurrSize := 0; end; // Prepare matrices glPushMatrix; glLoadMatrixf(@CurrentBuffer.BaseProjectionMatrix); glMatrixMode(GL_PROJECTION); glPushMatrix; projMatrix := IdentityHmgMatrix; projMatrix.X.X := 2 / rci.viewPortSize.cx; projMatrix.Y.Y := 2 / rci.viewPortSize.cy; glLoadMatrixf(@projMatrix); MakeVector(posVector, screenPos.X - rci.viewPortSize.cx * 0.5, screenPos.Y - rci.viewPortSize.cy * 0.5, 0); if AutoZTest then begin if dynamicSize and (TVXOcclusionQueryHandle.IsSupported = True) then //GL_OCCLUSION_TEST_HP begin // hardware-based occlusion test is possible FlareIsNotOccluded := True; rci.VXStates.SetColorMask([]); rci.VXStates.Disable(stAlphaTest); rci.VXStates.DepthWriteMask := GLboolean(False); rci.VXStates.Enable(stDepthTest); rci.VXStates.DepthFunc := cfLEqual; if TVXOcclusionQueryHandle.IsSupported > False then begin // preferred method, doesn't stall rendering too badly if not Assigned(FOcclusionQuery) then FOcclusionQuery := TVXOcclusionQueryHandle.Create; FOcclusionQuery.AllocateHandle; if FOcclusionQuery.IsDataNeedUpdate then FOcclusionQuery.NotifyDataUpdated else FlareIsNotOccluded := (FOcclusionQuery.PixelCount <> 0); FOcclusionQuery.BeginQuery; end else begin // occlusion_test, stalls rendering a bit glEnable(GL_OCCLUSION_TEST_HP); end; glBegin(GL_QUADS); glVertex3f(posVector.X + 2, posVector.Y, 1); glVertex3f(posVector.X, posVector.Y + 2, 1); glVertex3f(posVector.X - 2, posVector.Y, 1); glVertex3f(posVector.X, posVector.Y - 2, 1); glEnd; if TVXOcclusionQueryHandle.IsSupported > False then FOcclusionQuery.EndQuery else begin glDisable(GL_OCCLUSION_TEST_HP); glGetBooleanv(GL_OCCLUSION_TEST_RESULT_HP, @FFlareIsNotOccluded) end; rci.VXStates.DepthFunc := cfLEqual; rci.VXStates.SetColorMask(cAllColorComponents); end else begin // Compares the distance to the lensflare, to the z-buffer depth. // This prevents the flare from being occluded by objects BEHIND the light. depth := CurrentBuffer.PixelToDistance(Round(screenPos.X), Round(rci.viewPortSize.cy - screenPos.Y)); dist := VectorDistance(rci.cameraPosition, Self.AbsolutePosition); FlareIsNotOccluded := ((dist - depth) < 1); end; end; if FCurrSize >= 0 then begin // Random seed must be backed up, could be used for other purposes // (otherwise we essentially reset the random generator at each frame) oldSeed := RandSeed; RandSeed := Seed; SetupRenderingOptions(rci.VXStates); if [feGlow, feStreaks, feRays, feRing] * Elements <> [] then begin glTranslatef(posVector.X, posVector.Y, posVector.Z); // Glow (a circle with transparent edges): if feGlow in Elements then begin glBegin(GL_TRIANGLE_FAN); glColor4fv(GlowGradient.fromColor.AsAddress); glVertex2f(0, 0); glColor4fv(GlowGradient.toColor.AsAddress); for i := 0 to Resolution - 1 do glVertex2f(FCurrSize * FCosRes[i], Squeeze * FCurrSize * FSinRes[i]); glEnd; end; if feStreaks in Elements then RenderStreaks(rci.VXStates); // Rays (random-length lines from the origin): if feRays in Elements then begin if FTexRays.Handle <> 0 then begin {$IFDEF USE_OPENGL_DEBUG} if GL.GREMEDY_string_marker then GL.StringMarkerGREMEDY(19, 'LensFlare.RaysQuad'); {$ENDIF} rci.VXStates.TextureBinding[0, ttTexture2D] := FTexRays.Handle; rci.VXStates.ActiveTextureEnabled[ttTexture2D] := True; glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(-FCurrSize, -FCurrSize); glTexCoord2f(1, 0); glVertex2f(FCurrSize, -FCurrSize); glTexCoord2f(1, 1); glVertex2f(FCurrSize, FCurrSize); glTexCoord2f(0, 1); glVertex2f(-FCurrSize, FCurrSize); glEnd; rci.VXStates.ActiveTextureEnabled[ttTexture2D] := False; end else RenderRays(rci.VXStates, FCurrSize); end; if feRing in Elements then RenderRing; glLoadMatrixf(@projMatrix); end; if feSecondaries in Elements then RenderSecondaries(posVector); RandSeed := oldSeed; end; glPopMatrix; glMatrixMode(GL_MODELVIEW); glPopMatrix; if Count > 0 then Self.RenderChildren(0, Count - 1, rci); end; procedure TVXLensFlare.DoProgress(const progressTime: TVXProgressTimes); begin inherited; FDeltaTime := progressTime.deltaTime; end; procedure TVXLensFlare.PreRender(activeBuffer: TVXSceneBuffer); var texSize, maxSize: Integer; StateCache: TVXStateCache; begin if FTexRays.Handle <> 0 then Exit; with activeBuffer.RenderingContext do begin StateCache := VXStates; PipelineTransformation.Push; PipelineTransformation.SetProjectionMatrix(CreateOrthoMatrix(0, activeBuffer.Width, 0, activeBuffer.Height, -1, 1)); PipelineTransformation.SetViewMatrix(IdentityHmgMatrix); end; SetupRenderingOptions(StateCache); texSize := RoundUpToPowerOf2(size); if texSize < size * 1.5 then texSize := texSize * 2; glGetIntegerv(GL_MAX_TEXTURE_SIZE, @maxSize); if texSize > maxSize then texSize := maxSize; StateCache.Disable(stBlend); glColor4f(0, 0, 0, 0); glBegin(GL_QUADS); glVertex2f(0, 0); glVertex2f(texSize + 4, 0); glVertex2f(texSize + 4, texSize + 4); glVertex2f(0, texSize + 4); glEnd; StateCache.Enable(stBlend); glTranslatef(texSize * 0.5 + 2, texSize * 0.5 + 2, 0); RenderRays(StateCache, texSize * 0.5); FTexRays.AllocateHandle; StateCache.TextureBinding[0, ttTexture2D] := FTexRays.Handle; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, texSize, texSize, 0); activeBuffer.RenderingContext.PipelineTransformation.Pop; /// CheckOpenGLError; end; procedure TVXLensFlare.SetGlowGradient(const val: TVXFlareGradient); begin FGlowGradient.Assign(val); StructureChanged; end; procedure TVXLensFlare.SetRingGradient(const val: TVXFlareGradient); begin FRingGradient.Assign(val); StructureChanged; end; procedure TVXLensFlare.SetStreaksGradient(const val: TVXFlareGradient); begin FStreaksGradient.Assign(val); StructureChanged; end; procedure TVXLensFlare.SetRaysGradient(const val: TVXFlareGradient); begin FRaysGradient.Assign(val); StructureChanged; end; procedure TVXLensFlare.SetSecondariesGradient(const val: TVXFlareGradient); begin FSecondariesGradient.Assign(val); StructureChanged; end; procedure TVXLensFlare.SetSize(aValue: Integer); begin FSize := aValue; StructureChanged; end; procedure TVXLensFlare.SetSeed(aValue: Integer); begin FSeed := aValue; StructureChanged; end; procedure TVXLensFlare.SetSqueeze(aValue: Single); begin FSqueeze := aValue; StructureChanged; end; function TVXLensFlare.StoreSqueeze: Boolean; begin Result := (FSqueeze <> 1); end; procedure TVXLensFlare.SetNumStreaks(aValue: Integer); begin FNumStreaks := aValue; StructureChanged; end; procedure TVXLensFlare.SetStreakWidth(aValue: Single); begin FStreakWidth := aValue; StructureChanged; end; function TVXLensFlare.StoreStreakWidth: Boolean; begin Result := (FStreakWidth <> 2); end; procedure TVXLensFlare.SetStreakAngle(aValue: Single); begin FStreakAngle := aValue; StructureChanged; end; procedure TVXLensFlare.SetNumSecs(aValue: Integer); begin FNumSecs := aValue; StructureChanged; end; procedure TVXLensFlare.SetResolution(aValue: Integer); begin if FResolution <> aValue then begin FResolution := aValue; StructureChanged; SetLength(FSin20Res, 20 * FResolution); SetLength(FCos20Res, 20 * FResolution); PrepareSinCosCache(FSin20Res, FCos20Res, 0, 360); SetLength(FSinRes, FResolution); SetLength(FCosRes, FResolution); PrepareSinCosCache(FSinRes, FCosRes, 0, 360); end; end; procedure TVXLensFlare.SetAutoZTest(aValue: Boolean); begin if FAutoZTest <> aValue then begin FAutoZTest := aValue; StructureChanged; end; end; procedure TVXLensFlare.SetElements(aValue: TFlareElements); begin if FElements <> aValue then begin FElements := aValue; StructureChanged; end; end; procedure TVXLensFlare.SetDynamic(aValue: Boolean); begin if aValue <> FDynamic then begin FDynamic := aValue; NotifyChange(Self); end; end; procedure TVXLensFlare.SetPreRenderPoint(const val: TVXRenderPoint); begin if val <> FPreRenderPoint then begin if Assigned(FPreRenderPoint) then FPreRenderPoint.UnRegisterCallBack(Self.PreRenderEvent); FPreRenderPoint := val; if Assigned(FPreRenderPoint) then FPreRenderPoint.RegisterCallBack(Self.PreRenderEvent, Self.PreRenderPointFreed); end; end; procedure TVXLensFlare.PreRenderEvent(Sender: TObject; var rci: TVXRenderContextInfo); begin PreRender(rci.buffer as TVXSceneBuffer); end; procedure TVXLensFlare.PreRenderPointFreed(Sender: TObject); begin FPreRenderPoint := nil; end; // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ RegisterClasses([TVXLensFlare]); end.
unit Search; interface uses WinProcs, SysUtils, StdCtrls, Dialogs; const { Default word delimiters are any character except the core alphanumerics. } WordDelimiters: set of Char = [#0..#255] - ['a'..'z','A'..'Z','1'..'9','0']; { SearchMemo scans the text of a TEdit, TMemo, or other TCustomEdit-derived component for a given search string. The search starts at the current caret position in the control. The Options parameter determines whether the search runs forward (frDown) or backward from the caret position, whether or not the text comparison is case sensitive, and whether the matching string must be a whole word. If text is already selected in the control, the search starts at the 'far end' of the selection (SelStart if searching backwards, SelEnd if searching forwards). If a match is found, the control's text selection is changed to select the found text and the function returns True. If no match is found, the function returns False. } function SearchMemo(Memo: TCustomEdit; const SearchString: String; Options: TFindOptions): Boolean; { SearchBuf is a lower-level search routine for arbitrary text buffers. Same rules as SearchMemo above. If a match is found, the function returns a pointer to the start of the matching string in the buffer. If no match, the function returns nil. } function SearchBuf(Buf: PChar; BufLen: Integer; SelStart, SelLength: Integer; SearchString: String; Options: TFindOptions): PChar; implementation function SearchMemo(Memo: TCustomEdit; const SearchString: String; Options: TFindOptions): Boolean; var Buffer, P: PChar; Size: Word; begin Result := False; if (Length(SearchString) = 0) then Exit; Size := Memo.GetTextLen; if (Size = 0) then Exit; Buffer := StrAlloc(Size + 1); try Memo.GetTextBuf(Buffer, Size + 1); P := SearchBuf(Buffer, Size, Memo.SelStart, Memo.SelLength, SearchString, Options); if P <> nil then begin Memo.SelStart := P - Buffer; Memo.SelLength := Length(SearchString); Result := True; end; finally StrDispose(Buffer); end; end; function SearchBuf(Buf: PChar; BufLen: Integer; SelStart, SelLength: Integer; SearchString: String; Options: TFindOptions): PChar; var SearchCount, I: Integer; C: Char; Direction: Shortint; CharMap: array [Char] of Char; function FindNextWordStart(var BufPtr: PChar): Boolean; begin { (True XOR N) is equivalent to (not N) } Result := False; { (False XOR N) is equivalent to (N) } { When Direction is forward (1), skip non delimiters, then skip delimiters. } { When Direction is backward (-1), skip delims, then skip non delims } while (SearchCount > 0) and ((Direction = 1) xor (BufPtr^ in WordDelimiters)) do begin Inc(BufPtr, Direction); Dec(SearchCount); end; while (SearchCount > 0) and ((Direction = -1) xor (BufPtr^ in WordDelimiters)) do begin Inc(BufPtr, Direction); Dec(SearchCount); end; Result := SearchCount >= 0; if (Direction = -1) and (BufPtr^ in WordDelimiters) then begin { back up one char, to leave ptr on first non delim } Dec(BufPtr, Direction); Inc(SearchCount); end; end; begin Result := nil; if BufLen <= 0 then Exit; if frDown in Options then begin Direction := 1; Inc(SelStart, SelLength); { start search past end of selection } SearchCount := BufLen - SelStart - Length(SearchString); { SearchCount := BufLen - SelStart - Length(SearchString) + 1;} if SearchCount < 0 then Exit; if Longint(SelStart) + SearchCount > BufLen then Exit; end else begin Direction := -1; Dec(SelStart, Length(SearchString)); SearchCount := SelStart; { SearchCount := SelStart + 1;} end; if (SelStart < 0) or (SelStart > BufLen) then Exit; Result := @Buf[SelStart]; { Using a Char map array is faster than calling AnsiUpper on every character } for C := Low(CharMap) to High(CharMap) do CharMap[C] := C; if not (frMatchCase in Options) then begin AnsiUpperBuff(PChar(@CharMap), sizeof(CharMap)); AnsiUpperBuff(@SearchString[1], Length(SearchString)); end; while SearchCount >= 0 do begin if frWholeWord in Options then if not FindNextWordStart(Result) then Break; I := 0; while (CharMap[Result[I]] = SearchString[I+1]) do begin Inc(I); if I >= Length(SearchString) then begin if (not (frWholeWord in Options)) or (SearchCount = 0) or (Result[I] in WordDelimiters) then Exit; Break; end; end; Inc(Result, Direction); Dec(SearchCount); end; Result := nil; end; end.
{******************************************************************************* Title: iTEC-SOFTWARE Description: VO relational the table [NFC_01] The MIT License Copyright: Copyright (C) 2010 www.itecsoftware.com.br Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: william@itecsoftware.com.br @author William (william_mk@hotmail.com) @version 1.0 *******************************************************************************} unit Nfc01VO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('NFC_01')] TNfc01VO = class(TVO) private FID: Integer; FID_VENDA: Integer; FAMBIENTE: Integer; FMODELO: Integer; FSERIE: Integer; FUF: String; FIBGE_CIDADE: Integer; FSOFT_HOUSE: String; FSUBTOTAL: Extended; FDESCONTO: Extended; FTOTAL: Extended; FTROCO: Extended; FCLIENTE_NOME: String; FCLIENTE_DOC: String; FCHAVE: String; FQRCODE: String; FENVIADA: String; public [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_VENDA','Id Venda',80,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdVenda: Integer read FID_VENDA write FID_VENDA; [TColumn('AMBIENTE','Ambiente',80,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Ambiente: Integer read FAMBIENTE write FAMBIENTE; [TColumn('MODELO','Modelo',80,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Modelo: Integer read FMODELO write FMODELO; [TColumn('SERIE','Serie',80,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Serie: Integer read FSERIE write FSERIE; [TColumn('UF','Uf',16,[ldGrid, ldLookup, ldCombobox], False)] property Uf: String read FUF write FUF; [TColumn('IBGE_CIDADE','Ibge Cidade',80,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IbgeCidade: Integer read FIBGE_CIDADE write FIBGE_CIDADE; [TColumn('SOFT_HOUSE','Soft House',450,[ldGrid, ldLookup, ldCombobox], False)] property SoftHouse: String read FSOFT_HOUSE write FSOFT_HOUSE; [TColumn('SUBTOTAL','Subtotal',128,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Subtotal: Extended read FSUBTOTAL write FSUBTOTAL; [TColumn('DESCONTO','Desconto',128,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Desconto: Extended read FDESCONTO write FDESCONTO; [TColumn('TOTAL','Total',128,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Total: Extended read FTOTAL write FTOTAL; [TColumn('TROCO','Troco',128,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Troco: Extended read FTROCO write FTROCO; [TColumn('CLIENTE_NOME','Cliente Nome',450,[ldGrid, ldLookup, ldCombobox], False)] property ClienteNome: String read FCLIENTE_NOME write FCLIENTE_NOME; [TColumn('CLIENTE_DOC','Cliente Doc',112,[ldGrid, ldLookup, ldCombobox], False)] property ClienteDoc: String read FCLIENTE_DOC write FCLIENTE_DOC; [TColumn('CHAVE','Chave',360,[ldGrid, ldLookup, ldCombobox], False)] property Chave: String read FCHAVE write FCHAVE; [TColumn('QRCODE','Qrcode',450,[ldGrid, ldLookup, ldCombobox], False)] property Qrcode: String read FQRCODE write FQRCODE; [TColumn('ENVIADA','Enviada',8,[ldGrid, ldLookup, ldCombobox], False)] property Enviada: String read FENVIADA write FENVIADA; end; implementation end.
unit uDMPOS; interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, uDMParent, ADODB, DB, ImgList, ufrmServerInfo, Registry, PowerADOQuery, LookUpADOQuery, Provider, DBClient; type TDMPOS = class(TDMParent) ADOCommand: TADOCommand; imgLarge: TImageList; dsLookUpCashReg: TDataSource; LookUpCashReg: TLookUpADOQuery; LookUpCashRegIDCashRegister: TIntegerField; LookUpCashRegName: TStringField; quSearchPreSale: TADOQuery; quSearchCashRegMov: TADOQuery; quRun: TADOQuery; quSearchPreSaleID: TADOQuery; LookUpStore: TLookUpADOQuery; dsLookUpStore: TDataSource; LookUpStoreIDStore: TIntegerField; LookUpStoreName: TStringField; procedure DataModuleCreate(Sender: TObject); private FrmServerInfo: TFrmServerInfo; function StartConnection(AForceDialog: Boolean = False):Boolean; function StopConnection: Boolean; function FomartConnection(sParam: String): String; protected public procedure CloseConnection; function OpenConnection(AForceDialog: Boolean = False):Boolean; function GetConnectionInfo(sConnection: String): String; function GetConnection(AForceDialog: Boolean = False) : String; end; var DMPOS: TDMPOS; implementation uses uParamFunctions, uSystemConst, uDMGlobal, uMainConf, uOperationSystem; {$R *.dfm} procedure TDMPOS.DataModuleCreate(Sender: TObject); var buildInfo: String; begin inherited; // Abre o registry with TRegistry.Create do begin // to run in windows Vista and Windows 7 if ( getOS(buildInfo) = osW7 ) then RootKey := HKEY_CURRENT_USER else RootKey := HKEY_LOCAL_MACHINE; OpenKey(REGISTRY_PATH, True); if not ValueExists('DefaultLanguage') then WriteInteger('DefaultLanguage', LANG_ENGLISH); DMGlobal.IDLanguage := ReadInteger('DefaultLanguage'); Free; end; end; function TDMPOS.GetConnection(AForceDialog: Boolean = False) : String; var b: Boolean; begin //Server Connection b := False; if FrmServerInfo = nil then FrmServerInfo := TFrmServerInfo.Create(self); //Server Connection Result := FrmServerInfo.Start('4', AForceDialog, '', b); end; function TDMPOS.GetConnectionInfo(sConnection:String):String; var sServer, sDBAlias, sUserName, sPW : String; bWinLogin, bUseNetLib : String; begin sServer := ParseParam(sConnection, SV_SERVER); sDBAlias := ParseParam(sConnection, SV_DATABASE); sUserName := ParseParam(sConnection, SV_USER); sPW := ParseParam(sConnection, SV_PASSWORD); bWinLogin := ParseParam(sConnection, SV_WIN_LOGIN); bUseNetLib := ParseParam(sConnection, SV_USE_NETLIB); Result := 'Server=' + sServer + ';Database=' + sDBAlias + ';User=' + sUserName +' ;WinLogin=' + bWinLogin + ';UseNetLib=' + bUseNetLib + ';'; end; function TDMPOS.StartConnection(AForceDialog: Boolean = False):Boolean; begin Result := OpenConnection(AForceDialog); end; function TDMPOS.StopConnection:Boolean; begin CloseConnection; end; function TDMPOS.OpenConnection(AForceDialog: Boolean = False):Boolean; var sResult : String; b: Boolean; begin Result := False; //Connection open, exit if ADODBConnect.Connected then begin Result := True; Exit; end; //Server Connection b := False; sResult := GetConnection(AForceDialog); while not b do try sResult := FomartConnection(sResult); ADODBConnect.ConnectionString := sResult; ADODBConnect.Open; b := True; Result := True; except on E: Exception do sResult := FrmServerInfo.Start('4', True, E.Message, b); end; end; procedure TDMPOS.CloseConnection; begin if ADODBConnect.Connected then ADODBConnect.Close; end; function TDMPOS.FomartConnection(sParam: String): String; var sServer, sDBAlias, sUserName, sPW : String; bWinLogin, bUseNetLib : Boolean; begin sServer := ParseParam(sParam, SV_SERVER); sDBAlias := ParseParam(sParam, SV_DATABASE); sUserName := ParseParam(sParam, SV_USER); sPW := ParseParam(sParam, SV_PASSWORD); bWinLogin := (ParseParam(sParam, SV_WIN_LOGIN)[1] in ['Y']); bUseNetLib := (ParseParam(sParam, SV_USE_NETLIB)[1] = 'Y'); if not bWinLogin then if bUseNetLib then Result := SetConnectionStr(sUserName, sPW, sDBAlias, sServer) else Result := SetConnectionStrNoNETLIB(sUserName, sPW, sDBAlias, sServer) else if bUseNetLib then Result := SetWinConnectionStr(sDBAlias, sServer) else Result := SetWinConnectionStrNoNETLIB(sDBAlias, sServer); end; end.
unit fBitmap; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ExtDlgs, Vcl.Imaging.Jpeg, uGlobal; type TBitmapForm = class(TForm) Label1: TLabel; EditScale: TEdit; UnitRG: TRadioGroup; Label2: TLabel; EditWidth: TEdit; Label3: TLabel; EditHeight: TEdit; OKBitBtn: TBitBtn; SavePictureDialog: TSavePictureDialog; WidthLabel: TLabel; HeightLabel: TLabel; ColorDialog: TColorDialog; Label6: TLabel; EditBorder: TEdit; ColorButton: TSpeedButton; CloseBitBtn: TBitBtn; Label4: TLabel; procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FloatKeyPress(Sender: TObject; var Key: Char); procedure ScaleKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure numKeyPress(Sender: TObject; var Key: Char); procedure WidthKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure HeightKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure UnitRGClick(Sender: TObject); procedure EditBorderKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure ColorButtonClick(Sender: TObject); procedure EditBorderKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure CloseBitBtnClick(Sender: TObject); private bmpScale: double; bmpWidth: integer; { as pixels } bmpHeight: integer; { as pixels } BorderWidth: integer; BorderColor: TColor; procedure ShowData(Sender: TObject); function PixelTomm(v: integer): double; function PixelTocm(v: integer): double; function PixelToInch(v: integer): double; function mmToPixel(v: double): integer; function cmToPixel(v: double): integer; function InchToPixel(v: double): integer; end; var BitmapForm: TBitmapForm; //===================================================================== implementation //===================================================================== uses fMain; {$R *.dfm} procedure TBitmapForm.FormCreate(Sender: TObject); begin with Layout do begin if bmpScale = 0 then begin Left := (Screen.Width - Width) div 2; Top := (Screen.Height - Height) div 2; UnitRG.ItemIndex := 0; bmpScale := 1; BorderColor := ClRed; BorderWidth := 5; end else begin Left := BitmapLeft; Top := BitmapTop; UnitRG.ItemIndex := BitmapUnit; bmpScale := BitmapScale; BorderColor := BitmapBorderColor; BorderWidth := BitmapBorderWidth; end; end; bmpWidth := round(bmpScale*MainForm.GLViewer.Width); bmpHeight := round(bmpScale*MainForm.GLViewer.Height); ShowData(Sender); end; procedure TBitmapForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var BorderRect: TRect; GraphRect: TRect; bmp: TBitmap; jpg: TJPEGImage; filebmp: TBitmap; fName: TFileName; isJpeg: Boolean; function ScanText(const s: string): string; var i: integer; begin Result := s; for i := 1 to Length(s) do if CharInSet(Result[i], ['/', '\', ':', '*', '?', '<', '>', '|']) then Result[i] := ' '; end; begin if ModalResult = mrOK then begin isJpeg := pos('.jpg', Caption) > 0; BorderRect := Rect(BorderWidth div 2, BorderWidth div 2, bmpWidth - BorderWidth div 2 + 1, bmpHeight - BorderWidth div 2 + 1); GraphRect := Rect(0, 0, bmpWidth - 2*BorderWidth, bmpHeight - 2*BorderWidth); with SavePictureDialog do begin FName := ScanText(GraphData.PlotData.TextStr); if isJpeg then begin Filter := 'Jpeg (*.jpg)|*.jpg'; Title := 'Save Graph as ''.jpg'' File'; FileName := FName+'.jpg'; end else begin Filter := 'Bitmaps (*.bmp)|*.bmp'; Title := 'Save Graph as ''.bmp'' File'; FileName := FName+'.bmp'; end; InitialDir := ImagePath; if Execute then begin jpg := nil; if isJpeg then begin jpg := TJPEGImage.Create; jpg.CompressionQuality := 100; { default is 90; range 1..100; 100 best quality } end; bmp := TBitmap.Create; filebmp := TBitmap.Create; try bmp.PixelFormat := pf32bit; { bmp is a device-independent true-color 32 bits per pixel bitmap. } with GraphRect do begin bmp.Width := Right - Left; bmp.Height := Bottom - Top; end; filebmp.PixelFormat := pf32bit; with BorderRect do begin filebmp.Width := Right - Left + BorderWidth -1; filebmp.Height := Bottom - Top + BorderWidth -1; end; MainForm.GLViewer.Invalidate;; with MainForm.GLMemoryViewer do begin Width := bmp.Width; Height := bmp.Height; Buffer.BackgroundColor := GraphData.BackColor; Render; bmp := Buffer.CreateSnapShotBitmap; end; filebmp.Canvas.Pen.Color := BorderColor; filebmp.Canvas.Pen.Width := BorderWidth; filebmp.Canvas.Rectangle(BorderRect); filebmp.Canvas.Draw(BorderWidth, BorderWidth, bmp); if isJpeg then begin jpg.Assign(filebmp); jpg.SaveToFile(FileName); end else filebmp.SaveToFile(FileName); finally bmp.Free; filebmp.Free; if isJpeg then jpg.Free; end; ImagePath := ExtractFilePath(FileName); ImagePath := IncludeTrailingPathDelimiter(ImagePath); end; end; end; with Layout do begin BitmapLeft := Left; BitmapTop := Top; BitmapUnit := UnitRG.ItemIndex; BitmapScale := bmpScale; BitmapBorderColor := BorderColor; BitmapBorderWidth := BorderWidth; end; end; procedure TBitmapForm.FormShow(Sender: TObject); begin UnitRG.SetFocus; UnitRG.ItemIndex := 0; UnitRGClick(Sender); EditScale.SetFocus; end; procedure TBitmapForm.ColorButtonClick(Sender: TObject); begin ColorDialog.Color := BorderColor; if ColorDialog.Execute then BorderColor := ColorDialog.Color; end; procedure TBitmapForm.EditBorderKeyPress(Sender: TObject; var Key: Char); begin if not CharInSet(Key, ['0'..'9', #8]) then Key := #0 end; procedure TBitmapForm.EditBorderKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var v: integer; begin try v := StrToInt(EditBorder.Text); except v := 10; end; BorderWidth := v; ShowData(Sender); end; procedure TBitmapForm.FloatKeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do if not CharInSet(Key, ['0'..'9', '.', #8]) then Key := #0 end; procedure TBitmapForm.ScaleKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin try bmpScale := StrToFloat(EditScale.Text); except bmpScale := 1.0; end; bmpWidth := round(bmpScale*MainForm.GLViewer.Width); bmpHeight := round(bmpScale*MainForm.GLViewer.Height); ShowData(Sender); end; procedure TBitmapForm.numKeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do begin if UnitRG.ItemIndex = 0 then begin if not CharInSet(Key,['0'..'9', #8]) then Key := #0 end else if not CharInSet(Key, ['0'..'9', '.', #8]) then Key := #0 end; end; procedure TBitmapForm.WidthKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var v: double; begin try v := StrToFloat(EditWidth.Text); except v := bmpScale*MainForm.GLViewer.Width; end; case UnitRG.ItemIndex of 0:bmpWidth := round(v); 1:bmpWidth := mmToPixel(v); 2:bmpWidth := cmToPixel(v); 3:bmpWidth := InchToPixel(v); end; bmpScale := bmpWidth/MainForm.GLViewer.Width; bmpHeight := round(bmpScale*MainForm.GLViewer.Height); ShowData(Sender); end; procedure TBitmapForm.HeightKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var v: double; begin try v := StrToFloat(EditHeight.Text); except v := bmpScale*MainForm.GLViewer.Height; end; case UnitRG.ItemIndex of 0:bmpHeight := round(v); 1:bmpHeight := mmToPixel(v); 2:bmpHeight := cmToPixel(v); 3:bmpHeight := InchToPixel(v); end; bmpScale := bmpHeight/MainForm.GLViewer.Height; bmpWidth := round(bmpScale*MainForm.GLViewer.Width); ShowData(Sender); end; procedure TBitmapForm.UnitRGClick(Sender: TObject); begin ShowData(Sender); end; procedure TBitmapForm.ShowData(Sender: TObject); procedure TagIsZero; { not a change in the edit fields: Scale Width or Height } begin { TagIsZero } EditScale.Text := FloatToStrF(bmpScale, ffFixed, 8, 2); case UnitRg.ItemIndex of 0:begin { Pixels } EditWidth.Text := IntToStr(bmpWidth); EditHeight.Text := IntToStr(bmpHeight); WidthLabel.Caption := 'Pixels'; HeightLabel.Caption := 'Pixels'; end; 1:begin { mm } EditWidth.Text := FloatToStrF(PixelTomm(bmpWidth), ffFixed, 8, 2); EditHeight.Text := FloatToStrF(PixelTomm(bmpHeight), ffFixed, 8, 2); WidthLabel.Caption := 'mm'; HeightLabel.Caption := 'mm'; end; 2:begin { cm } EditWidth.Text := FloatToStrF(PixelTocm(bmpWidth), ffFixed, 8, 2); EditHeight.Text := FloatToStrF(PixelTocm(bmpHeight), ffFixed, 8, 2); WidthLabel.Caption := 'cm'; HeightLabel.Caption := 'cm'; end; 3:begin { inch } EditWidth.Text := FloatToStrF(PixelToInch(bmpWidth), ffFixed, 8, 2); EditHeight.Text := FloatToStrF(PixelToInch(bmpHeight), ffFixed, 8, 2); WidthLabel.Caption := 'inches'; HeightLabel.Caption := 'inches'; end; end; end; begin if Sender is TEdit then begin with Sender as TEdit do case Tag of 0:TagIsZero; { Factor } 1:begin { Scale } case UnitRg.ItemIndex of 0:begin EditWidth.Text := IntToStr(bmpWidth); EditHeight.Text := IntToStr(bmpHeight); end; 1:begin EditWidth.Text := FloatToStrF(PixelTomm(bmpWidth), ffFixed, 8, 2); EditHeight.Text := FloatToStrF(PixelTomm(bmpHeight), ffFixed, 8, 2); end; 2:begin EditWidth.Text := FloatToStrF(PixelTocm(bmpWidth), ffFixed, 8, 2); EditHeight.Text := FloatToStrF(PixelTocm(bmpHeight), ffFixed, 8, 2); end; 3:begin EditWidth.Text := FloatToStrF(PixelToInch(bmpWidth), ffFixed, 8, 2); EditHeight.Text := FloatToStrF(PixelToInch(bmpHeight), ffFixed, 8, 2); end; end; end; 2:begin { Width } EditScale.Text := FloatToStrF(bmpScale, ffFixed, 8, 2); case UnitRg.ItemIndex of 0:EditHeight.Text := IntToStr(bmpHeight); 1:EditHeight.Text := FloatToStrF(PixelTomm(bmpHeight), ffFixed, 8, 2); 2:EditHeight.Text := FloatToStrF(PixelTocm(bmpHeight), ffFixed, 8, 2); 3:EditHeight.Text := FloatToStrF(PixelToInch(bmpHeight), ffFixed, 8, 2); end; end; 3:begin { Height } EditScale.Text := FloatToStrF(bmpScale, ffFixed, 8, 2); case UnitRg.ItemIndex of 0:EditWidth.Text := IntToStr(bmpWidth); 1:EditWidth.Text := FloatToStrF(PixelTomm(bmpWidth), ffFixed, 8, 2); 2:EditWidth.Text := FloatToStrF(PixelTocm(bmpWidth), ffFixed, 8, 2); 3:EditWidth.Text := FloatToStrF(PixelToInch(bmpWidth), ffFixed, 8, 2); end; end; end; end else TagIsZero; { UnitRG } EditBorder.Text := IntToStr(BorderWidth); end; function TBitmapForm.PixelTomm(v: integer): double; begin Result := 25.4*v/Screen.PixelsPerInch; end; function TBitmapForm.PixelTocm(v: integer): double; begin Result := 2.54*v/Screen.PixelsPerInch; end; function TBitmapForm.PixelToInch(v: integer): double; begin Result := v/Screen.PixelsPerInch; end; function TBitmapForm.mmToPixel(v: double): integer; begin Result := round(Screen.PixelsPerInch*v/25.4); end; procedure TBitmapForm.CloseBitBtnClick(Sender: TObject); begin Close; end; function TBitmapForm.cmToPixel(v: double): integer; begin Result := round(Screen.PixelsPerInch*v/2.54); end; function TBitmapForm.InchToPixel(v: double): integer; begin Result := round(Screen.PixelsPerInch*v); end; end.
unit Odontologia.Controlador.Pedido; interface uses Data.DB, System.SysUtils, System.Generics.Collections, Odontologia.Controlador.Pedido.Interfaces, Odontologia.Controlador.PedidoItem, Odontologia.Modelo.Entidades.Pedido, Odontologia.Modelo.Pedido.Interfaces, Odontologia.Modelo; type TControllerPedido = class(TInterfacedObject, iControllerPedido) private FModel: iModelPedido; FDataSource: TDataSource; Flista: TObjectList<TPEDIDO>; FPedidoItem: iControllerPedidoItem; procedure DataChange (sender : tobject ; field : Tfield) ; public constructor Create; destructor Destroy; override; class function New : iControllerPedido; function DataSource(aDataSource: TDataSource): iControllerPedido; function Buscar: iControllerPedido; function Insertar: iControllerPedido; function Modificar: iControllerPedido; function Eliminar: iControllerPedido; function Entidad: TPEDIDO; function Item: iControllerPedidoItem; end; implementation { TControllerPedido } function TControllerPedido.Buscar: iControllerPedido; begin Result := Self; Flista := TObjectList<TPEDIDO>.Create; FModel.DAO.Find(Flista); end; constructor TControllerPedido.Create; begin FModel := TModel.New.Pedido; Fpedidoitem := TcontrollerpedidoItem.new; end; procedure TControllerPedido.DataChange(sender: tobject; field: Tfield); begin Fpedidoitem.buscar(FDataSource.DataSet.FieldByName('ID').AsInteger); end; function TControllerPedido.DataSource(aDataSource: TDataSource) : iControllerPedido; begin Result := Self; FDataSource := aDataSource; FModel.DataSource(FDataSource); FDataSource.OnDataChange := DataChange; end; destructor TControllerPedido.Destroy; begin if Assigned(Flista) then Flista.Free; inherited; end; function TControllerPedido.Eliminar: iControllerPedido; begin Result := Self; FModel.DAO.Delete(FModel.Entidad); end; function TControllerPedido.Entidad: TPEDIDO; begin Result := FModel.Entidad; end; function TControllerPedido.Insertar: iControllerPedido; begin Result := Self; FModel.DAO.Insert(FModel.Entidad); end; function TControllerPedido.Item: iControllerPedidoItem; begin Result := FPedidoItem; end; function TControllerPedido.Modificar: iControllerPedido; begin Result := Self; FModel.DAO.Update(FModel.Entidad); end; class function TControllerPedido.New: iControllerPedido; begin Result := Self.Create; end; end.
unit uPicturesImportPatternEdit; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Dmitry.Controls.WatermarkedMemo, uDBForm, uSettings, uConstants; type TPicturesImportPatternEdit = class(TDBForm) WmPatterns: TWatermarkedMemo; ImInfo: TImage; LbInfo: TLabel; BtnOk: TButton; BtnCancel: TButton; procedure BtnCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BtnOkClick(Sender: TObject); procedure WmPatternsChange(Sender: TObject); private { Private declarations } procedure LoadLanguage; protected { Protected declarations } function GetFormID: string; override; procedure CustomFormAfterDisplay; override; public { Public declarations } end; implementation {$R *.dfm} { TPicturesImportPatternEdit } procedure TPicturesImportPatternEdit.BtnCancelClick(Sender: TObject); begin Close; end; procedure TPicturesImportPatternEdit.BtnOkClick(Sender: TObject); begin if WmPatterns.Lines.Count > 0 then begin AppSettings.WriteString('ImportPictures', 'PatternList', WmPatterns.Text); Close; ModalResult := mrOk; end; end; procedure TPicturesImportPatternEdit.CustomFormAfterDisplay; begin inherited; if WmPatterns <> nil then WmPatterns.Refresh; end; procedure TPicturesImportPatternEdit.FormCreate(Sender: TObject); begin LoadLanguage; WmPatterns.Lines.Text := AppSettings.ReadString('ImportPictures', 'PatternList', DefaultImportPatternList); end; function TPicturesImportPatternEdit.GetFormID: string; begin Result := 'ImportPictures'; end; procedure TPicturesImportPatternEdit.LoadLanguage; var InfoText: string; begin BeginTranslate; try Caption := L('Edit directory fotmats'); BtnOk.Caption := L('Ok'); BtnCancel.Caption := L('Cancel'); InfoText := 'Please use the following format for pattern list:'; InfoText := InfoText + '$nl$' + ' Each line is a separated pattern'; InfoText := InfoText + '$nl$' + ' YYYY - year as "2010"'; InfoText := InfoText + '$nl$' + ' YY - year as "10"'; InfoText := InfoText + '$nl$' + ' mmmm - month as "january"'; InfoText := InfoText + '$nl$' + ' MMMM - month as "January"'; InfoText := InfoText + '$nl$' + ' mmm - month as "january"'; InfoText := InfoText + '$nl$' + ' MMM - month as "January"'; InfoText := InfoText + '$nl$' + ' MM - month as "07"'; InfoText := InfoText + '$nl$' + ' M - month as "7"'; InfoText := InfoText + '$nl$' + ' ddd - day as "monday"'; InfoText := InfoText + '$nl$' + ' DDD - day as "Monday"'; InfoText := InfoText + '$nl$' + ' DD - day as "07"'; InfoText := InfoText + '$nl$' + ' D - day as "7"'; LbInfo.Caption := L(InfoText); WmPatterns.Top := LbInfo.Top + LbInfo.Height + 10; ClientHeight := WmPatterns.Top + 150 + 7 + BtnOk.Height + 5; WmPatterns.Height := 150; finally EndTranslate; end; end; procedure TPicturesImportPatternEdit.WmPatternsChange(Sender: TObject); begin BtnOk.Enabled := WmPatterns.Lines.Count > 0; end; end.
unit UserScript; var lsFlags: TStringList; resetLevel: Integer; function Initialize: Integer; begin // default level to which leveled list entries are reset resetLevel := 1; // you can force the script to apply to only records with these flags // by uncommenting the lsFlags.Add() lines, or adding your own lsFlags := TStringList.Create; //lsFlags.Add('Calculate from all levels <= player''s level'); //lsFlags.Add('Calculate for each item in count'); end; function Process(e: IInterface): Integer; var i, matches: Integer; flag, flags, entry, entries, level, reference: IInterface; begin // if there are no Leveled List Entries, exit entries := ElementByName(e, 'Leveled List Entries'); if not Assigned(entries) then exit; if lsFlags.Count > 0 then begin // if there are no Flags, exit flags := ElementBySignature(e, 'LVLF'); if not Assigned(flags) then exit; if ElementCount(flags) <= 0 then exit; // if existing flags match lsFlags matches := 0; for i := 0 to ElementCount(flags) - 1 do begin flag := ElementByIndex(flags, i); if lsFlags.IndexOf(Name(flag)) <> -1 then matches := matches + 1; end; if matches <> lsFlags.Count then exit; end; // iterate through leveled list entries and reset entry levels to resetLevel for i := 0 to ElementCount(entries) - 1 do begin entry := ElementBySignature(ElementByIndex(entries, i), 'LVLO'); reference := ElementByName(entry, 'Reference'); level := ElementByName(entry, 'Level'); if GetNativeValue(level) <> resetLevel then begin AddMessage('Resetting level for: ' + GetEditValue(reference)); SetNativeValue(level, resetLevel); end; end; end; function Finalize: Integer; begin lsFlags.Free; end; end.
program WATEM_DK; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, fileutil, Dos, gdata, idrisi_proc, lateralredistribution, rdata, surface, vector, CustApp, variables,carboncycling, model_implementation; type { TWATEMApplication } TWATEMApplication = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; procedure Set_Parameter_Values; virtual; end; { TWATEMApplication } var //execution var hr, mins, se, s1 : word; procedure StartClock; begin GetTime (hr,mins,se,s1); end; Function StopClock:string; var hr2, min2, se2 : word; begin GetTime (hr2, min2, se2, s1); result := inttostr(se2-se+(min2-mins)*60+(hr2-hr)*60*60); end; Procedure TWATEMApplication.Set_Parameter_Values; begin if Hasoption('c14input') then c14filename:=GetOptionValue('c14input'); if Hasoption('c13input') then c13filename:=GetOptionValue('c13input'); if Hasoption('Cs137input') then Cs137filename:=GetOptionValue('Cs137input'); if Hasoption('d','dtm') then dtmfilename:=GetOptionValue('d','dtm'); if Hasoption('p','prc') then prcfilename:=GetOptionValue('p','prc'); if Hasoption('u','RKCP') then RKCPfilename:=GetOptionValue('u','RKCP'); if Hasoption('k','ktc') then ktcfilename:=GetOptionValue('k','ktc'); if Hasoption('o','outf') then outfilename:=GetOptionValue('o','outf') else outfilename:='watem_out.rst'; if Hasoption('t','tfca') then TFCA:=strtoint(GetOptionValue('t','tfca')) else TFCA:=100; if Hasoption('r','ra') then begin if GetOptionValue('r','ra')='sd' then ra:=sdra else if GetOptionValue('r','ra')='mf' then ra:=mfra; end else ra:=mfra; if Hasoption('b','BD') then BD:=strtoint(GetOptionValue('b','BD')) else BD:=1350; if Hasoption('erosion_start_year') then erosion_start_year:=strtoint(GetOptionValue('erosion_start_year')) else erosion_start_year:=1950; if Hasoption('erosion_end_year') then erosion_end_year:=strtoint(GetOptionValue('erosion_end_year')) else erosion_end_year:=2015; if Hasoption('depth_interval') then depth_interval:=strtoint(GetOptionValue('depth_interval')) else depth_interval:=5; if Hasoption('depth') then depth:=strtoint(GetOptionValue('depth')) else depth:=100; if Hasoption('tillage_depth') then tillage_depth:=strtoint(GetOptionValue('tillage_depth')) else tillage_depth:=25; if Hasoption('deltaC13_ini_top') then deltaC13_ini_top:=strtofloat(GetOptionValue('deltaC13_ini_top')) else deltaC13_ini_top:=-27.0; if Hasoption('deltaC13_ini_bot') then deltaC13_ini_bot:=strtofloat(GetOptionValue('deltaC13_ini_bot')) else deltaC13_ini_bot:=-26.0; if Hasoption('time_equilibrium') then time_equilibrium:=strtoint(GetOptionValue('time_equilibrium')) else time_equilibrium:=10000; if Hasoption('k1') then k1:=strtofloat(GetOptionValue('k1')) else k1:=2.1; if Hasoption('k2') then k2:=strtofloat(GetOptionValue('k2')) else k2:=0.03; if Hasoption('k3') then k3:=strtofloat(GetOptionValue('k3')) else k3:=0.002; if Hasoption('hAS') then hAS:=strtofloat(GetOptionValue('hAS')) else hAS:=0.12; if Hasoption('hAP') then hAP:=strtofloat(GetOptionValue('hAP')) else hAP:=0.01; if Hasoption('hSP') then hSP:=strtofloat(GetOptionValue('hSP')) else hSP:=0.12; if Hasoption('r0') then r0:=strtofloat(GetOptionValue('r0')) else r0:=1.0; if Hasoption('C_input') then C_input:=strtofloat(GetOptionValue('C_input')) else C_input:=2.0; if Hasoption('C_input2') then C_input2:=strtofloat(GetOptionValue('C_input2')) else C_input2:=0.5; if Hasoption('r_exp') then r_exp:=strtofloat(GetOptionValue('r_exp')) else r_exp:=3.30; if Hasoption('i_exp') then i_exp:=strtofloat(GetOptionValue('i_exp')) else i_exp:=6.0; if Hasoption('C13_discri') then C13_discri:=strtofloat(GetOptionValue('C13_discri')) else C13_discri:=0.9965; if Hasoption('C14_discri') then C14_discri:=strtofloat(GetOptionValue('C14_discri')) else C14_discri:=0.996; if Hasoption('deltaC13_input_default') then deltaC13_input_default:=strtofloat(GetOptionValue('deltaC13_input_default')) else deltaC13_input_default:=-29.0; if Hasoption('deltaC14_input_default') then deltaC14_input_default:=strtofloat(GetOptionValue('deltaC14_input_default')) else deltaC14_input_default:=100.0; if Hasoption('Cs137_input_default') then Cs137_input_default:=strtofloat(GetOptionValue('Cs137_input_default')) else Cs137_input_default:=0.0; if Hasoption('Sand_ini_top') then Sand_ini_top:=strtofloat(GetOptionValue('Sand_ini_top')) else Sand_ini_top:=15.0; if Hasoption('Silt_ini_top') then Silt_ini_top:=strtofloat(GetOptionValue('Silt_ini_top')) else Silt_ini_top:=70.0; if Hasoption('Clay_ini_top') then Clay_ini_top:=strtofloat(GetOptionValue('Clay_ini_top')) else Clay_ini_top:=15.0; if Hasoption('Sand_ini_bot') then Sand_ini_bot:=strtofloat(GetOptionValue('Sand_ini_bot')) else Sand_ini_bot:=15.0; if Hasoption('Silt_ini_bot') then Silt_ini_bot:=strtofloat(GetOptionValue('Silt_ini_bot')) else Silt_ini_bot:=70.0; if Hasoption('Clay_ini_bot') then Clay_ini_bot:=strtofloat(GetOptionValue('Clay_ini_bot')) else Clay_ini_bot:=15.0; if Hasoption('K0') then K0:=strtofloat(GetOptionValue('K0')) else K0:=0.09; if Hasoption('Kfzp') then Kfzp:=strtofloat(GetOptionValue('Kfzp')) else Kfzp:=0.01; if Hasoption('v0') then v0:=strtofloat(GetOptionValue('v0')) else v0:=0.018; if Hasoption('vfzp') then vfzp:=strtofloat(GetOptionValue('vfzp')) else vfzp:=0.01; if Hasoption('a_erer') then a_erer:=strtofloat(GetOptionValue('a_erer')) else a_erer:=1.0; if Hasoption('b_erero') then b_erero:=strtofloat(GetOptionValue('b_erero')) else b_erero:=2000.0; if Hasoption('b_erdepo') then b_erdepo:=strtofloat(GetOptionValue('b_erdepo')) else b_erdepo:=2000.0; if Hasoption('time_step') then time_step:=strtoint(GetOptionValue('time_step')) else time_step:=5; // if Hasoption('unstable') then unstable:=strtoboolean(GetOptionValue('unstable')) else unstable:=FALSE; end; procedure TWATEMApplication.DoRun; var Time:String; ErrorMsg: String; begin StartClock; writeln('WATEM V3 BETA version July 2014'); writeln('Reference: Van Oost et al 2000, Landscape Ecology'); Set_Parameter_Values; writeln('Reading data'); GetRFile(DTM,dtmfilename); GetRFile(RKCP,RKCPfilename); GetRFile(ktc,ktcfilename); Get32bitGFile(LS,prcfilename,PRC); // LS is temp RRaster to read in parcel Allocate_Memory; writeln('Reading data ... done'); // ////CalculateSlopeAspect; //writeln('topo calculations'); //Topo_Calculations(ra,DTM, LS, SLOPE, ASPECT, UPAREA, TFCA); //Water(WATEREROS, LS, RKCP, ktc, TFCA, ra, BD); //writeln('Water Erosion Module'); //writeIdrisi32file(ncol,nrow, outfilename, WATEREROS); //writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'_LS', LS); //writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'_uparea', UPAREA); carbon; export_txt; writeln('Writing Output'); Release_Memory; Time:=StopClock; Writeln('Program Execution Time: ',Time,' sec'); Terminate; end; constructor TWATEMApplication.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TWATEMApplication.Destroy; begin inherited Destroy; end; procedure TWATEMApplication.WriteHelp; begin { add your help code here } writeln('Usage: ',ExeName,' -h'); end; var Application: TWATEMApplication; begin Application:=TWATEMApplication.Create(nil); Application.Title:='Watem'; Application.Run; Application.Free; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.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. } { } {***************************************************************************} unit DependencyVersionTests; interface uses DUnitX.TestFramework; type [TestFixture] TVersionRangeTests = class public [Test] procedure Will_Fail_on_empty_string; [Test] procedure Will_Fail_on_fixed_major_minor; [Test] procedure Can_Parse_ValidFixed_Version; [Test] procedure Will_Normalize_To_Fixed; [Test] procedure Can_Parse_ExclusiveRange; [Test] procedure Can_Parse_ExclusiveRange_OpenEnded; [Test] procedure Can_Parse_ExclusiveRange_OpenStart; [Test] procedure Will_Fail_On_Exclusive_Range_Open_No_Gap; [Test] procedure Will_Fail_On_ExclusiveRange_NoComma; [Test] procedure Can_Parse_InclusiveRange; [Test] procedure Will_Fail_On_Empty_Exlusive_Range; [Test] procedure Will_Fail_On_InvalidSemver; [Test] procedure Will_Fail_On_Invalid_Float; end; implementation uses DPM.Core.Types, DPM.Core.Dependency.Version; { TdepVersionTests } procedure TVersionRangeTests.Can_Parse_ExclusiveRange; var depVersion :TVersionRange; error :string; begin Assert.IsTrue(TVersionRange.TryParseWithError('(1.0.1,1.0.3)', depVersion, error), error); Assert.IsTrue(depVersion.IsValid); Assert.IsFalse(depVersion.MinVersionIsInclusive); Assert.IsFalse(depVersion.MaxVersionIsInclusive); end; procedure TVersionRangeTests.Can_Parse_ExclusiveRange_OpenEnded; var depVersion :TVersionRange; maxVersion :TPackageVersion; error :string; begin Assert.IsTrue(TVersionRange.TryParseWithError('(1.0.1,)', depVersion, error), error); Assert.IsTrue(depVersion.IsValid); Assert.IsFalse(depVersion.MinVersionIsInclusive); maxVersion := TPackageVersion.Create(1, 0, High(word)); Assert.IsTrue(maxVersion = depVersion.MaxVersion); end; procedure TVersionRangeTests.Can_Parse_ExclusiveRange_OpenStart; var depVersion :TVersionRange; minVersion :TPackageVersion; error :string; begin Assert.IsTrue(TVersionRange.TryParseWithError('(,1.0.2)', depVersion, error), error); Assert.IsTrue(depVersion.IsValid); Assert.IsFalse(depVersion.MinVersionIsInclusive); minVersion := TPackageVersion.Create(1, 0, 0); Assert.IsTrue(minVersion = depVersion.MinVersion); end; procedure TVersionRangeTests.Can_Parse_InclusiveRange; var depVersion :TVersionRange; error :string; begin Assert.IsTrue(TVersionRange.TryParseWithError('[1.0.1, 1.0.3]', depVersion, error), error); Assert.IsTrue(depVersion.IsValid); Assert.IsTrue(depVersion.MinVersionIsInclusive); Assert.IsTrue(depVersion.MaxVersionIsInclusive); Assert.AreEqual('[1.0.1, 1.0.3]', depVersion.ToString); end; procedure TVersionRangeTests.Can_Parse_ValidFixed_Version; var depVersion :TVersionRange; error :string; begin Assert.IsTrue(TVersionRange.TryParseWithError('1.0.1', depVersion, error), error); Assert.IsTrue(depVersion.IsValid); Assert.IsTrue(depVersion.IsFixed); Assert.AreEqual<TPackageVersion>(depVersion.MinVersion, depVersion.MaxVersion); end; procedure TVersionRangeTests.Will_Fail_On_Empty_Exlusive_Range; var depVersion :TVersionRange; error :string; begin Assert.IsFalse(TVersionRange.TryParseWithError('(1.0.1,1.0.2)', depVersion, error), error); Assert.IsFalse(depVersion.IsValid); end; procedure TVersionRangeTests.Will_Fail_on_empty_string; var depVersion :TVersionRange; error :string; begin Assert.IsFalse(TVersionRange.TryParseWithError('', depVersion, error), error); end; procedure TVersionRangeTests.Will_Fail_On_ExclusiveRange_NoComma; var depVersion :TVersionRange; error :string; begin Assert.IsFalse(TVersionRange.TryParseWithError('(1.0.1)', depVersion, error), error); Assert.IsFalse(depVersion.IsValid); end; procedure TVersionRangeTests.Will_Fail_On_Exclusive_Range_Open_No_Gap; var depVersion :TVersionRange; error :string; begin Assert.IsFalse(TVersionRange.TryParseWithError('(,1.0.1)', depVersion, error), error); Assert.IsFalse(depVersion.IsValid); end; procedure TVersionRangeTests.Will_Fail_on_fixed_major_minor; var depVersion :TVersionRange; error :string; begin Assert.IsFalse(TVersionRange.TryParseWithError('1.0', depVersion, error), error); end; procedure TVersionRangeTests.Will_Fail_On_InvalidSemver; var depVersion :TVersionRange; error :string; begin Assert.IsFalse(TVersionRange.TryParseWithError('(1.0.1.2,1.0.2.2)', depVersion, error), error); Assert.IsFalse(depVersion.IsValid); end; procedure TVersionRangeTests.Will_Fail_On_Invalid_Float; var depVersion :TVersionRange; error :string; begin Assert.IsFalse(TVersionRange.TryParseWithError('[1.0.1,1.2.3]', depVersion, error), error); Assert.IsFalse(depVersion.IsValid); end; procedure TVersionRangeTests.Will_Normalize_To_Fixed; var depVersion :TVersionRange; error :string; begin Assert.IsTrue(TVersionRange.TryParseWithError('[1.0.1,1.0.2)', depVersion, error), error); Assert.IsTrue(depVersion.IsValid); Assert.IsTrue(depVersion.MinVersionIsInclusive); Assert.IsFalse(depVersion.MaxVersionIsInclusive); depVersion.Normalize; Assert.IsTrue(depVersion.IsFixed); Assert.AreEqual('1.0.1', depVersion.ToString); end; initialization TDUnitX.RegisterTestFixture(TVersionRangeTests); end.
program HelloWorld; uses Scanner; begin TokenOpenFile('../examples/Any.fy'); while lastToken <> TOK_EOF do begin if lastToken = TOK_IDENT then WriteLn('IDENT = ', lastIdent) else WriteLn('TOKEN = ', lastToken); TokenNext() end; end.
{ This file is part of R&Q. Under same license } unit RDtraylib; {$I ForRnQConfig.inc} {$I NoRTTI.inc} interface uses Messages, windows, RDGlobal, graphics, ShellApi; const WM_TRAY = WM_USER+1; cTRAY_uID = 100; flags_v2 = NIF_MESSAGE or NIF_ICON or NIF_TIP; flags_v4 = NIF_MESSAGE or NIF_ICON or NIF_TIP or NIF_SHOWTIP or NIF_GUID; flags_info = NIF_INFO or NIF_SHOWTIP or NIF_GUID; type TNotifyIconDataW_V2 = record cbSize: DWORD; Wnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; szTip: array [0..127] of WideChar; dwState: DWORD; dwStateMask: DWORD; szInfo: array [0..255] of WideChar; case Integer of 0: ( uTimeout: UINT); 1: (uVersion: UINT; szInfoTitle: array [0..63] of WideChar; dwInfoFlags: DWORD); // TimeoutOrVersion: TTimeoutOrVersion; // szInfoTitle: array [0..63] of WideChar; // dwInfoFlags: DWORD; end; TNotifyIconDataW_V4 = record cbSize: DWORD; Wnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; szTip: array [0 .. 127] of WideChar; dwState: DWORD; dwStateMask: DWORD; szInfo: array [0 .. 255] of WideChar; case Integer of 0: (uTimeout: UINT); 1: (uVersion: UINT; szInfoTitle: array [0..63] of WideChar; dwInfoFlags: DWORD; guidItem: TGUID; // Requires Windows Vista or later hBalloonIcon: HICON); // Requires Windows Vista or later end; PNotifyIconDataW_V2 = ^TNotifyIconDataW_V2; PNotifyIconDataW_V4 = ^TNotifyIconDataW_V4; const NOTIFYIconDataW_V2_SIZE = SizeOf(TNotifyIconDataW_V2); NOTIFYIconDataW_V4_SIZE = SizeOf(TNotifyIconDataW_V4); type {$IFDEF Use_Baloons} TBalloonIconType = (bitNone, // нет иконки bitInfo, // информационная иконка (синяя) bitWarning, // иконка восклицания (жёлтая) bitError); // иконка ошибки (красная) {$ENDIF Use_Baloons} { TBalloonType=(btNone, btError, btInfo, btWarning); } TtrayIcon=class private // data:TNotifyIconData; data: TNotifyIconDataW_V4; shown, fHidden: Boolean; Ico: TIcon; public constructor Create(hndl: HWND); destructor Destroy; override; procedure minimize; procedure update; procedure hide; procedure show; procedure setIcon(icon: Ticon); overload; procedure setIcon(const iName: TPicName); overload; procedure setTip(const s: String); // procedure setIconFile(fn: String); procedure updateHandle(hndl: HWND); property Hidden: boolean read fHidden; end; // TtrayIcon type TGetPicTipFunc = Procedure(var vPic: TPicName; var vTip: String); // of object; TstatusIcon = class private FOnGetPicTip: TGetPicTipFunc; public trayIcon: TtrayIcon; IcoName: TPicName; lastTip: String; constructor Create; destructor Destroy; override; procedure update; procedure empty; procedure ReDraw; procedure handleChanged(hndl: THandle); {$IFDEF Use_Baloons} procedure showballoon(const bldelay: Integer; const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType); procedure hideBalloon; {$ENDIF Use_Baloons} property OnGetPicTip: TGetPicTipFunc read FOnGetPicTip write FOnGetPicTip; // function AcceptBalloons: Boolean; // procedure BalloonHint (Title, Value: String; BalloonType: TBalloonType; Delay: Integer); end; // TstatusIcon var ShowBalloonTime: Int64; EnabledBaloons: Boolean; TrayIconDataVersion: Integer = 2; implementation uses forms, sysutils, RDUtils, RnQStrings, RnQLangs, //themesLib, RQUtil, RQThemes, RnQGlobal // dwTaskbarComponents, dwTaskbarList, // fspTaskbarCommon, fspTaskbarApi, ; const NIF_INFO = $00000010; { type TRnQTaskbarComponent = class(TdwTaskbarComponent) public property TaskbarList; property TaskbarList2; property TaskbarList3; end; var tbcmp : TRnQTaskbarComponent; } constructor TstatusIcon.create; begin if CheckWin32Version(6, 1) then TrayIconDataVersion := 4; trayIcon := TtrayIcon.create(0); trayIcon.setTip(Application.Title); IcoName := ''; lastTip := ''; {$IFDEF Use_Baloons} if GetShellVersion >= $00050000 then begin EnabledBaloons := true; // htimer := tmCreateIntervalTimerEx(handler, 2000, tmPeriod, // false, tnWinMsg, WM_TIMERNOTIFY, 2); end else EnabledBaloons := false; {$ENDIF Use_Baloons} end; // create destructor TstatusIcon.Destroy; begin trayIcon.hide; trayIcon.free; trayIcon := NIL; end; // destroy procedure TstatusIcon.update; var // nIco : String; // IcoDtl : TRnQThemedElementDtls; IcoPicName: TPicName; s: String; begin if self = nil then exit; if Assigned(FOnGetPicTip) then FOnGetPicTip(IcoPicName, S) else begin // IcoPicName := PIC_CLIENT_LOGO; IcoPicName := 'tray'; s := Application.Title; end; //if IcoDtl.picName <> IcoName then if IcoPicName <> IcoName then begin IcoName := IcoPicName; trayIcon.setIcon(IcoName); end; if s <> lastTip then begin lastTip := s; trayIcon.setTip(s); end; end; // update procedure TstatusIcon.empty; begin IcoName := PIC_EMPTY; trayIcon.setIcon(IcoName); end; procedure TstatusIcon.handleChanged(hndl: THandle); begin if Assigned(trayIcon) then trayIcon.updateHandle(hndl) end; procedure TstatusIcon.showballoon(const bldelay: integer; const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType); const aBalloonIconTypes: array[TBalloonIconType] of Byte = (NIIF_NONE, NIIF_INFO, NIIF_WARNING, NIIF_ERROR); var // NID_50: NotifyIconData_50; // NID_50: TNotifyIconData; NID_50: TNotifyIconDataW_V4; t: String; begin if (not EnabledBaloons) or (not ShowBalloons) then exit; if balloontext = '' then t := '_' else t := balloontext; ShowBalloonTime := 0; // tmStopTimer(hTimer); // DZBalloonTrayIcon(window, IconID, t, balloontitle, balloonicontype); ShowBalloonTime := bldelay; ZeroMemory(@NID_50, NOTIFYIconDataW_V4_SIZE); with NID_50 do begin if TrayIconDataVersion = 4 then cbSize := NOTIFYIconDataW_V4_SIZE else cbSize := NOTIFYIconDataW_V2_SIZE; Wnd := trayIcon.data.Wnd; uID := trayIcon.data.uID; uFlags := NIF_INFO; StrLCopy(PWideChar(@szInfo[0]), PChar(BalloonText), 255); // StrPCopy(szTip, BalloonText); uTimeout := 30000; StrLCopy(PWideChar(@szInfoTitle[0]), PChar(BalloonTitle), 63); dwInfoFlags := aBalloonIconTypes[BalloonIconType]; guidItem := TrayIcon.data.guidItem; end; Shell_NotifyIcon(NIM_MODIFY, @NID_50); end; procedure TstatusIcon.hideBalloon; var // NID_50: NotifyIconData_50; // NID_50: TNotifyIconData; NID_50: TNotifyIconDataW_V2; begin ShowBalloonTime := 0; if (not EnabledBaloons) or (not ShowBalloons) then exit; // ZeroMemory(@NID_50, SizeOf(NID_50)); ZeroMemory(@NID_50, NOTIFYIconDataW_V2_SIZE); with NID_50 do begin cbSize := NOTIFYIconDataW_V2_SIZE; Wnd := trayIcon.data.Wnd; uID := trayIcon.data.uID; uFlags := NIF_INFO; // StrPCopy(PWideChar(@szInfo[0]), ''); // StrPCopy(PWideChar(@szInfoTitle[0]), ''); // := trayIcon.data.; end; Shell_NotifyIcon(NIM_MODIFY, @NID_50); end; constructor TtrayIcon.create(hndl: HWND); var FGUID: TGUID; begin ZeroMemory(@data, NOTIFYIconDataW_V4_SIZE); if TrayIconDataVersion = 4 then CreateGUID(FGUID); with data do begin uCallbackMessage := WM_TRAY; if TrayIconDataVersion = 4 then cbSize := NOTIFYIconDataW_V4_SIZE else cbSize := NOTIFYIconDataW_V2_SIZE; Wnd := hndl; uID := cTRAY_uID; hIcon := 0; if TrayIconDataVersion = 4 then uFlags := flags_v4 else uFlags := flags_v2; uFlags := NIF_MESSAGE + NIF_ICON + NIF_TIP; guidItem := FGUID; end; // tbcmp := TRnQTaskbarComponent.Create(Application); setIcon(application.icon); setTip(application.title); { // if fspTaskbarMainAppWnd = 0 then if Application.MainFormOnTaskBar then fspTaskbarMainAppWnd := hndl else fspTaskbarMainAppWnd := Application.Handle; //Legacy App } end; // create destructor TtrayIcon.Destroy; begin if Assigned(ico) then ico.Free; ico := NIL; // tbcmp.Free; end; procedure TtrayIcon.updateHandle(hndl: HWND); begin { // if fspTaskbarMainAppWnd = 0 then if Application.MainFormOnTaskBar then fspTaskbarMainAppWnd := hndl else fspTaskbarMainAppWnd := Application.Handle; //Legacy App } if not shown then begin data.wnd := hndl; exit; end; hide; data.wnd := hndl; Shell_NotifyIcon(NIM_ADD, @data); // Для балунов тоже нада бы... end; procedure TtrayIcon.update; //var // ic : HICON; begin { if shown then begin ic := CopyIcon(data.hIcon); tbcmp.TaskbarList3.SetOverlayIcon(tbcmp.TaskBarEntryHandle, // data.hIcon, PWideChar(@data.szTip[0])) ic, PWideChar(@data.szTip[0])) end else tbcmp.TaskbarList3.SetOverlayIcon(tbcmp.TaskBarEntryHandle, 0, nil); tbcmp.SendUpdateMessage;} if shown and not hidden then if not Shell_NotifyIcon(NIM_MODIFY, @data) then Shell_NotifyIcon(NIM_ADD, @data); { if Assigned(pTaskBarList) then pTaskBarList.SetOverlayIcon(fspTaskbarMainAppWnd, data.hIcon, data.szTip); } end; { update } procedure TtrayIcon.setIcon(icon: Ticon); begin if icon=NIL then exit; if ico = NIL then ico := TIcon.Create; ico.Assign(icon); //if data.hIcon <> 0 then data.hIcon:=ico.Handle; if TrayIconDataVersion = 4 then data.hBalloonIcon := Ico.Handle; update; end; { setIcon } procedure TtrayIcon.setIcon(const iName: TPicName); begin if ico = NIL then ico := TIcon.Create; if theme.pic2ico(RQteTrayNotify, iName, ico) then // ico := theme.GetIco(iName); // if ico <> nil then begin data.hIcon:=ico.Handle; if TrayIconDataVersion = 4 then data.hBalloonIcon := Ico.Handle; end else begin ico.Handle := 0; // Application.Icon.Handle; data.hIcon := 0; data.hBalloonIcon := 0; end; update; end; { procedure TtrayIcon.setIconFile(fn: String); var ico:Ticon; begin ico:=Ticon.create; ico.loadFromFile(fn); setIcon(ico); end; // setIconFile} procedure TtrayIcon.setTip(const s: String); begin // strPCopy(data.szTip, s); strLCopy(data.szTip, PChar(s), 127); update; end; // setTip procedure TtrayIcon.minimize; begin show; // Application.ShowMainForm := False; // Toolwindows dont have a TaskIcon. (Remove if TaskIcon is to be show when form is visible) // SetWindowLong(Application.Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW); end; // minimizeToTray procedure TtrayIcon.show; begin shown := true; fHidden := False; Shell_NotifyIcon(NIM_ADD, @data) end; { show } procedure TtrayIcon.hide; begin fHidden := True; Shell_NotifyIcon(NIM_DELETE, @data) end; procedure TstatusIcon.ReDraw; begin trayIcon.setIcon(IcoName); end; { function TstatusIcon.AcceptBalloons: Boolean; begin Result:=GetShellVersion>=$00050000; end; procedure TstatusIcon.BalloonHint (Title, Value: string; BalloonType: TBalloonType; Delay: Integer); //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/Shell/reference/functions/shell_notifyicon.asp begin if AcceptBalloons then begin // FTime :=Now; // FTimeDelay:=Delay; // FIc.uFlags:=NIF_INFO; trayIcon.data.uFlags := NIF_INFO; with FIc do StrPLCopy (szInfoTitle, Title, SizeOf (szInfoTitle)-1); with FIc do StrPLCopy (szInfo, Value, SizeOf (szInfo)-1); FIc.uFlags:=NIF_MESSAGE or NIF_ICON or NIF_INFO or NIF_TIP; FIc.uTimeOut:=Delay; case BalloonType of btError: FIc.dwInfoFlags:=NIIF_ERROR; btInfo: FIc.dwInfoFlags:=NIIF_INFO; btNone: FIc.dwInfoFlags:=NIIF_NONE; btWarning: FIc.dwInfoFlags:=NIIF_WARNING; end; Shell_NotifyIcon (NIM_MODIFY, PNotifyIconData (@FIc)); end; end; } end.
unit SampleGenerator1; // Sample data generator for TPrototypeBindSource or TDataGeneratorAdapter. To make these generaters available at // design time, add this unit to a package and install the package. interface implementation uses Data.Bind.ObjectScope, Data.Bind.GenData, Generics.Collections; type TZipCodeGenerator = class(TDelegateValueGenerator) protected function CreateDelegate: TValueGeneratorDelegate; override; end; TCityGenerator = class(TDelegateValueGenerator) protected function CreateDelegate: TValueGeneratorDelegate; override; end; const sZipCodes = 'LocalZipCodes'; sZipCodeField = 'ZipField%d'; sCities = 'LocalCities'; sCityField = 'CityField%d'; sThisUnit = 'SampleGenerator1'; const CZipCity: array[0..2*33-1] of string = ( '95002','Alviso', '95003','Aptos', '95004','Aromas', '95005','Ben Lomand', '95006','Boulder Creek', '95008','Campbell', '95010','Capitola', '95012','Castroville', '95013','Coyote', '95014','Monte Vista', '95017','Davenport', '95018','Felton', '95019','Freedom', '95020','Gilroy', '95023','Hollister', '95030','Monte Sereno', '95032','Los Gatos', '95035','Milpitas', '95037','Morgan Hill', '95043','Paicines', '95045','San Juan Bautist', '95046','San Martin', '95050','Santa Clara', '95051','Santa Clara', '95054','Santa Clara', '95060','Scotts Valley', '95062','Santa Cruz', '95064','Santa Cruz', '95065','Santa Cruz', '95066','Scotts Valley', '95070','Saratoga', '95073','Soquel', '95076','La Selva Beach'); function GetStrings(AOffset: Integer): TArray<string>; var LList: TList<string>; I: Integer; begin LList := TList<string>.Create; try I := Low(CZipCity) + AOffset; while I <= High(CZipCity) do begin LList.Add(CZipCity[I]); Inc(I, 2); end; Result := LList.ToArray; finally LList.Free; end; end; { TZipCodeGenerator } function TZipCodeGenerator.CreateDelegate: TValueGeneratorDelegate; begin Result := nil; case FieldType of ftString: Result := TTypedListValueGeneratorDelegate<string>.Create(Options, GetStrings(0)); else Assert(False); end; end; function TCityGenerator.CreateDelegate: TValueGeneratorDelegate; begin Result := nil; case FieldType of ftString: Result := TTypedListValueGeneratorDelegate<string>.Create(Options, GetStrings(1)); else Assert(False); end; end; initialization RegisterValueGenerator(sZipCodes, [ftString], TValueGeneratorDescription.Create(TZipCodeGenerator, sZipCodeField, sThisUnit)); RegisterValueGenerator(sCities, [ftString], TValueGeneratorDescription.Create(TCityGenerator, sCityField, sThisUnit)); finalization UnRegisterValueGenerator(sZipCodes, [ftString], ''); UnRegisterValueGenerator(sCities, [ftString], ''); end.
{$A-,B-,D+,E-,F+,G-,I-,L+,N-,O-,P-,Q-,R-,S-,T-,V-,X+,Y+} Unit ASP_Util; interface uses Dos, ASP_Def; type EBpb = record { Extended BIOS Parametrs Block } sectsize : word; clustsize : byte; ressecs : word; fatcnt : byte; rootsecs, totsecs : word; media : byte; fatsize, seccnt, headcnt, hiddensec_low, hiddensec_hi : word; drvsecs : longint; end; DPB = record spec, devtype : byte; devattr, numofcyl: word; media_type : byte; bpb : ebpb; reserv : array [0..5] of byte; end; const DiskRead = 2; DiskWrite = 3; procedure MBR; procedure Boot; function TrueDosVersion : Word; { Get True MS-DOS Version } function DefaultDrive : Char; function NumberOfDrives : Char; procedure SelectDrive( Drv : Char ); function LastDrive : Char; procedure ClrEol; function BiosDisk( Funct, Drive, Head : Byte; TrackSector : Word; NSectors : Byte; Var Buffer ) : Boolean; function NFloppies : Byte; function DevType( NDrv : byte ) : byte; function ResolvePathStr( PStr : ComStr ) : ComStr; function ReadCh : Char; function CheckMem( Var Msk; Var P ) : Boolean; function VirSearch( var Msk ) : Word; function CheckVirus( Var Msk ) : Boolean; procedure DesactivResident( var SegX, OfsX : Word; SegOld, OfsOld : Word ); implementation procedure MBR; External; {$L MBR.OBJ} procedure Boot; External; {$L BOOT.OBJ} function TrueDosVersion : Word; Assembler; asm mov ax,3306h int 21h cmp ax,3306h mov ax,bx je @Dos5 mov ax,3000h int 21h @Dos5: end; function DefaultDrive : Char; Assembler; asm mov ah,19h int 21h add al,41h end; function NumberOfDrives : Char; Assembler; asm mov ah,19h int 21h mov dl,al mov ah,0eh int 21h add al,41h end; procedure SelectDrive( Drv : Char ); Assembler; asm mov dl,Drv cmp dl,7ah ja @exit cmp dl,61h jb @sub2 sub dl,20h @sub2: sub dl,41h mov ah,0eh int 21h @exit: end; function LastDrive : Char; var D, DType : Byte; begin D := 1; repeat DType := DevType( D ); Inc( D ); until DType = $0ff; LastDrive := Chr( D + Ord('>') ); end; procedure ClrEol; Assembler; const WindMax = $4f; asm mov ah,3 xor bh,bh int 10h mov ax,0600h mov bh,07h mov cx,dx mov dl,WindMax int 10h end; function BiosDisk( Funct, Drive, Head : Byte; TrackSector : Word; NSectors : Byte; Var Buffer ) : Boolean; Assembler; asm mov di,3 mov dl,Drive mov dh,Head mov cx,TrackSector @loop: les bx,Buffer mov al,NSectors mov ah,Funct push di int 13h pop di mov al,True jnc @ex xor ax,ax int 13h dec di jnz @loop mov al,False {=0} @ex: end; function NFloppies : Byte; Assembler; asm int 11h and al,11000000b mov cl,6 shr al,cl inc al end; function DevType( NDrv : byte ) : byte; Assembler; label Er; var _DPB : DPB; asm push ds push ss pop ds lea dx,_DPB mov _DPB.spec,0 mov ax, 440dh mov cx,0860h mov bl,NDrv int 21h mov al,0ffh jc @er mov al,_DPB.devtype @er: pop ds end; function ResolvePathStr( PStr : ComStr ) : ComStr; var _i : Byte; _PStr : ComStr; _PStr1 : array [1..128] of Char; begin ResolvePathStr := ''; DosError := 0; FillChar( _PStr[0], SizeOf(_PStr), 0 ); Move( PStr[1], _PStr[0], Ord(PStr[0]) ); asm push ds push ss push ss pop ds lea si,_PStr pop es lea di,_PStr1 mov ah,60h int 21h pop ds jnc @cont mov DosError,ax @cont: end; if DosError = 0 then begin _i := 1; while (_PStr1[_i] <> #0) and (_i <= 128) do Inc(_i); Dec(_i); if (_i = 0) or (_i = 128) then DosError := MaxInt else begin Move( _PStr1, _PStr[1], _i ); _PStr[0] :=Chr(_i); ResolvePathStr := _PStr; end; end; end; function ReadCh : Char; Assembler; asm mov ah,0 int 16h end; function CheckMem( Var Msk; Var P ) : Boolean; Assembler; asm push ds xor ax,ax {False} lds si,Msk les di,P xor cx,cx mov cl,[si] add si,3 cld repe cmpsb pop ds jne @exit mov al,True @exit: end; function VirSearch( Var Msk ) : Word; Assembler; asm mov bx,ds xor ax,ax lds si,Msk mov cx,-1 cld @loop: inc ax add si,cx inc si xor cx,cx mov cl,[si] inc si or cl,cl jz @last les di,A add di,[si] inc si inc si repe cmpsb jne @loop mov ds,bx inc word ptr InfectF jnz @exit inc word ptr InfectF+2 jmp @exit @last: xor ax,ax mov ds,bx @exit: end; function CheckVirus( Var Msk ) : Boolean; Assembler; asm push ds lds si,Msk xor cx,cx mov cl,[si] inc si les di,A add di,[si] inc si inc si xor ax,ax {False} cld repe cmpsb pop ds jne @exit inc ax {True} lea si,InfectF inc word ptr [si] jnz @exit inc word ptr [si+2] @exit: end; procedure DesactivResident( var SegX, OfsX: Word; SegOld, OfsOld : Word ); begin Mem[SegX:OfsX] := $ea; MemW[SegX:OfsX+1] := OfsOld; MemW[SegX:OfsX+3] := SegOld; Write( Lst, Cured ); Write( Cured ); SegX := SegOld; OfsX := OfsOld; end; end.
unit AlertForm_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; const PHONE_CLICK = WM_USER + 100; type TAlertTime = class fAudio: string; fNow: TDateTime; end; TAlertForm = class(TForm) Timer1: TTimer; Timer2: TTimer; procedure Timer1Timer(Sender: TObject); procedure FormPaint(Sender: TObject); procedure Timer2Timer(Sender: TObject); procedure FormClick(Sender: TObject); private fDrawBitmap: TBitmap; fTexts: TStringList; procedure resizeAlert; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; procedure show(messageText, audio: String); procedure hideAlert; procedure setOnTop(); var AlertForm: TAlertForm; implementation uses DateUtils, MainForm_Unit; {$R *.dfm} procedure show(messageText, audio: String); var AlertTime: TAlertTime; begin try if (AlertForm = nil) then Application.CreateForm(TAlertForm, AlertForm); with AlertForm do begin try AlertTime:= TAlertTime.Create; AlertTime.fNow := Now; AlertTime.fAudio := audio; fTexts.AddObject(messageText, AlertTime); resizeAlert; Timer1.Enabled := true; ShowWindow(Handle, SW_SHOWNOACTIVATE); setOnTop(); except hideAlert; end; end; except end; end; procedure hideAlert; begin try if (AlertForm <> nil) then begin AlertForm.Timer1.Enabled := false; FreeAndNil(AlertForm); end; except end; end; procedure setOnTop(); begin if (AlertForm <> nil) then SetWindowPos(AlertForm.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE); end; constructor TAlertForm.Create(AOwner: TComponent); begin inherited; fTexts := TStringList.Create; fDrawBitmap := TBitmap.Create; fDrawBitmap.Canvas.Font.Name := 'Arial'; fDrawBitmap.Canvas.Font.Charset := RUSSIAN_CHARSET; fDrawBitmap.Canvas.Font.Size := 9; end; destructor TAlertForm.Destroy; var k: integer; begin FreeAndNil(fDrawBitmap); for k := 0 to fTexts.Count - 1 do fTexts.Objects[k].Free; fTexts.Free; inherited Destroy; end; procedure TAlertForm.resizeAlert; var paddingW, paddingH: integer; procedure splitTextToLines(text: string; lines:TStringList); var i: integer; s: string; sl: TStringList; begin sl:= TStringList.Create; try sl.Delimiter := ' '; sl.DelimitedText := text; s := ''; for i := 0 to sl.Count - 1 do begin if (fDrawBitmap.Canvas.TextWidth(s + sl[i]) > Width - paddingW) then begin lines.Add(s); s := ''; end; s := s + sl[i] + ' '; if (i = sl.Count - 1) then lines.Add(s); end; finally sl.Free; end; end; function drawLine(s, audio: string): integer; var k: integer; sl: TStringList; t_h: integer; y: integer; begin t_h := fDrawBitmap.Canvas.TextHeight('W') - 2; sl:= TStringList.Create; try splitTextToLines(s, sl); y := fDrawBitmap.Height; fDrawBitmap.Height := fDrawBitmap.Height + sl.Count * t_h + paddingH; fDrawBitmap.Canvas.Brush.Color := clFuchsia; fDrawBitmap.Canvas.Pen.Color := Brush.Color; fDrawBitmap.Canvas.Rectangle(0, y, fDrawBitmap.Width, fDrawBitmap.Height); if (audio = 'alarm') then begin fDrawBitmap.Canvas.Brush.Color := clRed; fDrawBitmap.Canvas.Font.Color := clWhite; end else begin fDrawBitmap.Canvas.Brush.Color := $00333333; fDrawBitmap.Canvas.Font.Color := clWhite; end; fDrawBitmap.Canvas.Font.Charset := RUSSIAN_CHARSET; //fDrawBitmap.Canvas.Pen.Color := Brush.Color; fDrawBitmap.Canvas.Rectangle(0, y, fDrawBitmap.Width, fDrawBitmap.Height); y := y + paddingH div 2; for k:= 0 to sl.Count - 1 do begin fDrawBitmap.Canvas.TextOut(paddingW div 2, y + k * t_h, sl[k]); end; finally sl.Free; end; end; var k: integer; begin if (fDrawBitmap = nil) then exit; Width := MainForm.ClientWidth; paddingW := 20; paddingH := 20; fDrawBitmap.Width := Width; fDrawBitmap.Height := 0; for k := 0 to fTexts.Count - 1 do drawLine(fTexts[k], TAlertTime(fTexts.Objects[k]).fAudio); Height := fDrawBitmap.Height; Left := MainForm.Left + (MainForm.Width - MainForm.ClientWidth) div 2; Top := MainForm.Top + MainForm.Height - Height - 35; Repaint; end; procedure TAlertForm.Timer1Timer(Sender: TObject); var nowU: int64; k: integer; isDel: Boolean; begin isDel := false; nowU := DateTimeToUnix(Now) - 10; for k:= fTexts.Count - 1 downto 0 do begin if nowU > DateTimeToUnix(TAlertTime(fTexts.Objects[k]).fNow) then begin fTexts.Objects[k].Free; fTexts.Delete(k); isDel := true; end; end; if isDel then begin if (fTexts.Count > 0) then resizeAlert else hideAlert; end; end; procedure TAlertForm.FormPaint(Sender: TObject); begin Canvas.Draw(0, 0, fDrawBitmap); end; procedure TAlertForm.Timer2Timer(Sender: TObject); begin //setOnTop(); end; procedure TAlertForm.FormClick(Sender: TObject); begin hideAlert; end; end.
unit LuaTypes; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses LuaPas; //Wrapper for the lua state. Type TLua = Plua_state; //Used mainly for descending lua threads off a root one //so that it may be dereferenced later on and freed. Type TLuaInfo = record Lua : TLua; LuaID : Integer; ParentLua : TLua; end; implementation end.
unit ColorWheel; interface uses Windows, Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ActnList, StdCtrls, ExtCtrls, JPL.Colors, JPL.Math, GdiPlus, GdiPlusHelpers; procedure DrawColorWheel(Image: TImage; const CurrentColor: TColor; bTriadic, bTetradic: Boolean; DegShift: integer; bDrawAxes: Boolean; bDrawDiagonals, bShowComplementaryColor: Boolean; bDrawFrame: Boolean); implementation {$region ' DrawColorWheel '} procedure DrawColorWheel(Image: TImage; const CurrentColor: TColor; bTriadic, bTetradic: Boolean; DegShift: integer; bDrawAxes: Boolean; bDrawDiagonals, bShowComplementaryColor: Boolean; bDrawFrame: Boolean); const DEG = '°'; var bmp: TBitmap; xWidth, xHeight, i, xPies: integer; gr: IGPGraphics; Pen: IGPPen; Brush: IGPBrush; Margin, Radius, Hue, Sweep: Single; halfW, halfH: Single; SelColHue, SelColSat, SelColLum, CompColHue: integer; RectF: TGPRectF; AngleStart, AngleSweep, DeltaHue: Single; cl, clBg, clCurrent, clTriad1, clTriad2, clComplementary, clTetrad1, clTetrad2, clTetrad3: TColor; dxr, fi: Single; s: UnicodeString; xDegShift: integer; AFont: IGPFont; Point: TGPPointF; FontFamily: IGPFontFamily; const DashValues: array [0..1] of Single = (4, 4); function GPColor(Color: TColor; Alpha: Byte = 255): TGPColor; begin Result.Initialize(Alpha, GetRValue(Color), GetGValue(Color), GetBValue(Color)); end; {$region ' DrawHueLine '} procedure DrawHueLine(const HueValue: Single; const AColor: TColor; const LineWidth: Single; bDashed: Boolean = False); var pt1, pt2: TGPPointF; begin gr.ResetTransform; gr.TranslateTransform(halfW, halfH); gr.ScaleTransform(1, -1); Pen.Color := GPColor(AColor, 220); Pen.Width := LineWidth; if bDashed then Pen.SetDashPattern(DashValues) else Pen.DashStyle := DashStyleSolid; pt1.X := 0; pt1.Y := 0; fi := 90 - HueValue; dxr := Radius + 0; pt2.X := dxr * CosDeg(fi); pt2.Y := dxr * SinDeg(fi); gr.DrawLine(Pen, pt1, pt2); end; {$endregion DrawHueLine} {$region ' DrawHuePolygon '} procedure DrawHuePolygon(const Arr: array of Single; const AColor: TColor; const LineWidth: Single); var Points: array of TGPPointF; i: integer; begin if Length(Arr) = 0 then Exit; SetLength(Points{%H-}, Length(Arr)); for i := 0 to High(Arr) do begin fi := 90 - Arr[i]; Points[i].X := Radius * CosDeg(fi); Points[i].Y := Radius * SinDeg(fi); end; Pen.Color := GPColor(AColor, 255); Pen.Width := LineWidth; Pen.SetDashPattern(DashValues); gr.DrawPolygon(Pen, Points); end; {$endregion DrawHuePolygon} {$region ' DrawHuePoint '} procedure DrawHuePoint(const Hue: Single; AColor: TColor); var pt1: TGPPointF; begin gr.ResetTransform; gr.TranslateTransform(halfW, halfH); gr.ScaleTransform(1, -1); // ------ punkt środkowy okręgu --------------- fi := 90 - Hue; pt1.X := Radius * CosDeg(fi); pt1.Y := Radius * SinDeg(fi); dxr := 4; RectF.X := pt1.X - dxr; RectF.Y := pt1.Y - dxr; RectF.Width := dxr * 2; RectF.Height := dxr * 2; Brush := nil; Brush := TGPSolidBrush.Create(GPColor(AColor, 140)); Pen.Width := 2; Pen.Color := GPColor(clBlack, 255); Pen.DashStyle := DashStyleSolid; gr.DrawEllipse(Pen, RectF); gr.FillEllipse(Brush, RectF); end; {$endregion DrawHuePoint} begin bmp := TBitmap.Create; try xWidth := Image.Width; xHeight := Image.Height; bmp.SetSize(xWidth, xHeight); bmp.PixelFormat := pf32bit; halfW := xWidth / 2; halfH := xHeight / 2; Margin := 38; xPies := 360; clCurrent := CurrentColor; clComplementary := ComplementaryColor(clCurrent); clBg := clWhite; gr := TGPGraphics.Create(bmp.Canvas.Handle); gr.SmoothingMode := SmoothingModeAntiAlias; gr.ResetTransform; Pen := TGPPen.Create(GPColor(clBg), 1); // ------------- background ---------------- RectF.InitializeFromLTRB(0, 0, xWidth, xHeight); Brush := TGPSolidBrush.Create(GPColor(clBg)); gr.FillRectangle(Brush, RectF); gr.DrawRectangle(Pen, RectF); //Pen := TGPPen.Create(GPColor($00A8A8A8), 1); // ------------ frame ------------- if bDrawFrame then begin Pen.Color := GPColor($00A8A8A8); RectF.Width := RectF.Width - 1; RectF.Height := RectF.Height - 1; gr.DrawRectangle(Pen, RectF); end; // ----------- circle -------------- Pen.DashStyle := DashStyleSolid; Pen.Color := GPColor(clGray); Pen.Width := 1; RectF.InitializeFromLTRB(Margin, Margin, xWidth - Margin, xHeight - Margin); gr.DrawEllipse(Pen, RectF); // ----------- transformation of the coordinate system ------------- gr.TranslateTransform(halfW, halfH); // shifting the origin of the coordinate system to the center gr.RotateTransform(-90); // 0 degrees at the top // --------------------- Pies --------------------------- gr.SmoothingMode := SmoothingModeNone; Radius := halfW - Margin; DeltaHue := 360 / xPies; Sweep := DeltaHue; RectF.X := -Radius; RectF.Y := -Radius; RectF.Width := Radius * 2; RectF.Height := RectF.Width; SetHslCssMaxValues; ColortoHSLRange(clCurrent, SelColHue, SelColSat, SelColLum); CompColHue := GetHueCssValue(clComplementary); for i := 0 to xPies - 1 do begin Hue := i * DeltaHue; cl := HslCssToColor(Hue, SelColSat, SelColLum); Brush := nil; Brush := TGPSolidBrush.Create(GPColor(cl, 255)); AngleStart := Hue; // kąt początkowy AngleSweep := Sweep; // rozpiętość kątowa gr.FillPie(Brush, RectF, AngleStart, AngleSweep); end; gr.SmoothingMode := SmoothingModeAntiAlias; // ------------------ inner circle ------------------------ Brush := nil; Brush := TGPSolidBrush.Create(GPColor(clWhite, 120)); Pen.Color := GPColor(clGray, 100); dxr := Radius - (halfW / 2); RectF.InitializeFromLTRB(-dxr, dxr, dxr, -dxr); gr.FillEllipse(Brush, RectF); gr.DrawEllipse(Pen, RectF); gr.ResetTransform; Pen.SetDashPattern(DashValues); Pen.Color := GPColor(clSilver, 150); // ---------------- axes ------------------ if bDrawAxes then begin gr.DrawLine(Pen, 0, xHeight / 2, xWidth, xHeight / 2); // X axis gr.DrawLine(Pen, xWidth / 2, xHeight, xWidth / 2, 0); // Y axis end; // ------------ diagonals ------------- if bDrawDiagonals then begin gr.DrawLine(Pen, 0, 0, xWidth, xHeight); gr.DrawLine(Pen, xWidth, 0, 0, xHeight); end; gr.ResetTransform; gr.TranslateTransform(halfW, halfH); gr.ScaleTransform(1, -1); xDegShift := DegShift; if bTriadic then begin GetTriadicColors(clCurrent, clTriad1, clTriad2, xDegShift); DrawHueLine(SelColHue, InvertColor(clCurrent), 3); DrawHueLine(SelColHue + 180 - xDegShift, InvertColor(clTriad1), 1, True); DrawHueLine(SelColHue + 180 + xDegShift, InvertColor(clTriad2), 1, True); DrawHuePolygon([SelColHue, SelColHue + 180 - xDegShift, SelColHue + 180 + xDegShift], RGB3(22), 1.4); DrawHuePoint(SelColHue, clCurrent); DrawHuePoint(SelColHue + 180 - xDegShift, clTriad1); DrawHuePoint(SelColHue + 180 + xDegShift, clTriad2); if bShowComplementaryColor then DrawHuePoint(CompColHue, clComplementary); end; if bTetradic then begin GetTetradicColors(clCurrent, clTetrad1, clTetrad2, clTetrad3, xDegShift); DrawHueLine(SelColHue, InvertColor(clCurrent), 3); DrawHueLine(SelColHue + xDegShift, InvertColor(clTetrad1), 1, True); DrawHueLine(SelColHue + 180, InvertColor(clTetrad2), 1, True); DrawHueLine(SelColHue + 180 + xDegShift, InvertColor(clTetrad3), 1, True); DrawHuePolygon([SelColHue, SelColHue + xDegShift, SelColHue + 180, SelColHue + 180 + xDegShift], RGB3(22), 1.4); DrawHuePoint(SelColHue, clCurrent); DrawHuePoint(SelColHue + xDegShift, clTetrad1); DrawHuePoint(SelColHue + 180, clTetrad2); DrawHuePoint(SelColHue + 180 + xDegShift, clTetrad3); end; gr.ResetTransform; // ----------------- Text --------------------- Brush := nil; Brush := TGPSolidBrush.Create(GPColor(clBlack)); FontFamily := TGPFontFamily.Create('Verdana'); AFont := TGPFont.Create(FontFamily, 8, [], UnitPoint); s := '0' + DEG; Point := GPPointF(halfW, 2); Point := GPPointFMove(Point, -(GPTextWidthF(gr, s, AFont) / 2), 0); gr.DrawString(s, AFont, Point, Brush); s := '90' + DEG; Point := GPPointF(xWidth, xHeight / 2); Point := GPPointFMove(Point, -GPTextWidthF(gr, s, AFont) - 4, -GPTextHeightF(gr, s, AFont) / 2); gr.DrawString(s, AFont, Point, Brush); s := '180' + DEG; Point := GPPointF(halfW, 7); Point := GPPointFMove(Point, -(GPTextWidthF(gr, s, AFont) / 2), xHeight - GPTextHeightF(gr, s, AFont) - 8); gr.DrawString(s, AFont, Point, Brush); s := '270' + DEG; Point := GPPointF(0, xHeight / 2); Point := GPPointFMove(Point, 4, -GPTextHeightF(gr, s, AFont) / 2); gr.DrawString(s, AFont, Point, Brush); Image.Picture.Assign(bmp); finally bmp.Free; end; end; {$endregion DrawColorWheel} end.
unit UHPI; interface type THPI = record Caption: String; Model: String; InterfaceType: String; MediaType: String; PNPDeviceID: String; DeviceID: String; Size: String; Partitions: String; BytesPerSector: String; SectorsPerTrack: String; TotalCylinders: String; TotalHeads: String; TotalSectors: String; TotalTracks: String; TracksPerCylinder: String; FirmwareRevision: String; SerialNumber: String; end; function GetHPI(aVolume: Char): THPI; implementation uses Winapi.ActiveX, System.Win.ComObj, System.SysUtils, Winapi.Windows, System.Classes, System.Variants; function GetWMIInfo(const aWMIProperty, aWMIClass: String; const aDeviceId: String = ''): String; const wbemFlagForwardOnly = $00000020; var SWbemLocator: OleVariant; SWbemService: OleVariant; SWbemObjectSet: OleVariant; WbemObject: OleVariant; oEnum : IEnumvariant; iValue : Cardinal; begin; Result := ''; SWbemLocator := CreateOleObject('WbemScripting.SWbemLocator'); SWbemService := SWbemLocator.ConnectServer('.', 'root\CIMV2', '', ''); if Trim(aDeviceId) <> '' then SWbemObjectSet := SWbemService.ExecQuery(Format('Select %s from %s where %s',[aWMIProperty, aWMIClass, 'Tag = ' + aDeviceId]),'WQL',wbemFlagForwardOnly) else SWbemObjectSet := SWbemService.ExecQuery(Format('Select %s from %s',[aWMIProperty, aWMIClass]),'WQL',wbemFlagForwardOnly); oEnum := IUnknown(SWbemObjectSet._NewEnum) as IEnumVariant; if oEnum.Next(1, WbemObject, iValue) = 0 then Result := WbemObject.Properties_.Item(aWMIProperty).Value; end; function GetHPI(aVolume: Char): THPI; //////////////////////////////////////////////////////////////////////////////// function GetFirmwareRevision(aDiskDrive: OleVariant): String; begin try Result := aDiskDrive.FirmwareRevision; except Result := 'n/a'; end; end; function GetSerialNumber(aDiskDrive: OleVariant; aDeviceId: String): String; begin try Result := aDiskDrive.SerialNumber; except try Result := GetWMIInfo('SerialNumber', 'Win32_PhysicalMedia',QuotedStr(aDeviceId)); except Result := 'n/a'; end; end; end; //////////////////////////////////////////////////////////////////////////////// const wbemFlagForwardOnly = $00000020; var SWbemLocator: OleVariant; SWbemServices: OleVariant; DiskDrives: IEnumVARIANT; DiskDrive: OleVariant; DiskDrivesFetched: Cardinal; DiskPartitions: IEnumVARIANT; DiskPartition: OleVariant; DiskPartitionsFetched: Cardinal; DiskVolumes: IEnumVARIANT; DiskVolume: OleVariant; DiskVolumesFetched: Cardinal; EscapedDeviceID: String; HDDInformation: String; begin ZeroMemory(@Result,SizeOf(THPI)); CoInitialize(nil); with TStringList.Create do try { Realiza a conexão } SWbemLocator := CreateOleObject('WbemScripting.SWbemLocator'); SWbemServices := SWbemLocator.ConnectServer('.', 'root\CIMV2', '', ''); { Obtém uma lista de drives físicos e circula por ela } DiskDrives := IUnknown(SWbemServices.ExecQuery('SELECT * FROM Win32_DiskDrive','WQL',wbemFlagForwardOnly)._NewEnum) as IEnumVariant; while DiskDrives.Next(1, DiskDrive, DiskDrivesFetched) = 0 do begin EscapedDeviceID := StringReplace(String(DiskDrive.DeviceID),'\','\\',[rfReplaceAll]); { Para o drive físico atual, obtém uma lista de partições e circula por ela } DiskPartitions := IUnknown(SWbemServices.ExecQuery('ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' + EscapedDeviceID + '"} WHERE AssocClass = Win32_DiskDriveToDiskPartition','WQL',wbemFlagForwardOnly)._NewEnum) as IEnumVariant; while DiskPartitions.Next(1, DiskPartition, DiskPartitionsFetched) = 0 do begin { Para a partição atual, obtém uma lista de volumes (letras) e circula por ela } DiskVolumes := IUnknown(SWbemServices.ExecQuery('ASSOCIATORS OF {Win32_DiskPartition.DeviceID="' + String(DiskPartition.DeviceID) + '"} WHERE AssocClass = Win32_LogicalDiskToPartition','WQL',wbemFlagForwardOnly)._NewEnum) as IEnumVariant; while DiskVolumes.Next(1, DiskVolume, DiskVolumesFetched) = 0 do begin { Adiciona ao StringlList uma linha com as informações disponíveis indexada pela letra do volume } Add(String(DiskVolume.DeviceID)[1] + '=<' + DiskDrive.Caption + '><' + DiskDrive.Model + '><' + DiskDrive.InterfaceType + '><' + DiskDrive.MediaType + '><' + DiskDrive.PNPDeviceID + '><' + DiskDrive.DeviceID + '><' + String(DiskDrive.Size) + '><' + String(DiskDrive.Partitions) + '><' + String(DiskDrive.BytesPerSector) + '><' + String(DiskDrive.SectorsPerTrack) + '><' + String(DiskDrive.TotalCylinders) + '><' + String(DiskDrive.TotalHeads) + '><' + String(DiskDrive.TotalSectors) + '><' + String(DiskDrive.TotalTracks) + '><' + String(DiskDrive.TracksPerCylinder) + '><' + GetFirmwareRevision(DiskDrive) + '><' + GetSerialNumber(DiskDrive,EscapedDeviceID) + '>'); DiskVolume := Unassigned; end; DiskPartition := Unassigned; end; DiskDrive := Unassigned; end; { Busca no StringList a letra passada como parâmetro } HDDInformation := Values[aVolume]; with TStringList.Create do try Text := StringReplace(Copy(HDDInformation,2,Length(HDDInformation) - 2),'><',#13#10,[rfReplaceAll]); if Count > 0 then with Result do begin Caption := Trim(Strings[0]); Model := Trim(Strings[1]); InterfaceType := Trim(Strings[2]); MediaType := Trim(Strings[3]); PNPDeviceID := Trim(Strings[4]); DeviceID := Trim(Strings[5]); Size := Trim(Strings[6]); Partitions := Trim(Strings[7]); BytesPerSector := Trim(Strings[8]); SectorsPerTrack := Trim(Strings[9]); TotalCylinders := Trim(Strings[10]); TotalHeads := Trim(Strings[11]); TotalSectors := Trim(Strings[12]); TotalTracks := Trim(Strings[13]); TracksPerCylinder := Trim(Strings[14]); FirmwareRevision := Trim(Strings[15]); SerialNumber := Trim(Strings[16]); end; finally Free; end; finally Free; CoUninitialize; end; end; end.
unit API_MVC; interface uses System.Generics.Collections, System.Threading; type TModelAbstract = class; TModelClass = class of TModelAbstract; TControllerAbstract = class; TControllerClass = class of TControllerAbstract; TObjProc = procedure of object; TViewMessageProc = procedure(const aMsg: string) of object; TModelMessageProc = procedure(const aMsg: string; aModel: TModelAbstract) of object; TModelEventProc = procedure(aModel: TModelAbstract) of object; /// <summary> /// inheritor class name have to contain verb f.e. TModelDoSomething /// </summary> TModelAbstract = class abstract private FOnModelMessage: TModelMessageProc; function GetEndMessage: string; procedure Execute(Sender: TObject); protected FCanceled: Boolean; FDataObj: TObjectDictionary<string, TObject>; FIsAsync: Boolean; FTask: ITask; FTaskIndex: Integer; function CreateExternalModel(aModelClass: TModelClass): TModelAbstract; procedure AfterCreate; virtual; procedure BeforeDestroy; virtual; procedure SendMessage(aMsg: string; aSyncMainThread: Boolean = False); public /// <summary> /// Override this procedure as point of enter to Model work. /// </summary> procedure Start; virtual; abstract; procedure Stop; constructor Create(aDataObj: TObjectDictionary<string, TObject>; aTaskIndex: Integer = 0); virtual; destructor Destroy; override; property EndMessage: string read GetEndMessage; property TaskIndex: Integer read FTaskIndex; end; IViewAbstract = interface function GetCloseMessage: string; procedure InitMVC(var aControllerClass: TControllerClass); /// <summary> /// Message have to be a verb or a verb word at the begining /// For example: AddFiles, etc. /// </summary> procedure SendMessage(aMsg: string); property CloseMessage: string read GetCloseMessage; end; {$M+} TControllerAbstract = class abstract private FRunningModelArr: TArray<TModelAbstract>; function GetViewListener: TViewMessageProc; procedure DoViewListener(const aMsg: string); procedure ModelInit(aModel: TModelAbstract); procedure RemoveModel(aModel: TModelAbstract); protected FIsAsyncModelRunMode: Boolean; FDataObj: TObjectDictionary<string, TObject>; function GetRunningModel<T: TModelAbstract>(const aTaskIndex: Integer): T; procedure CallModel<T: TModelAbstract>(aThreadCount: Integer = 1); procedure CallModelAsync<T: TModelAbstract>(aThreadCount: Integer = 1); procedure ModelListener(const aMsg: string; aModel: TModelAbstract); virtual; procedure PerformViewMessage(const aMsg: string); virtual; procedure StopModel<T: TModelAbstract>; public constructor Create; virtual; destructor Destroy; override; property ViewListener: TViewMessageProc read GetViewListener; end; {$M-} TPlatformSupport = class abstract protected FController: TControllerAbstract; public constructor Create(aController: TControllerAbstract); end; implementation uses System.Classes, System.SysUtils; function TControllerAbstract.GetRunningModel<T>(const aTaskIndex: Integer): T; var Model: TModelAbstract; begin Result := nil; for Model in FRunningModelArr do if (Model is T) and (Model.FTaskIndex = aTaskIndex) then begin Result := Model as T; Break; end; end; function TModelAbstract.CreateExternalModel(aModelClass: TModelClass): TModelAbstract; begin Result := aModelClass.Create(nil); if Assigned(FOnModelMessage) then Result.FOnModelMessage := FOnModelMessage; end; procedure TControllerAbstract.StopModel<T>; var Model: TModelAbstract; TaskArr: array of ITask; begin TaskArr := []; for Model in FRunningModelArr do if Model is T then begin Model.Stop; TaskArr := TaskArr + [Model.FTask]; end; TTask.WaitForAll(TaskArr); for Model in FRunningModelArr do if Model is T then begin RemoveModel(Model); if Model.FIsAsync then Model.Free; end; end; procedure TControllerAbstract.CallModelAsync<T>(aThreadCount: Integer = 1); begin FIsAsyncModelRunMode := True; CallModel<T>(aThreadCount); FIsAsyncModelRunMode := False; end; constructor TPlatformSupport.Create(aController: TControllerAbstract); begin FController := aController; end; procedure TControllerAbstract.RemoveModel(aModel: TModelAbstract); var i: Integer; Model: TModelAbstract; begin for i := 0 to Length(FRunningModelArr) - 1 do if FRunningModelArr[i] = aModel then Break; Delete(FRunningModelArr, i, 1); end; procedure TModelAbstract.Stop; begin FCanceled := True; end; function TModelAbstract.GetEndMessage: string; begin Result := Format('On%sDone',[Self.ClassName.Substring(1)]); end; procedure TModelAbstract.BeforeDestroy; begin end; destructor TModelAbstract.Destroy; begin BeforeDestroy; inherited; end; procedure TModelAbstract.AfterCreate; begin end; function TControllerAbstract.GetViewListener: TViewMessageProc; begin Result := DoViewListener; end; procedure TControllerAbstract.ModelInit(aModel: TModelAbstract); var ModelInitProc: TModelEventProc; ModelInitProcName: string; begin ModelInitProcName := Format('On%sInit',[aModel.ClassName.Substring(1)]); TMethod(ModelInitProc).Code := Self.MethodAddress(ModelInitProcName); TMethod(ModelInitProc).Data := Self; if Assigned(ModelInitProc) then ModelInitProc(aModel); end; procedure TModelAbstract.SendMessage(aMsg: string; aSyncMainThread: Boolean = False); begin if Assigned(FOnModelMessage) and (not FCanceled or (aMsg = EndMessage) ) then if aSyncMainThread then TThread.Synchronize(nil, procedure() begin FOnModelMessage(aMsg, Self); end ) else FOnModelMessage(aMsg, Self); end; procedure TControllerAbstract.ModelListener(const aMsg: string; aModel: TModelAbstract); var ModelEventProc: TModelEventProc; begin if aMsg = aModel.EndMessage then RemoveModel(aModel); TMethod(ModelEventProc).Code := Self.MethodAddress(aMsg); TMethod(ModelEventProc).Data := Self; if Assigned(ModelEventProc) then ModelEventProc(aModel); end; constructor TModelAbstract.Create(aDataObj: TObjectDictionary<string, TObject>; aTaskIndex: Integer = 0); begin FTaskIndex := aTaskIndex; FDataObj := aDataObj; AfterCreate; end; procedure TModelAbstract.Execute(Sender: TObject); begin Start; if not FIsAsync then begin SendMessage(EndMessage); Free; end; end; procedure TControllerAbstract.CallModel<T>(aThreadCount: Integer = 1); var i: Integer; Model: TModelAbstract; ModelClass: TModelClass; Task: ITask; begin for i := 1 to aThreadCount do begin ModelClass := T; Model := ModelClass.Create(FDataObj, i - 1); Model.FOnModelMessage := ModelListener; Model.FIsAsync := FIsAsyncModelRunMode; ModelInit(Model); Task := TTask.Create(Self, Model.Execute); Model.FTask := Task; FRunningModelArr := FRunningModelArr + [Model]; Task.Start; end; end; destructor TControllerAbstract.Destroy; var Model: TModelAbstract; TaskArr: array of ITask; begin for Model in FRunningModelArr do begin Model.Stop; TaskArr := TaskArr + [Model.FTask]; end; TTask.WaitForAll(TaskArr); FDataObj.Free; inherited; end; procedure TControllerAbstract.PerformViewMessage(const aMsg: string); begin end; procedure TControllerAbstract.DoViewListener(const aMsg: string); var ControllerProc: TObjProc; begin TMethod(ControllerProc).Code := Self.MethodAddress(aMsg); TMethod(ControllerProc).Data := Self; if Assigned(ControllerProc) then ControllerProc else PerformViewMessage(aMsg); end; constructor TControllerAbstract.Create; begin FDataObj := TObjectDictionary<string, TObject>.Create([]); end; end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, Vcl.ExtCtrls, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps, VCL.TMSFNCGoogleMaps, Vcl.StdCtrls, AdvEdit, AdvGlowButton; type TFrmMain = class(TForm) Map: TTMSFNCGoogleMaps; Panel1: TPanel; btnCircle: TAdvGlowButton; btnRectangle: TAdvGlowButton; procedure FormCreate(Sender: TObject); procedure btnRectangleClick(Sender: TObject); procedure btnCircleClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses IOUtils, Flix.Utils.Maps, TMSFNCMapsCommonTypes ; procedure TFrmMain.btnCircleClick(Sender: TObject); var LCenter: TTMSFNCMapsCoordinateRec; LCircle: TTMSFNCGoogleMapsCircle; begin LCenter := CreateCoordinate( 26.686532, -80.388308 ); LCircle := Map.AddCircle(LCenter) as TTMSFNCGoogleMapsCircle; LCircle.StrokeColor := clRed; LCircle.FillColor := clYellow; LCircle.FillOpacity := 0.3; LCircle.Editable := True; LCircle.Draggable := True; Map.SetCenterCoordinate(LCenter); end; procedure TFrmMain.btnRectangleClick(Sender: TObject); var LLeft, LRight: TTMSFNCMapsCoordinateRec; LRect : TTMSFNCGoogleMapsRectangle; begin LLeft := CreateCoordinate( 27.201630, -81.038505 ); LRight := CreateCoordinate( 26.755389, -80.566928 ); LRect := Map.AddRectangle( CreateBounds( LLeft, LRight ) ) as TTMSFNCGoogleMapsRectangle; LRect.Editable := True; LRect.Draggable := True; LRect.FillColor := clNavy; LRect.FillOpacity := 0.3; LRect.StrokeColor := clGreen; Map.ZoomToBounds(CreateBounds(LLeft, LRight)); end; procedure TFrmMain.FormCreate(Sender: TObject); begin var LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) ); try Map.APIKey := LKeys.GetKey( msGoogleMaps ); finally LKeys.Free; end; end; end.
unit gr_ReCountData_Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCheckBox, dxBar, dxBarExtItems, cxSplitter, cxLabel, cxContainer, cxTextEdit, cxMaskEdit, cxDBEdit, ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, dxDockPanel, dxDockControl, cxMemo, FIBQuery, pFIBQuery, ZProc, gr_uCommonProc, Dates, ZTypes, gr_uMessage, PackageLoad, pFIBStoredProc, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase, cxCheckListBox, cxGridBandedTableView, cxGridDBBandedTableView, gr_uCommonConsts, gr_uCommonLoader, zcxLocateBar, gr_dmCommonStyles, gr_uWaitForm; type TFgrReCountData = class(TForm) BarManager: TdxBarManager; RefreshBtn: TdxBarLargeButton; ExitBtn: TdxBarLargeButton; PanelGridsChild: TPanel; SplitterPanelGridVed: TcxSplitter; PanelGridDatesAcc: TPanel; GridDates: TcxGrid; GridDatesView1: TcxGridDBTableView; GridMasterKodSetup2: TcxGridDBColumn; GridDatesLevel1: TcxGridLevel; PanelGridPeople: TPanel; DataSourceChild: TDataSource; DataSourceParent: TDataSource; DataBase: TpFIBDatabase; DataSetChild: TpFIBDataSet; DataSetParent: TpFIBDataSet; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; StoredProc: TpFIBStoredProc; Styles: TcxStyleRepository; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; dxBarDockControl2: TdxBarDockControl; GridBandedTableViewStyleSheetDevExpress: TcxGridBandedTableViewStyleSheet; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyle18: TcxStyle; cxStyle19: TcxStyle; cxStyle20: TcxStyle; cxStyle21: TcxStyle; cxStyle22: TcxStyle; cxStyle23: TcxStyle; cxStyle24: TcxStyle; cxStyle25: TcxStyle; cxStyle26: TcxStyle; cxStyle27: TcxStyle; cxStyle28: TcxStyle; cxStyle29: TcxStyle; cxStyle30: TcxStyle; GridMasterFIO: TcxGridDBColumn; GridMasterTin: TcxGridDBColumn; PanelDopData: TPanel; LabelDepartment: TcxLabel; LabelSmeta: TcxLabel; BarDockLocate: TdxBarDockControl; cxSplitter1: TcxSplitter; GridAcc: TcxGrid; GridAccDBBandedTableView1: TcxGridDBBandedTableView; GridChildColKodVidOpl: TcxGridDBBandedColumn; GridChildColNameVidOpl: TcxGridDBBandedColumn; GridChildColSumma: TcxGridDBBandedColumn; GridChildColP1: TcxGridDBBandedColumn; GridChildColDepartment: TcxGridDBBandedColumn; GridChildColSmeta: TcxGridDBBandedColumn; GridChildColKodSetup3: TcxGridDBBandedColumn; GridAccLevel1: TcxGridLevel; GridChildColNDay: TcxGridDBBandedColumn; DeleteBtn: TdxBarLargeButton; DeleteAllBtn: TdxBarLargeButton; LabelCategory: TcxLabel; EditCategory: TcxDBMaskEdit; EditDepartment: TcxDBMaskEdit; EditSmeta: TcxDBMaskEdit; dxBarStatic5: TdxBarStatic; dxBarStatic6: TdxBarStatic; SumLessNullBtn: TdxBarLargeButton; SumIsEveryBtn: TdxBarLargeButton; SumEqualsNullBtn: TdxBarLargeButton; SumMoreNullBtn: TdxBarLargeButton; SumIsNullBtn: TdxBarLargeButton; BarStaticFilter: TdxBarStatic; procedure ExitBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure RefreshBtnClick(Sender: TObject); procedure GridMasterKodSetup2GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure GridChildColP1GetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure GridDatesView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure GridDatesView1KeyPress(Sender: TObject; var Key: Char); procedure EditLocateEnter(Sender: TObject); procedure GridChildColKodSetup3GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure DeleteBtnClick(Sender: TObject); procedure DeleteAllBtnClick(Sender: TObject); procedure PanelDopDataResize(Sender: TObject); procedure GridAccDBBandedTableView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure GridAccDBBandedTableView1DataControllerSummaryFooterSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); procedure GetData(Sender: TObject); procedure SumIsEveryBtnClick(Sender: TObject); procedure SumMoreNullBtnClick(Sender: TObject); procedure SumEqualsNullBtnClick(Sender: TObject); procedure SumLessNullBtnClick(Sender: TObject); procedure SumIsNullBtnClick(Sender: TObject); private PItemFilter:byte; pLanguageIndex:byte; pBarLocate:TZBarLocate; pStylesDM:TStylesDM; pDiffWidth:integer; pLastFilterBtn:byte; public constructor Create(AOwner : TComponent;DB:TISC_DB_HANDLE);reintroduce; end; function View_ReCountData(AParameter:TObject):Variant;stdcall; exports View_ReCountData; implementation uses StrUtils, Math; {$R *.dfm} function View_ReCountData(AParameter:TObject):Variant; var ViewForm: TFgrReCountData; begin if ((IsMDIChildFormShow(TFgrReCountData)) or (AParameter.ClassType<>TgrSimpleParam)) then Exit; ViewForm := TFgrReCountData.Create(TgrSimpleParam(AParameter).Owner,TgrSimpleParam(AParameter).DB_Handle); end; constructor TFgrReCountData.Create(AOwner : TComponent;DB:TISC_DB_HANDLE); begin Inherited Create(AOwner); pDiffWidth:=PanelDopData.Width-EditDepartment.Width; cxSplitter1.Color := GridDatesView1.Styles.Selection.Color; PanelDopData.Color := GridDatesView1.Styles.Background.Color; pLastFilterBtn:=1; pLanguageIndex := IndexLanguage; //****************************************************************************** Caption := ViewRecData_Text[pLanguageIndex]; RefreshBtn.Caption := RefreshBtn_Caption[pLanguageIndex]; ExitBtn.Caption := ExitBtn_Caption[pLanguageIndex]; GridMasterTin.Caption := GridClTin_Caption[pLanguageIndex]; GridMasterFIO.Caption := GridClFIO_Caption[pLanguageIndex]; GridMasterKodSetup2.Caption := GridClKodSetup_Caption[pLanguageIndex]; GridChildColKodVidOpl.Caption := GridClKodVo_Caption[pLanguageIndex]; GridChildColSumma.Caption := GridClSumma_Caption[pLanguageIndex]; GridChildColNameVidOpl.Caption := GridClNameVo_Caption[pLanguageIndex]; GridChildColP1.Caption := GridClP1_Caption[pLanguageIndex]; GridChildColDepartment.Caption := GridClKodDepartment_Caption[pLanguageIndex]; GridChildColSmeta.Caption := GridClKodSmeta_Caption[pLanguageIndex]; GridChildColKodSetup3.Caption := GridClKodSetup_Caption[pLanguageIndex]; GridChildColNDay.Caption := GridClNday_Caption[pLanguageIndex]; LabelCategory.Caption := LabelCategory_Caption[pLanguageIndex]+': '; LabelDepartment.Caption := LabelDepartment_Caption[pLanguageIndex]+': '; LabelSmeta.Caption := LabelSmeta_Caption[pLanguageIndex]+': '; BarStaticFilter.Caption := Filter_Text[pLanguageIndex]+': '; SumIsEveryBtn.Caption := NotFilter_Text[PlanguageIndex]; SumMoreNullBtn.Caption := SumMoreNull_Text[PlanguageIndex]; SumLessNullBtn.Caption := SumLessNull_Text[PlanguageIndex]; SumEqualsNullBtn.Caption := SumEqualsNull_Text[PlanguageIndex]; SumIsNullBtn.Caption := SumIsNull_Text[PlanguageIndex]; //****************************************************************************** DataSetChild.SQLs.SelectSQL.Text:='SELECT * FROM GR_VIEW_RECOUNT(?ID_MAN,?KOD_SETUP)'; DataSetParent.SQLs.SelectSQL.Text:='SELECT * FROM GR_GET_RECOUNT_LIST(2)'; DataBase.Handle := DB; PItemFilter:=1; //****************************************************************************** SetOptionsBarManager(BarManager); SetOptionsGridView(GridDatesView1); SetOptionsGridView(GridAccDBBandedTableView1); dxBarDockControl2.SunkenBorder := True; GridDatesView1.OptionsView.Footer:=true; //------------------------------------------------------------------------------ pStylesDM := TStylesDM.Create(self); GridDatesView1.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; GridAccDBBandedTableView1.Styles.StyleSheet := pStylesDM.GridBandedTableViewStyleSheetDevExpress; //------------------------------------------------------------------------------ PBarLocate:=TZBarLocate.Create(BarManager); PBarLocate.DataSet := DataSetParent; PBarLocate.BorderStyle := bbsNone; PBarLocate.AddLocateItem('TIN', GridMasterTin.Caption, [loCaseInsensitive,loPartialKey]); PBarLocate.AddLocateItem('FIO', GridMasterFIO.Caption, [loCaseInsensitive,loPartialKey]); PBarLocate.DigitalField := 'TIN'; PBarLocate.DockControl := BarDockLocate; //------------------------------------------------------------------------------ GridAccDBBandedTableView1.DataController.Summary.FooterSummaryItems[1].Format := Summary_Text[pLanguageIndex]; end; procedure TFgrReCountData.ExitBtnClick(Sender: TObject); begin Close; end; procedure TFgrReCountData.FormClose(Sender: TObject; var Action: TCloseAction); begin if ReadTransaction.InTransaction then ReadTransaction.Commit; if FormStyle=fsMDIChild then Action:=caFree; end; procedure TFgrReCountData.FormCreate(Sender: TObject); begin GetData(sender); GridDatesView1FocusedRecordChanged(GridDatesView1,nil,GridDatesView1.Controller.FocusedRecord,True); end; procedure TFgrReCountData.RefreshBtnClick(Sender: TObject); var Id1:Variant; wf:TForm; begin wf:=ShowWaitForm(self,wfSelectData); ID1:=DataSetParent['ID_MAN']; DataSetChild.Close; DataSetParent.CloseOpen(True); DataSetParent.Locate('ID_MAN',ID1,[loCaseInsensitive,loPartialKey]); DataSetChild.Open; CloseWaitForm(wf); end; procedure TFgrReCountData.GridMasterKodSetup2GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if AText<>'' then Atext:=KodSetupToPeriod(StrToInt(AText),0); end; procedure TFgrReCountData.GridChildColP1GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if AText='False' then AText:=GridClP1_Ud_Text[pLanguageIndex]; if AText='True' then AText:=GridClP1_Nar_Text[pLanguageIndex]; end; procedure TFgrReCountData.GridDatesView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin if (AFocusedRecord=nil) or (AFocusedRecord.Expandable) then begin DeleteBtn.Enabled:=False; GridAccDBBandedTableView1.OptionsView.Footer := False; end else begin DeleteBtn.Enabled:=True; GridAccDBBandedTableView1.OptionsView.Footer := True; end; DeleteAllBtn.Enabled:=not(AFocusedRecord=nil); GridAccDBBandedTableView1FocusedRecordChanged(GridAccDBBandedTableView1,nil,GridAccDBBandedTableView1.Controller.FocusedRecord,True); end; procedure TFgrReCountData.GridDatesView1KeyPress(Sender: TObject; var Key: Char); begin If (Key in ['0'..'9']) then begin if (GridDatesView1.OptionsBehavior.IncSearchItem <> GridMasterTin)then begin GridDatesView1.Controller.IncSearchingText := ''; GridDatesView1.OptionsBehavior.IncSearchItem := GridMasterTin; end end else if (GridDatesView1.OptionsBehavior.IncSearchItem <> GridMasterFIO)then begin GridDatesView1.Controller.IncSearchingText := ''; GridDatesView1.OptionsBehavior.IncSearchItem := GridMasterFIO; end; end; procedure TFgrReCountData.EditLocateEnter(Sender: TObject); begin GridDates.SetFocus; end; procedure TFgrReCountData.GridChildColKodSetup3GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if AText<>'' then Atext:=KodSetupToPeriod(StrToInt(AText),0); end; procedure TFgrReCountData.DeleteBtnClick(Sender: TObject); begin if grShowMessage(Caption_Delete[pLanguageIndex],DeleteRecordQuestion_Text[pLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then try StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName:='GR_RECOUNT_LIST_DELETE_MAN'; StoredProc.Prepare; StoredProc.ParamByName('ID_MAN').AsInteger := DataSetParent['ID_MAN']; StoredProc.ParamByName('KOD_SETUP').AsInteger := DataSetParent['KOD_SETUP']; StoredProc.ExecProc; StoredProc.Transaction.Commit; DataSetParent.SQLs.DeleteSQL.Text:='execute procedure Z_EMPTY_PROC'; DataSetParent.Delete; except on E:Exception do begin StoredProc.Transaction.Rollback; grShowMessage(ECaption[pLanguageIndex],e.Message,mtError,[mbOk]); end; end; end; procedure TFgrReCountData.DeleteAllBtnClick(Sender: TObject); begin if grShowMessage(Caption_Delete[pLanguageIndex],DelAllRecordsQuestion_Text[pLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then try DataSetChild.Close; GridDatesView1.DataController.DataSource:=nil; try DataSetParent.First; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName:='GR_RECOUNT_LIST_DELETE_MAN'; StoredProc.Prepare; while not DataSetParent.Eof do begin StoredProc.ParamByName('ID_MAN').AsInteger := DataSetParent['ID_MAN']; StoredProc.ParamByName('KOD_SETUP').AsInteger := DataSetParent['KOD_SETUP']; StoredProc.ExecProc; DataSetParent.Next; end; StoredProc.Transaction.Commit; DataSetParent.CloseOpen(True); DataSetChild.Open; except on E:Exception do begin StoredProc.Transaction.Rollback; grShowMessage(ECaption[pLanguageIndex],e.Message,mtError,[mbOk]); end; end; finally DataSetChild.Open; GridDatesView1.DataController.DataSource := DataSourceParent; end; end; procedure TFgrReCountData.PanelDopDataResize(Sender: TObject); begin EditDepartment.Width := max(PanelDopData.Width-pDiffWidth,100); EditSmeta.Width := EditDepartment.Width; EditCategory.Width := EditDepartment.Width; end; procedure TFgrReCountData.GridAccDBBandedTableView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin if (AFocusedRecord=nil) or (AFocusedRecord.Expandable) then begin EditCategory.DataBinding.DataSource := nil; EditDepartment.DataBinding.DataSource := nil; EditSmeta.DataBinding.DataSource := nil; end else begin EditCategory.DataBinding.DataSource := DataSourceChild; EditDepartment.DataBinding.DataSource := DataSourceChild; EditSmeta.DataBinding.DataSource := DataSourceChild; end; end; procedure TFgrReCountData.GridAccDBBandedTableView1DataControllerSummaryFooterSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); var AItem: TcxGridTableSummaryItem; begin AItem := TcxGridTableSummaryItem(Arguments.SummaryItem); if (AItem.Column = GridChildColSumma) and (AItem.Kind = skSum) and (AItem.Position = spFooter) then begin if (VarToStr(GridAccDBBandedTableView1.DataController.Values[Arguments.RecordIndex, GridChildColP1.Index]) ='F') then OutArguments.Value:=-OutArguments.Value; end; end; procedure TFgrReCountData.GetData(Sender: TObject); var wf:TForm; begin wf := ShowWaitForm(self,wfSelectData); DataSetParent.Open; DataSetChild.Open; CloseWaitForm(wf); end; procedure TFgrReCountData.SumIsEveryBtnClick(Sender: TObject); begin if not (pLastFilterBtn=1) then begin DataSetChild.Close; DataSetParent.Close; DataSetParent.SQLs.SelectSQL.Text := 'SELECT * FROM GR_GET_RECOUNT_LIST(2)'; GetData(Sender); pLastFilterBtn := 1; end; end; procedure TFgrReCountData.SumMoreNullBtnClick(Sender: TObject); begin if not (pLastFilterBtn=2) then begin DataSetChild.Close; DataSetParent.Close; DataSetParent.SQLs.SelectSQL.Text := 'SELECT * FROM GR_GET_RECOUNT_LIST(1)'; GetData(Sender); pLastFilterBtn := 2; end; end; procedure TFgrReCountData.SumEqualsNullBtnClick(Sender: TObject); begin if not (pLastFilterBtn = 3) then begin DataSetChild.Close; DataSetParent.Close; DataSetParent.SQLs.SelectSQL.Text := 'SELECT * FROM GR_GET_RECOUNT_LIST(0)'; GetData(Sender); pLastFilterBtn := 3; end; end; procedure TFgrReCountData.SumLessNullBtnClick(Sender: TObject); begin if not (pLastFilterBtn = 4) then begin DataSetChild.Close; DataSetParent.Close; DataSetParent.SQLs.SelectSQL.Text := 'SELECT * FROM GR_GET_RECOUNT_LIST(-1)'; GetData(Sender); pLastFilterBtn := 4; end; end; procedure TFgrReCountData.SumIsNullBtnClick(Sender: TObject); begin if not (pLastFilterBtn = 5) then begin DataSetChild.Close; DataSetParent.Close; DataSetParent.SQLs.SelectSQL.Text := 'SELECT * FROM GR_GET_RECOUNT_LIST(NULL)'; GetData(Sender); pLastFilterBtn := 5; end; end; end.
{*****************************************************************} { ceosserver is part of Ceos middleware/n-tier JSONRPC components } { } { Beta version } { } { This library 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. } { } { by Jose Benedito - josebenedito@gmail.com } { www.jbsolucoes.net } {*****************************************************************} unit ceosserver; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, fpjson, variants, jsonparser, fphttpserver, ceostypes, ceosconsts; type THTTPServerThread = class; TOnCeosGetRequest = procedure(Sender: TObject; const ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse) of Object; TOnCeosRequest = procedure(Sender: TObject; const ARequest: TCeosRequestContent; var AResponse: TCeosResponseContent) of Object; TOnCeosRequestError = procedure(Sender: TObject; const E: exception; var AResponse: TCeosResponseContent) of Object; TOnCeosException = procedure(Sender: TObject; const E: exception) of Object; { TCeosServer } TCeosServer = class(TComponent) private FActive: boolean; FOnGetRequest: TOnCeosGetRequest; FPort: integer; FOnRequestError: TOnCeosRequestError; FOnException: TOnCeosException; FOnRequest: TOnCeosRequest; FOnStart: TNotifyEvent; FOnStop: TNotifyEvent; FThrdHTTPServer: THTTPServerThread; FThreaded: boolean; function IsPortStored: boolean; function IsThreadedStored: boolean; procedure SetPort(AValue: integer); procedure SetHeader(var AResponse: TFPHTTPConnectionResponse); procedure DoOnGetRequest(Sender: TObject; var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); procedure DoOnRequest(Sender: TObject; var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); procedure SetThreaded(AValue: boolean); { Private declarations } protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Start; procedure Stop; property Active: boolean read FActive; published { Published declarations } property Port: integer read FPort write SetPort stored IsPortStored default 8080; property Threaded: boolean read FThreaded write SetThreaded stored IsThreadedStored default true; property OnRequestError: TOnCeosRequestError read FOnRequestError write FOnRequestError; property OnException: TOnCeosException read FOnException write FOnException; property OnGetRequest: TOnCeosGetRequest read FOnGetRequest write FOnGetRequest; property OnRequest: TOnCeosRequest read FOnRequest write FOnRequest; property OnStart: TNotifyEvent read FOnStart write FOnStart; property OnStop: TNotifyEvent read FOnStop write FOnStop; end; { THTTPServerThread } THTTPServerThread = class(TThread) private FServer: TFPHTTPServer; FOnException: TOnCeosException; FActive: boolean; public constructor Create(APort: word; const AThreaded: boolean; const AOnRequest: THTTPServerRequestHandler; const AOnException: TOnCeosException); destructor Destroy; override; procedure Execute; override; procedure DoTerminate; override; property Active: boolean read FActive write FActive; property Server: TFPHTTPServer read FServer; property OnException: TOnCeosException read FOnException write FOnException; end; //Do Parse of Request content procedure DoParseRequest(var ARequest: TCeosRequestContent; AJSONString: TJSONStringType); var UsingServerMethods: boolean = false; procedure Register; implementation uses ceosmessages; procedure DoParseRequest(var ARequest: TCeosRequestContent; AJSONString: TJSONStringType); var parser: TJSONParser; begin parser := TJSONParser.Create(AJSONString); try try ARequest := TCeosRequestContent(parser.Parse as TJSONObject); except on e:exception do begin ARequest := nil; raise exception.create(e.message); end; end; finally parser.free; parser := nil; end; end; procedure Register; begin {$I ceosserver_icon.lrs} RegisterComponents('Ceos',[TCeosServer]); end; { TCeosServer } function TCeosServer.IsPortStored: boolean; begin result := true; end; function TCeosServer.IsThreadedStored: boolean; begin result := true; end; procedure TCeosServer.SetPort(AValue: integer); begin FPort := AValue; end; procedure TCeosServer.SetHeader(var AResponse: TFPHTTPConnectionResponse); begin AResponse.CustomHeaders.Clear; AResponse.SetCustomHeader('Access-Control-Allow-Origin','*'); AResponse.SetCustomHeader('Access-Control-Allow-Credentials','true'); AResponse.CustomHeaders.Add(JSON_HEADER_CONTENT_TYPE); end; procedure TCeosServer.DoOnGetRequest(Sender: TObject; var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); begin try if assigned(OnGetRequest) then begin AResponse.Code := 200; OnGetRequest(Sender, ARequest, AResponse) ; exit; end else AResponse.Code := 404; except on e:exception do begin if Assigned(OnException) then OnException(Sender,e); AResponse.Code := 500; end; end; end; procedure TCeosServer.DoOnRequest(Sender: TObject; var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); var ceosRequest: TCeosRequestContent; ceosResponse: TCeosResponseContent; iID: integer; begin ceosRequest := nil; ceosResponse := nil; if ARequest.Method = 'GET' then begin DoOnGetRequest(Sender, ARequest, AResponse); exit; end; SetHeader(AResponse); try try DoParseRequest(ceosRequest, ARequest.Content); if not UsingServerMethods then begin ceosResponse := TCeosResponseContent.create; ceosResponse.ID := ceosRequest.ID; end; if assigned(OnRequest) then OnRequest(Sender,ceosRequest,ceosResponse); if not assigned(ceosResponse) then ceosResponse := JSONRPCResult(TJSONString.create(MSG_NO_RESPONSE),ceosRequest.ID); except on e:exception do if Assigned(OnException) then OnRequestError(Sender,e,ceosResponse) else begin if ceosRequest <> nil then iID := ceosRequest.ID else iID := -1; ceosResponse := JSONRPCError(ERR_REQUEST_ERROR,ERROR_REQUEST_ERROR,iID); end; end; finally AResponse.content := ceosResponse.AsJSON; ceosRequest.free; ceosRequest := nil; ceosResponse.free; ceosResponse := nil; end; end; procedure TCeosServer.SetThreaded(AValue: boolean); begin FThreaded := AValue; end; constructor TCeosServer.Create(AOwner: TComponent); begin inherited Create(AOwner); FPort := CEOS_DEFAULT_PORT; FThreaded := true; end; destructor TCeosServer.Destroy; begin if assigned(FThrdHTTPServer) then begin FThrdHTTPServer.Terminate; FThrdHTTPServer.free; FThrdHTTPServer := nil; end; inherited Destroy; end; procedure TCeosServer.Start; begin try if Assigned(FThrdHTTPServer) then FThrdHTTPServer.free; FThrdHTTPServer := THTTPServerThread.Create(Port, Threaded, @DoOnRequest, OnException); FActive := FThrdHTTPServer.Active; if FActive and Assigned(OnStart) then OnStart(Self); except on e:exception do if Assigned(OnException) then OnException(Self,e) else raise exception.create(e.message); end; end; procedure TCeosServer.Stop; begin try FThrdHTTPServer.Terminate; FThrdHTTPServer.DoTerminate; if Assigned(OnStop) then OnStop(Self); FActive := false; except on e:exception do if Assigned(OnException) then OnException(Self,e) else raise exception.create(e.message); end; end; { THTTPServerThread } constructor THTTPServerThread.Create(APort: word; const AThreaded: boolean; const AOnRequest: THTTPServerRequestHandler; const AOnException: TOnCeosException); begin FServer := TFPHTTPServer.Create(nil); FServer.Active := false; FServer.Port := APort; FServer.Threaded := AThreaded; FServer.OnRequest := AOnRequest; FActive := true; OnException := AOnException; inherited Create(False); end; destructor THTTPServerThread.Destroy; begin if assigned(FServer) then begin FServer.free; FServer := nil; end; inherited Destroy; end; procedure THTTPServerThread.Execute; begin try try FServer.Active := True; except on e:exception do begin FActive := false; FServer.Active := false; if assigned(OnException) then OnException(Self,e); end; end; finally FreeAndNil(FServer); end; end; procedure THTTPServerThread.DoTerminate; begin inherited DoTerminate; if assigned(FServer) then FServer.Active := False; end; end.
unit MainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, lua, pLua, LuaWrapper; type { TfrmMain } TfrmMain = class(TForm) procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { private declarations } public { public declarations } Lua : TLua; end; var frmMain: TfrmMain; implementation uses luaConfig, pluaRecord; function lua_HexToInt(L : PLua_State) : integer; cdecl; begin result := 1; lua_pushinteger(L, StrToInt('$'+plua_tostring(L, 1))); end; function lua_SetConfig(L : PLua_State) : integer; cdecl; begin result := 0; lua_pushliteral(L, 'Caption'); lua_gettable(L, -2); if not lua_isnil(L, -1) then frmMain.Caption := plua_tostring(L, -1); lua_pop(L, 1); lua_pushliteral(L, 'Color'); lua_gettable(L, -2); if not lua_isnil(L, -1) then frmMain.Color := lua_tointeger(L, -1); lua_pop(L, 1); end; { TfrmMain } procedure TfrmMain.FormCreate(Sender: TObject); begin Lua := TLua.Create(self); Lua.LoadFile('config.lua'); Lua.RegisterLuaMethod('HexToInt', @lua_HexToInt); Lua.RegisterLuaMethod('SetConfig', @lua_SetConfig); // Create a "new" version of our virtual record type and register it to the lua // global name of "Config" plua_registerExistingRecord(Lua.LuaState, 'Config', nil, RecordTypesList['TConfig']); end; procedure TfrmMain.FormShow(Sender: TObject); begin Lua.Execute; end; initialization {$I MainForm.lrs} end.
unit trl_upersiststore; {$mode delphi}{$H+} interface uses Classes, SysUtils, trl_ipersist, trl_ifactory, trl_irttibroker, trl_dicontainer, fgl, trl_upersist; type { TSIDList } TSIDList = class(TInterfacedObject, ISIDList) protected type TSIDItems = class(TFPGList<TSID>) end; private fItems: TSIDItems; protected // ISIDList function GetCount: integer; function GetItems(AIndex: integer): TSID; procedure SetCount(AValue: integer); procedure SetItems(AIndex: integer; AValue: TSID); public procedure AfterConstruction; override; procedure BeforeDestruction; override; property Count: integer read GetCount write SetCount; property Items[AIndex: integer]: TSID read GetItems write SetItems; default; end; { TPersistFactory } TPersistFactory = class(TCustomDIFactory, IPersistFactory) protected // IPersistFactory function CreateObject(const AClass: string): IRBData; function Create(const AClass: string; const AID: string = ''): TObject; overload; function Create(AInterface: TGUID; const AID: string = ''): IUnknown; overload; end; { TStoreCache } TStoreCache = class(TDIObject) private type { TDataRecord } TDataRecord = record fSID: TSID; fData: IRBData; public class function Create(const ASID: TSID; const AData: IRBData): TDataRecord; static; procedure Clear; class operator =(a, b: TDataRecord): Boolean; end; TCache = TFPGList<TDataRecord>; private fCache: TCache; protected function FindIndex(const ASID: TSID): integer; overload; function FindIndex(const AData: IRBData): integer; overload; public constructor Create; override; destructor Destroy; override; procedure Add(const ASID: TSID; const AData: IRBData); procedure Remove(const ASID: TSID); overload; procedure Remove(const AData: IRBData); overload; function FindData(const ASID: TSID): IRBData; function FindSID(const AData: IRBData): TSID; end; { TPersistRef } TPersistRef = class(TInterfacedObject, IPersistRef) private fSID: TSID; fStore: IPersistStore; fData: IRBData; fClassName: string; protected // IPersistRef function GetClassName: string; virtual; function GetData: IRBData; function GetSID: TSID; function GetStore: IPersistStore; procedure SetClassName(AValue: string); procedure SetData(AValue: IRBData); procedure SetSID(AValue: TSID); procedure SetStore(AValue: IPersistStore); property Data: IRBData read GetData; property SID: TSID read GetSID write SetSID; property ClassName: string read GetClassName write SetClassName; public procedure AfterConstruction; override; published property Store: IPersistStore read GetStore write SetStore; end; TPersistRef<TItem: TObject> = class(TPersistRef, IPersistRef<TItem>) protected function GetItem: TItem; procedure SetItem(AValue: TItem); property Item: TItem read GetItem write SetItem; protected function GetClassName: string; override; end; { TPersistRefList } TPersistRefList = class(TInterfacedObject, IPersistRefList) private type TRefListItems = TFPGInterfacedObjectList<IPersistRef>; private fItems: TRefListItems; protected // IPersistRefList function GetCount: integer; function GetData(AIndex: integer): IRBData; function GetItems(AIndex: integer): IPersistRef; procedure SetCount(AValue: integer); procedure SetItems(AIndex: integer; AValue: IPersistRef); function IndexOfData(const AData: IRBData): integer; procedure Delete(AIndex: integer); procedure Insert(AIndex: integer; const AValue: IPersistRef); public procedure AfterConstruction; override; procedure BeforeDestruction; override; property Count: integer read GetCount write SetCount; property Items[AIndex: integer]: IPersistRef read GetItems write SetItems; default; property Data[AIndex: integer]: IRBData read GetData; end; { TPersistStore } TPersistStore = class(TInterfacedObject, IPersistStore, IPersistQuery) protected fFactory: IPersistFactory; fDevice: IPersistStoreDevice; fCache: TStoreCache; protected // IPersistStore function New(const AClass: string): IRBData; procedure Load(AData: IRBData); overload; procedure Save(AData: IRBData); procedure Delete(AData: IRBData); function Load(const ASID: TSID): IRBData; overload; function GetSID(const AData: IRBData): TSID; procedure Open; overload; procedure Open(const AFile: string); overload; procedure Open(const AStream: TStream); overload; procedure Close; overload; procedure Close(const AStream: TStream); overload; procedure Flush; property SID[const AData: IRBData]: TSID read GetSID; // IPersistQuery function SelectClass(const AClass: string): IPersistRefList; published property Factory: IPersistFactory read fFactory write fFactory; property Device: IPersistStoreDevice read fDevice write fDevice; property Cache: TStoreCache read fCache write fCache; end; { TPersistManyRefs } TPersistManyRefs = class(TPersistMany<IPersistRef>, IPersistManyRefs) private fFactory: IPersistFactory; protected function GetAsInterface(AIndex: integer): IUnknown; override; procedure SetAsInterface(AIndex: integer; AValue: IUnknown); override; function GetAsPersistData(AIndex: integer): IRBData; override; procedure SetAsPersistData(AIndex: integer; AValue: IRBData); override; protected function GetFactory: IPersistFactory; procedure SetFactory(AValue: IPersistFactory); published property Factory: IPersistFactory read GetFactory write SetFactory; end; TPersistManyRefs<TItem: TObject> = class(TPersistManyRefs, IPersistManyRefs<TItem>) protected function GetClassName: string; override; end; implementation { TPersistRef<TItem> } function TPersistRef<TItem>.GetClassName: string; begin Result := TItem.ClassName; end; function TPersistRef<TItem>.GetItem: TItem; begin if Data = nil then Result := TItem(nil) else Result := Data.UnderObject as TItem; end; procedure TPersistRef<TItem>.SetItem(AValue: TItem); begin Data.UnderObject := AValue; end; { TPersistManyRefs } function TPersistManyRefs.GetAsInterface(AIndex: integer): IUnknown; begin if AIndex > Count - 1 then Count := AIndex + 1; if Item[AIndex] = nil then begin Item[AIndex] := Factory.Create(IPersistRef) as IPersistRef; Item[AIndex].ClassName := ClassName; end; Result := Item[AIndex]; end; procedure TPersistManyRefs.SetAsInterface(AIndex: integer; AValue: IUnknown); begin Item[AIndex] := AValue as IPersistRef; end; function TPersistManyRefs.GetAsPersistData(AIndex: integer): IRBData; begin Result := (AsInterface[AIndex] as IPersistRef).Data; end; procedure TPersistManyRefs.SetAsPersistData(AIndex: integer; AValue: IRBData); begin (AsInterface[AIndex] as IPersistRef).Data := AValue; end; function TPersistManyRefs.GetFactory: IPersistFactory; begin Result := fFactory; end; procedure TPersistManyRefs.SetFactory(AValue: IPersistFactory); begin fFactory := AValue; end; function TPersistManyRefs<TItem>.GetClassName: string; begin Result := TItem.ClassName; end; { TSIDList } function TSIDList.GetCount: integer; begin Result := fItems.Count; end; function TSIDList.GetItems(AIndex: integer): TSID; begin Result := fItems[AIndex]; end; procedure TSIDList.SetCount(AValue: integer); begin fItems.Count := AValue; end; procedure TSIDList.SetItems(AIndex: integer; AValue: TSID); begin fItems[AIndex] := AValue; end; procedure TSIDList.BeforeDestruction; begin FreeAndNil(fItems); inherited BeforeDestruction; end; procedure TSIDList.AfterConstruction; begin inherited AfterConstruction; fItems := TSIDItems.Create; end; { TPersistRefList } function TPersistRefList.GetCount: integer; begin Result := fItems.Count; end; function TPersistRefList.GetData(AIndex: integer): IRBData; begin Result := Items[AIndex].Data; end; function TPersistRefList.GetItems(AIndex: integer): IPersistRef; begin Result := fItems[AIndex]; end; procedure TPersistRefList.SetCount(AValue: integer); begin fItems.Count := AValue; end; procedure TPersistRefList.SetItems(AIndex: integer; AValue: IPersistRef); begin fItems[AIndex] := AValue; end; function TPersistRefList.IndexOfData(const AData: IRBData): integer; var i: integer; begin Result := -1; for i := 0 to Count- 1 do begin if Data[i] = AData then begin Result := i; Break; end; end; end; procedure TPersistRefList.Delete(AIndex: integer); begin fItems.Delete(AIndex); end; procedure TPersistRefList.Insert(AIndex: integer; const AValue: IPersistRef); begin fItems.Insert(AIndex, AValue); end; procedure TPersistRefList.AfterConstruction; begin inherited AfterConstruction; fItems := TRefListItems.Create; end; procedure TPersistRefList.BeforeDestruction; begin FreeAndNil(fItems); inherited BeforeDestruction; end; { TPersistRef } procedure TPersistRef.SetClassName(AValue: string); begin if AValue <> fClassName then begin fData := nil; fSID.Clear; fClassName := AValue; end; end; function TPersistRef.GetClassName: string; begin if Data <> nil then Result := Data.ClassName else Result := fClassName; end; function TPersistRef.GetData: IRBData; begin if fData = nil then begin if not fSID.IsClear then fData := fStore.Load(fSID) else if fClassName <> '' then fData := fStore.New(fClassName) end; Result := fData; end; function TPersistRef.GetSID: TSID; begin if (fStore <> nil) and (fData <> nil) then Result := fStore.SID[fData] else Result := fSID; end; function TPersistRef.GetStore: IPersistStore; begin Result := fStore; end; procedure TPersistRef.SetData(AValue: IRBData); begin fData := AValue; end; procedure TPersistRef.SetSID(AValue: TSID); begin if GetSID <> AValue then begin fData := nil; fClassName := ''; fSID := AValue; end; end; procedure TPersistRef.SetStore(AValue: IPersistStore); begin fStore := AValue; end; procedure TPersistRef.AfterConstruction; begin inherited AfterConstruction; fSID.Clear; end; { TStoreCache.TDataRecord } class function TStoreCache.TDataRecord.Create(const ASID: TSID; const AData: IRBData): TDataRecord; begin Result.fSID := ASID; Result.fData := AData; end; procedure TStoreCache.TDataRecord.Clear; begin fSID.Clear; fData := nil; end; class operator TStoreCache.TDataRecord. = (a, b: TDataRecord): Boolean; begin Result := (a.fSID = b.fSID) and (a.fData = b.fData); end; { TStoreCache } constructor TStoreCache.Create; begin fCache := TCache.Create; end; destructor TStoreCache.Destroy; begin FreeAndNil(fCache); inherited Destroy; end; function TStoreCache.FindIndex(const ASID: TSID): integer; var i: integer; begin Result := -1; for i := 0 to fCache.Count - 1 do if fCache[i].fSID = ASID then begin Result := i; Break; end; end; function TStoreCache.FindIndex(const AData: IRBData): integer; var i: integer; begin Result := -1; for i := 0 to fCache.Count - 1 do if fCache[i].fData = AData then begin Result := i; Break; end; end; procedure TStoreCache.Add(const ASID: TSID; const AData: IRBData); var mIndex: integer; begin mIndex := FindIndex(AData); if mIndex = -1 then begin fCache.Add(TDataRecord.Create(ASID, AData)); end else begin raise Exception.create('already in cache'); end; end; procedure TStoreCache.Remove(const ASID: TSID); var mIndex: integer; begin mIndex := FindIndex(ASID); if mIndex <> -1 then begin fCache[mIndex].Clear; fCache.Delete(mIndex); end; end; procedure TStoreCache.Remove(const AData: IRBData); var mIndex: integer; begin mIndex := FindIndex(AData); if mIndex <> -1 then begin fCache[mIndex].Clear; fCache.Delete(mIndex); end; end; function TStoreCache.FindData(const ASID: TSID): IRBData; var mIndex: integer; begin Result := nil; mIndex := FindIndex(ASID); if mIndex <> - 1 then Result := fCache[mIndex].fData; end; function TStoreCache.FindSID(const AData: IRBData): TSID; var mIndex: integer; begin Result.Clear; mIndex := FindIndex(AData); if mIndex <> - 1 then Result := fCache[mIndex].fSID; end; { TPersistFactory } function TPersistFactory.CreateObject(const AClass: string): IRBData; begin if AClass = '' then raise Exception.Create('Try create IRBData object with empty class'); Result := Container.Locate(IRBData, AClass); end; function TPersistFactory.Create(const AClass: string; const AID: string ): TObject; begin Result := Container.Locate(AClass, AID); end; function TPersistFactory.Create(AInterface: TGUID; const AID: string): IUnknown; begin Result := Container.Locate(AInterface, AID); end; { TPersistStore } function TPersistStore.New(const AClass: string): IRBData; begin Result := Factory.CreateObject(AClass); end; procedure TPersistStore.Load(AData: IRBData); var mSID: TSID; begin mSID := fCache.FindSID(AData); if mSID.IsClear then raise exception.Create('cannot load object - not in cache'); fDevice.Load(mSID, AData); end; procedure TPersistStore.Save(AData: IRBData); var mSID: TSID; begin mSID := fCache.FindSID(AData); if mSID.IsClear then begin mSID := fDevice.NewSID; fCache.Add(mSID, AData); end; fDevice.Save(mSID, AData); end; procedure TPersistStore.Delete(AData: IRBData); var mSID: TSID; begin mSID := fCache.FindSID(AData); if mSID.IsClear then raise exception.Create('delete sid not in cache'); fDevice.Delete(mSID); fCache.Remove(AData); end; function TPersistStore.Load(const ASID: TSID): IRBData; var mClass: string; begin Result := nil; mClass := fDevice.GetSIDClass(ASID); if mClass = '' then Exit; Result := New(mClass); fDevice.Load(ASID, Result); fCache.Add(ASID, Result); end; function TPersistStore.GetSID(const AData: IRBData): TSID; begin Result := fCache.FindSID(AData); end; procedure TPersistStore.Open; begin fDevice.Open; end; procedure TPersistStore.Open(const AFile: string); begin fDevice.Open(AFile); end; procedure TPersistStore.Open(const AStream: TStream); begin fDevice.Open(AStream); end; procedure TPersistStore.Close; begin fDevice.Close; end; procedure TPersistStore.Close(const AStream: TStream); begin fDevice.Close(AStream); end; procedure TPersistStore.Flush; begin fDevice.Flush; end; function TPersistStore.SelectClass(const AClass: string): IPersistRefList; var mSIDs: ISIDList; i: integer; begin Result := Factory.Create(IPersistRefList) as IPersistRefList; mSIDs := Device.GetSIDs(AClass); Result.Count := mSIDs.Count; for i := 0 to mSIDs.Count - 1 do begin Result[i] := Factory.Create(IPersistRef) as IPersistRef; Result[i].Store := Self; Result[i].SID := mSIDs[i]; end; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.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. } { } {***************************************************************************} unit DPM.Core.Package.Installer.Interfaces; interface uses Spring.Collections, VSoft.Awaitable, DPM.Core.Types, DPM.Core.TargetPlatform, DPM.Core.Options.Cache, DPM.Core.Options.Install, DPM.Core.Options.Uninstall, DPM.Core.Options.Restore, DPM.Core.Package.Interfaces, DPM.Core.Dependency.Interfaces, DPM.Core.Spec.Interfaces; type IPackageInstallerContext = interface; //does the work of installing/restoring packages. IPackageInstaller = interface ['{554A0842-6C83-42BD-882C-B49FE4619DE0}'] function Install(const cancellationToken : ICancellationToken; const options : TInstallOptions; const context : IPackageInstallerContext) : boolean; function UnInstall(const cancellationToken : ICancellationToken; const options : TUnInstallOptions; const context : IPackageInstallerContext) : boolean; function Restore(const cancellationToken : ICancellationToken; const options : TRestoreOptions; const context : IPackageInstallerContext) : boolean; function Cache(const cancellationToken : ICancellationToken; const options : TCacheOptions) : boolean; function Context : IPackageInstallerContext; end; ///<summary> The installer context is use to collect package resolutions and detect /// package conflicts across projects in a project group. /// It is alos used to manage installing/uninstalling design time packages in the IDE. /// The IDE plugin provides it's own implementation of this interface so the core /// version can avoid doing design time stuff (methods do nothing). ///</summary> IPackageInstallerContext = interface ['{8FD229A2-FE7B-4315-84B2-FF18B78C76DC}'] //called from the project controller in the IDE when starting loading. This is probably wrong! procedure Clear; ///<summary>called from the ProjectController when a project is closed.</summary> procedure RemoveProject(const projectFile : string); ///<summary>called from the package installer during install/restore</summary> procedure RecordGraph(const projectFile : string; const platform : TDPMPlatform; const graph : IPackageReference); ///<summary> called from the package installer during install/restore - to install design time packages. See IDE implementation</summary> function InstallDesignPackages(const cancellationToken: ICancellationToken; const projectFile : string; const packageSpecs: IDictionary<string, IPackageSpec>) : boolean; ///<summary> Called from the dependency resolver to record package resolutions, so we can detect conflicts in other projects /// in the project group. ///</summary> procedure RecordResolutions(const projectFile: string; const platform : TDPMPlatform; const resolutions : TArray<IResolution>); ///<summary> Check for an existing package resolution in already loaded projects in the group. ///</summary> function FindPackageResolution(const projectFile: string; const platform : TDPMPlatform; const packageId : string ) : IResolution; end; implementation end.
unit Logger; interface uses System.Classes, System.SyncObjs, System.SysUtils; type TLogDetailLevel = (ldlNone, ldlFatalError, ldlError, ldlNormal, ldlDebug, ldlTrace); TLogFileMode = (lfmAppend, lfmClear, lfmNewFile); TLogFileNameGeneratingPart = (gpDate, gpTime, gpIndex); TLogFileNameGeneratingParts = set of TLogFileNameGeneratingPart; TLogFileNameGeneratingReason = (grChangeDate, grCheckFileSize); TLogFileNameGeneratingReasons = set of TLogFileNameGeneratingReason; TOnLogAddEvent = procedure (Sender: TObject; EventLevel: TLogDetailLevel; LogMessage: string) of object; TLogger = class(TComponent) private fLogLevel: TLogDetailLevel; fCriticalSection: TCriticalSection; fLogFileMode: TLogFileMode; fProjectName: string; fActive: boolean; fEncoding: TEncoding; fEncodingName: string; fFileName: string; fCurrentFileName: string; fLogFileSize: int64; fStartTime: TDateTime; fStartDate: TDate; fGenFileNameReasons: TLogFileNameGeneratingReasons; fGenFileNameParts: TLogFileNameGeneratingParts; fGenFileNameEnable: boolean; fLogBufferSize: integer; fOnInitialize: TNotifyEvent; fOnStartLog: TNotifyEvent; fOnStopLog: TNotifyEvent; fOnAddEvent: TOnLogAddEvent; fOnChangeFile: TNotifyEvent; procedure SetActive(const Value: boolean); function GetEncoding: string; procedure SetEncoding(const Value: string); function GetVersion: string; function GetCurrentFileName: string; procedure SetFileName(const Value: string); protected fLogFile: TStreamWriter; function GenerateFileName(const AFileName: string; const AParts: TLogFileNameGeneratingParts): string; function CheckFileName(const AContinueWrite: boolean = true): boolean; procedure SetCaptionLogFile; procedure StartLog(const Continue: boolean = false); procedure StopLog; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddEvent(const ADetailLevel: TLogDetailLevel; const AEvent: string; const AParams: array of const); property StartTime: TDateTime read fStartTime; published property Active: boolean read fActive write SetActive default false; property CurrentFileName: string read fCurrentFileName; property Encoding: string read GetEncoding write SetEncoding; property FileName: string read fFileName write SetFileName; property GeneratingEnable: boolean read fGenFileNameEnable write fGenFileNameEnable default false; property GeneratingParts: TLogFileNameGeneratingParts read fGenFileNameParts write fGenFileNameParts; property GeneratingReasons: TLogFileNameGeneratingReasons read fGenFileNameReasons write fGenFileNameReasons; property LogBufferSize: integer read fLogBufferSize write fLogBufferSize default 4096; property LogLevel: TLogDetailLevel read fLogLevel write fLogLevel default ldlNormal; property LogFileMode: TLogFileMode read fLogFileMode write fLogFileMode default lfmAppend; property LogFileSize: int64 read fLogFileSize write fLogFileSize default 524288; property ProjectName: string read fProjectName write fProjectName; property Version: string read GetVersion; property OnAddEvent: TOnLogAddEvent read fOnAddEvent write fOnAddEvent; property OnChangeFile: TNotifyEvent read fOnChangeFile write fOnChangeFile; property OnInitialize: TNotifyEvent read fOnInitialize write fOnInitialize; property OnStartLog: TNotifyEvent read fOnStartLog write fOnStartLog; property OnStopLog: TNotifyEvent read fOnStopLog write fOnStopLog; end; implementation uses System.IOUtils, System.Types; { TLogger } procedure TLogger.AddEvent(const ADetailLevel: TLogDetailLevel; const AEvent: string; const AParams: array of const); var s: string; begin if not fActive then begin raise Exception.Create('Logger not active!'); Exit; end; if ADetailLevel <= fLogLevel then begin fCriticalSection.Enter; CheckFileName; s := FormatDateTime('hh:nn:ss.zzz',Time)+#9+format(AEvent,AParams); fLogFile.WriteLine(s); fCriticalSection.Leave; if Assigned(fOnAddEvent) then fOnAddEvent(Self,ADetailLevel,s); end; end; function TLogger.CheckFileName(const AContinueWrite: boolean = true): boolean; var TempName: string; begin Result := true; if not fGenFileNameEnable or (fGenFileNameReasons = []) then Exit; TempName := ''; if (grChangeDate in fGenFileNameReasons) and (fStartDate < Date) then TempName := GenerateFileName(fCurrentFileName,fGenFileNameParts); if (grCheckFileSize in fGenFileNameReasons) and (fLogFile.BaseStream.Size >= fLogFileSize - 64) then TempName := GenerateFileName(fCurrentFileName,fGenFileNameParts + [gpIndex]); if (TempName <> '') and (TempName > fCurrentFileName) then begin if AContinueWrite then begin fLogFile.WriteLine('*********************************************'); fLogFile.WriteLine('Continue in file '+TempName+'...'); end else Result := False; fLogFile.Free; fCurrentFileName := TempName; if Assigned(fOnChangeFile) then fOnChangeFile(Self); StartLog(True); end; end; constructor TLogger.Create(AOwner: TComponent); begin inherited Create(AOwner); fCriticalSection := TCriticalSection.Create; fEncoding := TEncoding.ANSI; fLogLevel := ldlNormal; fLogFileMode := lfmAppend; fLogFileSize := 524288; fLogBufferSize := 4096; fGenFileNameParts := [gpDate, gpTime, gpIndex]; fGenFileNameReasons := [grChangeDate, grCheckFileSize]; fGenFileNameEnable := false; end; destructor TLogger.Destroy; begin if fActive then StopLog; fCriticalSection.Free; inherited; end; function TLogger.GenerateFileName(const AFileName: string; const AParts: TLogFileNameGeneratingParts): string; var n, Index: integer; FirstPart, Temp: string; begin FirstPart := ExtractFileName(AFileName); n := Pos('_',FirstPart); if n > 0 then begin Temp := Copy(FirstPart,n+1,length(FirstPart)); FirstPart := Copy(FirstPart,1,n-1); end else begin Temp := ExtractFileExt(FirstPart); FirstPart := Copy(FirstPart,1,Length(FirstPart) - Length(Temp)); Temp := ''; end; if Temp = '' then Index := 0 else begin n := Pos('_',Temp); if n>0 then begin Temp := Copy(Temp,n+1,length(Temp)); Temp := Copy(Temp,1,Length(Temp) - Length(ExtractFileExt(Temp))); Index := StrToIntDef(Temp,0); end; end; Temp := ''; if gpDate in AParts then Temp := FormatDateTime('yyyymmdd',Date); if gpTime in AParts then Temp := Temp + '_' + FormatDateTime('hhmmss',Time); if gpIndex in AParts then Temp := Temp + '_' + IntToStr(Index+1); if Temp[1] <> '_' then Temp := '_' + Temp; Result := FirstPart + Temp + ExtractFileExt(AFileName); Temp := ExtractFilePath(AFileName); if Temp = '' then Temp := ExtractFilePath(ParamStr(0)); Result := Temp + Result; end; function TLogger.GetCurrentFileName: string; begin Result := GenerateFileName(fFileName,fGenFileNameParts); end; function TLogger.GetEncoding: string; begin Result := fEncodingName; if Result = '' then Result := fEncoding.EncodingName; end; function TLogger.GetVersion: string; begin Result:='version 2.0 (18.07.2014)'; end; procedure TLogger.SetActive(const Value: boolean); begin if fActive=Value then Exit; fActive := Value; case fActive of True: StartLog; False: StopLog; end; end; procedure TLogger.SetCaptionLogFile; var s: string; i,n1: integer; begin fLogFile.WriteLine('************ (c)Nik RON, 2014 *************'); fLogFile.WriteLine('*** TLogger '+Version+' ***'); fLogFile.WriteLine('*********************************************'); if length(fProjectName)<45 then n1:=(45-length(fProjectName)) div 2-1 else n1:=3; s:='*'; for i:=1 to n1 do s:=s+' '; s:=s+fProjectName+' '; for i:=1 to n1-1 do s:=s+' '; fLogFile.WriteLine(s+'*'); fLogFile.WriteLine('*********************************************'); end; procedure TLogger.SetEncoding(const Value: string); begin fEncodingName := Value; fEncoding := TEncoding.GetEncoding(Value); end; procedure TLogger.SetFileName(const Value: string); begin fFileName := Value; end; procedure TLogger.StartLog(const Continue: boolean); var FlagAppend: boolean; FStream: TFileStream; FileList: TStringDynArray; s: string; begin if Assigned(fOnInitialize) then fOnInitialize(Self); case fLogFileMode of lfmAppend: begin FlagAppend := True; if not Continue then fCurrentFileName := fFileName; end; lfmClear: begin FlagAppend := False; if not Continue then fCurrentFileName := fFileName; end; lfmNewFile: begin FlagAppend := False; if not Continue then fCurrentFileName := GenerateFileName(fFileName,fGenFileNameParts + [gpDate,gpTime]); end; end; if (not Continue) and (not (fLogFileMode = lfmNewFile)) then fCurrentFileName := GenerateFileName(fCurrentFileName,fGenFileNameParts); if (not FileExists(fCurrentFileName)) or (not FlagAppend) then FStream := TFileStream.Create(fCurrentFileName, fmCreate or fmShareDenyWrite) else begin s := ChangeFileExt(ExtractFileName(fFileName),'*'+ExtractFileExt(fFileName)); FileList := TDirectory.GetFiles(ExtractFilePath(fCurrentFileName),s); fCurrentFileName := FileList[High(FileList)]; SetLength(FileList,0); FStream := TFileStream.Create(fCurrentFileName, fmOpenWrite or fmShareDenyWrite); FStream.Seek(0, soEnd); end; fLogFile := TStreamWriter.Create(FStream, fEncoding, fLogFileSize); fLogFile.OwnStream; fStartTime := Now; fStartDate := Date; if fLogFile.BaseStream.Size = 0 then SetCaptionLogFile; if not CheckFileName(false) then Exit; if not Continue then fLogFile.WriteLine(DateTimeToStr(Now)+'> Start log...') else fLogFile.WriteLine(DateTimeToStr(Now)+'> Continue log...'); if Assigned(fOnStartLog) then fOnStartLog(Self); end; procedure TLogger.StopLog; begin fLogFile.WriteLine(DateTimeToStr(Now)+'> Stop log.'); fLogFile.WriteLine('*********************************************'); fLogFile.Free; if Assigned(fOnStopLog) then fOnStopLog(Self); end; end.
(* Scanlines.pas, Sep 2003 (Delphi 7) Copyright Chris Willig 2003, All Rights Reserved. May be used freely for non-commercial purposes. chris@5thElephant.com ****** RotateBmp() uses code copyrighted by Earl F. Glynn ****** SmoothResize() and GrayScale() use code adapted from a newsgroup example posted by Charles Hacker Uses pointers to access TBitmap.Scanline[], roughly 3 times faster than accessing Scanline[] directly in a typical looping routine. *) unit Scanlines; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics; type TRGBArray = ARRAY[0..32767] OF TRGBTriple; //pf24bit pRGBArray = ^TRGBArray; // TScanlines is a wrapper for accessing scanlines with pointers. // see BitmapsEqual() and RotateBmp() for examples. TScanlines = class private FScanLine0 : PByte; FScanLineIncrement : integer; FMaxRow : integer; function GetRowPtr(Index: integer): PByte; public constructor Create(Bitmap: TBitmap); destructor Destroy; override; property RowPtr[Index: Integer]: PByte read GetRowPtr; default; end; TrgbaProc = procedure(pRGBA: pRGBArray; const Width: integer; var Dun: boolean) stdcall; TpbaProc = procedure(pB: PByteArray; const Width: integer; var Dun: boolean) stdcall; implementation // TScanlines... constructor TScanlines.Create(Bitmap: TBitmap); begin inherited Create; FScanLine0 := nil; FScanLineIncrement := 0; FMaxRow := 0; if Bitmap <> nil then begin FScanLine0 := Bitmap.ScanLine[0]; FScanLineIncrement := 0; if Bitmap.Height > 0 then FScanLineIncrement := NativeInt(Bitmap.Scanline[1]) - NativeInt(FScanLine0); FMaxRow := Bitmap.Height; end; end; destructor TScanlines.Destroy; begin inherited; end; function TScanlines.GetRowPtr(Index: integer): PByte; begin if (Index >= 0) and (Index < FMaxRow) then begin result := FScanLine0; Inc(result, FScanLineIncrement *Index); end else result := nil; end; // ...TScanlines end.
unit uBillListPromtion; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Frm_BillListBase, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxHyperLinkEdit, Menus, cxLookAndFeelPainters, ADODB, ActnList, DBClient, jpeg, Series, TeEngine, TeeProcs, Chart, DbChart, StdCtrls, cxButtons, cxMaskEdit, cxDropDownEdit, Buttons, cxPC, cxContainer, cxTextEdit, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, ExtCtrls, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox; type TFM_BillListPromt = class(TFM_BillListBase) procedure btn_NewBillClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Btn_QueryClick(Sender: TObject); procedure spt_AuditClick(Sender: TObject); procedure spt_uAuditClick(Sender: TObject); private { Private declarations } procedure cdsListFBASESTATUSGetText(Sender: TField; var Text: String; DisplayText: Boolean); public { Public declarations } procedure Open_Bill(KeyFields: String; KeyValues: String); override; function NotScmBillDelBill(BillFID:string;var ErrMsg:string):Boolean;override; function NotScmBillAuditBill(BillFID:string;var ErrMsg:string):Boolean;override; function NotScmBillUnAuditBill(BillFID:string;var ErrMsg:string):Boolean;override; end; var FM_BillListPromt: TFM_BillListPromt; implementation uses FrmCliDM,uBillPromotion; {$R *.dfm} procedure TFM_BillListPromt.Open_Bill(KeyFields: String; KeyValues: String); var tmpEditForm : TEditFormPar; begin inherited; tmpEditForm :=TEditFormPar.Create; tmpEditForm.BillFID := KeyValues; tmpEditForm.ListDataset := cdsList; OpenEditFrom_Promt(FM_BillPromotionEdit,TFM_BillPromotionEdit,tmpEditForm); end; procedure TFM_BillListPromt.btn_NewBillClick(Sender: TObject); begin inherited; Open_Bill('FID',''); end; procedure TFM_BillListPromt.FormCreate(Sender: TObject); begin Self.Bill_Sign := 'T_PRT_PROMT'; Self.BillKeyFields := 'FID'; Self.FBillTypeFID := BillConst.BILLTYPE_PM; FNotScmBill := True; inherited; end; procedure TFM_BillListPromt.Btn_QueryClick(Sender: TObject); begin inherited; cdsList.FieldByName('FBASESTATUS').OnGetText := cdsListFBASESTATUSGetText; // end; procedure TFM_BillListPromt.cdsListFBASESTATUSGetText(Sender: TField; var Text: String; DisplayText: Boolean); begin DisplayText := true ; if Sender.AsString='SAVE' then Text := '保存' else if Sender.AsString='ADD' then Text := '新增' else if Sender.AsString='SUBMIT' then Text := '提交' else if Sender.AsString='CLOSE' then Text := '关闭' else if Sender.AsString='AUDITE' then Text := '审核'; end; function TFM_BillListPromt.NotScmBillDelBill(BillFID:string;var ErrMsg:string):Boolean; var StrSql1, StrSql2,StrSql3,StrSql4,StrSql5,StrSql6,StrSql7 : string; begin Result := False; StrSql1 := ' delete from T_PRT_PROMT where FID='+quotedstr(BillFID); StrSql2 := ' delete from T_PRT_PROMTASSENTRY where FparentID='+quotedstr(BillFID); StrSql3 := ' delete from T_PRT_PROMTALLBILLENTRY where FparentID='+quotedstr(BillFID); StrSql4 := ' delete from T_PRT_PROMTENTRY where FparentID='+quotedstr(BillFID); StrSql5 := ' delete from t_Prt_Promtnotmaterial where FparentID='+quotedstr(BillFID); StrSql5 := ' delete from T_PRT_PROMTOTHERENTRY where FparentID='+quotedstr(BillFID); StrSql7 := ' delete from T_PRT_PROMTPROJECT where FparentID='+quotedstr(BillFID); CliDM.E_ExecSQLArrays(StrSql1,StrSql2,StrSql3,StrSql4,StrSql5,StrSql5,StrSql7,'',ErrMsg); if ErrMsg='' then Result := True else Result := False; end; function TFM_BillListPromt.NotScmBillAuditBill(BillFID:string;var ErrMsg:string):Boolean; var StrSql1 : string; begin Result := False; StrSql1 := 'update T_PRT_PROMT set Fauditorid='''+Userinfo.LoginUser_FID+''',Faudittime=sysdate,FBASESTATUS=''AUDITE'' where FID='+quotedstr(BillFID); CliDM.E_ExecSQLArrays(StrSql1,'','','','','','','',ErrMsg); if ErrMsg='' then Result := True else Result := False; end; function TFM_BillListPromt.NotScmBillUnAuditBill(BillFID:string;var ErrMsg:string):Boolean; var StrSql1 : string; begin Result := False; StrSql1 := 'update T_PRT_PROMT set Fauditorid=null,Faudittime=null,FBASESTATUS=''SAVE'' where FID='+quotedstr(BillFID); CliDM.E_ExecSQLArrays(StrSql1,'','','','','','','',ErrMsg); if ErrMsg='' then Result := True else Result := False; end; procedure TFM_BillListPromt.spt_AuditClick(Sender: TObject); begin inherited; //// end; procedure TFM_BillListPromt.spt_uAuditClick(Sender: TObject); begin inherited; //// end; end.
unit Compiler.BrainFuck; {$WARN WIDECHAR_REDUCED OFF} // Because CharInSet() is too slow for me interface uses System.SysUtils, Compiler, &Assembler.Global, Winapi.Windows, TicksMeter, Stack; const msvcrt = 'msvcrt.dll'; function putchar(C: AnsiChar): Integer; cdecl; external msvcrt; function getchar: AnsiChar; cdecl; external msvcrt; const CELLS_MIN = 64; CELLS_DEF = 30000; type TBrainFuckCompiler = object(TCompiler) private FInCount: Integer; // Amount of "." in code (needs for stack cleaning in the epilogue) FSrc: string; // Source code of compiled file FSrcName: string; // Source code's file name without expansion FSrcPos: Integer; // Number of the current compiling command FCellsReg: TRegIndex; // Register, that consists pointer to cells array FCellStart: Integer; // Starting cell FInReg: TRegIndex; // Register, that consists pointer at getchar function FOutReg: TRegIndex; // Register, that consists pointer at putchar function FLastCmdsData: array[0..15] of Integer; FLastCmds: TStack; FLoopStack: TStack; FLoopData: array[0..255] of Integer; protected FOpt: Boolean; FCells: Integer; FCellSize: TAddrSize; public property Optimization: Boolean read FOpt write FOpt; property CellsCount: Integer read FCells; property SourceCode: string read FSrc; procedure WriteMemSet(Reg: TRegIndex; Size: Cardinal; Value: Integer); procedure WriteStackFrame; procedure WritePrologue; // BrainFuck binary code start (stack and variables initialization) procedure WriteEpilogue; // BrainFuck binary code end (data release and exit) procedure WriteIn; procedure WriteOut; procedure WriteLoopBegin; procedure WriteLoopEnd; procedure Create; // Compiler config initialization via command line parameters // Maybe I should use contructor? procedure Init; procedure LoadFromFile(FileName: string); // Read source code and create binary data on it's basis. procedure CompileCode; procedure ExecuteCode; function CheckCode(const Cmds: string): Boolean; // Brainfuck Compiled Unit procedure SaveAsBCU; public procedure RaiseException(const Text: string); overload; procedure RaiseException(const Fmt: string; const Args: array of const); overload; end; implementation procedure Print(Value: AnsiChar); register; begin putchar(Value); end; function Read: AnsiChar; register; begin Result := getchar; end; function TBrainFuckCompiler.CheckCode(const Cmds: string): Boolean; begin Result := StrLIComp(PChar(@FSrc[FSrcPos + 1]), PChar(Cmds), Length(Cmds)) = 0; end; procedure TBrainFuckCompiler.Create; begin inherited; // I believe that 1048576 is enough bytes for compiled code FBuffer.Create(1024 * 1024); FOpt := False; FCellSize := msByte; FCells := CELLS_DEF * Ord(FCellSize); // Cells array size (inits in prologue) FOpt := False; // Optimization FInCount := 0; // Amount of "." calls FCellsReg := rEbx; // Register that consists pointer to byte cells FInReg := rEbp; // Register that consists "." function FOutReg := rEdi; // Register that consists "," function FSrcPos := 0; // Command number that processes by the interpreter FCellStart := FCells div 2; FLastCmds.Create(@FLastCmdsData[0], SizeOf(FLastCmdsData)); // Create a stack array of addresses. Needs to work with cycles. FLoopStack.Create(@FLoopData[0], SizeOf(FLoopData)); end; procedure TBrainFuckCompiler.ExecuteCode; type TFuckback = procedure; // callback begin TFuckback(FBuffer.Data)(); end; procedure TBrainFuckCompiler.Init; var I: Integer; Value: string; begin if FindCmdLineSwitch('F', Value) then LoadFromFile(Value); if FindCmdLineSwitch('O') then FOpt := True; if FindCmdLineSwitch('C', Value) then begin FCells := StrToIntDef(Value, CELLS_DEF); if FCells < CELLS_MIN then FCells := CELLS_DEF; end; if FindCmdLineSwitch('B', Value) then begin if StrIComp(PChar(Value), 'CENTER') = 0 then FCellStart := FCells div 2 else if StrIComp(PChar(Value), 'LEFT') = 0 then FCellStart := 0 else if StrIComp(PChar(Value), 'RIGHT') = 0 then FCellStart := FCells else FCellStart := StrToIntDef(Value, 0); end; if FindCmdLineSwitch('T', Value) then begin if StrIComp(PChar(Value), 'WIN32') = 0 then FTarget := tWin32 else if StrIComp(PChar(Value), 'WIN64') = 0 then FTarget := tWin64 else if StrIComp(PChar(Value), 'LINUX') = 0 then FTarget := tLinux else raise Exception.Create('TBrainFuckCompiler.Init: Unknown target.'); end; if FindCmdLineSwitch('S', Value) then begin if not TryStrToInt(Value, I) or not (I in [1, 2, 4]) then raise Exception.Create('TBrainFuckCompiler.Init: Incorrect cell size.'); FCellSize := TAddrSize(I); end; FCells := FCells * Ord(FCellSize); FCellStart := FCellStart * Ord(FCellSize); end; procedure TBrainFuckCompiler.LoadFromFile(FileName: string); var Line: string; F: TextFile; J: Integer; begin FSrcName := ChangeFileExt(FileName, ''); if IsRelativePath(FileName) then FileName := Format('%s\%s', [ExtractFileDir(ParamStr(0)), FileName]); AssignFile(F, FileName); {$I-} Reset(F); if IOResult <> 0 then RaiseLastOSError; {$I+} FSrc := ''; while not Eof(F) do begin ReadLn(F, Line); J := Pos('#', Line); if J <> 0 then Line := Copy(Line, 1, J - 1); FSrc := FSrc + Line; end; CloseFile(F); end; function Relative(FAddr, SAddr: Pointer): Pointer; inline; begin Result := Pointer(Integer(FAddr) - Integer(SAddr) - 5); end; procedure TBrainFuckCompiler.CompileCode; var P: PChar; C: Char; CmdCount: Integer; Cells: array of Byte; CellsPtr: Integer; Ticks: TTicksMeter; begin Ticks.Start; // Create function prologue (stack, registers, ...). WritePrologue; // Write pointer to "Code" first symbol for easier way to work with it P := PChar(FSrc); SetLength(Cells, FCells * Ord(FCellSize)); CellsPtr := FCellStart; if not FOpt then begin while P^ <> #0 do begin case P^ of '>': WriteAdd(FCellsReg, Ord(FCellSize)); '<': WriteSub(FCellsReg, Ord(FCellSize)); '+': WriteInc(FCellsReg, FCellsReg, FCellSize); // WriteAdd(1, FCellsReg, FCellsReg, FCellSize); '-': WriteDec(FCellsReg, FCellsReg, FCellSize); // WriteSub(1, FCellsReg, FCellsReg, FCellSize); '.': WriteIn; ',': WriteOut; '[': WriteLoopBegin; ']': WriteLoopEnd; end; Inc(P); end; end else begin while P^ <> #0 do begin if CheckCode('[-]') or CheckCode('[+]') then begin WriteMov(0, FCellsReg, FCellsReg, FCellSize); FLastCmds.Push<Char>('['); FLastCmds.Push<Char>(P[1]); FLastCmds.Push<Char>(']'); Cells[CellsPtr] := 0; Inc(P, 3); Inc(FSrcPos, 3); Continue; end; C := P^; // if StrLIComp(P, '//', 2) = 0 then // begin // P2 := StrScan(P, #10); // // Inc(FSrcPos, Integer(P2 - P)); // P := P2 + 1; // end; // Commands that can be compressed into a single operand if C in ['>', '<', '+', '-'] then begin CmdCount := 0; repeat Inc(P); // Skip symbols that do not affect anything while (P^ in [' ', #9, #10, #13]) do Inc(P); Inc(CmdCount); until (P^ <> C) or (P^ = #0); Inc(FSrcPos, CmdCount); {$REGION 'Optimizable commands'} case C of '>': begin if FCellSize <> msByte then begin WriteAdd(FCellsReg, CmdCount * Ord(FCellSize)); Inc(CellsPtr, CmdCount * Ord(FCellSize)); end else begin if CmdCount > 1 then begin WriteAdd(FCellsReg, CmdCount * Ord(FCellSize)); Inc(CellsPtr, CmdCount * Ord(FCellSize)); end else begin WriteInc(FCellsReg); Inc(CellsPtr); end; end; end; '<': if FCellSize <> msByte then begin WriteSub(FCellsReg, CmdCount * Ord(FCellSize)); Dec(CellsPtr, CmdCount * Ord(FCellSize)); end else begin if CmdCount > 1 then begin WriteSub(FCellsReg, CmdCount * Ord(FCellSize)); Dec(CellsPtr, CmdCount * Ord(FCellSize)); end else begin WriteDec(FCellsReg); Dec(CellsPtr); end; end; '+': if FCellSize <> msByte then begin WriteAdd(CmdCount, FCellsReg, FCellsReg, FCellSize); Inc(Cells[CellsPtr], CmdCount * Ord(FCellSize)); end else begin if CmdCount > 1 then begin WriteAdd(CmdCount, FCellsReg, FCellsReg, FCellSize); Inc(Cells[CellsPtr], CmdCount); end else begin WriteInc(FCellsReg, FCellsReg, FCellSize); Inc(Cells[CellsPtr]); end; end; '-': if FCellSize <> msByte then begin WriteSub(CmdCount, FCellsReg, FCellsReg, FCellSize); Dec(Cells[CellsPtr], CmdCount * Ord(FCellSize)); end else begin if CmdCount > 1 then begin WriteSub(CmdCount, FCellsReg, FCellsReg, FCellSize); Dec(Cells[CellsPtr], CmdCount); end else begin WriteDec(FCellsReg, FCellsReg, FCellSize); Dec(Cells[CellsPtr]); end; end; end; FLastCmds.Push<Char>(C); Continue; end; Inc(FSrcPos); case C of '.': WriteIn; ',': WriteOut; '[': WriteLoopBegin; ']': WriteLoopEnd; end; FLastCmds.Push<Char>(C); Inc(P); end; end; Ticks.Stop; WriteLn('Target: ', Target.ToString); WriteLn('Optimization: ', FOpt); WriteLn('Compiled successfully. Code size: ', FBuffer.Position, ' bytes.'); WriteLn(Ticks.ToString); WriteLn; WriteEpilogue; end; procedure TBrainFuckCompiler.RaiseException(const Text: string); begin inherited RaiseException('[Fatal Error] %s(%d): %s', [FSrcName, Succ(FSrcPos), Text]); end; procedure TBrainFuckCompiler.RaiseException(const Fmt: string; const Args: array of const); var Text: string; begin Text := Format(Fmt, Args); Text := Format('[Fatal Error] %s(%d): %s', [FSrcName, Succ(FSrcPos), Text]); inherited RaiseException(Text); end; procedure TBrainFuckCompiler.SaveAsBCU; var S: string; begin S := Format('%s.bcu', [FSrcName]); FBuffer.SaveToFile(S); end; procedure TBrainFuckCompiler.WriteEpilogue; begin WriteAdd(rEsp, FCells); if FOpt then begin WritePop(FInReg); WritePop(FOutReg); end; WritePop(FCellsReg); WriteRet; end; procedure TBrainFuckCompiler.WriteIn; begin WriteMov(rEax, FCellsReg, FCellsReg, FCellSize); if FOpt then begin WritePush(rEax); WriteCall(FInReg); WritePop(rEcx); end else WriteCall(@Print); Inc(FInCount); end; procedure TBrainFuckCompiler.WriteLoopBegin; begin // if Cells[CellsPtr] = 0 then // begin // P2 := StrScan(P, ']'); // if P2 = nil then // RaiseException('Cannot find end loop.'); // // Inc(FSrcPos, Integer(P2 - P)); // P := P2 + 1; // // Continue; // end; // We don't need to create "cmp" instruction because "add", "sub", "inc" // and "dec" ones are already set ZF before if not (Char(FLastCmds.GetLast) in ['+', '-']) then WriteCmp(0, FCellsReg, FCellsReg, FCellSize); // Create dummy jump which will be contain skip loop address WriteJump(jtJz, Pointer($CCCCCCCC)); FLoopStack.Push<Pointer>(IP); end; procedure TBrainFuckCompiler.WriteLoopEnd; var JmpBegin: Pointer; begin if FLoopStack.Length = 0 then RaiseException('Loop is not initialized by "%s" command.', ['[']); JmpBegin := Pointer(FLoopStack.Pop); WriteCmp(0, FCellsReg, FCellsReg, FCellSize); WriteJump(jtJnz, JmpBegin); PPointer(@PByte(JmpBegin)[-4])^ := Relative(IP, @PByte(JmpBegin)[-5]); end; procedure TBrainFuckCompiler.WriteMemSet(Reg: TRegIndex; Size: Cardinal; Value: Integer); var Divisible: Boolean; begin if Size <= 0 then Exit; // Reserve edi register WritePush(rEdi); // A little optimization. If we need to set register as 0, we do it via "xor" command if Value = 0 then WriteXor(rEax, rEax) else WriteMov(rEax, Value); // We need "lea" here to avoud spoil the saved value in edi WriteLea(rEdi, Reg, 4); // Write amount of cells for zeroing WriteMov(rEcx, Size); // Divide by 4, because we are going to use stosd for zeroing WriteShr(rEcx, 2); // Divisible - is a variable, that contains result of checking of the // possibility of division by four. Divisible := Size mod 4 = 0; if not Divisible then begin WriteMov(rEdx, rEcx); WriteAnd(rEdx, 3); end; WriteStoS(cpRepNZ, msDWord); if not Divisible then begin WriteMov(rEcx, rEdx); WriteStoS(cpRepNZ, msByte); end; WritePop(rEdi); end; procedure TBrainFuckCompiler.WriteOut; begin WriteCall(FOutReg); FBuffer.Write<Byte>($88); FBuffer.Write<Byte>(Byte(FCellsReg)); end; procedure TBrainFuckCompiler.WritePrologue; begin // If we are under debugger, then we need to create int3 instruction right // before compiled brainfuck code. if IsDebuggerPresent then WriteInt(3); // Reserve for pointer at cells WritePush(FCellsReg); if FOpt then begin WritePush(FOutReg); WritePush(FInReg); WriteMov(FInReg, Cardinal(@putchar)); WriteMov(FOutReg, Cardinal(@getchar)); end; // Create CellsCount cells WriteSub(rEsp, FCells); // Fill cells with 0 WriteMemSet(rEsp, FCells, 0); // Write pointer at memory cells WriteLea(FCellsReg, rEsp, FCellStart); end; procedure TBrainFuckCompiler.WriteStackFrame; begin WritePush(rEbp); WriteMov(rEbp, rEsp); end; end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: MultiAnimationLib.pas,v 1.7 2007/02/05 22:21:10 clootie Exp $ *----------------------------------------------------------------------------*) //----------------------------------------------------------------------------- // File: MultiAnimation.h // // Desc: Header file for the MultiAnimation library. This contains the // declarations of // // MultiAnimFrame (no .cpp file) // MultiAnimMC (MultiAnimationLib.cpp) // CMultiAnimAllocateHierarchy (AllocHierarchy.cpp) // CMultiAnim (MultiAnimationLib.cpp) // CAnimInstance (AnimationInstance.cpp) // // Copyright (c) Microsoft Corporation. All rights reserved //----------------------------------------------------------------------------- {$I DirectX.inc} unit MultiAnimationLib; interface uses Windows, Classes, {$IFNDEF FPC}Contnrs, {$ENDIF}Direct3D9, D3DX9; {.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders {.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders type //----------------------------------------------------------------------------- // Forward declarations PMultiAnim = ^CMultiAnim; CMultiAnim = class; PAnimInstance = ^CAnimInstance; CAnimInstance = class; //----------------------------------------------------------------------------- // Name: class CMultiAnimAllocateHierarchy // Desc: Inheriting from ID3DXAllocateHierarchy, this class handles the // allocation and release of the memory used by animation frames and // meshes. Applications derive their own version of this class so // that they can customize the behavior of allocation and release. //----------------------------------------------------------------------------- CMultiAnimAllocateHierarchy = class(ID3DXAllocateHierarchy) private m_pMA: CMultiAnim; public // callback to create a D3DXFRAME-derived object and initialize it function CreateFrame(Name: PAnsiChar; out ppNewFrame: PD3DXFrame): HResult; override; // callback to create a D3DXMESHCONTAINER-derived object and initialize it function CreateMeshContainer(Name: PAnsiChar; const pMeshData: TD3DXMeshData; pMaterials: PD3DXMaterial; pEffectInstances: PD3DXEffectInstance; NumMaterials: DWORD; pAdjacency: PDWORD; pSkinInfo: ID3DXSkinInfo; out ppNewMeshContainer: PD3DXMeshContainer): HResult; override; // callback to release a D3DXFRAME-derived object function DestroyFrame(pFrameToFree: PD3DXFrame): HResult; override; // callback to release a D3DXMESHCONTAINER-derived object function DestroyMeshContainer(pMeshContainerToFree: PD3DXMeshContainer): HResult; override; public constructor Create; // Setup method function SetMA(pMA: CMultiAnim): HRESULT; end; //----------------------------------------------------------------------------- // Name: struct MultiAnimFrame // Desc: Inherits from D3DXFRAME. This represents an animation frame, or // bone. //----------------------------------------------------------------------------- //struct MultiAnimFrame : public D3DXFRAME PMultiAnimFrame = ^TMultiAnimFrame; TMultiAnimFrame = packed record Name: PAnsiChar; TransformationMatrix: TD3DXMatrix; pMeshContainer: PD3DXMeshContainer; pFrameSibling: PD3DXFrame; pFrameFirstChild: PD3DXFrame; end; PAD3DXMaterial = ^AD3DXMaterial; AD3DXMaterial = array[0..MaxInt div SizeOf(TD3DXMaterial) - 1] of TD3DXMaterial; PAIDirect3DTexture9 = ^TAIDirect3DTexture9; TAIDirect3DTexture9 = array[0..MaxInt div SizeOf(IDirect3DTexture9) - 1] of IDirect3DTexture9; PAD3DXMatrix = ^AD3DXMatrix; AD3DXMatrix = array[0..MaxInt div SizeOf(TD3DXMatrix)-1] of TD3DXMatrix; PD3DXMatrixPointerArray = ^TD3DXMatrixPointerArray; TD3DXMatrixPointerArray = array[0..MaxInt div SizeOf(PD3DXMatrix)-1] of PD3DXMatrix; //----------------------------------------------------------------------------- // Name: struct MultiAnimMC // Desc: Inherits from D3DXMESHCONTAINER. This represents a mesh object // that gets its vertices blended and rendered based on the frame // information in its hierarchy. //----------------------------------------------------------------------------- //struct MultiAnimMC : public D3DXMESHCONTAINER PMultiAnimMC = ^TMultiAnimMC; TMultiAnimMC = packed record // TD3DXMeshContainer Name: PAnsiChar; MeshData: TD3DXMeshData; pMaterials: PAD3DXMaterial; //PD3DXMaterial; pEffects: PD3DXEffectInstance; NumMaterials: DWORD; pAdjacency: PDWORD; pSkinInfo: ID3DXSkinInfo; pNextMeshContainer: PD3DXMeshContainer; // TMultiAnimMC m_apTextures: PAIDirect3DTexture9; //^IDirect3DTexture9; m_pWorkingMesh: ID3DXMesh; m_amxBoneOffsets: PAD3DXMatrix; //PD3DXMatrix; // Bone offset matrices retrieved from pSkinInfo m_apmxBonePointers: PD3DXMatrixPointerArray; // ^PD3DXMatrix; // Provides index to bone matrix lookup m_dwNumPaletteEntries: DWORD; m_dwMaxNumFaceInfls: DWORD; m_dwNumAttrGroups: DWORD; m_pBufBoneCombos: ID3DXBuffer; // HRESULT SetupBonePtrs( D3DXFRAME * pFrameRoot ); // function TMultiAnimMC_SetupBonePtrs(Self: PMultiAnimMC; pFrameRoot: PD3DXFrame): HRESULT; end; //----------------------------------------------------------------------------- // Name: class CMultiAnim // Desc: This class encapsulates a mesh hierarchy (typically loaded from an // .X file). It has a list of CAnimInstance objects that all share // the mesh hierarchy here, as well as using a copy of our animation // controller. CMultiAnim loads and keeps an effect object that it // renders the meshes with. //----------------------------------------------------------------------------- CMultiAnim = class { friend class CMultiAnimAllocateHierarchy; friend class CAnimInstance; friend struct MultiAnimFrame; friend struct MultiAnimMC; } protected m_pDevice: IDirect3DDevice9; m_pEffect: ID3DXEffect; m_sTechnique: PAnsiChar; // character rendering technique m_dwWorkingPaletteSize: DWORD; m_amxWorkingPalette: PAD3DXMatrix; // PD3DXMatrix; {$IFDEF FPC} m_v_pAnimInstances: TList; // must be at least 1; otherwise, clear all {$ELSE} m_v_pAnimInstances: TObjectList; // must be at least 1; otherwise, clear all {$ENDIF} m_pFrameRoot: PMultiAnimFrame; // shared between all instances m_pAC: ID3DXAnimationController; // AC that all children clone from -- to clone clean, no keys // useful data an app can retrieve m_fBoundingRadius: Single; private function CreateInstance(out ppAnimInstance: CAnimInstance): HRESULT; function SetupBonePtrs(pFrame: PMultiAnimFrame): HRESULT; public constructor Create; destructor Destroy; override; function Setup(pDevice: IDirect3DDevice9; sXFile, sFxFile: PWideChar; pAH: CMultiAnimAllocateHierarchy; pLUD: ID3DXLoadUserData = nil): HRESULT; virtual; function Cleanup(pAH: CMultiAnimAllocateHierarchy): HRESULT; virtual; function GetDevice: IDirect3DDevice9; function GetEffect: ID3DXEffect; function GetNumInstances: DWORD; function GetInstance(dwIndex: DWORD): CAnimInstance; function GetBoundingRadius: Single; function CreateNewInstance(out pdwNewIdx: DWORD): HRESULT; virtual; procedure SetTechnique(sTechnique: PChar); virtual; function Draw: HRESULT; virtual; end; //----------------------------------------------------------------------------- // Name: class CAnimInstance // Desc: Encapsulates an animation instance, with its own animation controller. //----------------------------------------------------------------------------- PCAnimInstance = ^CAnimInstance; CAnimInstance = class { friend class CMultiAnim; } protected m_pMultiAnim: CMultiAnim; m_mxWorld: TD3DXMatrix; m_pAC: ID3DXAnimationController; private function Setup(pAC: ID3DXAnimationController): HRESULT; virtual; procedure UpdateFrames(pFrame: PMultiAnimFrame; const pmxBase: TD3DXMatrix); virtual; procedure DrawFrames(pFrame: PMultiAnimFrame); virtual; procedure DrawMeshFrame(pFrame: PMultiAnimFrame); virtual; public constructor Create(pMultiAnim: CMultiAnim); destructor Destroy; override; procedure Cleanup; virtual; function GetMultiAnim: CMultiAnim; procedure GetAnimController(out ppAC: ID3DXAnimationController); function GetWorldTransform: TD3DXMatrix; procedure SetWorldTransform(const pmxWorld: TD3DXMatrix); function AdvanceTime(dTimeDelta: DOUBLE; var pCH: ID3DXAnimationCallbackHandler): HRESULT; virtual; function ResetTime: HRESULT; virtual; function Draw: HRESULT; virtual; end; function TMultiAnimMC_SetupBonePtrs(Self: PMultiAnimMC; pFrameRoot: PD3DXFrame): HRESULT; implementation uses SysUtils, Math, DXUTmisc; //###########################################################################// //###########################################################################// //###########################################################################// //###########################################################################// //###########################################################################// //----------------------------------------------------------------------------- // File: AllocHierarchy.cpp // // Desc: Implementation of the CMultiAnimAllocateHierarchy class, which // handles creating and destroying animation frames and mesh containers // for the CMultiAnimation library. // // Copyright (c) Microsoft Corporation. All rights reserved //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Name: HeapCopy() // Desc: Allocate buffer in memory and copy the content of sName to the // buffer, then return the address of the buffer. //----------------------------------------------------------------------------- // HeapCopy == StrNew //----------------------------------------------------------------------------- // Name: CMultiAnimAllocateHierarchy::CMultiAnimAllocateHierarchy() // Desc: Constructor of CMultiAnimAllocateHierarchy //----------------------------------------------------------------------------- constructor CMultiAnimAllocateHierarchy.Create; begin m_pMA:= nil; end; //----------------------------------------------------------------------------- // Name: CMultiAnimAllocateHierarchy::SetMA() // Desc: Sets the member CMultiAnimation pointer. This is the CMultiAnimation // we work with during the callbacks from D3DX. //----------------------------------------------------------------------------- function CMultiAnimAllocateHierarchy.SetMA(pMA: CMultiAnim): HRESULT; begin m_pMA := pMA; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: CMultiAnimAllocateHierarchy::CreateFrame() // Desc: Called by D3DX during the loading of a mesh hierarchy. The app can // customize its behavior. At a minimum, the app should allocate a // D3DXFRAME or a child of it and fill in the Name member. //----------------------------------------------------------------------------- function CMultiAnimAllocateHierarchy.CreateFrame(Name: PAnsiChar; out ppNewFrame: PD3DXFrame): HResult; var pFrame: PMultiAnimFrame; begin Assert(m_pMA <> nil); ppNewFrame := nil; try GetMem(pFrame, SizeOf(TMultiAnimFrame)); ZeroMemory(pFrame, SizeOf(TMultiAnimFrame)); if (Name <> nil) then pFrame.Name := StrNew(Name) else begin // TODO: Add a counter to append to the string below // so that we are using a different name for // each bone. pFrame.Name := StrNew('<no_name>'); end; except //todo: Fill bug report !!! // DestroyFrame(PD3DXFrame(pFrame)); Result:= E_OUTOFMEMORY; Exit; end; ppNewFrame := PD3DXFrame(pFrame); Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: CMultiAnimAllocateHierarchy::CreateMeshContainer() // Desc: Called by D3DX during the loading of a mesh hierarchy. At a minumum, // the app should allocate a D3DXMESHCONTAINER or a child of it and fill // in the members based on the parameters here. The app can further // customize the allocation behavior here. In our case, we initialize // m_amxBoneOffsets from the skin info for convenience reason. // Then we call ConvertToIndexedBlendedMesh to obtain a new mesh object // that's compatible with the palette size we have to work with. //----------------------------------------------------------------------------- function CMultiAnimAllocateHierarchy.CreateMeshContainer(Name: PAnsiChar; const pMeshData: TD3DXMeshData; pMaterials: PD3DXMaterial; pEffectInstances: PD3DXEffectInstance; NumMaterials: DWORD; pAdjacency: PDWORD; pSkinInfo: ID3DXSkinInfo; out ppNewMeshContainer: PD3DXMeshContainer): HResult; var pMC: PMultiAnimMC; dwNumFaces: DWORD; i: Integer; sNewPath: array[0..MAX_PATH-1] of WideChar; wszTexName: array[0..MAX_PATH-1] of WideChar; iPaletteSize: Integer; dwOldFVF: DWORD; dwNewFVF: DWORD; pMesh: ID3DXMesh; pDecl: TFVFDeclaration; pDeclCur: PD3DVertexElement9; begin Assert(m_pMA <> nil); ppNewMeshContainer := nil; Result := S_OK; pMC := nil; try try GetMem(pMC, SizeOf(TMultiAnimMC)); ZeroMemory(pMC, SizeOf(TMultiAnimMC)); // if this is a static mesh, exit early; we're only interested in skinned meshes if (pSkinInfo = nil) then Exit; // S_OK; // only support mesh type if (pMeshData._Type <> D3DXMESHTYPE_MESH) then begin Result := E_FAIL; Exit; end; if (Name <> nil) then pMC.Name := StrNew(Name) else pMC.Name := StrNew('<no_name>'); // copy the mesh over pMC.MeshData._Type := pMeshData._Type; pMC.MeshData.pMesh := pMeshData.pMesh; // copy adjacency over begin dwNumFaces := ID3DXMesh(pMC.MeshData.pMesh).GetNumFaces; GetMem(pMC.pAdjacency, SizeOf(DWORD) * 3 * dwNumFaces); Move(pAdjacency^, pMC.pAdjacency^, 3 * SizeOf(DWORD) * dwNumFaces); end; // ignore effects instances pMC.pEffects := nil; // alloc and copy materials pMC.NumMaterials := max(1, NumMaterials); GetMem(pMC.pMaterials, SizeOf(TD3DXMaterial)*pMC.NumMaterials); GetMem(pMC.m_apTextures, SizeOf(IDirect3DTexture9)*pMC.NumMaterials); ZeroMemory(pMC.m_apTextures, SizeOf(IDirect3DTexture9)*pMC.NumMaterials); if (NumMaterials > 0) then begin Move(pMaterials^, pMC.pMaterials^, NumMaterials * SizeOf(TD3DXMaterial)); for i := 0 to NumMaterials - 1 do begin if (pMC.pMaterials[i].pTextureFilename <> nil) then begin // CALLBACK to get valid filename if (MultiByteToWideChar(CP_ACP, 0, pMC.pMaterials[i].pTextureFilename, -1, wszTexName, MAX_PATH ) = 0) then pMC.m_apTextures[i] := nil else if SUCCEEDED(DXUTFindDXSDKMediaFile(sNewPath, MAX_PATH, wszTexName)) then begin // create the D3D texture if FAILED(D3DXCreateTextureFromFileW(m_pMA.m_pDevice, sNewPath, pMC.m_apTextures[i])) then pMC.m_apTextures[i] := nil; end else pMC.m_apTextures[i] := nil; end else pMC.m_apTextures[i] := nil; end; end else // mock up a default material and set it begin ZeroMemory(@pMC.pMaterials[0].MatD3D, SizeOf(TD3DMaterial9)); pMC.pMaterials[0].MatD3D.Diffuse.r := 0.5; pMC.pMaterials[0].MatD3D.Diffuse.g := 0.5; pMC.pMaterials[0].MatD3D.Diffuse.b := 0.5; pMC.pMaterials[0].MatD3D.Specular := pMC.pMaterials[0].MatD3D.Diffuse; pMC.pMaterials[0].pTextureFilename := nil; end; // save the skininfo object pMC.pSkinInfo := pSkinInfo; // Get the bone offset matrices from the skin info GetMem(pMC.m_amxBoneOffsets, SizeOf(TD3DXMatrix)*pSkinInfo.GetNumBones); begin for i := 0 to pSkinInfo.GetNumBones - 1 do pMC.m_amxBoneOffsets[i] := pSkinInfo.GetBoneOffsetMatrix(i)^; end; // // Determine the palette size we need to work with, then call ConvertToIndexedBlendedMesh // to set up a new mesh that is compatible with the palette size. // begin iPaletteSize := 0; m_pMA.m_pEffect.GetInt('MATRIX_PALETTE_SIZE', iPaletteSize); pMC.m_dwNumPaletteEntries := Min(iPaletteSize, pMC.pSkinInfo.GetNumBones); end; // generate the skinned mesh - creates a mesh with blend weights and indices Result := pMC.pSkinInfo.ConvertToIndexedBlendedMesh(ID3DXMesh(pMC.MeshData.pMesh), D3DXMESH_MANAGED or D3DXMESHOPT_VERTEXCACHE, pMC.m_dwNumPaletteEntries, pMC.pAdjacency, nil, nil, nil, @pMC.m_dwMaxNumFaceInfls, pMC.m_dwNumAttrGroups, pMC.m_pBufBoneCombos, pMC.m_pWorkingMesh); if FAILED(Result) then Exit; // Make sure the working set is large enough for this mesh. // This is a bone array used for all mesh containers as a working // set during drawing. If one was created previously that isn't // large enough for this mesh, we have to reallocate. if (m_pMA.m_dwWorkingPaletteSize < pMC.m_dwNumPaletteEntries) then begin if (m_pMA.m_amxWorkingPalette <> nil) then FreeMem(m_pMA.m_amxWorkingPalette); m_pMA.m_dwWorkingPaletteSize := 0; GetMem(m_pMA.m_amxWorkingPalette, SizeOf(TD3DXMatrix)*pMC.m_dwNumPaletteEntries); m_pMA.m_dwWorkingPaletteSize := pMC.m_dwNumPaletteEntries; end; // ensure the proper vertex format for the mesh begin dwOldFVF := pMC.m_pWorkingMesh.GetFVF; dwNewFVF := (dwOldFVF and D3DFVF_POSITION_MASK) or D3DFVF_NORMAL or D3DFVF_TEX1 or D3DFVF_LASTBETA_UBYTE4; if (dwNewFVF <> dwOldFVF) then begin Result := pMC.m_pWorkingMesh.CloneMeshFVF(pMC.m_pWorkingMesh.GetOptions, dwNewFVF, m_pMA.m_pDevice, pMesh); if FAILED(Result) then Exit; pMC.m_pWorkingMesh := nil; pMC.m_pWorkingMesh := pMesh; // if the loaded mesh didn't contain normals, compute them here if (dwOldFVF and D3DFVF_NORMAL = 0) then begin Result := D3DXComputeNormals(pMC.m_pWorkingMesh, nil); if FAILED(Result) then Exit; end; end; end; // Interpret the UBYTE4 as a D3DCOLOR. // The GeForce3 doesn't support the UBYTE4 decl type. So, we convert any // blend indices to a D3DCOLOR semantic, and later in the shader convert // it back using the D3DCOLORtoUBYTE4() intrinsic. Note that we don't // convert any data, just the declaration. Result := pMC.m_pWorkingMesh.GetDeclaration(pDecl); if FAILED(Result) then Exit; pDeclCur := @pDecl; while (pDeclCur.Stream <> $ff) do begin if (pDeclCur.Usage = D3DDECLUSAGE_BLENDINDICES) and (pDeclCur.UsageIndex = 0) then pDeclCur._Type := D3DDECLTYPE_D3DCOLOR; Inc(pDeclCur); end; Result := pMC.m_pWorkingMesh.UpdateSemantics(pDecl); if FAILED(Result) then Exit; except on EOutOfMemory do Result:= E_OUTOFMEMORY; end finally if FAILED(Result) then begin if (pMC <> nil) then DestroyMeshContainer(PD3DXMeshContainer(pMC)); end else ppNewMeshContainer := PD3DXMeshContainer(pMC); end; end; //----------------------------------------------------------------------------- // Name: CMultiAnimAllocateHierarchy::DestroyFrame() // Desc: Called by D3DX during the release of a mesh hierarchy. Here we should // free all resources allocated in CreateFrame(). //----------------------------------------------------------------------------- function CMultiAnimAllocateHierarchy.DestroyFrame(pFrameToFree: PD3DXFrame): HResult; var pFrame: PMultiAnimFrame; begin Assert(m_pMA <> nil); pFrame := PMultiAnimFrame(pFrameToFree); if (pFrame.Name <> nil) then StrDispose(pFrame.Name); FreeMem(pFrame); Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: CMultiAnimAllocateHierarchy::DestroyMeshContainer() // Desc: Called by D3DX during the release of a mesh hierarchy. Here we should // free all resources allocated in CreateMeshContainer(). //----------------------------------------------------------------------------- function CMultiAnimAllocateHierarchy.DestroyMeshContainer(pMeshContainerToFree: PD3DXMeshContainer): HResult; var pMC: PMultiAnimMC; i: Integer; begin Assert(m_pMA <> nil); pMC := PMultiAnimMC(pMeshContainerToFree); if (pMC.Name <> nil) then StrDispose(pMC.Name); pMC.MeshData.pMesh := nil; if (pMC.pAdjacency <> nil) then FreeMem(pMC.pAdjacency); if (pMC.pMaterials <> nil) then FreeMem(pMC.pMaterials); for i := 0 to pMC.NumMaterials - 1 do pMC.m_apTextures[i]:= nil; if (pMC.m_apTextures <> nil) then FreeMem(pMC.m_apTextures); pMC.pSkinInfo := nil; if (pMC.m_amxBoneOffsets <> nil) then FreeMem(pMC.m_amxBoneOffsets); pMC.m_pWorkingMesh := nil; pMC.m_dwNumPaletteEntries := 0; pMC.m_dwMaxNumFaceInfls := 0; pMC.m_dwNumAttrGroups := 0; pMC.m_pBufBoneCombos := nil; if (pMC.m_apmxBonePointers <> nil) then FreeMem(pMC.m_apmxBonePointers); FreeMem(pMeshContainerToFree); Result:= S_OK; end; //###########################################################################// //###########################################################################// //###########################################################################// //###########################################################################// //###########################################################################// //----------------------------------------------------------------------------- // File: MultiAnimationLib.cpp // // Desc: Implementation of the CMultiAnim class. This class manages the animation // data (frames and meshes) obtained from a single X file. // // Copyright (c) Microsoft Corporation. All rights reserved //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Name: MultiAnimMC::SetupBonePtrs() // Desc: Initialize the m_apmxBonePointers member to point to the bone matrices // so that we can access the bones by index easily. Called from // CMultiAnim::SetupBonePtrs(). //----------------------------------------------------------------------------- function TMultiAnimMC_SetupBonePtrs(Self: PMultiAnimMC; pFrameRoot: PD3DXFrame): HRESULT; var dwNumBones: DWORD; i: Integer; pFrame: PMultiAnimFrame; begin with Self^ do begin if (pSkinInfo <> nil) then begin if (m_apmxBonePointers <> nil) then FreeMem(m_apmxBonePointers); dwNumBones := pSkinInfo.GetNumBones; try GetMem(m_apmxBonePointers, SizeOf(PD3DXmatrix)*dwNumBones); except Result:= E_OUTOFMEMORY; Exit; end; for i := 0 to dwNumBones - 1 do begin pFrame := PMultiAnimFrame(D3DXFrameFind(pFrameRoot, pSkinInfo.GetBoneName(i))); if (pFrame = nil) then begin Result:= E_FAIL; Exit; end; m_apmxBonePointers[i] := @pFrame.TransformationMatrix; end; end; end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::CreateInstance() // Desc: Create a new animation instance based on our animation frames and // animation controller. //----------------------------------------------------------------------------- function CMultiAnim.CreateInstance(out ppAnimInstance: CAnimInstance): HRESULT; //HRESULT CMultiAnim::CreateInstance( CAnimInstance ** ppAnimInstance ) var pNewAC: ID3DXAnimationController; pAI: CAnimInstance; begin Result:= S_OK; ppAnimInstance := nil; pNewAC := nil; pAI := nil; try try // Clone the original AC. This clone is what we will use to animate // this mesh; the original never gets used except to clone, since we // always need to be able to add another instance at any time. Result := m_pAC.CloneAnimationController(m_pAC.GetMaxNumAnimationOutputs, m_pAC.GetMaxNumAnimationSets, m_pAC.GetMaxNumTracks, m_pAC.GetMaxNumEvents, pNewAC); if SUCCEEDED(Result) then begin // create the new AI pAI := CAnimInstance.Create(Self); // set it up Result := pAI.Setup(pNewAC); if FAILED(Result) then Exit; ppAnimInstance := pAI; end; except on EOutOfMemory do Result:= E_OUTOFMEMORY; end; finally if FAILED(Result) then begin if (pAI <> nil) then FreeAndNil(pAI); if (pNewAC <> nil) then pNewAC:= nil; end; end; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::SetupBonePtrs() // Desc: Recursively initialize the bone pointers for all the mesh // containers in the hierarchy. //----------------------------------------------------------------------------- function CMultiAnim.SetupBonePtrs(pFrame: PMultiAnimFrame): HRESULT; begin Assert(pFrame <> nil); if (pFrame.pMeshContainer <> nil) then begin // call setup routine Result := TMultiAnimMC_SetupBonePtrs(PMultiAnimMC(pFrame.pMeshContainer), PD3DXFrame(m_pFrameRoot)); if FAILED(Result) then Exit; end; if (pFrame.pFrameSibling <> nil) then begin // recursive call Result := SetupBonePtrs(PMultiAnimFrame(pFrame.pFrameSibling)); if FAILED(Result) then Exit; end; if (pFrame.pFrameFirstChild <> nil) then begin // recursive call Result := SetupBonePtrs(PMultiAnimFrame(pFrame.pFrameFirstChild)); if FAILED(Result) then Exit; end; Result:= S_OK; end; constructor CMultiAnim.Create; begin {$IFDEF FPC} m_v_pAnimInstances:= TList.Create; {$ELSE} m_v_pAnimInstances:= TObjectList.Create; {$ENDIF} m_pDevice := nil; m_pEffect := nil; m_dwWorkingPaletteSize := 0; m_amxWorkingPalette := nil; m_pFrameRoot := nil; m_pAC := nil; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::~CMultiAnim() // Desc: Destructor for CMultiAnim //----------------------------------------------------------------------------- destructor CMultiAnim.Destroy; {$IFDEF FPC} var i: Integer; {$ENDIF} begin {$IFDEF FPC} for i:= 0 to m_v_pAnimInstances.Count - 1 do GetInstance(i).Free; {$ENDIF} // m_v_pAnimInstances.Clear; m_v_pAnimInstances.Free; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::Setup() // Desc: The class is initialized with this method. // We create the effect from the fx file, and load the animation mesh // from the given X file. We then call SetupBonePtrs() to initialize // the mesh containers to enable bone matrix lookup by index. The // Allocation Hierarchy is passed by pointer to allow an app to subclass // it for its own implementation. //----------------------------------------------------------------------------- function CMultiAnim.Setup(pDevice: IDirect3DDevice9; sXFile, sFxFile: PWideChar; pAH: CMultiAnimAllocateHierarchy; pLUD: ID3DXLoadUserData = nil): HRESULT; var vCenter: TD3DXVector3; pEC: ID3DXEffectCompiler; const mac: array[0..1] of TD3DXMacro = ( (Name: 'MATRIX_PALETTE_SIZE_DEFAULT'; Definition: '35'), (Name: nil; Definition: nil ) ); var caps: TD3DCaps9; pmac: PD3DXMacro; wszPath: array[0..MAX_PATH-1] of WideChar; dwShaderFlags: DWORD; pNewAC: ID3DXAnimationController; i: Integer; begin Result:= S_OK; Assert(pDevice <> nil); Assert(sXFile <> nil); Assert(sFxFile <> nil); Assert(pAH <> nil); // set the MA instance for CMultiAnimAllocateHierarchy pAH.SetMA(Self); // set the device m_pDevice := pDevice; // Increase the palette size if the shader allows it. We are sort // of cheating here since we know tiny has 35 bones. The alternative // is use the maximum number that vs_2_0 allows. (* D3DXMACRO mac[2] = { { "MATRIX_PALETTE_SIZE_DEFAULT", "35" }, { NULL, NULL } }; *) // If we support VS_2_0, increase the palette size; else, use the default // of 26 bones from the .fx file by passing NULL pmac := nil; m_pDevice.GetDeviceCaps(caps); if (caps.VertexShaderVersion > D3DVS_VERSION(1,1)) then pmac := @mac; try // create effect -- do this first, so LMHFX has access to the palette size Result := DXUTFindDXSDKMediaFile(wszPath, MAX_PATH, sFxFile); if FAILED(Result) then Exit; // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the shader debugger. // Debugging vertex shaders requires either REF or software vertex processing, and debugging // pixel shaders requires REF. The D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug // experience in the shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile against the next // higher available software target, which ensures that the unoptimized shaders do not exceed // the shader model limitations. Setting these flags will cause slower rendering since the shaders // will be unoptimized and forced into software. See the DirectX documentation for more information // about using the shader debugger. dwShaderFlags := D3DXFX_NOT_CLONEABLE; {$IFDEF DEBUG} // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG; {$ENDIF} {$IFDEF DEBUG_VS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; {$ENDIF} {$IFDEF DEBUG_PS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; {$ENDIF} Result := D3DXCreateEffectFromFileW(m_pDevice, wszPath, pmac, nil, dwShaderFlags, nil, m_pEffect, nil); if FAILED(Result) then Exit; // create the mesh, frame hierarchy, and animation controller from the x file Result := DXUTFindDXSDKMediaFile(wszPath, MAX_PATH, sXFile); if FAILED(Result) then Exit; Result := D3DXLoadMeshHierarchyFromXW(wszPath, 0, m_pDevice, pAH, pLUD, PD3DXFrame(m_pFrameRoot), m_pAC); if FAILED(Result) then Exit; if (m_pAC = nil) then begin Result := E_FAIL; MessageBox(0, 'The sample is attempting to load a mesh without animation or incompatible animation. This sample requires tiny_4anim.x or a mesh with identical animation sets. The program will now exit.', 'Mesh Load Error', MB_OK); Exit; end; // set up bone pointers Result := SetupBonePtrs(m_pFrameRoot); if FAILED(Result) then Exit; // get bounding radius Result := D3DXFrameCalculateBoundingSphere(PD3DXFrame(m_pFrameRoot), vCenter, m_fBoundingRadius); if FAILED(Result) then Exit; // If there are existing instances, update their animation controllers. begin for i:= 0 to m_v_pAnimInstances.Count - 1 do begin pNewAC := nil; Result := m_pAC.CloneAnimationController(m_pAC.GetMaxNumAnimationOutputs, m_pAC.GetMaxNumAnimationSets, m_pAC.GetMaxNumTracks, m_pAC.GetMaxNumEvents, pNewAC); // Release existing animation controller with CAnimInstance (m_v_pAnimInstances[i]) do begin m_pAC:= nil; Setup(pNewAC); end; end; end; finally if FAILED(Result) then begin if (m_amxWorkingPalette <> nil) then begin FreeMem(m_amxWorkingPalette); m_amxWorkingPalette := nil; m_dwWorkingPaletteSize := 0; end; m_pAC:= nil; if (m_pFrameRoot <> nil) then begin D3DXFrameDestroy(PD3DXFrame(m_pFrameRoot), pAH); m_pFrameRoot := nil; end; m_pEffect := nil; pEC:= nil; //todo: What the Heck!!!! m_pDevice := nil; end; end; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::Cleanup() // Desc: Performs clean up work and free up memory. //----------------------------------------------------------------------------- function CMultiAnim.Cleanup(pAH: CMultiAnimAllocateHierarchy): HRESULT; begin if (m_amxWorkingPalette <> nil) then begin FreeMem(m_amxWorkingPalette); m_amxWorkingPalette := nil; m_dwWorkingPaletteSize := 0; end; m_pAC := nil; if (m_pFrameRoot <> nil) then begin D3DXFrameDestroy(PD3DXFrame(m_pFrameRoot), pAH); m_pFrameRoot := nil; end; m_pEffect := nil; m_pDevice := nil; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::GetDevice() // Desc: Returns the D3D device we work with. The caller must call Release() // on the pointer when done with it. //----------------------------------------------------------------------------- function CMultiAnim.GetDevice: IDirect3DDevice9; begin Result:= m_pDevice; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::GetEffect() // Desc: Returns the D3D effect object that the mesh is rendered with. The // caller must call Release() when done. //----------------------------------------------------------------------------- function CMultiAnim.GetEffect: ID3DXEffect; begin Result:= m_pEffect; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::GetNumInstance() // Desc: Returns the number of animation instances using our animation frames. //----------------------------------------------------------------------------- function CMultiAnim.GetNumInstances: DWORD; begin Result:= m_v_pAnimInstances.Count; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::GetInstance() // Desc: Returns a CAnimInstance object by index. //----------------------------------------------------------------------------- function CMultiAnim.GetInstance(dwIndex: DWORD): CAnimInstance; begin Assert(Integer(dwIndex) < m_v_pAnimInstances.Count); Result:= CAnimInstance(m_v_pAnimInstances[dwIndex]); end; //----------------------------------------------------------------------------- // Name: CMultiAnim::GetBoundingRadius() // Desc: Returns the bounding radius for the mesh object. //----------------------------------------------------------------------------- function CMultiAnim.GetBoundingRadius: Single; begin Result:= m_fBoundingRadius; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::CreateNewInstance() // Desc: Creates a new animation instance and adds it to our instance array. // Then returns the index of the newly created instance. //----------------------------------------------------------------------------- function CMultiAnim.CreateNewInstance(out pdwNewIdx: DWORD): HRESULT; var pAI: CAnimInstance; begin // create the AI Result := CreateInstance(pAI); if FAILED(Result) then Exit; // add it try m_v_pAnimInstances.Add(pAI); except Result := E_OUTOFMEMORY; Exit; end; pdwNewIdx := m_v_pAnimInstances.Count - 1; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::SetTechnique() // Desc: Sets the name of the technique to render the mesh in. //----------------------------------------------------------------------------- procedure CMultiAnim.SetTechnique(sTechnique: PChar); begin m_sTechnique := sTechnique; end; //----------------------------------------------------------------------------- // Name: CMultiAnim::Draw() // Desc: Render all animtion instances using our mesh frames. //----------------------------------------------------------------------------- function CMultiAnim.Draw: HRESULT; var i: Integer; hr: HRESULT; begin // TODO: modify this for much faster bulk rendering Result := S_OK; for i:= 0 to m_v_pAnimInstances.Count - 1 do begin hr:= CAnimInstance(m_v_pAnimInstances[i]).Draw; if FAILED(hr) then Result:= hr; end; end; //###########################################################################// //###########################################################################// //###########################################################################// //###########################################################################// //###########################################################################// //----------------------------------------------------------------------------- // File: AnimationInstance.cpp // // Desc: Implementation of the CAnimaInstance class, which encapsulates a // specific animation instance used by the CMultiAnimation library. // // Copyright (c) Microsoft Corporation. All rights reserved //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Name: CAnimInstance::Setup() // Desc: Initialize ourselves to use the animation controller passed in. Then // initialize the animation controller. //----------------------------------------------------------------------------- function CAnimInstance.Setup(pAC: ID3DXAnimationController): HRESULT; var i, dwTracks: DWORD; begin Assert(pAC <> nil); m_pAC := pAC; // Start with all tracks disabled dwTracks := m_pAC.GetMaxNumTracks; for i := 0 to dwTracks - 1 do m_pAC.SetTrackEnable(i, False); Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: CAnimInstance::UpdateFrame() // Desc: Recursively walk the animation frame hierarchy and for each frame, // transform the frame by its parent, starting with a world transform to // place the mesh in world space. This has the effect of a hierarchical // transform over all the frames. //----------------------------------------------------------------------------- procedure CAnimInstance.UpdateFrames(pFrame: PMultiAnimFrame; const pmxBase: TD3DXMatrix); begin Assert(pFrame <> nil); Assert(@pmxBase <> nil); // transform the bone D3DXMatrixMultiply(pFrame.TransformationMatrix, pFrame.TransformationMatrix, pmxBase); // transform siblings by the same matrix if (pFrame.pFrameSibling <> nil) then UpdateFrames(PMultiAnimFrame(pFrame.pFrameSibling), pmxBase); // transform children by the transformed matrix - hierarchical transformation if (pFrame.pFrameFirstChild <> nil) then UpdateFrames(PMultiAnimFrame(pFrame.pFrameFirstChild), pFrame.TransformationMatrix); end; //----------------------------------------------------------------------------- // Name: CAnimInstance::DrawFrames() // Desc: Recursively walk the frame hierarchy and draw each mesh container as // we find it. //----------------------------------------------------------------------------- procedure CAnimInstance.DrawFrames(pFrame: PMultiAnimFrame); begin if (pFrame.pMeshContainer <> nil) then DrawMeshFrame(pFrame); if (pFrame.pFrameSibling <> nil) then DrawFrames(PMultiAnimFrame(pFrame.pFrameSibling)); if (pFrame.pFrameFirstChild <> nil) then DrawFrames(PMultiAnimFrame(pFrame.pFrameFirstChild)); end; //----------------------------------------------------------------------------- // Name: CAnimInstance::DrawMeshFrame() // Desc: Renders a mesh container. Here we go through each attribute group // and set up the matrix palette for each group by multiplying the // bone offsets to its bone transformation. This gives us the completed // bone matrices that can be used and blended by the pipeline. We then // set up the effect and render the mesh. //----------------------------------------------------------------------------- type PD3DXBoneCombinationArray = ^TD3DXBoneCombinationArray; TD3DXBoneCombinationArray = array[0..0] of TD3DXBoneCombination; procedure CAnimInstance.DrawMeshFrame(pFrame: PMultiAnimFrame); var pMC: PMultiAnimMC; pBC: PD3DXBoneCombinationArray; // PD3DXBoneCombination; dwAttrib, dwPalEntry: DWORD; dwMatrixIndex: DWORD; uiPasses, uiPass: Integer; const UINT_MAX = $FFFFFFFF; begin pMC := PMultiAnimMC(pFrame.pMeshContainer); if (pMC.pSkinInfo = nil) then Exit; // get bone combinations pBC := PD3DXBoneCombinationArray(pMC.m_pBufBoneCombos.GetBufferPointer); // for each palette for dwAttrib := 0 to pMC.m_dwNumAttrGroups - 1 do begin // set each transform into the palette for dwPalEntry := 0 to pMC.m_dwNumPaletteEntries - 1 do begin dwMatrixIndex := pBC[dwAttrib].BoneId[dwPalEntry]; if (dwMatrixIndex <> UINT_MAX) then D3DXMatrixMultiply(m_pMultiAnim.m_amxWorkingPalette[dwPalEntry], pMC.m_amxBoneOffsets[dwMatrixIndex], pMC.m_apmxBonePointers[dwMatrixIndex]^); end; // set the matrix palette into the effect m_pMultiAnim.m_pEffect.SetMatrixArray('amPalette', PD3DXMatrix(m_pMultiAnim.m_amxWorkingPalette), pMC.m_dwNumPaletteEntries); // we're pretty much ignoring the materials we got from the x-file; just set // the texture here m_pMultiAnim.m_pEffect.SetTexture('g_txScene', pMC.m_apTextures[pBC[dwAttrib].AttribId]); // set the current number of bones; this tells the effect which shader to use m_pMultiAnim.m_pEffect.SetInt('CurNumBones', pMC.m_dwMaxNumFaceInfls - 1); // set the technique we use to draw if FAILED(m_pMultiAnim.m_pEffect.SetTechnique(TD3DXHandle(m_pMultiAnim.m_sTechnique))) then Exit; // run through each pass and draw m_pMultiAnim.m_pEffect._Begin(@uiPasses, 0 {D3DXFX_DONOTSAVESTATE}); for uiPass := 0 to uiPasses - 1 do begin m_pMultiAnim.m_pEffect.BeginPass(uiPass); pMC.m_pWorkingMesh.DrawSubset(dwAttrib); m_pMultiAnim.m_pEffect.EndPass; end; m_pMultiAnim.m_pEffect._End; end; end; //----------------------------------------------------------------------------- // Name: CAnimInstance::CAnimInstance() // Desc: Constructor of CAnimInstance //----------------------------------------------------------------------------- constructor CAnimInstance.Create(pMultiAnim: CMultiAnim); begin m_pMultiAnim := pMultiAnim; m_pAC := nil; Assert(pMultiAnim <> nil); end; //----------------------------------------------------------------------------- // Name: CAnimInstance::~CAnimInstance() // Desc: Destructor of CAnimInstance //----------------------------------------------------------------------------- destructor CAnimInstance.Destroy; begin inherited; end; //----------------------------------------------------------------------------- // Name: CAnimInstance::Cleanup() // Desc: Performs the cleanup task //----------------------------------------------------------------------------- procedure CAnimInstance.Cleanup; begin m_pAC := nil; end; //----------------------------------------------------------------------------- // Name: CAnimInstance::GetMultiAnim() // Desc: Returns the CMultiAnimation object that this instance uses. //----------------------------------------------------------------------------- function CAnimInstance.GetMultiAnim: CMultiAnim; begin Result:= m_pMultiAnim; end; //----------------------------------------------------------------------------- // Name: CAnimInstance::GetAnimController() // Desc: Returns the animation controller for this instance. The caller // must call Release() when done with it. //----------------------------------------------------------------------------- procedure CAnimInstance.GetAnimController(out ppAC: ID3DXAnimationController); begin Assert(@ppAC <> nil); ppAC := m_pAC; end; //----------------------------------------------------------------------------- // Name: CAnimInstance::GetWorldTransform() // Desc: Returns the world transformation matrix for this animation instance. //----------------------------------------------------------------------------- function CAnimInstance.GetWorldTransform: TD3DXMatrix; begin Result:= m_mxWorld; end; //----------------------------------------------------------------------------- // Name: CAnimInstance::SetWorldTransform() // Desc: Sets the world transformation matrix for this instance. //----------------------------------------------------------------------------- procedure CAnimInstance.SetWorldTransform(const pmxWorld: TD3DXMatrix); begin Assert(@pmxWorld <> nil); m_mxWorld := pmxWorld; end; //----------------------------------------------------------------------------- // Name: CAnimInstance::AdvanceTime() // Desc: Advance the local time of this instance by dTimeDelta with a // callback handler to handle possible callback from the animation // controller. Then propagate the animations down the hierarchy while // transforming it into world space. //----------------------------------------------------------------------------- function CAnimInstance.AdvanceTime(dTimeDelta: DOUBLE; var pCH: ID3DXAnimationCallbackHandler): HRESULT; begin // apply all the animations to the bones in the frame hierarchy. Result := m_pAC.AdvanceTime(dTimeDelta, pCH); if FAILED(Result) then Exit; // apply the animations recursively through the hierarchy, and set the world. UpdateFrames(m_pMultiAnim.m_pFrameRoot, m_mxWorld); Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: CAnimInstance::ResetTime() // Desc: Resets the local time for this instance. //----------------------------------------------------------------------------- function CAnimInstance.ResetTime: HRESULT; begin Result:= m_pAC.ResetTime; end; //----------------------------------------------------------------------------- // Name: CAnimInstance::Draw() // Desc: Renders the frame hierarchy of our CMultiAnimation object. This is // normally called right after AdvanceTime() so that we render the // mesh with the animation for this instance. //----------------------------------------------------------------------------- function CAnimInstance.Draw: HRESULT; begin DrawFrames(m_pMultiAnim.m_pFrameRoot); Result:= S_OK; end; end.
unit MathResourceIntf; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns; type IMathResource = interface(IInvokable) ['{D7C2E1AF-E5F0-4272-BF2D-CFF6D10DE12E}'] function Add(A, B: Integer): Integer; function Multiply(A, B: Integer): Integer; end; implementation initialization InvRegistry.RegisterInterface(TypeInfo(IMathResource)); end.
unit untTCPIPPatcher; interface uses Windows; procedure ptcpip; implementation function checkos: boolean; var verinfo :tosversioninfo; begin result := false; verinfo.dwOSVersionInfoSize := sizeof(tosversioninfo); getversionex(verinfo); if (verinfo.dwMajorVersion = 5) and (verinfo.dwMinorVersion = 1) and (verinfo.szCSDVersion[13] = '2') then result := true; end; procedure Disable_WFP(szFile :string); type cpp = function(param1:dword; param2:pwidechar; param3: dword): dword; stdcall; var path :pwidechar; hmod :thandle; SetSfcFileException: cpp; begin getmem(path, 256); multibytetowidechar(cp_acp, 0, pchar(szfile), -1, path, 256); hmod := loadlibrary('sfc_os.dll'); SetSfcFileException := getprocaddress(hmod, LPCSTR(5)); SetSfcFileException(0, path, dword(-1)); end; function patch_tcpip: boolean; type orglist = record offset :integer; value :char; end; bytelist = record offset :integer; value :char; end; const orgb :array [0..3] of orglist = ((offset:$00130;value:#$6E), (offset:$00131;value:#$12), (offset:$4f322;value:#$0A), (offset:$4f323;value:#$00)); bytes :array [0..3] of bytelist = ((offset:$00130;value:#$4C), (offset:$00131;value:#$16), (offset:$4f322;value:#$E8), (offset:$4f323;value:#$03)); var szByte :byte; szPath :string; szSysDir :array[0..MAX_PATH] of char; c :array[0..8] of char; f :file; i :integer; match :integer; begin result := false; szByte := 1; if not checkos() then exit; GetSystemDirectory(szSysDir, sizeof(szSysDir)); szPath := szSysDir + '\drivers\tcpip.sys'; Disable_WFP(szpath); assignfile(f, szpath); reset(f, 1); zeromemory(@i, sizeof(i)); match := 0; for i := 0 to 3 do begin seek(f, orgb[i].offset); blockread(f, szByte, 1); if chr(szByte) = orgb[i].value then inc(match); end; zeromemory(@i, sizeof(i)); for i := 0 to 3 do begin seek(f, bytes[i].offset); blockwrite(f, bytes[i].value, 1); end; closefile(f); result := true; end; function backup: boolean; var szSysDir :array[0..MAX_PATH] of char; szPath :string; szBckPath :string; begin GetSystemDirectory(szSysDir, sizeof(szSysDir)); szPath := szSysDir + '\drivers\tcpip.sys'; szBckPath := szSysDir + '\drivers\tcpip.sys.bck'; if copyfile(pchar(szPath), pchar(szBckPath), false) then result := true else result := false; end; procedure ptcpip; begin backup(); patch_tcpip(); end; end.
unit u_ast_constructions; {$mode objfpc}{$H+} interface uses Classes, SysUtils, u_tokens, u_ast, u_ast_blocks, u_ast_expression, u_ast_expression_blocks, u_ast_constructions_blocks; type TMashAST = class(TMashBaseAST) public CornerNodes: TList; BlockVect: TList; BlockObjectVect: TList; imports_lst, regapi_lst, uses_lst, const_lst: TList; constructor Create(_tokens, _imports_lst, _regapi_lst, _uses_lst, _const_lst: TList); destructor Destroy; override; procedure Process; private function CurrBlock: TList; function NextNode(var token_id: cardinal): TMashASTBlock; function NextExpr(var token_id: cardinal): TMashASTB_Expression; procedure NextExprTokens(var token_id: cardinal; list: TList); function NextParam(var token_id: cardinal): TMashASTB_Param; function ExtractMethod(var token_id: cardinal; is_function: boolean; tk: TMashToken): TMashASTB_Method; function ExtractFor(var token_id: cardinal; tk: TMashToken): TMashASTBlock; function ExtractWhile(var token_id: cardinal; is_whilst: boolean; tk: TMashToken): TMashASTBlock; function ExtractClass(var token_id: cardinal; tk: TMashToken): TMashASTB_Class; function ExtractClassField(var token_id: cardinal): TMashASTB_ClassField; function ExtractEnum(var token_id: cardinal; tk:TMashToken): TMashASTB_Enum; end; implementation constructor TMashAST.Create(_tokens, _imports_lst, _regapi_lst, _uses_lst, _const_lst: TList); begin inherited Create(_tokens); imports_lst := _imports_lst; regapi_lst := _regapi_lst; uses_lst := _uses_lst; const_lst := _const_lst; self.CornerNodes := self.nodes; self.BlockObjectVect := TList.Create; self.BlockVect := TList.Create; self.BlockVect.add(self.nodes); end; destructor TMashAST.Destroy; begin FreeAndNil(self.BlockVect); FreeAndNil(self.BlockObjectVect); inherited; end; function TMashAST.CurrBlock: TList; begin if self.BlockVect.count > 0 then Result := TList(self.BlockVect[self.BlockVect.count - 1]) else Result := self.CornerNodes; end; procedure TMashAST.Process; const BlocksWithNodes: set of TMashASTBlockType = [ btMethod, btIf, btForEach, btWhile, btWhilst, btSwitch, btCase, btLaunch, btAsync, btTry, btClass, btClassField, btPublic, btProtected, btPrivate, btEnum ]; var token_id: cardinal; node, parent_block: TMashASTBlock; ok: boolean; begin token_id := 0; while token_id < self.tokens.count do begin node := self.NextNode(token_id); if node <> nil then begin if node.GetType in BlocksWithNodes then begin parent_block := nil; if self.BlockObjectVect.count > 0 then parent_block := TMashASTBlock(self.BlockObjectVect[self.BlockObjectVect.count - 1]); ok := false; if parent_block <> nil then begin case parent_block.GetType of btSwitch: begin if node.GetType <> btCase then raise Exception.Create( 'Switch block can contain only case statements. ' + 'Invalid switch-case construction at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + '''.' ); ok := true; if TMashASTB_Case(node).isElse then begin self.BlockObjectVect.Add(node); self.BlockVect.Add(TMashASTB_Case(node).Nodes); TMashASTB_Switch(parent_block).hasElse := true; TMashASTB_Switch(parent_block).ElseCase := node; end else begin self.CurrBlock.Add(node); self.BlockObjectVect.Add(node); self.BlockVect.Add(TMashASTB_Case(node).Nodes); end; end; btClass: case node.GetType of btClassField: begin ok := true; TMashASTB_Class(parent_block).class_vars.AddStrings( TMashASTB_ClassField(node).names ); end; btMethod: begin ok := true; if not TMashASTB_Method(node).is_class_method then begin TMashASTB_Method(node).is_class_method := true; TMashASTB_Method(node).class_name := TMashASTB_Class(parent_block).class_name; self.CornerNodes.Add(node); self.BlockObjectVect.Add(node); self.BlockVect.Add(TMashASTB_Method(node).nodes); end else raise Exception.Create( 'Invalid class method (' + TMashASTB_Method(node).class_name + '::' + TMashASTB_Method(node).method_name + ') declaration at line ' + IntToStr(TMashASTB_Method(node).line + 1) + ' at file ''' + TMashASTB_Method(node).fp^ + '''.' ); end; btPublic, btProtected, btPrivate: ok := true; else raise Exception.Create( 'Invalid class field statement at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + '''.' ); end; end; end; if not ok then case node.GetType of btCase: raise Exception.Create( 'Case statement without switch at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + '''.' ); btClass: if parent_block = nil then begin self.CurrBlock.Add(node); self.BlockObjectVect.Add(node); self.BlockVect.Add(nil); end else raise Exception.Create( 'Class declaration can''t be contained. Invalid class declaration at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + '''.' ); btEnum: if parent_block = nil then self.CurrBlock.add(node) else raise Exception.Create( 'Enum declaration can''t be contained. Invalid enum declaration at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + '''.' ); btClassField, btPublic, btProtected, btPrivate: if parent_block.GetType <> btClass then raise Exception.Create( 'Class field declaration contained not in a class. Invalid class field declaration at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + '''.' ); else begin self.CurrBlock.add(node); self.BlockObjectVect.add(node); self.BlockVect.add(TMashASTBlockWithNodes(node).GetNodes); end; end; end else self.CurrBlock.add(node); end; end; end; function TMashAST.NextNode(var token_id: cardinal): TMashASTBlock; var tk, t: TMashToken; p: Pointer; begin Result := nil; tk := self.Token(token_id); self.lastTk := tk; case tk.info of ttToken: if tk.short in MashExprTokens then Result := self.NextExpr(token_id) else case tk.short of tkImport: begin self.imports_lst.add( TMashASTB_Import.Create( self.TkWordValue(self.Token(token_id + 1)), self.TkStrValue(self.Token(token_id + 2)), self.TkStrValue(self.Token(token_id + 3)) ) ); Inc(token_id, 4); end; tkAPI: begin self.regapi_lst.add( TMashASTB_RegAPI.Create( self.TkStrValue(self.Token(token_id + 1)), self.TkDigitValue(self.Token(token_id + 2)) ) ); Inc(token_id, 3); end; tkUses: begin Inc(token_id); p := TMashASTB_Uses.Create; self.NextExprTokens(token_id, TMashASTB_Uses(p).Expr); self.uses_lst.add(p); end; tkInline: begin Result := TMashASTB_Inline.Create( self.TkStrValue(self.Token(token_id + 1)) ); Inc(token_id, 2); end; tkConst: if self.TkCheckID(self.Token(token_id + 2)) = tkResource then begin self.const_lst.add( TMashASTB_Const.Create( self.TkWordValue(self.Token(token_id + 1)), self.TkNotNull(self.Token(token_id + 3)), true ) ); Inc(token_id, 4); end else if self.TkCheckID(self.Token(token_id + 2)) = tkSubSym then begin p := self.TkNotNull(self.Token(token_id + 3)); TMashToken(p).value := '-' + self.TkDigitValue(TMashToken(p)); self.const_lst.add( TMashASTB_Const.Create( self.TkWordValue(self.Token(token_id + 1)), TMashToken(p), false ) ); Inc(token_id, 4); end else begin self.const_lst.add( TMashASTB_Const.Create( self.TkWordValue(self.Token(token_id + 1)), self.TkNotNull(self.Token(token_id + 2)), false ) ); Inc(token_id, 3); end; tkProc: Result := self.ExtractMethod(token_id, false, tk); tkFunc: Result := self.ExtractMethod(token_id, true, tk); tkEnd: begin if self.BlockObjectVect.count > 0 then self.BlockObjectVect.delete(self.BlockObjectVect.count - 1); self.BlockVect.delete(self.BlockVect.count - 1); if self.BlockVect.count = 0 then raise Exception.Create( 'Unexpected ''end'' at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); Inc(token_id); end; tkIf: begin Inc(token_id); Result := TMashASTB_If.Create( self.NextExpr(token_id) ); if self.TkTokenID(self.Token(token_id)) = tkBegin then Inc(token_id) else raise Exception.Create( 'Missed '':'' in ''if'' statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; tkElse: begin t := self.TkNotNull(self.Token(token_id + 1)); if self.TkTokenID(t) <> tkBegin then raise Exception.Create( 'Unexpected token ''' + t.value + ''' at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); Inc(token_id, 2); if self.BlockObjectVect.count > 0 then begin p := self.BlockObjectVect[self.BlockObjectVect.count - 1]; if TMashASTBlock(p).GetType = btIf then begin if TMashASTB_If(p).hasElse then raise Exception.Create( 'Second ''else'' for one ''if'' statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); with TMashASTB_If(p) do begin hasElse := true; self.BlockVect.delete(self.BlockVect.count - 1); self.BlockVect.add(ElseNodes); end; end else raise Exception.Create( 'Unexpected ''else'' at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end else raise Exception.Create( 'Unexpected ''else'' at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; tkFor: Result := self.ExtractFor(token_id, tk); tkWhile: Result := self.ExtractWhile(token_id, false, tk); tkWhilst: Result := self.ExtractWhile(token_id, true, tk); tkReturn: begin Inc(token_id); Result := TMashASTB_Return.Create(self.NextExpr(token_id)); end; tkBreak: begin Inc(token_id); Result := TMashASTB_Break.Create; end; tkContinue: begin Inc(token_id); Result := TMashASTB_Continue.Create; end; tkSwitch: begin Inc(token_id); Result := TMashASTB_Switch.Create(self.NextExpr(token_id)); if self.TkTokenID(self.NextToken(token_id)) = tkBegin then Inc(token_id) else raise Exception.Create( 'Missed '':'' in ''switch'' statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; tkCase: begin Inc(token_id); Result := TMashASTB_Case.Create(self.NextExpr(token_id), false); if self.TkTokenID(self.NextToken(token_id)) = tkBegin then Inc(token_id) else raise Exception.Create( 'Missed '':'' in ''case'' statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; tkDefault: begin Inc(token_id); Result := TMashASTB_Case.Create(nil, true); if self.TkTokenID(self.NextToken(token_id)) = tkBegin then Inc(token_id) else raise Exception.Create( 'Missed '':'' in ''default'' statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; tkLaunch: begin Inc(token_id); Result := TMashASTB_Launch.Create; if self.TkTokenID(self.NextToken(token_id)) = tkBegin then Inc(token_id) else raise Exception.Create( 'Missed '':'' in ''launch'' statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; tkAsync: begin Inc(token_id); Result := TMashASTB_Async.Create( self.TkWordValue(self.NextToken(token_id)) ); Inc(token_id); if self.TkTokenID(self.NextToken(token_id)) = tkBegin then Inc(token_id) else raise Exception.Create( 'Missed '':'' in ''async'' statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; tkWait: begin Inc(token_id); Result := TMashASTB_Wait.Create(self.NextExpr(token_id)); end; tkClass: Result := self.ExtractClass(token_id, tk); tkVar: Result := self.ExtractClassField(token_id); tkPublic, tkProtected, tkPrivate: begin Inc(token_id); if self.TkCheckID(self.Token(token_id)) <> tkBegin then raise Exception.Create( 'Missed '':'' in ''' + tk.value + ''' statement at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); case tk.short of tkPublic: Result := TMashASTB_Public.Create; tkProtected: Result := TMashASTB_Protected.Create; tkPrivate: Result := TMashASTB_Private.Create; end; Inc(token_id); end; tkTry: begin Inc(token_id); if self.TkCheckID(self.NextToken(token_id)) <> tkBegin then raise Exception.Create( 'Missed '':'' in ''try'' statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); Result := TMashASTB_Try.Create; Inc(token_id); end; tkCatch: begin Inc(token_id); p := self.BlockObjectVect[self.BlockObjectVect.count - 1]; if TMashASTBlock(p).GetType <> btTry then raise Exception.Create( 'Unexpected ''catch'' statement at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); if TMashASTB_Try(p).hasCatch then raise Exception.Create( 'Second ''catch'' declaration for one ''try'' statement at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); with TMashASTB_Try(p) do begin hasCatch := true; forVar := self.TkWordValue(self.NextToken(token_id)); self.BlockVect.Delete(self.BlockVect.count - 1); self.BlockVect.Add(NodesCatch); end; Inc(token_id); if self.TkCheckID(self.NextToken(token_id)) <> tkBegin then raise Exception.Create( 'Missed '':'' in ''try'' statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); Inc(token_id); end; tkRaise: begin Inc(token_id); Result := TMashASTB_Raise.Create(self.NextExpr(token_id)); end; {tkSafe: begin Inc(token_id); Result := TMashASTB_Safe.Create(self.NextExpr(token_id)); end; } tkEnum: Result := self.ExtractEnum(token_id, tk); else raise Exception.Create( 'Invalid construction at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; ttDigit, ttString, ttWord: Result := self.NextExpr(token_id); ttEndOfLine: Inc(token_id); end; end; function TMashAST.NextExpr(var token_id: cardinal): TMashASTB_Expression; begin Result := TMashASTB_Expression.Create; self.NextExprTokens(token_id, Result.tokens); TMashASTExpression(Result.ast).Process; end; procedure TMashAST.NextExprTokens(var token_id: cardinal; list: TList); var tk: TMashToken; br_cnt: integer; begin br_cnt := 0; tk := nil; repeat tk := self.Token(token_id); if tk <> nil then if ((tk.short in MashExprTokens) and (tk.info = ttToken)) or (tk.info in [ttWord, ttDigit, ttString]) then begin case tk.short of tkOBr: Inc(br_cnt); tkCBr: Dec(br_cnt); end; if br_cnt < 0 then break; list.add(tk); Inc(token_id); end else break; until tk = nil; end; function TMashAST.NextParam(var token_id: cardinal): TMashASTB_Param; var tk: TMashToken; isEnumerable: boolean; begin isEnumerable := false; tk := self.NextToken(token_id); Inc(token_id); if tk.short = tkORBr then begin tk := self.NextToken(token_id); Inc(token_id); isEnumerable := true; end; if tk.info = ttWord then Result := TMashASTB_Param.Create(tk, isEnumerable) else raise Exception.Create( 'Unexpected token ''' + tk.value + ''' at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); if isEnumerable then begin tk := self.NextToken(token_id); if tk <> nil then begin if tk.short = tkCRBr then Inc(token_id) else raise Exception.Create( 'Unexpected token ''' + tk.value + ''' at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end else raise Exception.Create( 'Unexpected end of code at file ''' + self.lastTk.filep^ + '''.' ); end; end; // Constructions extraction function TMashAST.ExtractMethod(var token_id: cardinal; is_function: boolean; tk: TMashToken): TMashASTB_Method; var method_name: string; is_class_method: boolean; class_name: string; t: TMashToken; begin if self.TkCheckID(self.Token(token_id + 2)) = tkCMSep then begin is_class_method := true; class_name := self.TkWordValue(self.Token(token_id + 1)); method_name := self.TkWordValue(self.Token(token_id + 3)); Inc(token_id, 4); end else begin is_class_method := false; class_name := ''; method_name := self.TkWordValue(self.Token(token_id + 1)); Inc(token_id, 2); end; Result := TMashASTB_Method.Create(is_function, method_name, is_class_method, class_name, tk.line, tk.filep^); if self.TkTokenID(self.NextToken(token_id)) = tkOBr then begin Inc(token_id); while self.TkCheckID(self.NextToken(token_id)) <> tkCBr do begin Result.params.add( self.NextParam(token_id) ); t := self.NextToken(token_id); case self.TkCheckID(t) of tkComma: Inc(token_id); tkCBr:; else raise Exception.Create( 'Unexpected token ''' + t.value + ''' at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); end; end; Inc(token_id); end; if self.TkTokenID(self.Token(token_id)) = tkBegin then Inc(token_id) else raise Exception.Create( 'Missed '':'' at method declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; function TMashAST.ExtractFor(var token_id: cardinal; tk: TMashToken): TMashASTBlock; var forVar: string; isBack: boolean; t: TMashToken; begin Inc(token_id); forVar := self.TkWordValue(self.NextToken(token_id)); Inc(token_id); t := self.TkNotNull(self.NextToken(token_id)); case self.TkTokenID(t) of tkIn: isBack := false; tkBack: isBack := true; else raise Exception.Create( 'Unexpected token ''' + t.value + ''' at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); end; Inc(token_id); Result := TMashASTB_ForEach.Create( forVar, isBack, self.NextExpr(token_id) ); if self.TkCheckID(self.NextToken(token_id)) = tkBegin then Inc(token_id) else raise Exception.Create( 'Missed '':'' in ''for'' statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; function TMashAST.ExtractWhile(var token_id: cardinal; is_whilst: boolean; tk: TMashToken): TMashASTBlock; var t: TMashToken; begin Inc(token_id); if is_whilst then Result := TMashASTB_Whilst.Create(self.NextExpr(token_id)) else Result := TMashASTB_While.Create(self.NextExpr(token_id)); t := self.TkNotNull(self.NextToken(token_id)); if t.short = tkBegin then Inc(token_id) else raise Exception.Create( 'Missed '':'' in while/whilst statement declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; function TMashAST.ExtractClass(var token_id: cardinal; tk: TMashToken): TMashASTB_Class; var t: TMashToken; p: TMashASTB_Param; begin Inc(token_id); Result := TMashASTB_Class.Create(self.TkWordValue(self.NextToken(token_id))); Inc(token_id); if self.TkTokenID(self.NextToken(token_id)) = tkOBr then begin Inc(token_id); while self.TkCheckID(self.NextToken(token_id)) <> tkCBr do begin p := self.NextParam(token_id); Result.class_parents.add(p.param.value); if p.is_enumerable then raise Exception.Create( 'Unexpected token in class declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); t := self.NextToken(token_id); case self.TkCheckID(t) of tkComma: Inc(token_id); tkCBr:; else raise Exception.Create( 'Unexpected token ''' + t.value + ''' at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); end; end; Inc(token_id); end; t := self.TkNotNull(self.NextToken(token_id)); if self.TkTokenID(t) = tkBegin then Inc(token_id) else raise Exception.Create( 'Missed '':'' at class declaration at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); end; function TMashAST.ExtractClassField(var token_id: cardinal): TMashASTB_ClassField; var t: TMashToken; begin Inc(token_id); Result := TMashASTB_ClassField.Create; t := self.NextToken(token_id); while self.TkCheckType(t) = ttWord do begin Result.names.add(t.value); Inc(token_id); t := self.NextToken(token_id); if self.TkCheckID(t) = tkComma then begin Inc(token_id); t := self.TkNotNull(self.NextToken(token_id)); if self.TkCheckType(t) <> ttWord then raise Exception.Create( 'Unexpected token ''' + t.value + ''' at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); end else begin t := self.TkNotNull(self.NextToken(token_id)); if self.TkCheckType(t) = ttWord then raise Exception.Create( 'Unexpected token ''' + t.value + ''' at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); end; end; if Result.names.count = 0 then raise Exception.Create( 'Invalid class field declaration at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); end; function TMashAST.ExtractEnum(var token_id: cardinal; tk:TMashToken): TMashASTB_Enum; var EI: TMashASTB_EnumItem; t: TMashToken; begin Inc(token_id); Result := TMashASTB_Enum.Create(self.TkWordValue(self.NextToken(token_id))); Inc(token_id); if self.TkCheckID(self.NextToken(token_id)) = tkORBr then begin Inc(token_id); while self.TkCheckID(self.NextToken(token_id)) <> tkCRBr do begin EI := TMashASTB_EnumItem.Create(self.TkWordValue(self.NextToken(token_id))); Inc(token_id); if self.TkCheckID(self.NextToken(token_id)) = tkMov then begin Inc(token_id); EI.hasDefValue := true; if self.TkCheckID(self.NextToken(token_id)) = tkSubSym then begin Inc(token_id); t := self.TkNotNull(self.NextToken(token_id)); Inc(token_id); t.value := '-' + self.TkDigitValue(t); EI.DefValue := t; end else begin t := self.TkNotNull(self.NextToken(token_id)); Inc(token_id); if not (t.info in [ttDigit, ttString]) then raise Exception.Create( 'Unexpected token ''' + t.value + ''' at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); EI.DefValue := t; end; end; Result.Nodes.Add(EI); t := self.TkNotNull(self.NextToken(token_id)); case self.TkCheckID(t) of tkCRBr:; tkComma: Inc(token_id); else raise Exception.Create( 'Unexpected token ''' + t.value + ''' at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); end; end; Inc(token_id); end else raise Exception.Create( 'Invalid ''enum'' declaration at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; end.
unit UserApiInterface; interface Const C_GameShareDLLName = 'gameShare.DLL'; {uses UserTypes; function WinGBToBIG5(Source, Destination: PChar; iLen: integer; LanguageType: TLanguageType): WordBool; stdcall; External 'gameShare.DLL'; function WinBIG5ToGB(Source, Destination: PChar; iLen: integer; LanguageType: TLanguageType): WordBool; stdcall; External 'gameShare.DLL'; function LCMAPConvert(Source, Destination: PChar; iLen: integer; LanguageType: TLanguageType): WordBool; stdcall; External 'gameShare.DLL';} function GetProcessID(EXE_Name: PChar): THandle; stdcall; External C_GameShareDLLName; function GetModuleMainFileName(ProcessID: THandle; EXE_Name, ModuleMainFileName:PChar; iLen: Integer): integer; stdcall; External C_GameShareDLLName; function GetProcessMemory(EXE_Name: PChar; Address: LongWord; Buf: Pointer; Len: LongWord): LongWord; stdcall; External C_GameShareDLLName; function SetProcessMemory(EXE_Name: PChar; Address: LongWord; Buf: Pointer; Len: LongWord): LongWord; stdcall; External C_GameShareDLLName; function GetProcessMemoryForID(ProcessID: THandle; Address: LongWord; Buf: Pointer; Len: LongWord): boolean; stdcall; External C_GameShareDLLName; function SetProcessMemoryForID(ProcessID: THandle; Address: LongWord; Buf: Pointer; Len: LongWord): boolean; stdcall; External C_GameShareDLLName; function GetFileVersionInVersionInfo(pFileName, pInfo:PChar; const BufLen:Integer):WordBool; stdcall; External C_GameShareDLLName; implementation end.
unit uMobileUtils; interface uses Windows, uLogger, Graphics, SysUtils, uResourceUtils, Dmitry.Utils.Files, uMemory, Registry, uGUIDUtils, uTranslate, uConstants, acWorkRes, uTime, Classes, Dmitry.Utils.System, uResources; const FSLanguageFileName = 'Language.xml'; FSLicenseFileName = 'License.txt'; type TInternalFSHeader = record Name: string[255]; Size: Int64; end; function CreateMobileDBFilesInDirectory(DestinationName: string): Boolean; procedure UpdateExeResources(ExeFileName: string); function ReadInternalFSContent(Name: string): string; procedure LoadLanguageFromMobileFS(var Language: TLanguage; var LanguageCode: string); procedure AddStyleToMobileEXE(Update: Cardinal); implementation function CreateMobileDBFilesInDirectory(DestinationName: string): Boolean; begin CopyFile(PChar(ParamStr(0)), PChar(DestinationName), False); UpdateExeResources(DestinationName); Result := True; end; procedure UpdateExeResources(ExeFileName: string); var MS: TMemoryStream; LanguageXMLFileName, LicenseTxtFileName: string; Header: TInternalFSHeader; Files: TStrings; Counter: Integer; Update: DWORD; procedure AddFileToStream(FileName: string; Name: string = ''; Content: string = ''); var FS: TFileStream; SW: TStreamWriter; TMS: TMemoryStream; begin TW.I.Check('AddFileToStream: ' + FileName); if Name = '' then Name := ExtractFileName(FileName); if Content <> '' then begin TMS := TMemoryStream.Create; try SW := TStreamWriter.Create(TMS, TEncoding.UTF8); try SW.Write(Content); TMS.Seek(0, soFromBeginning); FillChar(Header, SizeOf(Header), #0); Header.Name := AnsiString(Name); Header.Size := TMS.Size; MS.Write(Header, SizeOf(Header)); MS.CopyFrom(TMS, TMS.Size); finally F(SW); end; finally F(TMS); end; Exit; end; FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try FillChar(Header, SizeOf(Header), #0); Header.Name := AnsiString(Name); Header.Size := FS.Size; FS.Seek(0, soFromBeginning); MS.Write(Header, SizeOf(Header)); MS.CopyFrom(FS, FS.Size); finally F(FS); end; TW.I.Check('AddFileToStream - END: ' + FileName); end; begin TW.I.Check('UpdateExeResources start: ' + ExeFileName); MS := TMemoryStream.Create; Files := TStringList.Create; try AddFileToStream('', 'ID', GUIDToString(GetGUID)); LanguageXMLFileName := ExtractFilePath(ParamStr(0)) + Format('Languages\%s%s.xml', [LanguageFileMask, TTranslateManager.Instance.Language]); AddFileToStream(LanguageXMLFileName, FSLanguageFileName); LicenseTxtFileName := ExtractFilePath(ParamStr(0)) + Format('Licenses\License%s.txt', [TTranslateManager.Instance.Language]); AddFileToStream(LicenseTxtFileName, FSLicenseFileName); TW.I.Check('BeginUpdateResourceW'); Counter := 0; Update := 0; repeat if Counter > 100 then Break; Update := BeginUpdateResourceW(PChar(ExeFileName), False); //in some cases file can be busy (IO error 32), just wait 10sec... if Update = 0 then begin Inc(Counter); Sleep(100); end; until Update <> 0; if Update = 0 then begin MessageBox(0, PChar(Format('An unexpected error occurred: %s', ['I/O Error: ' + IntToStr(GetLastError)])), PChar(TA('Error')), MB_OK + MB_ICONERROR); Exit; end; try TW.I.Check('LoadFileResourceFromStream'); LoadFileResourceFromStream(Update, RT_RCDATA, 'MOBILE_FS', MS); AddStyleToMobileEXE(Update); finally TW.I.Check('EndUpdateResourceW'); EndUpdateResourceW(Update, False); end; finally F(Files); F(MS); end; TW.I.Check('END'); end; procedure AddStyleToMobileEXE(Update: Cardinal); var StyleFileName: string; Reg: TRegistry; FS: TFileStream; MS: TMemoryStream; begin TW.I.Start('LoadLanguageFromFile - START'); Reg := TRegistry.Create(KEY_READ); try Reg.RootKey := Windows.HKEY_CURRENT_USER; Reg.OpenKey(RegRoot + cUserData + 'Style', False); StyleFileName := Reg.ReadString('FileName'); if StyleFileName = '' then StyleFileName := DefaultThemeName; finally F(Reg); end; if StyleFileName <> '' then begin if Pos(':', StyleFileName) = 0 then StyleFileName := ExtractFilePath(ParamStr(0)) + StylesFolder + StyleFileName; try FS := TFileStream.Create(StyleFileName, fmOpenRead, fmShareDenyWrite); try MS := TMemoryStream.Create; try MS.CopyFrom(FS, FS.Size); MS.Seek(0, soFromBeginning); LoadFileResourceFromStream(Update, PChar(StyleResourceSection), 'MOBILE_STYLE', MS); finally F(MS); end; finally F(FS); end; except on e: Exception do EventLog(e); end; end; end; function ReadInternalFSContent(Name: string): string; var MS: TMemoryStream; Header: TInternalFSHeader; SR: TStringStream; begin Result := ''; MS := GetRCDATAResourceStream('MOBILE_FS'); if MS = nil then Exit; try MS.Seek(0, soFromBeginning); while MS.Position <> MS.Size do begin MS.Read(Header, SizeOf(Header)); if AnsiLowerCase(Name) = AnsiLowerCase(string(Header.Name)) then begin SR := TStringStream.Create(Result, TEncoding.UTF8); try SR.CopyFrom(MS, Header.Size); Result := SR.DataString; //Delete UTF8 marker if Result <> '' then Delete(Result, 1, 1); Break; finally F(SR); end; end; MS.Seek(Header.Size, TSeekOrigin.soCurrent); end; finally F(MS); end; end; procedure LoadLanguageFromMobileFS(var Language : TLanguage; var LanguageCode : string); begin Language := TLanguage.CreateFromXML(ReadInternalFSContent(FSLanguageFileName)); LanguageCode := Language.Code; end; end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * 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 ufrmConfig; interface uses LCLIntf, LCLType, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, Buttons, ComCtrls, {Tabnotbk,} uinifile, Dialogs, uFrmMessageBox, ExtCtrls, Spin, ColorBox, uLanguage; type { TfrmConfig } TfrmConfig = class(TForm) bbAcept: TBitBtn; bbCancel: TBitBtn; cbbgcolor: TColorBox; cbbgcolorFPG: TColorBox; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; OpenDialog: TOpenDialog; pcConfig: TPageControl; tsEnviroment: TTabSheet; gbImageEdit: TGroupBox; edProgram: TEdit; bbLocateFile: TBitBtn; gbLanguaje: TGroupBox; edLanguage: TEdit; bbLanguaje: TBitBtn; gbEnviroment: TGroupBox; cbAutoloadImages: TCheckBox; cbFlat: TCheckBox; cbSplash: TCheckBox; lbSizeOfIcon: TLabel; seSizeOfIcon: TSpinEdit; lbPixels: TLabel; gbTimeAnimate: TGroupBox; lbMiliseconds: TLabel; seAnimateDelay: TSpinEdit; cbAutoloadRemove: TCheckBox; cbAlfaNegro: TCheckBox; procedure edSizeIconKeyPress(Sender: TObject; var Key: Char); procedure bbAceptClick(Sender: TObject); procedure bbLocateFileClick(Sender: TObject); procedure bbLanguajeClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure GroupBox1Click(Sender: TObject); procedure Label1Click(Sender: TObject); procedure lbcolorClick(Sender: TObject); procedure seSizeOfIconEnter(Sender: TObject); procedure seSizeOfIconExit(Sender: TObject); procedure seAnimateDelayEnter(Sender: TObject); procedure seAnimateDelayExit(Sender: TObject); procedure edProgramEnter(Sender: TObject); procedure edProgramExit(Sender: TObject); procedure edLanguageEnter(Sender: TObject); procedure edLanguageExit(Sender: TObject); private { Private declarations } _lng_str : string; procedure _set_lng; public { Public declarations } //strinifile : string; end; var frmConfig: TfrmConfig; implementation {$R *.lfm} procedure TfrmConfig._set_lng; begin if _lng_str = inifile_language then Exit; _lng_str := inifile_language; SetDefaultLangByFile(_lng_str); end; procedure TfrmConfig.edSizeIconKeyPress(Sender: TObject; var Key: Char); begin case key of '0' .. '9', chr(8): begin end; else key := chr(13); end; end; procedure TfrmConfig.bbAceptClick(Sender: TObject); begin inifile_sizeof_icon := seSizeOfIcon.Value; inifile_program_edit := edProgram.Text; inifile_animate_delay := seAnimateDelay.Value; inifile_autoload_images := cbAutoLoadImages.Checked; inifile_autoload_remove := cbAutoLoadRemove.Checked; inifile_language := edLanguage.Text; inifile_show_flat := cbFlat.Checked; inifile_show_splash := cbSplash.Checked; inifile_bg_color := cbbgcolor.Selected; inifile_bg_colorFPG := cbbgcolorFPG.Selected; write_inifile; SetDefaultLangByFile(inifile_language); frmConfig.ModalResult := mrYes; end; procedure TfrmConfig.bbLocateFileClick(Sender: TObject); begin OpenDialog.Filter := 'EXE|*.EXE|(*.*)|*.*'; if OpenDialog.Execute then edProgram.Text := OpenDialog.FileName; end; procedure TfrmConfig.bbLanguajeClick(Sender: TObject); var temp : string; begin OpenDialog.Filter := 'PO|*.po|(*.*)|*.*'; OpenDialog.InitialDir := ExtractFileDir(Application.ExeName) + DirectorySeparator+'languages'; if OpenDialog.Execute then begin temp := inifile_language; inifile_language := OpenDialog.FileName; edLanguage.Text := OpenDialog.FileName; end; end; procedure TfrmConfig.FormActivate(Sender: TObject); begin _set_lng; end; procedure TfrmConfig.FormCreate(Sender: TObject); begin end; procedure TfrmConfig.GroupBox1Click(Sender: TObject); begin end; procedure TfrmConfig.Label1Click(Sender: TObject); begin end; procedure TfrmConfig.lbcolorClick(Sender: TObject); begin end; procedure TfrmConfig.seSizeOfIconEnter(Sender: TObject); begin seSizeOfIcon.Color := clWhite; end; procedure TfrmConfig.seSizeOfIconExit(Sender: TObject); begin seSizeOfIcon.Color := clMedGray; end; procedure TfrmConfig.seAnimateDelayEnter(Sender: TObject); begin seAnimateDelay.Color := clWhite; end; procedure TfrmConfig.seAnimateDelayExit(Sender: TObject); begin seAnimateDelay.Color := clMedGray; end; procedure TfrmConfig.edProgramEnter(Sender: TObject); begin edProgram.Color := clWhite; end; procedure TfrmConfig.edProgramExit(Sender: TObject); begin edProgram.Color := clMedGray; end; procedure TfrmConfig.edLanguageEnter(Sender: TObject); begin edLanguage.Color := clWhite; end; procedure TfrmConfig.edLanguageExit(Sender: TObject); begin edLanguage.Color := clMedGray; end; end.
unit PesquisaBase.View; // Herança // Todos os formulários de pesquisa descendem deste formulário. interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Base.View, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, dxBevel, cxControls, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxContainer, cxTextEdit, 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, Base.View.Interf, Tipos.Controller.Interf, cxLabel, dxGDIPlusClasses, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinDarkRoom, dxSkinDarkSide, dxSkinMetropolisDark, dxSkinVisualStudio2013Dark, dxSkinBlack, dxSkinSilver; type TFPesquisaView = class(TFBaseView, IBasePesquisaView) StGrid: TcxStyleRepository; StHeader: TcxStyle; FdDados: TFDMemTable; DsDados: TDataSource; BtDuplicar: TcxButton; BtExcluir: TcxButton; BtConsultar: TcxButton; BtAlterar: TcxButton; BtNovo: TcxButton; VwDados: TcxGridDBTableView; LvDados: TcxGridLevel; DbDados: TcxGrid; StBackground: TcxStyle; StContentOdd: TcxStyle; StContentEven: TcxStyle; StSelection: TcxStyle; PnPesquisa: TPanel; ImPesquisa: TImage; TePesquisa: TcxTextEdit; StInactive: TcxStyle; PnCrud: TPanel; cxLabel2: TcxLabel; cxLabel3: TcxLabel; procedure FdDadosAfterRefresh(DataSet: TDataSet); procedure FormShow(Sender: TObject); procedure VwDadosColumnHeaderClick(Sender: TcxGridTableView; AColumn: TcxGridColumn); procedure BtNovoClick(Sender: TObject); procedure BtAlterarClick(Sender: TObject); procedure BtConsultarClick(Sender: TObject); procedure BtExcluirClick(Sender: TObject); procedure BtDuplicarClick(Sender: TObject); procedure TePesquisaPropertiesChange(Sender: TObject); private procedure listarRegistros; protected FCampoOrdem: string; procedure filtrarRegistros; procedure controlaBotoesAtivos; function removerCaracteresEspeciais(AValue: string): string; public class function New: IBasePesquisaView; function incluirRegistro: IBasePesquisaView; function alterarRegistro: IBasePesquisaView; function consultarRegistro: IBasePesquisaView; function excluirRegistro: IBasePesquisaView; function duplicarRegistro: IBasePesquisaView; procedure &executar; end; var FPesquisaView: TFPesquisaView; implementation {$R *.dfm} { TFPesquisaView } function TFPesquisaView.alterarRegistro: IBasePesquisaView; begin Result := Self; FOperacao := toAlterar; end; procedure TFPesquisaView.BtAlterarClick(Sender: TObject); begin inherited; alterarRegistro; end; procedure TFPesquisaView.BtConsultarClick(Sender: TObject); begin inherited; consultarRegistro; end; procedure TFPesquisaView.BtDuplicarClick(Sender: TObject); begin inherited; duplicarRegistro; end; procedure TFPesquisaView.BtExcluirClick(Sender: TObject); begin inherited; excluirRegistro; end; procedure TFPesquisaView.BtNovoClick(Sender: TObject); begin inherited; incluirRegistro; end; function TFPesquisaView.consultarRegistro: IBasePesquisaView; begin Result := Self; FOperacao := toConsultar; end; procedure TFPesquisaView.controlaBotoesAtivos; begin BtAlterar.Enabled := not(FdDados.IsEmpty); BtConsultar.Enabled := not(FdDados.IsEmpty); BtExcluir.Enabled := not(FdDados.IsEmpty); BtDuplicar.Enabled := not(FdDados.IsEmpty); end; function TFPesquisaView.duplicarRegistro: IBasePesquisaView; begin Result := Self; FOperacao := toDuplicar; end; function TFPesquisaView.excluirRegistro: IBasePesquisaView; begin Result := Self; FOperacao := toExcluir; end; procedure TFPesquisaView.executar; begin Show; end; procedure TFPesquisaView.FdDadosAfterRefresh(DataSet: TDataSet); begin inherited; controlaBotoesAtivos; end; procedure TFPesquisaView.filtrarRegistros; begin FdDados.Filtered := false; if not(TePesquisa.Text = EmptyStr) then begin FdDados.Filter := UpperCase(FCampoOrdem) + ' Like ''%' + AnsiUpperCase(TePesquisa.Text) + '%'''; FdDados.Filtered := True; end; end; procedure TFPesquisaView.FormShow(Sender: TObject); begin inherited; FCampoOrdem := ''; end; function TFPesquisaView.incluirRegistro: IBasePesquisaView; begin Result := Self; FOperacao := toIncluir; end; procedure TFPesquisaView.listarRegistros; begin end; class function TFPesquisaView.New: IBasePesquisaView; begin Result := Self.Create(nil); end; function TFPesquisaView.removerCaracteresEspeciais(AValue: string): string; begin AValue := StringReplace(AValue, ' ', '', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, 'â', 'a', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, 'ã', 'a', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, '/', '', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, 'ç', 'c', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, 'õ', 'o', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, 'í', 'i', [rfReplaceAll, rfIgnoreCase]); Result := AValue; end; procedure TFPesquisaView.TePesquisaPropertiesChange(Sender: TObject); begin inherited; filtrarRegistros; end; procedure TFPesquisaView.VwDadosColumnHeaderClick(Sender: TcxGridTableView; AColumn: TcxGridColumn); begin inherited; FCampoOrdem := removerCaracteresEspeciais(AColumn.Caption); end; end.
unit MinCategoryAdd; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLabel, cxCurrencyEdit, cxControls, cxContainer, cxEdit, cxTextEdit, cxLookAndFeelPainters, ActnList, StdCtrls, cxButtons, cxMaskEdit, cxDropDownEdit, cxCalendar, uFControl, uLabeledFControl, uCharControl, uFloatControl, cxCheckBox, BaseTypes, uIntControl, cxCalc, DB, FIBDataSet, pFIBDataSet, DateUtils; type TfrmMinCatAdd = class(TForm) lblDateEnd: TcxLabel; btnOk: TcxButton; btnCancel: TcxButton; ActList: TActionList; ActOk: TAction; ActCancel: TAction; lblDateBeg: TcxLabel; lblCategory: TcxLabel; CatDateBeg: TcxDateEdit; CatDateEnd: TcxDateEdit; cMinValue: TcxCalcEdit; CheckDates: TpFIBDataSet; procedure ActOkExecute(Sender: TObject); procedure ActCancelExecute(Sender: TObject); private { Private declarations } ModeEdit:Boolean; public { Public declarations } constructor Create(AOwner:TComponent; EditMode:Boolean); function IsPeriodCrossWithOld(DateBeg, DateEnd: TDate):Boolean; end; var frmMinCatAdd: TfrmMinCatAdd; implementation uses MinCategoryMain; {$R *.dfm} constructor TfrmMinCatAdd.Create(AOwner:TComponent; EditMode:Boolean); begin inherited Create(AOwner); if EditMode=False then begin cMinValue.EditValue:=0; CatDateBeg.Date:=EncodeDate(YearOf(Date), MonthOf(Date), 1); CatDateEnd.Date:=EncodeDate(9999, 12, 31); end; ModeEdit:=EditMode; end; function TfrmMinCatAdd.IsPeriodCrossWithOld(DateBeg, DateEnd: TDate):Boolean; begin Result:=False; if ModeEdit=False then begin try CheckDates.Close; CheckDates.SQLs.SelectSQL.Text:='select * '+ ' from sp_min_category s'+ ' where :date_beg between s.date_beg and s.date_end'; CheckDates.ParamByName('date_beg').AsDate:=DateBeg; //CheckDates.ParamByName('date_end').AsDate:=DateEnd; CheckDates.Open; except on e:Exception do agShowMessage(e.Message); end; if CheckDates.IsEmpty then Result:=False else Result:=True; end; end; procedure TfrmMinCatAdd.ActOkExecute(Sender: TObject); begin If (CatDateBeg.Date>CatDateEnd.Date) then begin agMessageDlg('Увага!', 'Дата початку повинна бути менш, ніж дата кінця!', mtInformation, [mbOK]); Exit; end; if IsPeriodCrossWithOld(CatDateBeg.Date, CatDateEnd.Date)=True then begin if agMessageDlg('Підтвердження', 'Вже є запис на цей період! Ви бажаєте закрити старий запис?', mtInformation, [mbYes, mbNo])=mrYes then ModalResult:=mrOk else Exit; end else ModalResult:=mrOk; end; procedure TfrmMinCatAdd.ActCancelExecute(Sender: TObject); begin ModalResult:=mrCancel; end; end.
unit LrBar; interface uses Windows, Classes, Controls, Messages, StdCtrls, ExtCtrls, Forms, Graphics; const cLrDefaultHue = $00EDBA9E; cLrGroupMarginW = 8; type TLrBar = class(TScrollingWinControl) private FColorSkin: TImageList; FGradient: TBitmap; FSpecialGradient: TBitmap; FSkin: TImageList; FSkinHue: TColor; FMargin: Integer; protected procedure SetMargin(const Value: Integer); procedure SetSkin(const Value: TImageList); procedure SetSkinHue(const Value: TColor); protected procedure AdjustClientRect(var Rect: TRect); override; procedure AlignControls(AControl: TControl; var Rect: TRect); override; procedure CreateColorSkin; procedure CreateGradient; procedure InvalidateChildren; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property ColorSkin: TImageList read FColorSkin; published property Align default alLeft; property Color; property Enabled; property Font; property Margin: Integer read FMargin write SetMargin default 16; property Skin: TImageList read FSkin write SetSkin; property SkinHue: TColor read FSkinHue write SetSkinHue default cLrDefaultHue; property Visible; end; // TLrGroupHeader = class(TCustomPanel) private FSpecial: Boolean; FGradient: TBitmap; FBackColor: TColor; FColorSkin: TImageList; FClosed: Boolean; FHot: Boolean; FSpecialFontColor: TColor; procedure SetSpecial(const Value: Boolean); protected procedure SetSpecialFontColor(const Value: TColor); protected procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; procedure PaintBlockHeader; procedure PaintGradientHeader; procedure SelectHeaderRgn; public constructor Create(AOwner: TComponent); override; property BackColor: TColor read FBackColor write FBackColor; property Closed: Boolean read FClosed write FClosed; property ColorSkin: TImageList read FColorSkin write FColorSkin; property Gradient: TBitmap read FGradient write FGradient; property Hot: Boolean read FHot write FHot; property Special: Boolean read FSpecial write SetSpecial; property SpecialFontColor: TColor read FSpecialFontColor write SetSpecialFontColor; end; // TLrGroup = class(TCustomPanel) private FBorderColor: TColor; FClosed: Boolean; FClosedHeight: Integer; FHeader: TLrGroupHeader; FHot: Boolean; FOpenHeight: Integer; FRollup: Integer; FRollupPer: Integer; FSpecial: Boolean; FTimer: TTimer; FMargin: Integer; protected function GetHeaderColor: TColor; function GetHeaderFont: TFont; function GetHeaderHeight: Integer; function GetHeaderParentFont: Boolean; function GetHeaderRect: TRect; function GetHeaderSpecialFontColor: TColor; procedure SetBorderColor(const Value: TColor); procedure SetClosed(const Value: Boolean); procedure SetHeaderColor(const Value: TColor); procedure SetHeaderFont(const Value: TFont); procedure SetHeaderParentFont(const Value: Boolean); procedure SetHeaderSpecialFontColor(const Value: TColor); procedure SetHot(const Value: Boolean); procedure SetMargin(const Value: Integer); procedure SetSpecial(const Value: Boolean); protected procedure AdjustClientRect(var Rect: TRect); override; procedure AlignControls(AControl: TControl; var Rect: TRect); override; function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override; procedure CMControlChange( var Message: TCMControlChange); message CM_CONTROLCHANGE; procedure CreateHeader; procedure CreateTimer; procedure HeaderMouseUp(BSender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure OpenClose; procedure Paint; override; procedure PrepareHeader; procedure Timer(inSender: TObject); public constructor Create(AOwner: TComponent); override; function LrBar: TLrBar; property Hot: Boolean read FHot write SetHot; published property Align; property AutoSize; property BorderColor: TColor read FBorderColor write SetBorderColor default clWhite; property Color; property Caption; property Closed: Boolean read FClosed write SetClosed; property Enabled; property Font; //property Header: TLrGroupHeader read FHeader; property HeaderFont: TFont read GetHeaderFont write SetHeaderFont; property HeaderParentFont: Boolean read GetHeaderParentFont write SetHeaderParentFont; property HeaderSpecialFontColor: TColor read GetHeaderSpecialFontColor write SetHeaderSpecialFontColor default clWhite; property HeaderColor: TColor read GetHeaderColor write SetHeaderColor; property Margin: Integer read FMargin write SetMargin default cLrGroupMarginW; property Special: Boolean read FSpecial write SetSpecial; property Visible; end; implementation uses Math, GraphUtil, LrColor; const cLrHeaderMarginH = 6; // cGradientCount = 3; cGradientIndex = 0; cGlyphIndex = cGradientIndex + cGradientCount; cSpecialOffset = cGlyphIndex + 4; cSpecialGradientIndex = cGradientIndex + cSpecialOffset; cSpecialGlyphIndex = cSpecialGradientIndex + cGradientCount; // cClosedHeight = 25; cAnimSpeed = 5; cTicksToRollup = 8; //cRollupPixels = 8; { TLrGroupHeader } constructor TLrGroupHeader.Create(AOwner: TComponent); begin inherited; DoubleBuffered := true; end; procedure TLrGroupHeader.Paint; var i: Integer; r: TRect; begin Canvas.Brush.Color := BackColor; Canvas.FillRect(ClientRect); // SelectHeaderRgn; PaintGradientHeader; SelectClipRgn(Canvas.Handle, 0); // if (ColorSkin <> nil) then begin i := cGlyphIndex + Ord(Closed) * 2 + Ord(Hot) + Ord(Special) * cSpecialOffset; ColorSkin.Draw(Canvas, ClientWidth - ColorSkin.Width - 3, 1, i) end; // Canvas.Font := Font; if Special then Canvas.Font.Color := SpecialFontColor; if Hot then Canvas.Font.Color := ColorAdjustLuma(ColorToRGB(Canvas.Font.Color), 40, true); // Canvas.Font.Color := ColorSetLum(ColorToRGB(Canvas.Font.Color), 96); // r := ClientRect; OffsetRect(r, cLrGroupMarginW, cLrHeaderMarginH); SetBkMode(Canvas.Handle, Windows.TRANSPARENT); DrawText(Canvas.Handle, PChar(Caption), Length(Caption), r, 0); SetBkMode(Canvas.Handle, OPAQUE); end; procedure TLrGroupHeader.SelectHeaderRgn; var r, rs: HRGN; begin r := CreateRoundRectRgn(0, 0, ClientWidth + 1, ClientHeight, 6, 6); try rs := CreateRectRgn(0, 8, ClientWidth + 1, ClientHeight); try CombineRgn(r, r, rs, RGN_OR); finally DeleteObject(rs); end; SelectClipRgn(Canvas.Handle, r); finally DeleteObject(r); end; end; procedure TLrGroupHeader.PaintBlockHeader; begin Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); end; procedure TLrGroupHeader.PaintGradientHeader; //var // r: TRect; begin // r := ClientRect; // r.Right := r.Right - 26; // Canvas.StretchDraw(r, Gradient) Canvas.StretchDraw(ClientRect, Gradient) end; procedure TLrGroupHeader.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if not Hot then begin Hot := true; Invalidate; end; end; procedure TLrGroupHeader.CMMouseLeave(var Message: TMessage); begin inherited; if Hot then begin Hot := false; Invalidate; end; end; procedure TLrGroupHeader.SetSpecialFontColor(const Value: TColor); begin FSpecialFontColor := Value; Invalidate; end; procedure TLrGroupHeader.SetSpecial(const Value: Boolean); begin FSpecial := Value; Invalidate; end; { TLrGroup } constructor TLrGroup.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [ csAcceptsControls, csOpaque ]; DoubleBuffered := true; FBorderColor := clWhite; FClosedHeight := cClosedHeight; FMargin := cLrGroupMarginW; CreateHeader; CreateTimer; end; procedure TLrGroup.CreateHeader; begin FHeader := TLrGroupHeader.Create(Self); FHeader.Parent := Self; FHeader.OnMouseUp := HeaderMouseUp; FHeader.Cursor := crHandPoint; FHeader.Align := alNone; FHeader.Color := $C45519; FHeader.SpecialFontColor := clWhite; end; procedure TLrGroup.CreateTimer; begin FTimer := TTimer.Create(Self); FTimer.Enabled := False; FTimer.Interval := cAnimSpeed; FTimer.OnTimer := Timer; end; function TLrGroup.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; var i, b: Integer; begin if not FTimer.Enabled then begin b := 0; for i := 0 to Pred(ControlCount) do b := Max(b, Controls[i].BoundsRect.Bottom); NewHeight := b + cLrHeaderMarginH; end; Result := true; end; function TLrGroup.GetHeaderHeight: Integer; begin Canvas.Font := Font; Result := Canvas.TextHeight('W') + cLrHeaderMarginH + cLrHeaderMarginH; end; function TLrGroup.GetHeaderRect: TRect; begin Result := Rect(0, 0, ClientWidth, GetHeaderHeight); end; procedure TLrGroup.AdjustClientRect(var Rect: TRect); begin inherited; InflateRect(Rect, -Margin, -GetHeaderHeight - 4); Rect.Top := Rect.Top - FRollup; end; procedure TLrGroup.AlignControls(AControl: TControl; var Rect: TRect); begin inherited; FHeader.SetBounds(0, 0, ClientWidth, GetHeaderHeight); end; procedure TLrGroup.CMControlChange(var Message: TCMControlChange); begin inherited; with Message do if Inserting then with Control do Align := alTop; end; procedure TLrGroup.PrepareHeader; begin if Parent <> nil then FHeader.BackColor := TLabel(Parent).Color; FHeader.Caption := Caption; FHeader.Closed := Closed; //FHeader.Color := HeadColor; FHeader.Special := Special; if LrBar = nil then begin FHeader.ColorSkin := nil; FHeader.Gradient := nil end else begin FHeader.ColorSkin := LrBar.ColorSkin; if Special then FHeader.Gradient := LrBar.FSpecialGradient else FHeader.Gradient := LrBar.FGradient; end; end; procedure TLrGroup.Paint; begin PrepareHeader; Canvas.Pen.Color := BorderColor; if LrBar <> nil then Color := ColorSetLum(LrBar.SkinHue, 232); Canvas.Brush.Color := Color; Canvas.Rectangle(ClientRect); end; procedure TLrGroup.SetBorderColor(const Value: TColor); begin FBorderColor := Value; Invalidate; end; procedure TLrGroup.SetSpecial(const Value: Boolean); begin FSpecial := Value; FHeader.Invalidate; Invalidate; end; function TLrGroup.LrBar: TLrBar; begin Result := TLrBar(Parent); end; procedure TLrGroup.OpenClose; begin FTimer.Enabled := true; if not Closed then begin FOpenHeight := Height; FRollupPer := Max(1, Height div cTicksToRollup); end; FClosed := not FClosed; end; procedure TLrGroup.HeaderMouseUp(BSender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin OpenClose; end; procedure TLrGroup.SetClosed(const Value: Boolean); begin if FClosed <> Value then begin FHeader.Invalidate; OpenClose; end; end; procedure TLrGroup.SetHot(const Value: Boolean); begin if FHot <> Value then begin FHot := Value; FHeader.Invalidate; Invalidate; end; end; procedure TLrGroup.Timer(inSender: TObject); begin if Closed then begin if Height > FClosedHeight then begin Inc(FRollup, FRollupPer); //cRollupPixels); Height := Max(FClosedHeight, Height - FRollupPer); //cRollupPixels); end else begin FTimer.Enabled := false; //FRollup := OpenHeight - FRollup; end; end else begin if Height < FOpenHeight then begin FRollup := Max(0, FRollup - FRollupPer); //cRollupPixels); Height := Min(FOpenHeight, Height + FRollupPer); //cRollupPixels); end else begin FTimer.Enabled := false; FRollup := 0; Realign; end; end; end; function TLrGroup.GetHeaderColor: TColor; begin Result := FHeader.Color; end; function TLrGroup.GetHeaderFont: TFont; begin Result := FHeader.Font; end; function TLrGroup.GetHeaderParentFont: Boolean; begin Result := FHeader.ParentFont; end; function TLrGroup.GetHeaderSpecialFontColor: TColor; begin Result := FHeader.SpecialFontColor; end; procedure TLrGroup.SetHeaderColor(const Value: TColor); begin FHeader.Color := Value; end; procedure TLrGroup.SetHeaderFont(const Value: TFont); begin FHeader.Font.Assign(Value); end; procedure TLrGroup.SetHeaderParentFont(const Value: Boolean); begin FHeader.ParentFont := Value; end; procedure TLrGroup.SetHeaderSpecialFontColor(const Value: TColor); begin FHeader.SpecialFontColor := Value; end; procedure TLrGroup.SetMargin(const Value: Integer); begin FMargin := Value; if not (csLoading in ComponentState) then begin //FHeader.Invalidate; Invalidate; Realign; end; end; { TLrBar } constructor TLrBar.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [ csAcceptsControls ]; Align := alLeft; SkinHue := cLrDefaultHue; FMargin := 16; end; destructor TLrBar.Destroy; begin ColorSkin.Free; FGradient.Free; FSpecialGradient.Free; inherited; end; procedure TLrBar.CreateColorSkin; var b: TBitmap; i, x, y: Integer; begin if Skin = nil then exit; if ColorSkin = nil then FColorSkin := TImageList.CreateSize(23, 23); ColorSkin.Clear; b := TBitmap.Create; with b do try Width := Skin.Width; Height := Skin.Height; for i := 0 to Pred(Skin.Count) do begin Skin.GetBitmap(i, b); for y := 0 to Pred(Height) do for x := 0 to Pred(Width) do Canvas.Pixels[x, y] := Colorize(Canvas.Pixels[x, y], SkinHue); ColorSkin.Add(b, nil); end; finally b.Free; end; end; procedure TLrBar.CreateGradient; const cGW = 23; var i, w: Integer; di: Single; begin if ColorSkin <> nil then w := ColorSkin.Width else w := cGW; // if FGradient = nil then begin FGradient := TBitmap.Create; FGradient.Width := w * cGradientCount; FGradient.Height := w; FGradient.PixelFormat := pf24Bit; FSpecialGradient := TBitmap.Create; FSpecialGradient.Width := w * cGradientCount; FSpecialGradient.Height := w; FSpecialGradient.PixelFormat := pf24Bit; end; // if (ColorSkin <> nil) then with ColorSkin do for i := 0 to Pred(cGradientCount) do begin Draw(FGradient.Canvas, w*i, 0, cGradientIndex+i); Draw(FSpecialGradient.Canvas, w*i, 0, cSpecialGradientIndex+i); end else begin for i := 0 to Pred(FGradient.Width) do begin di := i / cGW; di := di * di * di; FGradient.Canvas.Pixels[i, 0] := ((255 - Round(di * 8)) shl 16) + ((255 - Round(di * 42)) shl 8) + (255 - Round(di * 55)); FSpecialGradient.Canvas.Pixels[i, 0] := (255 shl 16) + (Round(di * 42) shl 8) + Round(di * 55); end; end; end; procedure TLrBar.AdjustClientRect(var Rect: TRect); begin inherited; InflateRect(Rect, -Margin, -Margin); end; procedure TLrBar.AlignControls(AControl: TControl; var Rect: TRect); var r: TRect; t, w, i: Integer; begin r := ClientRect; AdjustClientRect(r); t := r.Top; // w := ClientWidth - Margin - Margin; // for i := 0 to Pred(ControlCount) do with Controls[i] do begin SetBounds(Margin, t, w, Height); if Visible then Inc(t, Height + Margin); end; end; procedure TLrBar.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) then if AComponent = FSkin then FSkin := nil; end; procedure TLrBar.SetSkin(const Value: TImageList); begin if FSkin <> nil then FSkin.RemoveFreeNotification(Self); FSkin := Value; if FSkin <> nil then begin FSkin.FreeNotification(Self); CreateColorSkin; CreateGradient; end; Invalidate; InvalidateChildren; end; procedure TLrBar.SetSkinHue(const Value: TColor); begin FSkinHue := Value; if not (csLoading in ComponentState) then begin Color := ColorSetLum(Value, 166); CreateColorSkin; CreateGradient; Invalidate; InvalidateChildren; end; end; procedure TLrBar.InvalidateChildren; var i: Integer; begin for i := 0 to Pred(ControlCount) do Controls[i].Invalidate; end; procedure TLrBar.SetMargin(const Value: Integer); begin FMargin := Value; Invalidate; Realign; end; end.
unit ListDefine; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, Ora, MemDS, VirtualTable, Grids, DBGridEh, StdCtrls, Buttons, ExtCtrls, uImportFunc, Menus, GridsEh, DBGridEhGrouping, DBAccess; type TListDefineForm = class(TForm) VirtualTable: TVirtualTable; VirtualTableVALUE: TStringField; VirtualTableID: TIntegerField; VirtualTableINST: TIntegerField; VirtualTableNAME: TStringField; pBottom: TPanel; pBtn: TPanel; bbOk: TBitBtn; bbCancel: TBitBtn; pnlGrid: TPanel; Grid: TDBGridEh; ds: TOraDataSource; pm: TPopupMenu; miNotUse: TMenuItem; procedure bbOkClick(Sender: TObject); procedure GridEditButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure miNotUseClick(Sender: TObject); procedure VirtualTableBeforePost(DataSet: TDataSet); private FDefined: boolean; FDataType: TOilDataType; FExeLinkProgram: integer; FParamDataSet: TDataSet; FParamInField: string; FParamOutFields: TStringList; FPossibleFields: array[0..2] of string; FStoreDefineUnit: TStoreDefineUnit; procedure Init; procedure Save; procedure Test; procedure SetDataType(const Value: TOilDataType); public { Пример: TListDefineForm.Create(odtOrg, Query, 'IMPORT_NAME', ['ID', 'ORG_ID', 'INST', 'ORG_INST', 'NAME', 'ORG_NAME'], 6); } class function CreateEx(ADataType: TOilDataType; AParamDataSet: TDataSet; AParamInField: string; AParamOutFields: array of variant; AExeLinkProgram: integer = 0): TListDefineForm; destructor Destory; class function Define(AQuiet: boolean; ADataType: TOilDataType; ATable: TVirtualTable; AFileName: string): boolean; procedure LoadFromFile(AFilePath: string); procedure SaveToFile(AFilePath: string); property Defined: boolean read FDefined; property DataType: TOilDataType read FDataType write SetDataType; property ExeLinkProgram: integer read FExeLinkProgram; property ParamDataSet: TDataSet read FParamDataSet; property ParamInField: string read FParamInField; property ParamOutFields: TStringList read FParamOutFields; end; var ListDefineForm: TListDefineForm; implementation uses NPTypeRef, uXMLForm, ChooseOrg, Main, ExFunc, UDbFunc, OperTypeRef; {$R *.dfm} { TListCompareForm } class function TListDefineForm.CreateEx(ADataType: TOilDataType; AParamDataSet: TDataSet; AParamInField: string; AParamOutFields: array of variant; AExeLinkProgram: integer = 0): TListDefineForm; var i: integer; ListForm: TListDefineForm; begin ListForm := TListDefineForm.Create(nil); ListForm.DataType := ADataType; ListForm.FParamDataSet := AParamDataSet; ListForm.FParamInField := AParamInField; ListForm.FParamOutFields := TStringList.Create; ListForm.FExeLinkProgram := AExeLinkProgram; if high(AParamOutFields) mod 2 = 0 then raise Exception.Create('TListDefineForm: нечетное число элементов в AParamOutFields'); for i := 0 to (high(AParamOutFields) div 2) do ListForm.FParamOutFields.Values[AParamOutFields[i*2]] := AParamOutFields[i*2+1]; Result := ListForm; end; procedure TListDefineForm.Init; var i, j: integer; IsFound: boolean; pk: TPrimaryKey; begin FPossibleFields[0] := 'ID'; FPossibleFields[1] := 'INST'; FPossibleFields[2] := 'NAME'; // Проверка на правильно переданые параметры for i := 0 to ParamOutFields.Count - 1 do begin IsFound := False; for j := low(FPossibleFields) to high(FPossibleFields) do begin if ParamOutFields.Names[i] = FPossibleFields[j] then IsFound := True; end; if not IsFound then raise Exception.CreateFmt('Неизвестный параметр %s',[ParamOutFields.ValueFromIndex[i]]); end; // Переносим данные FStoreDefineUnit.UserMode := False; VirtualTable.Open; ParamDataSet.DisableControls; try FDefined := True; ParamDataSet.First; while not ParamDataSet.Eof do begin VirtualTable.Append; VirtualTable.FieldByName('VALUE').AsString := ParamDataSet.FieldByName(ParamInField).AsString; // Автоподбор данных try pk := FStoreDefineUnit.GetLink(ParamDataSet.FieldByName(ParamInField).AsString,ExeLinkProgram,MAIN_ORG.Inst).AsPrimaryKey; VirtualTable.FieldByName('ID').AsInteger := pk.Id; VirtualTable.FieldByName('INST').AsInteger := pk.Inst; VirtualTable.FieldByName('NAME').AsString := nvl(GetQValueByIdInst('NAME', DefineTableArray[DataType], pk.Id, pk.Inst),''); except on E: ENoDataFound do FDefined := False; on E: Exception do raise; end; VirtualTable.Post; ParamDataSet.Next; end; finally ParamDataSet.EnableControls; end; end; procedure TListDefineForm.Save; var i: integer; begin VirtualTable.DisableControls; ParamDataSet.DisableControls; VirtualTable.Filtered := False; VirtualTable.First; try // Переносим значения обратно while not VirtualTable.Eof do begin // Сохраняем данные в структуру if VirtualTable.FieldByName('NAME').AsString <> '' then begin FStoreDefineUnit.SetLink( VirtualTable.FieldByName('VALUE').AsString, 0, TDefineResult.Create(VirtualTable.FieldByName('ID').AsInteger,VirtualTable.FieldByName('INST').AsInteger)); end; ParamDataSet.Filtered := False; if VirtualTable.FieldByName('VALUE').AsString = '' then ParamDataSet.Filter := Format(' %s = null ',[ParamInField]) else ParamDataSet.Filter := Format(' %s = %s',[ParamInField, QuotedStr(VirtualTable.FieldByName('VALUE').AsString)]); ParamDataSet.Filtered := True; if ParamDataSet.IsEmpty then raise Exception.Create('Не найдено значение поля NAME для возврата'); ParamDataSet.Edit; for i := low(FPossibleFields) to high(FPossibleFields) do if ParamDataSet.Fields.FindField(ParamOutFields.Values[FPossibleFields[i]]) <> nil then ParamDataSet.FieldByName(ParamOutFields.Values[FPossibleFields[i]]).Value := VirtualTable.FieldByName(FPossibleFields[i]).Value; ParamDataSet.Post; VirtualTable.Next; end; finally ParamDataSet.Filtered := False; ParamDataSet.EnableControls; VirtualTable.EnableControls; end; end; procedure TListDefineForm.Test; begin VirtualTable.Filtered := False; VirtualTable.Filter := 'NAME = '''' '; VirtualTable.Filtered := True; if not VirtualTable.IsEmpty then raise Exception.Create('Не все поля заполнены!'); end; procedure TListDefineForm.bbOkClick(Sender: TObject); begin Test; Save; ModalResult := mrOk; end; procedure TListDefineForm.GridEditButtonClick(Sender: TObject); var vName: string; vId, vInst: integer; OTR: TOperTypeRefForm; begin if Grid.SelectedField.FieldName = 'NAME' then begin case DataType of odtNpGroup: begin if XMLChoose('npgroupref',vId,vName) then begin VirtualTable.Edit; VirtualTable.FieldByName('ID').AsInteger := vId; VirtualTable.FieldByName('NAME').AsString := vName; VirtualTable.Post; end; end; odtNpType: begin TNPTypeRefForm.Choose(VirtualTable.FieldByName('ID'), VirtualTable.FieldByName('NAME')); end; odtAZS: begin if ChooseOrg.CaptureOrg(2,Main_id,Main_id,'yyy',vId,vInst,vName) then begin VirtualTable.Edit; VirtualTable.FieldByName('ID').AsInteger := vId; VirtualTable.FieldByName('INST').AsInteger := vInst; VirtualTable.FieldByName('NAME').AsString := vName; VirtualTable.Post; end; end; odtOrg: begin if ChooseOrg.CaptureOrg(3,Main_id,Inst,'yyy',vId,vInst,vName) then begin VirtualTable.Edit; VirtualTable.FieldByName('ID').AsInteger := vId; VirtualTable.FieldByName('INST').AsInteger := vInst; VirtualTable.FieldByName('NAME').AsString := vName; VirtualTable.Post; end; end; odtOper: begin Application.CreateForm(TOperTypeRefForm, OTR); try OTR.ShowModal; if OTR.ModalResult = mrOk then begin VirtualTable.Edit; VirtualTable.FieldByName('ID').AsInteger := OTR.q.fieldbyname('ID').AsInteger; VirtualTable.FieldByName('NAME').AsString := OTR.q.fieldbyname('NAME').AsString; VirtualTable.Post; end; finally OTR.Free; end; end else raise Exception.Create('Неудалось распознать тип данных'); end; end; end; destructor TListDefineForm.Destory; begin if Assigned(FStoreDefineUnit) then FStoreDefineUnit.Free; inherited; end; procedure TListDefineForm.LoadFromFile(AFilePath: string); begin FStoreDefineUnit.LoadFromFile(AFilePath); end; procedure TListDefineForm.SaveToFile(AFilePath: string); begin FStoreDefineUnit.SaveToFile(AFilePath); end; procedure TListDefineForm.SetDataType(const Value: TOilDataType); begin FDataType := Value; if Assigned(FStoreDefineUnit) then FStoreDefineUnit.Free; FStoreDefineUnit := TStoreDefineUnit.Create(Value); end; procedure TListDefineForm.FormShow(Sender: TObject); begin Init; end; class function TListDefineForm.Define(AQuiet: boolean; ADataType: TOilDataType; ATable: TVirtualTable; AFileName: string): boolean; var ListDefine: TListDefineForm; begin Result := False; ListDefine := TListDefineForm.CreateEx(ADataType, ATable, 'VALUE', ['ID', 'ALIAS'], 6); try if FileExists(GetMainDir+AFileName) then ListDefine.LoadFromFile(GetMainDir+AFileName); if AQuiet then begin ListDefine.Init; if ListDefine.Defined then Result := True; ListDefine.Save; ListDefine.SaveToFile(GetMainDir+AFileName); end else if ListDefine.ShowModal = mrOk then begin Result := True; ListDefine.SaveToFile(GetMainDir+AFileName); end; finally ListDefine.Free; end; end; procedure TListDefineForm.miNotUseClick(Sender: TObject); begin VirtualTable.Edit; VirtualTable.FieldByName('ID').AsInteger := -1; if DefineKeyCountArray[DataType] = 2 then VirtualTable.FieldByName('INST').AsInteger := -1; VirtualTable.Post; end; procedure TListDefineForm.VirtualTableBeforePost(DataSet: TDataSet); begin if VirtualTable.FieldByName('ID').AsInteger = -1 then VirtualTable.FieldByName('NAME').AsString := 'Не использовать'; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2011 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit SampleAppTypeFrameUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, SampleExpertTypes; type TApplicationTypeFrame = class(TFrame) RadioButtonVCLApplication: TRadioButton; RadioButtonConsoleApplication: TRadioButton; procedure RadioButtonVCLApplicationClick(Sender: TObject); private FOnApplicationTypeChange: TNotifyEvent; function GetApplicationType: TSampleApplicationType; procedure SetApplicationType(AType: TSampleApplicationType); { Private declarations } public { Public declarations } property OnApplicationTypeChange: TNotifyEvent read FOnApplicationTypeChange write FOnApplicationTypeChange; property ApplicationType: TSampleApplicationType read GetApplicationType write SetApplicationType; end; implementation {$R *.dfm} function TApplicationTypeFrame.GetApplicationType: TSampleApplicationType; begin if RadioButtonVCLApplication.Checked then Exit(appVCL) else if RadioButtonConsoleApplication.Checked then Exit(appConsole) else raise Exception.Create('Unexpected'); end; procedure TApplicationTypeFrame.SetApplicationType(AType: TSampleApplicationType); begin case AType of appVCL: RadioButtonVCLApplication.Checked := True; appConsole: RadioButtonConsoleApplication.Checked := True; else raise Exception.Create('Unexpected'); end; end; procedure TApplicationTypeFrame.RadioButtonVCLApplicationClick(Sender: TObject); begin if Assigned(FOnApplicationTypeChange) then FOnApplicationTypeChange(Self); end; end.
unit M_wads; interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, FileCtrl, ExtCtrls, Dialogs, SysUtils, IniFiles, M_Global, _files, _strings, M_Util, M_MapUt, G_Util, W_Util, M_WadMap, M_Progrs, M_Multi, M_mapfun, M_Editor, M_WadsUt, M_IO; TYPE {linedef action description} TLDA_DESC = record act : Char; {action type} elev : String; {elevator type} master : Boolean; {master at start} event : Char; {event mask} rep : Char; {repeatability} trig : Char; {trigger action} stops : String; {nb of stop / Variable} first : string; {first stop} next : string; {next stop} speed : Integer; {speed REFERENCE} hold : Integer; {-1 for hold, or hold time} spec : String; {specials e.g. keys, crush bits, ...} desc : String; {textual description} end; TYPE {things description} TTH_DESC = record debug : String; {Y/N} dfclas : String; dfdata : String; logic : String; duplic : Integer; spec : String; {specials e.g. keys, crush bits, ...} dmclas : String; dmroot : String; desc : String; {textual description} end; procedure DO_LoadWAD(TheWAD : TFileName); procedure DO_LoadWADMap(TheWAD : TFileName; TheMAP : String); procedure DO_ReadWADSectors(wf : Integer; numsectors : LongInt); procedure DO_ReadWADVertexes(wf : Integer; numvertexes : LongInt); procedure DO_ReadWADLinedefs(wf : Integer; numlinedefs : LongInt); procedure DO_ReadWADSidedefs(wf : Integer; numsidedefs : LongInt); procedure DO_ReadWADThings(wf : Integer; numthings : LongInt); procedure DO_ConvertSectors; procedure DO_RecreateDiscarded; procedure DO_CorrectSectors; procedure DO_ConvertSectorFlags(TheMAP : String); procedure DO_ConvertWallFlags; procedure DO_NameSectors; procedure DO_AllAdjoins; procedure DO_Texturing; procedure DO_FlagDoors; procedure DO_ConvertLinedefActions; procedure DO_ConvertLinedefSpecialActions; procedure DO_CreateTrueSectorLights; procedure DO_CreateSectorLights; procedure DO_Create_30_300_Specials; procedure DO_CreateSectorFloorAnims; procedure DO_CreateSectorCeilingAnims; procedure Do_ConvertThings; procedure DO_CreateListForAlex; procedure DO_InitWadINF; procedure WI_CR; procedure WI_COMMENT(s : String); procedure WI_ITEMSECTOR(s : String); procedure WI_ITEMLINE(s : String; num : Integer); procedure WI_SEQ; procedure WI_CLASS(s : String); procedure WI_MASTEROFF; procedure WI_EVENTMASK(s : String); procedure WI_MESSAGE(s : String); procedure WI_ENTITYMASK(s : String); procedure WI_STOP(s : String); procedure WI_SPEED(s : String); procedure WI_OTHER(s : String); procedure WI_KEY(s : String); procedure WI_CLIENT(s : String); procedure WI_SLAVE(s : String); procedure WI_SEQEND; procedure DO_WriteWadINF; procedure DO_CreateDummySector(name : String); function GetLineActionData(num : Integer; VAR lda : TLDA_DESC) : Boolean; function GetThingData(num : Integer; VAR thd : TTH_DESC) : Boolean; function DOOM_GetOBColor(thing : String) : LongInt; procedure DOOM_FillLogic(thing : String); VAR WAD_CNVRTLOG : TStringList; WAD_VERTEXES : TStringList; WAD_LINEDEFS : TStringList; WAD_SIDEDEFS : TStringList; WAD_THINGS : TStringList; WAD_INF : TStringList; ElevMade : TStringList; DiscardedLD : TStringList; WAD_INF_ITEMS : Integer; WAD_INF_ADDS : Integer; WAD_INF_TRGS : Integer; WAD_INF_ADJS : Integer; WAD_INF_DONS : Integer; TheSky : String; TmpSeqs : TStringList; IWAD : String; W2GSWITCHES : String; implementation uses Mapper; procedure DO_LoadWAD(TheWAD : TFileName); var SelMap : String; begin SelMap := ''; {get data from ini} MapSelectWindow.ED_Doom.Text := Ini.ReadString('WAD CONVERSION', 'Doom', ''); MapSelectWindow.ED_Doom2.Text := Ini.ReadString('WAD CONVERSION', 'Doom2', ''); MapSelectWindow.ED_W2GSwitches.Text := Ini.ReadString('WAD CONVERSION', 'W2Gsw', ''); GetWADMaps(TheWAD, MapSelectWindow.WadDirList.Items); if MapSelectWindow.WadDirList.Items.Count <> 0 then if Copy(MapSelectWindow.WadDirList.Items[0],1,3) = 'MAP' then MapSelectWindow.RGIwad.ItemIndex := 1 else MapSelectWindow.RGIwad.ItemIndex := 0; MapSelectWindow.ShowModal; if MapSelectWindow.ModalResult = mrOk then begin {save data to ini} Ini.WriteString('WAD CONVERSION', 'Doom', MapSelectWindow.ED_Doom.Text); Ini.WriteString('WAD CONVERSION', 'Doom2', MapSelectWindow.ED_Doom2.Text); Ini.WriteString('WAD CONVERSION', 'W2Gsw', MapSelectWindow.ED_W2GSwitches.Text); if MapSelectWindow.RGIwad.ItemIndex = 0 then IWAD := MapSelectWindow.ED_Doom.Text else IWAD := MapSelectWindow.ED_Doom2.Text; W2GSWITCHES := MapSelectWindow.ED_W2GSwitches.Text; SelMap := MapSelectWindow.WadDirList.Items[MapSelectWindow.WadDirList.ItemIndex]; if SelMap <> '' then DO_LoadWADMap(TheWAD, SelMap); end; end; procedure DO_LoadWADMap(TheWAD : TFileName; TheMAP : String); var numSECTORS, numVERTEXES, numLINEDEFS, numSIDEDEFS, numTHINGS : Integer; wf : Integer; sectors_ix : LongInt; sectors_len : LongInt; vertexes_ix : LongInt; vertexes_len : LongInt; linedefs_ix : LongInt; linedefs_len : LongInt; sidedefs_ix : LongInt; sidedefs_len : LongInt; things_ix : LongInt; things_len : LongInt; OldCursor : HCursor; tmp : array[0..127] of char; begin {first do some checks / initializations with the WAD file} if not GetWADEntryInfo(TheWAD, TheMAP, 'SECTORS', sectors_ix, sectors_len) then begin Application.MessageBox('Invalid WAD file (cannot find SECTORS entry)', 'WDFUSE Mapper - NEW Project', mb_Ok or mb_IconExclamation); exit; end; if not GetWADEntryInfo(TheWAD, TheMAP, 'VERTEXES', vertexes_ix, vertexes_len) then begin Application.MessageBox('Invalid WAD file (cannot find VERTEXES entry)', 'WDFUSE Mapper - NEW Project', mb_Ok or mb_IconExclamation); exit; end; if not GetWADEntryInfo(TheWAD, TheMAP, 'LINEDEFS', linedefs_ix, linedefs_len) then begin Application.MessageBox('Invalid WAD file (cannot find LINEDEFS entry)', 'WDFUSE Mapper - NEW Project', mb_Ok or mb_IconExclamation); exit; end; if not GetWADEntryInfo(TheWAD, TheMAP, 'SIDEDEFS', sidedefs_ix, sidedefs_len) then begin Application.MessageBox('Invalid WAD file (cannot find SIDEDEFS entry)', 'WDFUSE Mapper - NEW Project', mb_Ok or mb_IconExclamation); exit; end; if not GetWADEntryInfo(TheWAD, TheMAP, 'THINGS', things_ix, things_len) then begin Application.MessageBox('Invalid WAD file (cannot find THINGS entry)', 'WDFUSE Mapper - NEW Project', mb_Ok or mb_IconExclamation); exit; end; WAD_CNVRTLOG := TStringList.Create; WAD_CNVRTLOG.Add('Converting ' + TheWad + ' ' + TheMap); OldCursor := SetCursor(LoadCursor(0, IDC_WAIT)); ProgressWindow.Progress1.Caption := 'Converting WAD File'; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Gauge.MinValue := 0; ProgressWindow.Gauge.MaxValue := 0; ProgressWindow.Show; ProgressWindow.Update; {! To initializations done in IO_ReadLEV O and INF } LAYER_MIN := 0; LAYER_MAX := 0; MAP_SEC := TStringList.Create; WAD_VERTEXES := TStringList.Create; WAD_LINEDEFS := TStringList.Create; WAD_SIDEDEFS := TStringList.Create; WAD_THINGS := TStringList.Create; TX_LIST := TStringList.Create; MAP_OBJ := TStringList.Create; POD_LIST := TStringList.Create; SPR_LIST := TStringList.Create; FME_LIST := TStringList.Create; SND_LIST := TStringList.Create; DiscardedLD := TStringList.Create; wf := FileOpen(TheWAD, fmOpenRead); numSECTORS := sectors_len div WAD_SIZE_SECTOR; FileSeek(wf, sectors_ix, 0); DO_ReadWADSectors(wf, numSECTORS); WAD_CNVRTLOG.Add(''); WAD_CNVRTLOG.Add('SECTORS : ' + IntToStr(numSECTORS)); numVERTEXES := vertexes_len div WAD_SIZE_VERTEX; FileSeek(wf, vertexes_ix, 0); DO_ReadWADVertexes(wf, numVERTEXES); WAD_CNVRTLOG.Add('VERTEXES : ' + IntToStr(numVERTEXES)); numLINEDEFS := linedefs_len div WAD_SIZE_LINEDEF; FileSeek(wf, linedefs_ix, 0); DO_ReadWADLinedefs(wf, numLINEDEFS); WAD_CNVRTLOG.Add('LINEDEFS : ' + IntToStr(numLINEDEFS)); numSIDEDEFS := sidedefs_len div WAD_SIZE_SIDEDEF; FileSeek(wf, sidedefs_ix, 0); DO_ReadWADSidedefs(wf, numSIDEDEFS); WAD_CNVRTLOG.Add('SIDEDEFS : ' + IntToStr(numSIDEDEFS)); numTHINGS := things_len div WAD_SIZE_THING; FileSeek(wf, things_ix, 0); DO_ReadWADThings(wf, numTHINGS); WAD_CNVRTLOG.Add('THINGS : ' + IntToStr(numTHINGS)); WAD_CNVRTLOG.Add(''); WAD_CNVRTLOG.Add('*** Convert Sectors'); DO_ConvertSectors; {create the "bad" linedefs as new sectors, then free them} WAD_CNVRTLOG.Add('*** Recreate discarded linedefs as "thin sectors"'); DO_RecreateDiscarded; DiscardedLD.Free; WAD_CNVRTLOG.Add('*** Delete Unreferenced Sectors'); DO_CorrectSectors; {this will delete sectors without walls or vertices} WAD_CNVRTLOG.Add('*** Convert Sector Flags'); DO_ConvertSectorFlags(TheMAP); WAD_CNVRTLOG.Add('*** Convert Linedef Flags'); DO_ConvertWallFlags; DO_CreateDummySector('complete'); DO_NameSectors; DOOM := TRUE; SetDOOMEditors; OFILELoaded := TRUE; MODIFIED := TRUE; {different here 'cause the conversion IS a modif :-)} BACKUPED := FALSE; LEV_LEVELNAME := 'SECBASE'; LEV_PALETTE := 'SECBASE.PAL'; LEV_MUSIC := 'NOTUSED.GMD'; LEV_PARALLAX1 := 1024; LEV_PARALLAX2 := 1024; LEV_VERSION := '2.1'; O_LEVELNAME := 'SECBASE'; O_VERSION := '1.1'; Xoffset := 0; Zoffset := 0; Scale := 1; ScreenX := MapWindow.Map.Width; ScreenZ := MapWindow.Map.Height; ScreenCenterX := MapWindow.Map.Width div 2; ScreenCenterZ := MapWindow.Map.Height div 2; MAP_RECT.Left := 0; MAP_RECT.Right := MapWindow.Map.Width; MAP_RECT.Top := 0; MAP_RECT.Bottom := MapWindow.Map.Height; MapWindow.PanelLevelName.Caption := LEVELName; LEVELLoaded := TRUE; DO_SetMapButtonsState; DO_Center_Map; MAP_MODE := MM_VX; DO_Switch_To_SC_Mode; WAD_CNVRTLOG.Add('*** Create Adjoins'); DO_AllAdjoins; WAD_CNVRTLOG.Add('*** Convert Texturing'); DO_Texturing; {DO_FlagDoors;} DO_InitWadINF; {handle Doom actions} WAD_CNVRTLOG.Add('*** Convert Linedef Actions'); DO_ConvertLinedefActions; WAD_CNVRTLOG.Add('*** Convert Linedef Special Actions'); DO_ConvertLinedefSpecialActions; {create light elevators} WAD_CNVRTLOG.Add('*** Create True Sector Lights'); DO_CreateTrueSectorLights; WAD_CNVRTLOG.Add('*** Approximate Other Sector Lights'); DO_CreateSectorLights; {create close after 30 sec and open after 300 sec specials} WAD_CNVRTLOG.Add('*** Create close 30 sec and open 300 sec Sector Types'); DO_Create_30_300_Specials; {create floor animations} WAD_CNVRTLOG.Add('*** Create Sector Floor Animations'); DO_CreateSectorFloorAnims; {create ceiling animations} WAD_CNVRTLOG.Add('*** Create Sector Ceiling Animations'); DO_CreateSectorCeilingAnims; {create ceiling animations} WAD_CNVRTLOG.Add('*** Create Flats & Textures List'); {!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!} WAD_CNVRTLOG.Add('*** Convert Things'); DO_ConvertThings; WAD_CNVRTLOG.Add('*** Write INF file'); DO_WriteWadINF; WAD_CNVRTLOG.Add('*** Create Doom Resources List (doom_res.lst)'); DO_CreateListForAlex; {clean up wad stuff} FileClose(wf); WAD_VERTEXES.Free; WAD_LINEDEFS.Free; WAD_SIDEDEFS.Free; WAD_THINGS.Free; WAD_INF.Free; ProgressWindow.Hide; {reread the INF for the display colors to be correct} IO_ReadINF(LEVELPath + '\SECBASE.INF'); SC_HILITE := 0; WL_HILITE := 0; VX_HILITE := 0; OB_HILITE := 0; MAP_MODE := MM_VX; DO_Switch_To_SC_Mode; MapWindow.Map.Invalidate; MapWindow.Map.Update; MapWindow.SetFocus; SetCursor(OldCursor); {write and display the log file} WAD_CNVRTLOG.SaveToFile(ChangeFileExt(ProjectFile, '.LOG')); WAD_CNVRTLOG.Free; if MapSelectWindow.CBExecWad2Gob.Checked then begin ChDir(LEVELPath); strPcopy(tmp, WDFUSEdir + '\wad2gob ' + MapSelectWindow.ED_W2GSwitches.Text + 'doom_res.lst ' + IWAD); WinExec(tmp, SW_SHOWNORMAL); end; if MapSelectWindow.CBShowLog.Checked then begin strPcopy(tmp, 'notepad ' + ChangeFileExt(ProjectFile, '.LOG')); WinExec(tmp, SW_SHOWMAXIMIZED); end; MapWindow.Caption := 'WDFUSE - ' + LowerCase(PROJECTFile) + ' : SECTORS'; end; procedure DO_ReadWADSectors(wf : Integer; numsectors : LongInt); var WADSector : TWAD_Sector; TheSector : TSector; i : LongInt; begin if numsectors = 0 then exit; ProgressWindow.Gauge.MaxValue := numsectors - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Loading SECTORS...'; ProgressWindow.Progress2.Update; for i := 0 to numsectors - 1 do begin WADSector := TWAD_Sector.Create; FileRead(wf, WADSector.H_FLOOR, 4); FileRead(wf, WADSector.TX_FLOOR, 8); WADSector.TX_FLOOR[8] := #0; FileRead(wf, WADSector.TX_CEILI, 8); WADSector.TX_CEILI[8] := #0; FileRead(wf, WADSector.LIGHT, 6); TheSector := TSector.Create; { Notes Floor.i stores the sector original TAG Ceili.i stores the sector original TYPE } with TheSector do begin Mark := 0; Reserved := 0; Name := ''; Layer := 0; Floor_alt := WADSector.H_FLOOR / 8; Ceili_alt := WADSector.H_CEILI / 8; Second_alt := 0; Ambient := WADSector.LIGHT div 8; Flag1 := 0; Flag2 := 0; Flag3 := 0; {there are lowercase tx in some wads, this is a sure way to kill DF!} Floor.Name := UpperCase(StrPas(WADSector.TX_FLOOR))+'.BM'; Floor.f1 := 0.0; {flat offsets don't exist in Doom} Floor.f2 := 0.0; Floor.i := WADSector.TAG; Ceili.Name := UpperCase(StrPas(WADSector.TX_CEILI))+'.BM'; Ceili.f1 := 0.0; Ceili.f2 := 0.0; Ceili.i := WADSector.STYPE; Elevator := FALSE; Trigger := FALSE; Secret := FALSE; end; MAP_SEC.AddObject('SC', TheSector); WADSector.Free; if i mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; end; procedure DO_ReadWADVertexes(wf : Integer; numvertexes : LongInt); var WADVertex : TWAD_vertex; TheVertex : TVertex; i : LongInt; begin if numvertexes = 0 then exit; ProgressWindow.Gauge.MaxValue := numvertexes - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Loading VERTEXES...'; ProgressWindow.Progress2.Update; for i := 0 to numvertexes - 1 do begin WADVertex := TWAD_Vertex.Create; FileRead(wf, WADVertex.X, 4); TheVertex := TVertex.Create; with TheVertex do begin Mark := i; {may be useful to keep original vx num} X := WADVertex.X / 8; Z := WADVertex.Y / 8; end; WAD_VERTEXES.AddObject('VX', TheVertex); WADVertex.Free; if i mod 100 = 99 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 100; end; end; procedure DO_ReadWADLinedefs(wf : Integer; numlinedefs : LongInt); var WADLinedef : TWAD_Linedef; i : LongInt; begin if numlinedefs = 0 then exit; ProgressWindow.Gauge.MaxValue := numlinedefs - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Loading LINEDEFS...'; ProgressWindow.Progress2.Update; for i := 0 to numlinedefs - 1 do begin WADLinedef := TWAD_Linedef.Create; FileRead(wf, WADLinedef.VERTEX1, WAD_SIZE_LINEDEF); WAD_LINEDEFS.AddObject('LD', WADLinedef); if i mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; end; procedure DO_ReadWADSidedefs(wf : Integer; numsidedefs : LongInt); var WADSidedef : TWAD_Sidedef; i : LongInt; begin if numsidedefs = 0 then exit; ProgressWindow.Gauge.MaxValue := numsidedefs - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Loading SIDEDEFS...'; ProgressWindow.Progress2.Update; for i := 0 to numsidedefs - 1 do begin WADSidedef := TWAD_Sidedef.Create; FileRead(wf, WADSidedef.X_OFFSET, 4); FileRead(wf, WADSidedef.TX_UPPER, 8); WADSidedef.TX_UPPER[8] := #0; FileRead(wf, WADSidedef.TX_LOWER, 8); WADSidedef.TX_LOWER[8] := #0; FileRead(wf, WADSidedef.TX_MAIN, 8); WADSidedef.TX_MAIN[8] := #0; FileRead(wf, WADSidedef.SECTOR, 2); WAD_SIDEDEFS.AddObject('SD', WADSidedef); if i mod 100 = 99 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 100; end; end; procedure DO_ReadWADThings(wf : Integer; numthings : LongInt); var WADThing : TWAD_Thing; i : LongInt; begin if numthings = 0 then exit; ProgressWindow.Gauge.MaxValue := numthings - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Loading THINGS...'; ProgressWindow.Progress2.Update; for i := 0 to numthings - 1 do begin WADThing := TWAD_Thing.Create; FileRead(wf, WADThing.X, WAD_SIZE_THING); WAD_THINGS.AddObject('TH', WADThing); if i mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; end; procedure DO_ConvertSectors; var sc, ld, sd : Integer; TheSector : TSector; TheVertex : TVertex; TheVertex2 : TVertex; TheWall : TWall; TheWall2 : TWall; WADLinedef : TWAD_Linedef; WADSidedef1 : TWAD_Sidedef; WADSidedef2 : TWAD_Sidedef; conv : Integer; i, j : Integer; onesided : Integer; v1 : Integer; curvx : Integer; endvx : Integer; thecycle : Integer; endofcycle : Boolean; vertexnum : Integer; vxcycle : Integer; counter : Integer; tmp : array[0..127] of Char; str : string; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Converting GEOMETRY...'; ProgressWindow.Progress2.Update; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); tmpWalls := TStringList.Create; for ld := 0 to WAD_LINEDEFS.Count - 1 do begin WADLinedef := TWAD_Linedef(WAD_LINEDEFS.Objects[ld]); { Drop the linedefs that have the same sector reference on both sides. This is a bad Doom habit that cannot be converted easily!} if WADLinedef.SIDEDEF2 <> -1 then begin WADSidedef1 := TWAD_Sidedef(WAD_SIDEDEFS.Objects[WADLinedef.SIDEDEF1]); WADSidedef2 := TWAD_Sidedef(WAD_SIDEDEFS.Objects[WADLinedef.SIDEDEF2]); if WADSidedef1.SECTOR = WADSidedef2.SECTOR then BEGIN if sc = 0 then {only do it at first pass!} begin if WADLinedef.TAG = 0 then {let's make it more visual if linedef is tagged} begin str := Format('Linedef %d will be DISCARDED because both sides refer to sector (%d)', [ld, WADSidedef1.SECTOR]); WAD_CNVRTLOG.Add(' ' + str); end else begin str := Format('Linedef %d (TAG=%d) will be DISCARDED because both sides refer to sector (%d)', [ld, WADLinedef.TAG, WADSidedef1.SECTOR]); WAD_CNVRTLOG.Add(' ' + str); end; {store the discarded LDs} DiscardedLD.Add(Format('%4.4d%4.4d', [ld, WADSidedef1.SECTOR])); end; continue; END; end; { Notes Flag2 stores the linedef original FLAGS Mid.i stores the linedef original TAG Top.i stores the linedef original ACTION Bot.i stores 1 if 1S or 2 for 2S } WADSidedef1 := TWAD_Sidedef(WAD_SIDEDEFS.Objects[WADLinedef.SIDEDEF1]); if WADSidedef1.SECTOR = sc then begin TheWall := TWall.Create; with TheWall do begin Mark := 0; Reserved := 0; Left_vx := WADLinedef.VERTEX1; Right_vx := WADLinedef.VERTEX2; Adjoin := -1; Mirror := -1; Walk := -1; Light := 0; Flag1 := 0; Flag2 := WADLinedef.FLAGS; {it is unused in DF anyway} Flag3 := 0; if StrPas(WadSidedef1.TX_MAIN) <> '-' then Mid.Name := UpperCase(StrPas(WadSidedef1.TX_MAIN))+'.BM' else Mid.Name := '-'; Mid.f1 := WadSidedef1.X_OFFSET / 8.0; Mid.f2 := WadSidedef1.Y_OFFSET / 8.0; Mid.i := WADLinedef.TAG; if StrPas(WadSidedef1.TX_UPPER) <> '-' then Top.Name := UpperCase(StrPas(WadSidedef1.TX_UPPER))+'.BM' else Top.Name := '-'; Top.f1 := WadSidedef1.X_OFFSET / 8.0; Top.f2 := WadSidedef1.Y_OFFSET / 8.0; Top.i := WADLinedef.ACTION; if StrPas(WadSidedef1.TX_LOWER) <> '-' then Bot.Name := UpperCase(StrPas(WadSidedef1.TX_LOWER))+'.BM' else Bot.Name := '-'; Bot.f1 := WadSidedef1.X_OFFSET / 8.0; Bot.f2 := WadSidedef1.Y_OFFSET / 8.0; Bot.i := 1; {use this to say: was a 1st SD} Sign.Name := ''; if Copy(Top.Name,1,2) = 'SW' then Sign.Name := Top.Name; if Copy(Bot.Name,1,2) = 'SW' then Sign.Name := Bot.Name; if Copy(Mid.Name,1,2) = 'SW' then Sign.Name := Mid.Name; Sign.f1 := 0; Sign.f2 := 0; Sign.i := 0; Elevator := FALSE; Trigger := FALSE; Cycle := -1; end; tmpWalls.AddObject('WL', TheWall); end; if WADLinedef.SIDEDEF2 <> -1 then begin WADSidedef2 := TWAD_Sidedef(WAD_SIDEDEFS.Objects[WADLinedef.SIDEDEF2]); if WADSidedef2.SECTOR = sc then begin TheWall := TWall.Create; with TheWall do begin Mark := 0; Reserved := 0; Left_vx := WADLinedef.VERTEX2; Right_vx := WADLinedef.VERTEX1; Adjoin := -1; Mirror := -1; Walk := -1; Light := 0; Flag1 := 0; Flag2 := WADLinedef.FLAGS; {it is unused in DF anyway} Flag3 := 0; if StrPas(WadSidedef2.TX_MAIN) <> '-' then Mid.Name := UpperCase(StrPas(WadSidedef2.TX_MAIN))+'.BM' else Mid.Name := '-'; Mid.f1 := WadSidedef2.X_OFFSET / 8.0; Mid.f2 := WadSidedef2.Y_OFFSET / 8.0; Mid.i := WADLinedef.TAG; if StrPas(WadSidedef2.TX_UPPER) <> '-' then Top.Name := UpperCase(StrPas(WadSidedef2.TX_UPPER))+'.BM' else Top.Name := '-'; Top.f1 := WadSidedef2.X_OFFSET / 8.0; Top.f2 := WadSidedef2.Y_OFFSET / 8.0; Top.i := WADLinedef.ACTION; if StrPas(WadSidedef2.TX_LOWER) <> '-' then Bot.Name := UpperCase(StrPas(WadSidedef2.TX_LOWER))+'.BM' else Bot.Name := '-'; Bot.f1 := WadSidedef2.X_OFFSET / 8.0; Bot.f2 := WadSidedef2.Y_OFFSET / 8.0; Bot.i := 2; {use this to say: was a 2nd SD} Sign.Name := ''; if Copy(Top.Name,1,2) = 'SW' then Sign.Name := Top.Name; if Copy(Bot.Name,1,2) = 'SW' then Sign.Name := Bot.Name; if Copy(Mid.Name,1,2) = 'SW' then Sign.Name := Mid.Name; Sign.f1 := 0; Sign.f2 := 0; Sign.i := 0; Elevator := FALSE; Trigger := FALSE; Cycle := -1; end; tmpWalls.AddObject('WL', TheWall); end; end; end; {tmpWalls contains all the walls for this sector. We must now SORT them by cycles WDFUSE must have them ordered by cycles, even if the primary cycle isn't first} {we'll use the Cycle attribute to set the walls in order "in place" then we'll copy them at their final place, with the vertices} endofcycle := TRUE; thecycle := 0; i := GetFirstUncheckedWall; while i <> -1 do {while there are still walls to handle} begin TheWall := TWall(tmpWalls.Objects[i]); TheWall.Cycle := theCycle; Inc(theCycle); if theCycle > tmpWalls.Count - 1 then begin {sector is too complicated OR trivial, PROBLEM !!!} {should log this somewhere} if tmpWalls.Count < 3 then begin Str := Format('sc# %3.3d has only %d wall(s)', [sc, tmpWalls.Count]); end else begin str := Format('sc# %3.3d could not be converted to cycles correctly (%d walls)', [sc, tmpWalls.Count]); end; WAD_CNVRTLOG.Add(' ' + str); i := -1; break; end; if endofcycle then begin endvx := TheWall.Left_vx; endofcycle := FALSE; end; curvx := TheWall.Right_vx; j := GetWallBeginningWith(curvx); if j = -1 then begin Str:= Format('sc# %3.3d is not closed (%d walls)', [sc, tmpWalls.Count]); WAD_CNVRTLOG.Add(' ' + str); i := -1; break; end else begin TheWall2 := TWall(tmpWalls.Objects[j]); if TheWall2.Right_vx = endvx then begin endofcycle := TRUE; TheWall2.Sign.i := 1; TheWall2.Cycle := theCycle; Inc(theCycle); i := GetFirstUncheckedWall; end else i := j; end; end; {now, transfer the walls by order of cycle, but keeping in mind the vertices must now be created also. We have to remember the first vertex each time} vertexnum := -1; vxcycle := -1; for i := 0 to tmpWalls.Count - 1 do begin j := GetWallWithCycle(i); if j <> -1 then begin TheWall2 := TWall(tmpWalls.Objects[j]); TheWall := TWall.Create; TheWall.Adjoin := TheWall2.Adjoin; TheWall.Mirror := TheWall2.Mirror; TheWall.Walk := TheWall2.Walk; TheWall.Light := TheWall2.Light; TheWall.Flag1 := TheWall2.Flag1; TheWall.Flag2 := TheWall2.Flag2; TheWall.Flag3 := TheWall2.Flag3; TheWall.Mid.Name := TheWall2.Mid.Name; TheWall.Mid.f1 := TheWall2.Mid.f1; TheWall.Mid.f2 := TheWall2.Mid.f2; TheWall.Mid.i := TheWall2.Mid.i; TheWall.Top.Name := TheWall2.Top.Name; TheWall.Top.f1 := TheWall2.Top.f1; TheWall.Top.f2 := TheWall2.Top.f2; TheWall.Top.i := TheWall2.Top.i; TheWall.Bot.Name := TheWall2.Bot.Name; TheWall.Bot.f1 := TheWall2.Bot.f1; TheWall.Bot.f2 := TheWall2.Bot.f2; TheWall.Bot.i := TheWall2.Bot.i; TheWall.Sign.Name := TheWall2.Sign.Name; TheWall.Sign.f1 := TheWall2.Sign.f1; TheWall.Sign.f2 := TheWall2.Sign.f2; TheWall.Sign.i := TheWall2.Sign.i; if vxcycle = -1 then begin Inc(vertexnum); vxcycle := vertexnum; TheVertex := TVertex.Create; TheVertex2 := TVertex(WAD_VERTEXES.Objects[TheWall2.Left_vx]); TheVertex.Mark := 0; TheVertex.X := TheVertex2.X; TheVertex.Z := TheVertex2.Z; TheSector.Vx.AddObject('VX', TheVertex); end; TheWall.Left_vx := vertexnum; if TheWall.Sign.i <> 1 then begin TheVertex := TVertex.Create; TheVertex2 := TVertex(WAD_VERTEXES.Objects[TheWall2.Right_vx]); TheVertex.Mark := 0; TheVertex.X := TheVertex2.X; TheVertex.Z := TheVertex2.Z; TheSector.Vx.AddObject('VX', TheVertex); Inc(vertexnum); TheWall.Right_vx := vertexnum; end else begin {don't create a new vertex here, cycle back to vxcycle} TheWall.Right_vx := vxcycle; TheWall.Sign.i := 0; vxcycle := -1; end; TheSector.Wl.AddObject('WL', TheWall); end else begin {invalid wall, don't write it} {WARNING, if there are NO walls, MUST delete the sector !!!!!} end; end; tmpwalls.Free; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; end; procedure DO_CorrectSectors; var sc : Integer; TheSector : TSector; num : Integer; str : string; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Deleting Unreferenced SECTORS...'; ProgressWindow.Progress2.Update; {make a first pass just for the log!} for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Wl.Count = 0) or (TheSector.Vx.Count = 0) then WAD_CNVRTLOG.Add(' ' + 'Deleted WAD Sector # ' + IntToStr(sc)); end; num := 0; sc := 0; while sc < MAP_SEC.Count do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Wl.Count = 0) or (TheSector.Vx.Count = 0) then begin Inc(num); MAP_SEC.Delete(sc); ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; end else Inc(sc); if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; if num <> 0 then begin str := Format('Deleted %d unreferenced sectors', [num]); WAD_CNVRTLOG.Add(' ' + str); end; end; procedure DO_ConvertSectorFlags(TheMAP : String); var sc : Integer; TheSector : TSector; num : Integer; str : string; code, mapnum : Integer; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Converting SECTOR types to DF Flags...'; ProgressWindow.Progress2.Update; TheSky := 'SKY1'; if Copy(TheMAP,1,2) = 'E2' then TheSky := 'SKY2' else if Copy(TheMAP,1,2) = 'E3' then TheSky := 'SKY3' else if Copy(TheMAP,1,2) = 'E4' then TheSky := 'SKY4' else if Copy(TheMAP,1,3) = 'MAP' then begin Val(Copy(TheMAP,4,2), mapnum, code); if code = 0 then if mapnum > 20 then TheSky := 'SKY3' else if mapnum > 10 then TheSky := 'SKY2'; end; num := 0; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); {WAD sector types are stored in Ceili.i} CASE TheSector.Ceili.i OF 0,1,2,3,8,10,12,13,14,17 : ;{nothing to do here} {all damages converted to GAS, to be able to use the gas mask to emulate the RADSUIT. Doesn't change things too much anyway! } 4 : TheSector.Flag1 := 6144; {10-20%} 5 : TheSector.Flag1 := 6144; {5-10%} 7 : TheSector.Flag1 := 6144; {2-5%} 9 : TheSector.Flag1 := 524288; {secret} 11 : TheSector.Flag1 := 6144; {10-20%} 16 : TheSector.Flag1 := 6144; {10-20%} ELSE begin Inc(num); TheSector.Ceili.i := 0; end; END; {handle skys: both the exterior AND exterior adjoin bits} if Copy(TheSector.Ceili.Name, 1, 5) = 'F_SKY' then begin TheSector.Ceili.Name := TheSky + '.BM'; TheSector.Flag1 := TheSector.Flag1 + 9; end; {handle floor skys: both the exterior AND exterior adjoin bits} if Copy(TheSector.Floor.Name, 1, 5) = 'F_SKY' then begin TheSector.Floor.Name := TheSky + '.BM'; TheSector.Flag1 := TheSector.Flag1 + 384; {add this second altitude so the player doesn't fall down, as this isn't the Doom behavior. It doesn't work with -0.01 which would have ensured the player came in from above... ...anyway, floor skys are nearly always recessed} TheSector.Second_alt := 0.01; end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; if num <> 0 then begin Str := Format('Found %d invalid sector types (corrected)', [num]); WAD_CNVRTLOG.Add(' ' + str); end; end; procedure DO_ConvertWallFlags; var sc, wl : Integer; TheSector : TSector; TheWall : TWall; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Converting LINEDEF Flags to DF Flags...'; ProgressWindow.Progress2.Update; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); for wl := 0 to TheSector.Wl.Count - 1 do begin TheWall := TWall(TheSector.Wl.Objects[wl]); {WAD linedef flags are stored in Flag2} if IsBitSet(TheWall.Flag2, 0) then {impassable} begin Inc(TheWall.Flag3, 2); {cannot walk} end; if IsBitSet(TheWall.Flag2, 1) then {block monsters} begin Inc(TheWall.Flag3, 4); {fence} end; if IsBitSet(TheWall.Flag2, 2) then {two sided} begin if TheWall.Mid.Name <> '-' then Inc(TheWall.Flag1, 1); {adjoining Mid Tx} end; if IsBitSet(TheWall.Flag2, 3) then {upper tx not pegged} begin end; if not IsBitSet(TheWall.Flag2, 4) then { NOT lower tx not pegged !} begin {elevators look good this way ! but it is far from being the answer} TheWall.Flag1 := TheWall.Flag1 or 16; {wall tx anchored} end; if IsBitSet(TheWall.Flag2, 5) then {secret} begin Inc(TheWall.Flag1, 2048); {show as normal on map} end; if IsBitSet(TheWall.Flag2, 6) then {block sound} begin {not in DF} end; if IsBitSet(TheWall.Flag2, 7) then {Never on map} begin Inc(TheWall.Flag1, 1024); {Hide on map} end; if IsBitSet(TheWall.Flag2, 8) then {Always on map} begin {does not exists ?} end; end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; end; procedure DO_AllAdjoins; var sc : Integer; num : Integer; str : string; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Preparing to Adjoin...'; ProgressWindow.Progress2.Update; for sc := 0 to MAP_SEC.Count -1 do begin DO_MultiSel_SC(sc); if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; ProgressWindow.Progress2.Caption := 'Adjoining...'; ProgressWindow.Progress2.Update; DO_Switch_To_WL_Mode; if MakeAdjoin(SC_HILITE, WL_HILITE) then num := 1 else num := 0; num := num + MultiMakeAdjoin; DO_Fill_WallEditor; if num <> 0 then begin Str := Format('Made %d adjoins', [num]); WAD_CNVRTLOG.Add(' ' + str); end; DO_Switch_To_SC_Mode; DO_Clear_MultiSel; end; procedure DO_FlagDoors; var sc, wl : Integer; TheSector : TSector; TheSector2 : TSector; TheWall : TWall; tmpAlt : Real; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Converting Local Doors to Flag Doors...'; ProgressWindow.Progress2.Update; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); for wl := 0 to TheSector.Wl.Count - 1 do begin TheWall := TWall(TheSector.Wl.Objects[wl]); {WAD linedef action are stored in Top.i} if (TheWall.Bot.i = 1) and (TheWall.Top.i = 1) then {first side and local door} begin if (TheWall.Adjoin <> -1) then begin TheSector2 := TSector(MAP_SEC.Objects[TheWall.Adjoin]); if (TheSector2.Flag1 and 2) = 0 then begin TheSector2.Flag1 := TheSector2.Flag1 or 2; {set the ceiling altitude correctly, because Doom uses the ceiling = floor trick, DF not} tmpAlt := GetNearAltitude(TheWall.Adjoin, 'LHC'); if tmpAlt <> 999999 then TheSector2.Ceili_Alt := tmpAlt; end; end; end; end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; end; procedure DO_CreateDummySector(name : String); var TheSector : TSector; minX, minY, minZ, maxX, maxY, maxZ : Real; begin DO_GetMapLimits(minX, minY, minZ, maxX, maxY, maxZ); CreatePolygonSector(4, 4, minX + 4, minZ - 15 , 0); TheSector := TSector(MAP_SEC.Objects[MAP_SEC.Count-1]); TheSector.Name := name; {set it back to a normal untagged sector in case sector 0 was special} TheSector.Floor.i := 0; TheSector.Ceili.i := 0; end; procedure DO_NameSectors; var sc, t : Integer; TheSector : TSector; tag : Integer; tags : array[1..999] of Integer; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Naming Tagged Sectors...'; ProgressWindow.Progress2.Update; for t := 1 to 999 do tags[t] := 0; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); tag := TheSector.Floor.i; if (tag = 666) or (tag = 667) then WAD_CNVRTLOG.Add(' WARNING! Sector #' + Format('%3.3d ', [sc]) + ' has tag ' + Format('%3.3d',[tag])); if tag <> 0 then {if it has a tag} begin if tags[tag] = 0 then begin TheSector.Name := Format('tag%3.3d', [tag]); Inc(tags[tag]); end else begin TheSector.Name := Format('tag%3.3d_slave%3.3d', [tag, tags[tag]]); Inc(tags[tag]); end; end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; end; {WAD_INF helper functions} procedure DO_InitWadINF; begin WAD_INF := TStringList.Create; WAD_INF_ITEMS := 0; WAD_INF_ADDS := 0; WAD_INF_TRGS := 0; WAD_INF_ADJS := 0; WAD_INF_DONS := 0; WAD_INF.Add('INF 1.0'); WAD_INF.Add(''); WAD_INF.Add('LEVELNAME SECBASE'); WAD_INF.Add(''); WAD_INF.Add('items 1'); {line 4 of WAD_INF is the items value} WAD_INF.Add(''); WI_ITEMSECTOR('complete'); WI_CLASS('elevator move_floor'); WI_SPEED('0'); WI_STOP('1 hold'); WI_STOP('2 complete'); WI_SEQEND; WI_CR; end; procedure WI_CR; begin WAD_INF.Add(''); end; procedure WI_COMMENT(s : String); begin WAD_INF.Add('/* ' + s + ' */'); end; procedure WI_ITEMSECTOR(s : String); begin WAD_INF.Add('item: sector name: ' + s); WAD_INF.Add(' seq'); Inc(WAD_INF_ITEMS); end; procedure WI_ITEMLINE(s : String; num : Integer); begin WAD_INF.Add('item: line name: ' + s + ' num: ' + IntToStr(num)); WAD_INF.Add(' seq'); Inc(WAD_INF_ITEMS); end; procedure WI_SEQ; begin {moved in ITEMSECTOR and ITEMLINE} end; procedure WI_CLASS(s : String); begin WAD_INF.Add(' class: ' + s); end; procedure WI_MASTEROFF; begin WAD_INF.Add(' master: off'); end; procedure WI_STOP(s : String); begin WAD_INF.Add(' stop: ' + s); end; procedure WI_EVENTMASK(s : String); begin WAD_INF.Add(' event_mask: ' + s); end; procedure WI_ENTITYMASK(s : String); begin if s <> '' then WAD_INF.Add(' entity_mask: ' + s); end; procedure WI_MESSAGE(s : String); begin WAD_INF.Add(' message: ' + s); end; procedure WI_SPEED(s : String); begin WAD_INF.Add(' speed: ' + s); end; procedure WI_OTHER(s : String); begin WAD_INF.Add(' ' + s); end; procedure WI_KEY(s : String); begin WAD_INF.Add(' key: ' + s); end; procedure WI_CLIENT(s : String); begin WAD_INF.Add(' client: ' + s); end; procedure WI_SLAVE(s : String); begin WAD_INF.Add(' slave: ' + s); end; procedure WI_SEQEND; begin WAD_INF.Add(' seqend'); end; procedure DO_WriteWadINF; begin WAD_INF[4] := 'items ' + IntToStr(WAD_INF_ITEMS); WAD_INF.SaveToFile(LEVELPath + '\SECBASE.INF'); end; function GetLineActionData(num : Integer; VAR lda : TLDA_DESC) : Boolean; var doomdata : TIniFile; datastr : String; pars : TStringParserWithColon; tmp : array[0..127] of char; str : string; i : Integer; begin doomdata := TIniFile.Create(WDFUSEdir + '\WDFDATA\DOOMDATA.WDF'); datastr :=doomdata.ReadString('LineDef_Actions', Format('%3.3d', [num]), '***'); if datastr = '***' then begin Result := FALSE; Str := Format('ERROR!!!! Invalid Linedef action %d',[num]); WAD_CNVRTLOG.Add(' ' + str); StrPcopy(tmp, str); Application.MessageBox(tmp, 'WDFUSE Mapper - WAD Convert', mb_Ok or mb_IconInformation); end else begin {split the data in the different parts} pars := TStringParserWithColon.Create(datastr); if pars.Count < 14 then begin Result := FALSE; Str := Format('ERROR!!!! in DOOMDATA.WDF [Linedef_Actions] item %d',[num]); WAD_CNVRTLOG.Add(' ' + str); StrPcopy(tmp, str); Application.MessageBox(tmp, 'WDFUSE Mapper - WAD Convert', mb_Ok or mb_IconInformation); end else begin Result := TRUE; lda.act := pars[1][1]; lda.elev := pars[2]; lda.master := (pars[3] = '1'); lda.event := pars[4][1]; lda.rep := pars[5][1]; lda.trig := pars[6][1]; lda.stops := pars[7]; lda.first := pars[8]; lda.next := pars[9]; if pars[10] = '-' then lda.speed := -1 else lda.speed := StrToInt(pars[10]); lda.speed := doomdata.ReadInteger('LineDef_Speeds', IntToStr(lda.speed), -1); if pars[11] = '-' then lda.hold := -32000 else lda.hold := StrToInt(pars[11]); lda.spec := pars[12]; lda.desc := ''; for i := 13 to pars.Count - 1 do lda.desc := lda.desc + ' ' + pars[i]; lda.desc := LTrim(lda.desc); end; pars.Free; end; doomdata.Free; end; procedure DO_ConvertLinedefActions; var sc, wl, i, j : Integer; TheSector : TSector; TheSector2 : TSector; TheSectorTag : TSector; TheWall : TWall; lda : TLDA_DESC; TheClass : string; TheTriggerCls : string; TheEventMask : string; TheEntityMask : string; TheStop1 : String; TheStop2 : String; TheSectorName : String; TheTrSecName : String; TheMessage : string; ConstructElevator : Boolean; ConstructTrigger : Boolean; reference : Integer; dummy : Integer; secnum : Integer; tmp1 : string; tmpfloor : Real; tmpceili : Real; tmpstop : Real; tmpinc : Real; curstop : Integer; tmp : array[0..127] of char; str : string; mustdone : Boolean; donename : String; begin if MAP_SEC.Count = 0 then exit; ElevMade := TStringList.Create; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Converting Linedef Actions...'; ProgressWindow.Progress2.Update; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); for wl := 0 to TheSector.Wl.Count - 1 do begin TheWall := TWall(TheSector.Wl.Objects[wl]); {WAD linedef action are stored in Top.i} if (TheWall.Top.i > 0) then {don't include 0 (no action)} if TheWall.Bot.i = 1 then {only take first sides} if GetLineActionData(TheWall.Top.i, lda) then begin ConstructElevator := TRUE; ConstructTrigger := TRUE; IF lda.Act = 'X' then BEGIN {special handling handled afterwards !} END ELSE BEGIN {what elevator} if lda.elev = 'MC' then TheClass := 'elevator move_ceiling'; if lda.elev = 'MF' then TheClass := 'elevator move_floor'; if lda.elev = 'CL' then TheClass := 'elevator change_light'; if lda.elev = '--' then ConstructElevator := FALSE; {event_mask and entity_mask} case lda.event of 'W' : begin TheEventMask := '3'; TheEntityMask := ''; end; 'S' : begin TheEventMask := '16'; TheEntityMask := ''; end; 'G' : begin TheEventMask := '256'; TheEntityMask := '8'; end; 'e' : begin TheEventMask := '4'; TheEntityMask := ''; ConstructTrigger := FALSE; {?} end; 'n' : begin TheEventMask := '32'; TheEntityMask := ''; ConstructTrigger := FALSE; {?} end; end; {!! to the switches !!} mustdone := FALSE; if lda.rep = 'R' then if TheWall.Sign.Name = '' then TheTriggerCls := 'trigger standard' else begin TheTriggerCls := 'trigger switch1'; mustdone := TRUE; if TheSector.Name = '' then {precalculate the trigger name, not cute :-)} doneName := Format('trg%3.3d', [WAD_INF_TRGS]) else doneName := TheSector.Name; donename := donename + '(' + IntToStr(wl) + ')'; end else TheTriggerCls := 'trigger single'; {on what to act ?} Case lda.Act Of 'T' : begin TheSectorName := Format('tag%3.3d', [TheWall.Mid.i]); secnum := GetTaggedSector(TheWall.Mid.i); if secnum = -1 then begin Str := Format('ERROR!!!! Invalid TAG sc# %3.3d wl# %2.2d',[sc, wl]); WAD_CNVRTLOG.Add(' ' + str); continue; end; end; 'A' : begin if TheWall.Adjoin <> -1 then begin secnum := TheWall.Adjoin; TheSector2 := TSector(MAP_SEC.Objects[secnum]); if TheSector2.Name = '' then begin TheSector2.Name := Format('adj%3.3d', [WAD_INF_ADJS]); TheSectorName := Format('adj%3.3d', [WAD_INF_ADJS]); Inc(WAD_INF_ADJS); end else begin {sector is already named, probably by another linedef, ignore the elevator, but still construct the trigger !} {we have to make an exception: if the (bad?) wad maker did put a tag on a 'A' elevator, the sector will be named ! so use ElevMade !!!} TheSectorName := TheSector2.Name; if ElevMade.IndexOf(TheSectorName) <> -1 then ConstructElevator := FALSE; end; end else begin {error, 'A' action on unadjoined wall} Str := Format('ERROR!!!! "A" action on unadjoined wall sc# %3.3d wl# %2.2d',[sc, wl]); WAD_CNVRTLOG.Add(' ' + str); continue; end; end; 'C' : begin TheSectorName := 'complete'; ConstructElevator := FALSE; end; End; if ConstructElevator then {if the elevator doesn't exist yet} if ElevMade.IndexOf(TheSectorName) = -1 then begin WI_CR; WI_ITEMSECTOR(TheSectorName); ElevMade.Add(TheSectorName); WI_CLASS(TheClass); if not lda.master then WI_MASTEROFF; if not ConstructTrigger then WI_EVENTMASK(TheEventMask); if lda.Spec = 'R' then WI_KEY('red'); if lda.Spec = 'B' then WI_KEY('blue'); if lda.Spec = 'Y' then WI_KEY('yellow'); if lda.Speed <> -1 then WI_SPEED(IntToStr(lda.Speed)); {the stops} if lda.stops = '2' then begin {classic 2 stops elevator} if lda.first <> 'LIG' then {with altitudes} begin tmp1 := Format('%5.2f', [GetNearAltitude(secnum, lda.first)]) + ' '; if lda.hold = -32000 then tmp1 := tmp1 + 'hold' else if lda.hold < 0 then tmp1 := tmp1 + IntToStr(abs(lda.hold)) else tmp1 := tmp1 + 'hold'; WI_STOP(tmp1); if MustDone then WI_MESSAGE('0 ' + donename + ' done'); tmp1 := Format('%5.2f', [GetNearAltitude(secnum, lda.next)]) + ' '; if lda.hold = -32000 then tmp1 := tmp1 + 'hold' else tmp1 := tmp1 + IntToStr(abs(lda.hold)); WI_STOP(tmp1); end else {with lights} begin tmp1 := Format('%d', [GetNearAmbient(secnum, lda.first)]) + ' '; if lda.hold = -32000 then tmp1 := tmp1 + 'hold' else if lda.hold < 0 then tmp1 := tmp1 + IntToStr(abs(lda.hold)) else tmp1 := tmp1 + 'hold'; WI_STOP(tmp1); if MustDone then WI_MESSAGE('0 ' + donename + ' done'); tmp1 := Format('%d', [GetNearAmbient(secnum, lda.next)]) + ' '; if lda.hold = -32000 then tmp1 := tmp1 + 'hold' else tmp1 := tmp1 + IntToStr(abs(lda.hold)); WI_STOP(tmp1); end; end else begin {variable generate more than two stops, all with 'hold'} tmp1 := Format('%5.2f', [GetNearAltitude(secnum, lda.first)]) + ' hold'; WI_STOP(tmp1); tmpfloor := GetNearAltitude(secnum, 'FLO'); tmpceili := GetNearAltitude(secnum, 'CEI'); tmpinc := GetNearAltitude(secnum, lda.next); tmpstop := tmpfloor + tmpinc; curstop := 0; repeat tmp1 := Format('%5.2f', [tmpstop]) + ' hold'; WI_STOP(tmp1); if MustDone then WI_MESSAGE(IntToStr(curstop) + ' ' + donename + ' done'); tmpstop := tmpstop + tmpinc; Inc(curstop); until tmpstop > tmpceili; end; {the slaves} if lda.Act = 'T' then {'A' actions cannot have slaves} begin j := -1; for i := 0 to MAP_SEC.Count - 1 do begin TheSectorTag := TSector(MAP_SEC.Objects[i]); if (TheSectorTag.Floor.i = TheWall.Mid.i) then begin Inc(j); if j > 0 then WI_SLAVE(Format('tag%3.3d_slave%3.3d', [TheWall.Mid.i, j])); end; end; end; WI_SEQEND; end else begin Str := Format('Elevator was already created at sc# %3.3d wl# %2.2d',[sc, wl]); WAD_CNVRTLOG.Add(' ' + str); end; if ConstructTrigger then begin {if the sector in which the current line is not named, we'll have to do it !} if TheSector.Name = '' then begin TheSector.Name := Format('trg%3.3d', [WAD_INF_TRGS]); Inc(WAD_INF_TRGS); end; WI_CR; WI_ITEMLINE(TheSector.Name, wl); WI_CLASS(TheTriggerCls); WI_EVENTMASK(TheEventMask); WI_ENTITYMASK(TheEntityMask); WI_CLIENT(TheSectorName); {which message do we send ?} case lda.trig of 'Z' : WI_MESSAGE('goto_stop 0'); 'O' : WI_MESSAGE('goto_stop 1'); 'N' : WI_MESSAGE('next_stop'); '0' : WI_MESSAGE('master_off'); '1' : WI_MESSAGE('master_on'); end; WI_SEQEND; end; {is there a special handling ? i.e. the 'C' set crush bit and 'S' set smart object reaction bit} TheSector2 := TSector(MAP_SEC.Objects[secnum]); if lda.spec = 'C' then TheSector2.Flag1 := TheSector2.Flag1 or 512; if lda.spec = 'S' then TheSector2.Flag1 := TheSector2.Flag1 or 16384; END; end; end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; end; procedure DO_ConvertLinedefSpecialActions; var sc, wl : Integer; TheSector : TSector; TheWall : TWall; lda : TLDA_DESC; str : string; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Converting Linedef Special Actions...'; ProgressWindow.Progress2.Update; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); for wl := 0 to TheSector.Wl.Count - 1 do begin TheWall := TWall(TheSector.Wl.Objects[wl]); {WAD linedef action are stored in Top.i} if (TheWall.Top.i > 0) then {don't include 0 (no action)} if TheWall.Bot.i = 1 then {only take first sides} if GetLineActionData(TheWall.Top.i, lda) then begin IF lda.Act = 'X' then BEGIN {special handling here for : 048=X -- - - - - - --- --- - - - scrolling wall (left) 008=X -- - W 1 1 2 --- --- 1 - - stairs (8) 007=X -- - S 1 1 2 --- --- 1 - - stairs (8) 100=X -- - W 1 1 2 --- --- 4 - C stairs (16) + crush 127=X -- - S 1 1 2 --- --- 4 - C stairs (16) + crush 039=X -- - W 1 - - --- --- - - S teleport 097=X -- - W R - - --- --- - - S teleport 125=X -- - W 1 - - --- --- - - S teleport monsters only 126=X -- - W R - - --- --- - - S teleport monsters only } case TheWall.Top.i of 48: begin {allow all textures to scroll, whatever the rest if more than one wall scrolls, everything will be ok this way} TheWall.Flag1 := TheWall.Flag1 or 348; {if this room is already an elevator, warn the user and don't create the scrolling wall. He'll have to do a multiclass manually} if ElevMade.IndexOf(TheSector.Name) <> -1 then begin Str := Format('Scrolling wall sc# %3.3d wl# %2.2d is already an elevator. Not created!',[sc, wl]); WAD_CNVRTLOG.Add(' ' + str); end else begin {if the sector hasn't got a name, set it!} if TheSector.Name = '' then begin TheSector.Name := Format('swl%3.3d', [WAD_INF_ADDS]); Inc(WAD_INF_ADDS); end; WI_ITEMSECTOR(TheSector.Name); ElevMade.Add(TheSector.Name); WI_CLASS('elevator scroll_wall'); WI_OTHER('angle: 90'); WI_SPEED('20'); WI_SEQEND; end; end; 39, 97, 125, 126: begin Str := Format('WARNING! Wall sc# %3.3d wl# %2.2d is a teleporter',[sc, wl]); WAD_CNVRTLOG.Add(' ' + str); end; 7, 8, 100, 127: begin Str := Format('WARNING! Wall sc# %3.3d wl# %2.2d starts rising stairs',[sc, wl]); WAD_CNVRTLOG.Add(' ' + str); end; else ;{case} end; {case} END; end; end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; ElevMade.Free; end; procedure DO_Texturing; var sc, wl : Integer; TheSector : TSector; TheSector2 : TSector; TheWall : TWall; offset : Real; offset2 : Real; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Converting Texturing...'; ProgressWindow.Progress2.Update; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); for wl := 0 to TheSector.Wl.Count - 1 do begin TheWall := TWall(TheSector.Wl.Objects[wl]); {WAD linedef flags are stored in Flag2} if TheWall.Adjoin <> -1 then {two sided} begin TheSector2 := TSector(MAP_SEC.Objects[TheWall.Adjoin]); if IsBitSet(TheWall.Flag2, 4) then {lower not pegged} begin TheWall.Mid.f2 := -TheWall.Mid.f2; TheWall.Bot.f2 := -TheWall.Bot.f2; end else begin offset := TheSector.Ceili_alt - TheSector.Floor_alt; offset2 := TheSector2.Floor_alt - TheSector.Floor_alt; TheWall.Mid.f2 := -TheWall.Mid.f2 - offset; TheWall.Bot.f2 := -TheWall.Bot.f2 - offset2; end; if IsBitSet(TheWall.Flag2, 3) then {upper not pegged} begin offset2 := TheSector.Ceili_alt - TheSector2.Ceili_alt; TheWall.Top.f2 := -TheWall.Top.f2 -offset2; end else begin TheWall.Top.f2 := -TheWall.Top.f2; {normal upper same as DF} end; end else begin {The line is 1S, so there can only be a Mid Tx} if IsBitSet(TheWall.Flag2, 4) then begin {as lower tx is not pegged, texturing goes from bottom to top which is identical to DF => nothing to do, but still reverse the sign of the offset, because DF y axis goes down It still isn't good, because Doom handles this case very very strangely...} TheWall.Mid.f2 := -TheWall.Mid.f2; end else begin {the offsets are computed for a texture going top to bottom here we have to reverse that! So compute the offset that will put the top of the texture at the top of the wall. Or said in another way, we could also put the top of the 'next' texture at the top of the wall, or yet again the bottom of the texture ! => simply add the height of the sector don't forget DF y axis goes down} offset := TheSector.Ceili_alt - TheSector.Floor_alt; TheWall.Mid.f2 := -TheWall.Mid.f2 - offset; end; end; (*if IsBitSet(TheWall.Flag2, 3) then {upper tx not pegged}*) (*if IsBitSet(TheWall.Flag2, 4) then {lower tx not pegged} *) end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; end; { 01=Blink (random) 02=Blink (1/2 second) 03=Blink (1 second) 04=-10/20% health, blink (1/2 second) 05=-5/10% health 06=Invalid Sector Type 07=-2/5% health 08=Light oscillates 09=Secret 10=Ceiling drops (after 30 seconds) 11=-10/20% health, end level/game 12=Blink (1/2 second sync.) 13=Blink (1 second sync.) 14=Ceiling rises (after 300 seconds) 15=Invalid Sector Type 16=-10/20% health 17=Flicker on and off (1.666+) } procedure DO_CreateTrueSectorLights; var TheSector : TSector; sc, num : Integer; minl, maxl : Integer; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := 5 * (MAP_SEC.Count - 1); ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Converting True Sector Lights...'; ProgressWindow.Progress2.Update; {begin random blink} num := 0; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 1) then begin if TheSector.Name = '' then begin TheSector.Name := Format('li_random_%3.3d', [num]); maxl := TheSector.Ambient; minl := GetNearAmbient(sc, 'DIM'); WI_CR; WI_ITEMSECTOR(TheSector.Name); WI_CLASS('elevator change_light'); WI_SPEED('0'); WI_STOP(IntToStr(maxl) + ' 1.1'); WI_STOP(IntToStr(minl) + ' 0.3'); WI_STOP(IntToStr(maxl) + ' 1.1'); WI_STOP(IntToStr(minl) + ' 0.2'); WI_STOP(IntToStr(maxl) + ' 0.1'); WI_STOP(IntToStr(minl) + ' 0.7'); WI_STOP(IntToStr(maxl) + ' 1.1'); WI_STOP(IntToStr(minl) + ' 0.3'); WI_STOP(IntToStr(maxl) + ' 0.1'); WI_STOP(IntToStr(minl) + ' 0.1'); WI_STOP(IntToStr(maxl) + ' 0.7'); WI_STOP(IntToStr(minl) + ' 0.1'); WI_STOP(IntToStr(maxl) + ' 0.1'); WI_STOP(IntToStr(minl) + ' 0.3'); WI_STOP(IntToStr(maxl) + ' 1.2'); WI_STOP(IntToStr(minl) + ' 0.3'); WI_SEQEND; {we'll have to change that back afterwards} TheSector.Ceili.i := -TheSector.Ceili.i; Inc(num); end; end; if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d li_random elevator(s)', [num])); {end random blink} {begin blink 0.5} num := 0; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 2) or (TheSector.Ceili.i = 4) or (TheSector.Ceili.i = 12) then begin if TheSector.Name = '' then begin TheSector.Name := Format('li_blk0.5_%3.3d', [num]); maxl := TheSector.Ambient; minl := GetNearAmbient(sc, 'DIM'); WI_CR; WI_ITEMSECTOR(TheSector.Name); WI_CLASS('elevator change_light'); WI_SPEED('0'); WI_STOP(IntToStr(maxl) + ' 0.1'); WI_STOP(IntToStr(minl) + ' 0.4'); WI_SEQEND; {we'll have to change that back afterwards} TheSector.Ceili.i := -TheSector.Ceili.i; Inc(num); end; end; if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d li_blk0.5_ elevator(s)', [num])); {end blink 0.5} {begin blink 1.0} num := 0; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 3) or (TheSector.Ceili.i = 13) then begin if TheSector.Name = '' then begin TheSector.Name := Format('li_blk1.0_%3.3d', [num]); maxl := TheSector.Ambient; minl := GetNearAmbient(sc, 'DIM'); WI_CR; WI_ITEMSECTOR(TheSector.Name); WI_CLASS('elevator change_light'); WI_SPEED('0'); WI_STOP(IntToStr(maxl) + ' 0.1'); WI_STOP(IntToStr(minl) + ' 0.9'); WI_SEQEND; {we'll have to change that back afterwards} TheSector.Ceili.i := -TheSector.Ceili.i; Inc(num); end; end; if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d li_blk1.0_ elevator(s)', [num])); {end blink 1.0} {begin flicker} num := 0; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 17) then begin if TheSector.Name = '' then begin TheSector.Name := Format('li_flicker_%3.3d', [num]); maxl := TheSector.Ambient; minl := GetNearAmbient(sc, 'DIM'); WI_CR; WI_ITEMSECTOR(TheSector.Name); WI_CLASS('elevator change_light'); WI_SPEED('0'); WI_STOP(IntToStr(maxl) + ' 0.95'); WI_STOP(IntToStr(minl) + ' 0.05'); WI_STOP(IntToStr(maxl) + ' 0.03'); WI_STOP(IntToStr(minl) + ' 0.02'); WI_STOP(IntToStr(maxl) + ' 0.01'); WI_STOP(IntToStr(minl) + ' 0.05'); WI_SEQEND; {we'll have to change that back afterwards} TheSector.Ceili.i := -TheSector.Ceili.i; Inc(num); end; end; if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d li_flicker_ elevator(s)', [num])); {end flicker} {begin oscillate} num := 0; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 8) then begin if TheSector.Name = '' then begin TheSector.Name := Format('li_oscill_%3.3d', [num]); maxl := TheSector.Ambient; minl := GetNearAmbient(sc, 'DIM'); WI_CR; WI_ITEMSECTOR(TheSector.Name); WI_CLASS('elevator change_light'); WI_SPEED('80'); WI_STOP(IntToStr(maxl) + ' 0.05'); WI_STOP(IntToStr(minl) + ' 0.05'); WI_SEQEND; {we'll have to change that back afterwards} TheSector.Ceili.i := -TheSector.Ceili.i; Inc(num); end; end; if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d li_oscill_ elevator(s)', [num])); {end oscillate} end; procedure DO_CreateSectorLights; var TheSector : TSector; minX, minY, minZ, maxX, maxY, maxZ : Real; i, sc, num : Integer; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := 5 * (MAP_SEC.Count - 1); ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Approximating Other Sector Lights...'; ProgressWindow.Progress2.Update; {create the 5 needed "master" sectors in a row, below the complete elevator} DO_GetMapLimits(minX, minY, minZ, maxX, maxY, maxZ); for i := 0 to 4 do begin CreatePolygonSector(4, 4, minX + 15 * i + 4, minZ - 15 , 0); TheSector := TSector(MAP_SEC.Objects[MAP_SEC.Count-1]); Case i of 0: TheSector.Name := 'light_random'; 1: TheSector.Name := 'light_blk0.5'; 2: TheSector.Name := 'light_blk1.0'; 3: TheSector.Name := 'light_flickr'; 4: TheSector.Name := 'light_oscill'; end; {set it back to a normal untagged sector in case sector 0 was special} TheSector.Floor.i := 0; TheSector.Ceili.i := 0; end; {they are now numbered MAP_SEC.Count-5 to MAP_SEC.Count-1} {begin random blink} WI_CR; WI_COMMENT('Handles the blink random special sector type'); WI_ITEMSECTOR('light_random'); WI_CLASS('elevator change_light'); WI_SPEED('0'); WI_STOP('20 0.3'); WI_STOP('31 1.1'); WI_STOP('20 0.2'); WI_STOP('31 0.1'); WI_STOP('20 0.7'); WI_STOP('31 1.1'); WI_STOP('20 0.3'); WI_STOP('31 0.1'); WI_STOP('20 0.1'); WI_STOP('31 0.7'); WI_STOP('20 0.1'); WI_STOP('31 0.1'); WI_STOP('20 0.3'); WI_STOP('31 1.2'); WI_STOP('20 0.3'); WI_STOP('31 1.2'); num := 0; for sc := 0 to MAP_SEC.Count - 6 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 1) then begin {if it hasn't got a name, create it} if TheSector.Name = '' then begin TheSector.Name := Format('slave_random_%3.3d', [num]); end; WI_SLAVE(TheSector.Name); Inc(num); end; if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d light_random slave(s)', [num])); WI_SEQEND; {end random blink} {begin blink 0.5} WI_CR; WI_COMMENT('Handles the blink 0.5 special sector type'); WI_ITEMSECTOR('light_blk0.5'); WI_CLASS('elevator change_light'); WI_SPEED('0'); WI_STOP('20 0.4'); WI_STOP('31 0.1'); num := 0; for sc := 0 to MAP_SEC.Count - 6 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 2) or (TheSector.Ceili.i = 4) or (TheSector.Ceili.i = 12) then begin {if it hasn't got a name, create it} if TheSector.Name = '' then begin TheSector.Name := Format('slave_blk0.5_%3.3d', [num]); end; WI_SLAVE(TheSector.Name); Inc(num); end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d light_blk0.5 slave(s)', [num])); WI_SEQEND; {end blink 0.5} {begin blink 1.0} WI_CR; WI_COMMENT('Handles the blink 1.0 special sector type'); WI_ITEMSECTOR('light_blk1.0'); WI_CLASS('elevator change_light'); WI_SPEED('0'); WI_STOP('20 0.9'); WI_STOP('31 0.1'); num := 0; for sc := 0 to MAP_SEC.Count - 6 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 3) or (TheSector.Ceili.i = 13) then begin {if it hasn't got a name, create it} if TheSector.Name = '' then begin TheSector.Name := Format('slave_blk1.0_%3.3d', [num]); end; WI_SLAVE(TheSector.Name); Inc(num); end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d light_blk1.0 slave(s)', [num])); WI_SEQEND; {end blink 1.0} {begin flicker} WI_CR; WI_COMMENT('Handles the flicker sector type'); WI_ITEMSECTOR('light_flickr'); WI_CLASS('elevator change_light'); WI_SPEED('0'); WI_STOP('20 0.1'); WI_STOP('31 0.1'); WI_STOP('20 0.1'); WI_STOP('31 0.1'); WI_STOP('20 0.1'); WI_STOP('31 0.1'); num := 0; for sc := 0 to MAP_SEC.Count - 6 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 17) then begin {if it hasn't got a name, create it} if TheSector.Name = '' then begin TheSector.Name := Format('slave_flickr_%3.3d', [num]); end; WI_SLAVE(TheSector.Name); Inc(num); end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d light_flickr slave(s)', [num])); WI_SEQEND; {end flicker} {begin oscillate} WI_CR; WI_COMMENT('Handles the oscillate sector type'); WI_ITEMSECTOR('light_oscill'); WI_CLASS('elevator change_light'); WI_SPEED('90'); WI_STOP('20 0'); WI_STOP('31 0'); num := 0; for sc := 0 to MAP_SEC.Count - 6 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 8) then begin {if it hasn't got a name, create it} if TheSector.Name = '' then begin TheSector.Name := Format('slave_oscill_%3.3d', [num]); end; WI_SLAVE(TheSector.Name); Inc(num); end; if sc mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d light_oscill slave(s)', [num])); WI_SEQEND; {end oscillate} {restore the sector types we changed in TRUE lights} for sc := 0 to MAP_SEC.Count - 6 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if TheSector.Ceili.i < 0 then TheSector.Ceili.i := - TheSector.Ceili.i; end; end; { 10=Ceiling drops (after 30 seconds) 14=Ceiling rises (after 300 seconds) } procedure DO_Create_30_300_Specials; var TheSector : TSector; sc, num : Integer; Str : String; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := 2 * (MAP_SEC.Count - 1); ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Converting Close 30s and Open 300s...'; ProgressWindow.Progress2.Update; {begin close after 30 sec} num := 0; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 10) then begin if TheSector.Name = '' then begin TheSector.Name := Format('close_30sec_%3.3d', [num]); WI_CR; WI_ITEMSECTOR(TheSector.Name); WI_CLASS('elevator move_ceiling'); WI_SPEED('30'); WI_STOP(Format('%5.2f 30',[TheSector.Ceili_Alt])); WI_STOP(Format('%5.2f terminate',[TheSector.Floor_Alt])); WI_SEQEND; Inc(num); end else begin Str := Format('Close 30 sec : elevator already exists at sc# %3.3d',[sc]); WAD_CNVRTLOG.Add(' ' + str); end; end; if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d close_30sec_ elevator(s)', [num])); {end close after 30 sec} {begin open after 300 sec} num := 0; for sc := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.i = 14) then begin if TheSector.Name = '' then begin TheSector.Name := Format('open_300sec_%3.3d', [num]); WI_CR; WI_ITEMSECTOR(TheSector.Name); WI_CLASS('elevator move_ceiling'); WI_SPEED('30'); WI_STOP(Format('%5.2f 300',[TheSector.Floor_Alt])); WI_STOP(Format('%5.2f terminate',[GetNearAltitude(sc,'LHC')])); WI_SEQEND; Inc(num); end else begin Str := Format('Open 300 sec : elevator already exists at sc# %3.3d',[sc]); WAD_CNVRTLOG.Add(' ' + str); end; end; if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d open_300sec_ elevator(s)', [num])); {end open after 300 sec} end; { NUKAGE1 NUKAGE3 All 3 FWATER1 FWATER4 r 4 LAVA1 LAVA4 r 4 BLOOD1 BLOOD3 r 3 RROCK05 RROCK08 2 4 SLIME01 SLIME04 2 4 SLIME05 SLIME08 2 4 SLIME09 SLIME12 2 4 all must also have a second altitude when on the floor, except RROCK05 } procedure DO_CreateSectorFloorAnims; var TheSector : TSector; minX, minY, minZ, maxX, maxY, maxZ : Real; i, sc, num : Integer; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Creating Sector Floor Animations...'; ProgressWindow.Progress2.Update; {create the 2 needed "master" sectors in a row, below the light elevators} {note that it also creates the one for ceilings} DO_GetMapLimits(minX, minY, minZ, maxX, maxY, maxZ); for i := 0 to 1 do begin CreatePolygonSector(4, 4, minX + 15 * i + 4, minZ - 15 , 0); TheSector := TSector(MAP_SEC.Objects[MAP_SEC.Count-1]); Case i of 0: TheSector.Name := 'anim_floor'; 1: TheSector.Name := 'anim_ceili'; end; {set it back to a normal untagged sector in case sector 0 was special} TheSector.Floor.i := 0; TheSector.Ceili.i := 0; end; {they are now numbered MAP_SEC.Count-2 to MAP_SEC.Count-1} WI_CR; WI_COMMENT('Handles the floor animated flats (not perfect...)'); WI_ITEMSECTOR('anim_floor'); WI_CLASS('elevator scroll_floor'); WI_SPEED('0'); WI_OTHER('angle: 90'); WI_STOP('0 0.7'); WI_STOP('2 0.7'); WI_STOP('1.7 0.5'); WI_STOP('2 0.7'); num := 0; for sc := 0 to MAP_SEC.Count - 3 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Floor.name = 'NUKAGE1.BM') or (TheSector.Floor.name = 'FWATER1.BM') or (TheSector.Floor.name = 'LAVA1.BM') or (TheSector.Floor.name = 'BLOOD1.BM') or (TheSector.Floor.name = 'SLIME01.BM') or (TheSector.Floor.name = 'SLIME05.BM') or (TheSector.Floor.name = 'SLIME09.BM') or (TheSector.Floor.name = 'RROCK05.BM') then begin {if it hasn't got a name, create it} if TheSector.Name = '' then begin TheSector.Name := Format('slave_floor_%3.3d', [num]); end; WI_SLAVE(TheSector.Name); Inc(num); {if it is not RROCK05 give it a second altitude to make it watery} if (TheSector.Floor.name <> 'RROCK05.BM') then TheSector.Second_alt := -2; end; if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d anim_floor slave(s)', [num])); WI_SEQEND; end; procedure DO_CreateSectorCeilingAnims; var TheSector : TSector; i, sc, num : Integer; begin if MAP_SEC.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := MAP_SEC.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Creating Sector Ceiling Animations...'; ProgressWindow.Progress2.Update; {...they are now numbered MAP_SEC.Count-2 to MAP_SEC.Count-1} WI_CR; WI_COMMENT('Handles the ceiling animated flats (not perfect...)'); WI_ITEMSECTOR('anim_ceili'); WI_CLASS('elevator scroll_ceiling'); WI_SPEED('0'); WI_OTHER('angle: 90'); WI_STOP('0 0.7'); WI_STOP('2 0.7'); WI_STOP('1.7 0.5'); WI_STOP('2 0.7'); num := 0; for sc := 0 to MAP_SEC.Count - 3 do begin TheSector := TSector(MAP_SEC.Objects[sc]); if (TheSector.Ceili.name = 'NUKAGE1.BM') or (TheSector.Ceili.name = 'FWATER1.BM') or (TheSector.Ceili.name = 'LAVA1.BM') or (TheSector.Ceili.name = 'BLOOD1.BM') or (TheSector.Ceili.name = 'SLIME01.BM') or (TheSector.Ceili.name = 'SLIME05.BM') or (TheSector.Ceili.name = 'SLIME09.BM') or (TheSector.Ceili.name = 'RROCK05.BM') then begin {if it hasn't got a name, create it} if TheSector.Name = '' then begin TheSector.Name := Format('slave_ceili_%3.3d', [num]); end; WI_SLAVE(TheSector.Name); Inc(num); end; if sc mod 50 = 49 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 50; end; if num <> 0 then WAD_CNVRTLOG.Add(Format(' ' + 'Made %d anim_ceili slave(s)', [num])); WI_SEQEND; end; procedure DO_RecreateDiscarded; var ld, sc, nsc, i, j : Integer; WADLinedef : TWAD_Linedef; WADSidedef : TWAD_Sidedef; TheSector : TSector; TheWall : TWall; NewSector : TSector; vxld1, vxld2 : TVertex; vx0, vx1, vx2 : TVertex; vxa, vxb, vxc : TVertex; vcount : Integer; begin if DiscardedLD.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := DiscardedLD.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Creating thin sectors for discarded linedefs...'; ProgressWindow.Progress2.Update; for i := 0 to DiscardedLD.Count - 1 do begin sc := StrToInt(Copy(DiscardedLD[i],5,4)); ld := StrToInt(Copy(DiscardedLD[i],1,4)); {first create a new sector, identical to the surrounding sector} TheSector := TSector(MAP_SEC.Objects[sc]); NewSector := TSector.Create; NewSector.Mark := 0; {yes or no ? this would possibly make a slave...} NewSector.Name := TheSector.Name; NewSector.Ambient := TheSector.Ambient; NewSector.Flag1 := TheSector.Flag1; NewSector.Flag2 := TheSector.Flag2; NewSector.Flag3 := TheSector.Flag3; NewSector.Floor_Alt := TheSector.Floor_Alt; NewSector.Floor.Name := TheSector.Floor.Name; NewSector.Floor.f1 := TheSector.Floor.f1; NewSector.Floor.f2 := TheSector.Floor.f2; NewSector.Floor.i := TheSector.Floor.i; NewSector.Ceili_Alt := TheSector.Ceili_Alt; NewSector.Ceili.Name := TheSector.Ceili.Name; NewSector.Ceili.f1 := TheSector.Ceili.f1; NewSector.Ceili.f2 := TheSector.Ceili.f2; NewSector.Ceili.i := TheSector.Ceili.i; NewSector.Second_Alt := TheSector.Second_Alt; NewSector.Layer := TheSector.Layer; MAP_SEC.AddObject('SC', NewSector); nsc := MAP_SEC.Count - 1; {now, get the vertices positions} {new sector} vx0 := TVertex.Create; vx1 := TVertex.Create; vx2 := TVertex.Create; {old sector} vxa := TVertex.Create; vxb := TVertex.Create; vxc := TVertex.Create; WADLinedef := TWAD_Linedef(WAD_LINEDEFS.Objects[ld]); vxld1 := TVertex(WAD_VERTEXES.Objects[WADLinedef.VERTEX1]); vxld2 := TVertex(WAD_VERTEXES.Objects[WADLinedef.VERTEX2]); vx0.X := vxld1.X; vx0.Z := vxld1.Z; vx1.X := vxld2.X; vx1.Z := vxld2.Z; vx2.X := (vxld1.X + vxld2.X)/2; vx2.Z := (vxld1.Z + vxld2.Z)/2; NewSector.Vx.AddObject('VX', vx0); NewSector.Vx.AddObject('VX', vx1); NewSector.Vx.AddObject('VX', vx2); vxa.X := vxld1.X; vxa.Z := vxld1.Z; vxb.X := vxld2.X; vxb.Z := vxld2.Z; vxc.X := (vxld1.X + vxld2.X)/2; vxc.Z := (vxld1.Z + vxld2.Z)/2; {this is the number of the first new vx} vcount := TheSector.Vx.Count; TheSector.Vx.AddObject('VX', vxa); TheSector.Vx.AddObject('VX', vxb); TheSector.Vx.AddObject('VX', vxc); {the new sector has walls 01 12 20; 01 beeing the "bad" linedef} TheWall := TWall.Create; {arbitrarily take the first sidedef for the new sector} WADSidedef := TWAD_Sidedef(WAD_SIDEDEFS.Objects[WADLinedef.SIDEDEF1]); with TheWall do begin Mark := 0; Reserved := 0; Left_vx := 1; Right_vx := 0; Adjoin := -1; Mirror := -1; Walk := -1; Light := 0; Flag1 := 0; Flag2 := WADLinedef.FLAGS; Flag3 := 0; if StrPas(WadSidedef.TX_MAIN) <> '-' then Mid.Name := UpperCase(StrPas(WadSidedef.TX_MAIN))+'.BM' else Mid.Name := '-'; Mid.f1 := WadSidedef.X_OFFSET / 8.0; Mid.f2 := WadSidedef.Y_OFFSET / 8.0; Mid.i := WADLinedef.TAG; if StrPas(WadSidedef.TX_UPPER) <> '-' then Top.Name := UpperCase(StrPas(WadSidedef.TX_UPPER))+'.BM' else Top.Name := '-'; Top.f1 := WadSidedef.X_OFFSET / 8.0; Top.f2 := WadSidedef.Y_OFFSET / 8.0; Top.i := WADLinedef.ACTION; if StrPas(WadSidedef.TX_LOWER) <> '-' then Bot.Name := UpperCase(StrPas(WadSidedef.TX_LOWER))+'.BM' else Bot.Name := '-'; Bot.f1 := WadSidedef.X_OFFSET / 8.0; Bot.f2 := WadSidedef.Y_OFFSET / 8.0; Bot.i := 1; {use this to say: was a 1st SD} Sign.Name := ''; if Copy(Top.Name,1,2) = 'SW' then Sign.Name := Top.Name; if Copy(Bot.Name,1,2) = 'SW' then Sign.Name := Bot.Name; if Copy(Mid.Name,1,2) = 'SW' then Sign.Name := Mid.Name; Sign.f1 := 0; Sign.f2 := 0; Sign.i := 0; Elevator := FALSE; Trigger := FALSE; Cycle := -1; end; NewSector.Wl.AddObject('WL', TheWall); for j := 1 to 2 do begin TheWall := TWall.Create; with TheWall do begin Mark := 0; Reserved := 0; if j = 1 then begin Left_vx := 0; Right_vx := 2; end else begin Left_vx := 2; Right_vx := 1; end; Adjoin := -1; Mirror := -1; Walk := -1; Light := 0; Flag1 := 0; Flag2 := 0; Flag3 := 0; Mid.Name := '-'; Mid.f1 := 0; Mid.f2 := 0; Mid.i := 0; Top.Name := '-'; Top.f1 := 0; Top.f2 := 0; Top.i := 0; Bot.Name := '-'; Bot.f1 := 0; Bot.f2 := 0; Bot.i := 3; {use this to say: was an added line} Sign.Name := ''; Sign.f1 := 0; Sign.f2 := 0; Sign.i := 0; Elevator := FALSE; Trigger := FALSE; Cycle := -1; end; NewSector.Wl.AddObject('WL', TheWall); end; {the old sector has new walls ac cb ba, ba beeing the "bad" linedef vx # begin after the last existing vx and forming a new cycle} for j := 1 to 2 do begin TheWall := TWall.Create; with TheWall do begin Mark := 0; Reserved := 0; if j = 1 then begin Left_vx := vcount; Right_vx := vcount+1; end else begin Left_vx := vcount+1; Right_vx := vcount+2; end; Adjoin := -1; Mirror := -1; Walk := -1; Light := 0; Flag1 := 0; Flag2 := 0; Flag3 := 0; Mid.Name := '-'; Mid.f1 := 0; Mid.f2 := 0; Mid.i := 0; Top.Name := '-'; Top.f1 := 0; Top.f2 := 0; Top.i := 0; Bot.Name := '-'; Bot.f1 := 0; Bot.f2 := 0; Bot.i := 3; {use this to say: was an added line} Sign.Name := ''; Sign.f1 := 0; Sign.f2 := 0; Sign.i := 0; Elevator := FALSE; Trigger := FALSE; Cycle := -1; end; TheSector.Wl.AddObject('WL', TheWall); end; TheWall := TWall.Create; {arbitrarily take the second sidedef for the old sector} WADSidedef := TWAD_Sidedef(WAD_SIDEDEFS.Objects[WADLinedef.SIDEDEF2]); with TheWall do begin Mark := 0; Reserved := 0; Left_vx := vcount+2; Right_vx := vcount; Adjoin := -1; Mirror := -1; Walk := -1; Light := 0; Flag1 := 0; Flag2 := WADLinedef.FLAGS; Flag3 := 0; if StrPas(WadSidedef.TX_MAIN) <> '-' then Mid.Name := UpperCase(StrPas(WadSidedef.TX_MAIN))+'.BM' else Mid.Name := '-'; Mid.f1 := WadSidedef.X_OFFSET / 8.0; Mid.f2 := WadSidedef.Y_OFFSET / 8.0; Mid.i := WADLinedef.TAG; if StrPas(WadSidedef.TX_UPPER) <> '-' then Top.Name := UpperCase(StrPas(WadSidedef.TX_UPPER))+'.BM' else Top.Name := '-'; Top.f1 := WadSidedef.X_OFFSET / 8.0; Top.f2 := WadSidedef.Y_OFFSET / 8.0; Top.i := WADLinedef.ACTION; if StrPas(WadSidedef.TX_LOWER) <> '-' then Bot.Name := UpperCase(StrPas(WadSidedef.TX_LOWER))+'.BM' else Bot.Name := '-'; Bot.f1 := WadSidedef.X_OFFSET / 8.0; Bot.f2 := WadSidedef.Y_OFFSET / 8.0; Bot.i := 2; {use this to say: was a 2nd SD} Sign.Name := ''; if Copy(Top.Name,1,2) = 'SW' then Sign.Name := Top.Name; if Copy(Bot.Name,1,2) = 'SW' then Sign.Name := Bot.Name; if Copy(Mid.Name,1,2) = 'SW' then Sign.Name := Mid.Name; Sign.f1 := 0; Sign.f2 := 0; Sign.i := 0; Elevator := FALSE; Trigger := FALSE; Cycle := -1; end; TheSector.Wl.AddObject('WL', TheWall); ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 1; WAD_CNVRTLOG.Add(Format(' ' + 'Recreated Linedef# %4.4d as sc# %3.3d', [ld, nsc])); end; end; procedure Do_ConvertThings; var TheObject : TOB; TheObject2 : TOB; TheSector : TSector; WADThing : TWAD_Thing; t : Integer; thd : TTH_DESC; dup : Integer; begin if WAD_THINGS.Count = 0 then exit; ProgressWindow.Gauge.MaxValue := WAD_THINGS.Count - 1; ProgressWindow.Gauge.Progress := 0; ProgressWindow.Progress2.Caption := 'Converting Things...'; ProgressWindow.Progress2.Update; SPR_LIST.Sorted := TRUE; SPR_LIST.Duplicates := dupIgnore; FME_LIST.Sorted := TRUE; FME_LIST.Duplicates := dupIgnore; for t := 0 to WAD_THINGS.Count - 1 do begin WADThing := TWAD_Thing(WAD_THINGS.Objects[t]); if GetThingData(WADThing.ID, thd) then if thd.debug = 'Y' then begin if thd.spec = '!' then begin WAD_CNVRTLOG.Add(' WARNING! Unconvertible Object (' + thd.desc + ') at [' + Format('%5.2f, %5.2f]', [WADThing.X / 8, WADThing.Y / 8])); continue; end; TheObject := TOB.Create; with TheObject do begin Mark := 0; X := WADThing.X / 8; Z := WADThing.Y / 8; Sec := -1; GetNearestSC(X, Z, Sec); if Sec <> -1 then begin TheSector := TSector(MAP_SEC.Objects[Sec]); Y := TheSector.Floor_Alt; end; case WADThing.FACING of 0 : Yaw := 90.0; 45 : Yaw := 45.0; 90 : Yaw := 0.0; 135 : Yaw := 315.0; 180 : Yaw := 270.0; 225 : Yaw := 225.0; 270 : Yaw := 180.0; 315 : Yaw := 135.0; else Yaw := 0.0; end; Pch := 0.0; Rol := 0.0; if (WADThing.FLAGS and 16) <> 0 then begin {thing is present in deathmatch only, don't convert it} TheObject.Free; continue; end; {clear the deaf bit (8) and any possible higher other bit} WADThing.FLAGS := WADThing.FLAGS and 7; CASE WADThing.FLAGS of 0: Diff := 0; {EMH not correct, but this shouldn't appear in WADs !} 1: Diff := -1; 2: Diff := 2; {MH not correct, should be M only (impossible)} 3: Diff := -2; 4: Diff := 3; 5: Diff := 0; {EMH not correct, should be EH only (impossible)} 6: Diff := 2; 7: Diff := 1; END; Otype := 0; Special := 0; end; if thd.dfclas = 'FRAME' then begin TheObject.ClassName := thd.dfclas; TheObject.DataName := thd.dfdata; FME_LIST.Add(thd.dfdata); end else if thd.dfclas = 'SPRITE' then begin TheObject.ClassName := thd.dfclas; TheObject.DataName := thd.dfdata; SPR_LIST.Add(thd.dfdata); end else if thd.dfclas = 'SAFE' then begin TheObject.ClassName := thd.dfclas; TheObject.DataName := thd.dfclas; end else if thd.dfclas = 'SPIRIT' then begin TheObject.ClassName := thd.dfclas; TheObject.DataName := thd.dfclas; end; TheObject.Col := DOOM_GetOBColor(TheObject.DataName); if thd.logic[1] <> '*' then {general case} begin TmpSeqs := TStringList.Create; DOOM_FillLogic(thd.Logic); if TmpSeqs.Count <> 0 then TheObject.Seq.AddStrings(TmpSeqs); TmpSeqs.Free; end else {special speed enhanced logics (no dm_seqs.wdf access)} begin {nothing to do for *N} {*A} if thd.Logic[2] = 'A' then TheObject.Seq.Add('LOGIC: ANIM'); {*a} if thd.Logic[2] = 'a' then begin TheObject.Seq.Add('LOGIC: ANIM'); TheObject.Seq.Add('RADIUS: 0'); end; {*r} if thd.Logic[2] = 'r' then TheObject.Seq.Add('RADIUS: 0'); {*S} if thd.Logic[2] = 'S' then begin TheObject.Seq.Add('LOGIC: SCENERY'); TheObject.Seq.Add('LOGIC: ANIM'); end; end; {handle duplicated objects ex boxes of ammo by storing the object more than once} if thd.duplic > 1 then for dup := 2 to thd.duplic do begin TheObject2 := TOB.Create; TheObject2.Mark := 0; TheObject2.Sec := TheObject.Sec; TheObject2.X := TheObject.X; TheObject2.Y := TheObject.Y; TheObject2.Z := TheObject.Z; TheObject2.Yaw := TheObject.Yaw; TheObject2.Pch := TheObject.Pch; TheObject2.Rol := TheObject.Rol; TheObject2.Diff := TheObject.Diff; TheObject2.ClassName := TheObject.ClassName; TheObject2.DataName := TheObject.DataName; TheObject2.Seq.AddStrings(TheObject.Seq); TheObject2.Col := TheObject.Col; TheObject2.Otype := TheObject.OType; TheObject2.Special := TheObject.Special; MAP_OBJ.AddObject('OB', TheObject2); end; MAP_OBJ.AddObject('OB', TheObject); if thd.spec = 'B' then begin WAD_CNVRTLOG.Add(' WARNING! Object #' + Format('%3.3d (', [MAP_OBJ.Count - 1]) + thd.desc + ') may be a tag 666/667 Boss'); end; if thd.spec = 'L' then begin WAD_CNVRTLOG.Add(' MESSAGE: Object #' + Format('%3.3d is a ', [MAP_OBJ.Count - 1]) + thd.desc); end; end; if t mod 20 = 19 then ProgressWindow.Gauge.Progress := ProgressWindow.Gauge.Progress + 20; END; {to keep the list in the same state as if this came from opening a GOB not a WAD} SPR_LIST.Sorted := FALSE; FME_LIST.Sorted := FALSE; WAD_CNVRTLOG.Add(' Created ' + IntToStr(MAP_OBJ.Count) + ' object(s)'); end; (* TYPE {things description} TTH_DESC = record debug : String; {Y/N} dfclas : String; dfdata : String; logic : String; spec : String; {specials e.g. keys, crush bits, ...} dmclas : String; dmroot : String; desc : String; {textual description} end; *) function GetThingData(num : Integer; VAR thd : TTH_DESC) : Boolean; var doomdata : TIniFile; datastr : String; pars : TStringParserWithColon; tmp : array[0..127] of char; str : string; i : Integer; begin doomdata := TIniFile.Create(WDFUSEdir + '\WDFDATA\DOOMDATA.WDF'); datastr :=doomdata.ReadString('Thing_Types', Format('0x%3.3x', [num]), '***'); if datastr = '***' then begin Result := FALSE; Str := Format('ERROR!!!! Invalid Thing Type %d (0x%3.3x)',[num, num]); WAD_CNVRTLOG.Add(' ' + str); StrPcopy(tmp, str); Application.MessageBox(tmp, 'WDFUSE Mapper - WAD Convert', mb_Ok or mb_IconInformation); end else begin {split the data in the different parts} pars := TStringParserWithColon.Create(datastr); if pars.Count < 9 then begin Result := FALSE; Str := Format('ERROR!!!! in DOOMDATA.WDF [Thing_Types] item %d (0x%3.3x)',[num, num]); WAD_CNVRTLOG.Add(' ' + str); StrPcopy(tmp, str); Application.MessageBox(tmp, 'WDFUSE Mapper - WAD Convert', mb_Ok or mb_IconInformation); end else begin Result := TRUE; thd.debug := pars[1]; thd.dfclas := pars[2]; thd.dfdata := pars[3]; thd.logic := pars[4]; if pars[5] <> '-' then thd.duplic := StrToInt(pars[5]) else thd.duplic := 1; thd.spec := pars[6]; thd.dmclas := pars[7]; thd.dmroot := pars[8]; thd.desc := ''; for i := 9 to pars.Count - 1 do thd.desc := thd.desc + ' ' + pars[i]; thd.desc := LTrim(thd.desc); end; pars.Free; end; doomdata.Free; end; function DOOM_GetOBColor(thing : String) : LongInt; var COLORini : TIniFile; begin COLORini := TIniFile.Create(WDFUSEdir + '\WDFDATA\DM_COLS.WDF'); try Result := COLORini.ReadInteger(thing, 'COLOR', Ccol_shadow); finally COLORini.Free; end; end; procedure DOOM_FillLogic(thing : String); var obs : TIniFile; cnt : Integer; lines : Integer; i : Integer; ALine : String; begin obs := TIniFile.Create(WDFUSEdir + '\WDFDATA\dm_seqs.wdf'); try cnt := obs.ReadInteger(thing, 'CNT', 0); if cnt = 1 then begin lines := obs.ReadInteger(thing, '100', 0); for i := 1 to lines do begin ALine := obs.ReadString(thing, IntToStr(100+i), ''); TmpSeqs.Add(ALine); end; end; finally obs.Free; end; end; procedure DO_CreateListForAlex; var s,w : Integer; TheSector : TSector; TheWall : TWall; FL_LIST : TStringList; TE_LIST : TStringList; ALEX_LIST : TStringList; begin FL_LIST := TStringList.Create; FL_LIST.Sorted := TRUE; FL_LIST.Duplicates := dupIgnore; TE_LIST := TStringList.Create; TE_LIST.Sorted := TRUE; TE_LIST.Duplicates := dupIgnore; for s := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[s]); FL_LIST.Add(TheSector.Floor.Name); FL_LIST.Add(TheSector.Ceili.Name); for w := 0 to TheSector.Wl.Count - 1 do begin TheWall := TWall(TheSector.Wl.Objects[w]); TE_LIST.Add(TheWall.Mid.Name); TE_LIST.Add(TheWall.Top.Name); TE_LIST.Add(TheWall.Bot.Name); {!!!!! we should handle switches for the new WAD2GOB !!!!!} if TheWall.Sign.Name <> '' then TE_LIST.Add(TheWall.Sign.Name); end; end; {construct my own TX_LIST now, as I have all the info} TX_LIST.Clear; TX_LIST.Sorted := TRUE; TX_LIST.Duplicates := dupIgnore; TX_LIST.AddStrings(FL_LIST); TX_LIST.AddStrings(TE_LIST); {Get rid of - in my list, replace it everywhere by DEFAULT.BM} TX_LIST.Sorted := FALSE; s := TX_LIST.IndexOf('-'); if s <> -1 then TX_LIST.Delete(s); TX_List.Add('DEFAULT.BM'); TX_LIST.Sorted := TRUE; for s := 0 to MAP_SEC.Count - 1 do begin TheSector := TSector(MAP_SEC.Objects[s]); if TheSector.Floor.Name = '-' then TheSector.Floor.Name := 'DEFAULT.BM'; if TheSector.Ceili.Name = '-' then TheSector.Ceili.Name := 'DEFAULT.BM'; for w := 0 to TheSector.Wl.Count - 1 do begin TheWall := TWall(TheSector.Wl.Objects[w]); if TheWall.Mid.Name = '-' then TheWall.Mid.name := 'DEFAULT.BM'; if TheWall.Top.Name = '-' then TheWall.Top.name := 'DEFAULT.BM'; if TheWall.Bot.Name = '-' then TheWall.Bot.name := 'DEFAULT.BM'; end; end; {remove '-' and all the '.BM' from Alex' list} s := TE_LIST.IndexOf('-'); if s <> -1 then TE_LIST.Delete(s); {mandatory to allow direct access in a sorted list} FL_LIST.Sorted := FALSE; TE_LIST.Sorted := FALSE; for s := 0 to FL_LIST.Count - 1 do begin FL_LIST[s] := Copy(FL_LIST[s], 1, Pos('.BM', FL_LIST[s])-1); end; {remove sky from the flats} s := FL_LIST.IndexOf(TheSky); if s <> -1 then FL_LIST.Delete(s); for s := 0 to TE_LIST.Count - 1 do begin TE_LIST[s] := Copy(TE_LIST[s], 1, Pos('.BM', TE_LIST[s])-1); end; ALEX_LIST := TStringList.Create; ALEX_LIST.Add('[FLATS]'); ALEX_LIST.AddStrings(FL_LIST); ALEX_LIST.Add(''); ALEX_LIST.Add('[TEXTURES]'); ALEX_LIST.Add(TheSky); ALEX_LIST.AddStrings(TE_LIST); ALEX_LIST.Add(''); ALEX_LIST.Add('[SPRITES]'); for s := 0 to SPR_LIST.Count - 1 do begin ALEX_LIST.Add(Copy(SPR_LIST[s], 1, Pos('.WAX', SPR_LIST[s])-1)); end; ALEX_LIST.Add(''); ALEX_LIST.Add('[FRAMES]'); for s := 0 to FME_LIST.Count - 1 do begin ALEX_LIST.Add(Copy(FME_LIST[s], 1, Pos('.FME', FME_LIST[s])-1)); end; FL_LIST.Free; TE_LIST.Free; ALEX_LIST.SaveToFile(LEVELPath+'\doom_res.lst'); WAD_CNVRTLOG.Add(''); WAD_CNVRTLOG.Add('Contents of ' + LEVELPath+'\doom_res.lst'); WAD_CNVRTLOG.Add(''); WAD_CNVRTLOG.AddStrings(ALEX_LIST); ALEX_LIST.Free; end; end.
unit SplashScreenUnit; interface uses Windows, Dialogs, SysUtils, Classes, Forms, Controls, StdCtrls, ExtCtrls, Vcl.Imaging.PNGImage, Graphics, Types; type TSplashScreen = class(TForm) procedure FormCreate(Sender: TObject); procedure RenderForm; procedure SetProgress(Progress: Single); private BMPBack, BMPGray, BMPLogo, BMPLogoPart: TBitmap; LoadingProgress: Single; public end; var SplashScreen: TSplashScreen; implementation {$R *.dfm} uses MainWindowUnit; procedure BuildPNG2BMP(PNGID: string; var BMP: TBitmap); const MaxPixelCountA = MaxInt div SizeOf(TRGBQuad); type PRGBAArray = ^TRGBAArray; TRGBAArray = array [0 .. MaxPixelCountA - 1] of TRGBQuad; var i1, i2: Integer; PNG: TPngImage; PRGBArr: PRGBAArray; pByteArr: pByteArray; begin PNG := TPngImage.Create; try PNG.LoadFromResourceName(HInstance, PNGID); PNG.CreateAlpha; BMP.Assign(PNG); BMP.PixelFormat := pf32bit; for i2 := 0 to BMP.Height - 1 do begin PRGBArr := BMP.ScanLine[i2]; pByteArr := PNG.AlphaScanline[i2]; for i1 := 0 to BMP.Width - 1 do begin PRGBArr[i1].rgbReserved := pByteArr[i1]; end; end; finally PNG.free; end; end; procedure Multed(BMPout: TBitmap); const MaxPixelCountA = MaxInt div SizeOf(TRGBQuad); type PRGBAArray = ^TRGBAArray; TRGBAArray = array [0 .. MaxPixelCountA - 1] of TRGBQuad; var x, y: Integer; RowOut: PRGBAArray; begin for y := 0 to BMPout.Height - 1 do begin RowOut := BMPout.ScanLine[y]; for x := 0 to BMPout.Width - 1 do begin RowOut[x].rgbBlue := byte(trunc(RowOut[x].rgbBlue * RowOut[x].rgbReserved / 255)); RowOut[x].rgbGreen := byte(trunc(RowOut[x].rgbGreen * RowOut[x].rgbReserved / 255)); RowOut[x].rgbRed := byte(trunc(RowOut[x].rgbRed * RowOut[x].rgbReserved / 255)); end; end; end; procedure TSplashScreen.FormCreate(Sender: TObject); begin LoadingProgress := -5.0; BMPLogo := TBitmap.Create; BuildPNG2BMP('LOGO', BMPLogo); BMPBack := TBitmap.Create; BuildPNG2BMP('SSBACK', BMPBack); BMPLogoPart := TBitmap.Create; BMPLogoPart.Width := BMPLogo.Width; BMPLogoPart.Height := BMPLogo.Height; BMPGray := TBitmap.Create; BMPGray.Width := BMPBack.Width; BMPGray.Height := BMPBack.Height; BMPGray.Assign(BMPBack); Multed(BMPBack); SetProgress(0); RenderForm; end; procedure TSplashScreen.RenderForm; var bf: TBlendFunction; TopLeft, pnt: TPoint; sz: TSize; begin SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_LAYERED); sz.cx := BMPBack.Width; sz.cy := BMPBack.Height; pnt := Point(0, 0); with bf do begin BlendOp := AC_SRC_OVER; BlendFlags := 0; AlphaFormat := AC_SRC_ALPHA; SourceConstantAlpha := 255; end; TopLeft := BoundsRect.TopLeft; UpdateLayeredWindow(Handle, GetDC(0), @TopLeft, @sz, BMPBack.Canvas.Handle, @pnt, 0, @bf, ULW_ALPHA); end; procedure TSplashScreen.SetProgress(Progress: Single); var h: Integer; begin LoadingProgress := Progress / 100 * 105 - 5; with BMPLogoPart.Canvas do begin Draw(0, 0, BMPLogo); Brush.Color := clBlack; h := BMPLogo.Height - Round(BMPLogo.Height / 100 * LoadingProgress); Rectangle(0, 0, BMPLogo.Width, h); BMPBack.Assign(BMPGray); BitBlt(BMPBack.Canvas.Handle, 188, 70, BMPLogo.Width, BMPLogo.Height, Handle, 0, 0, SRCPAINT); end; RenderForm; end; end.
unit Chapter07._05_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, AI.TreeNode; /// 437. Path Sum III /// https://leetcode.com/problems/path-sum-iii/description/ /// 时间复杂度: O(n), n为树的节点个数 /// 空间复杂度: O(h), h为树的高度 type TSolution = class(TObject) private // 在以node为根节点的二叉树中,寻找包含node的路径,和为num // 返回这样的路径个数 function __findPath(node: TTreeNode; num: integer): integer; public // 在以root为根节点的二叉树中,寻找和为sum的路径,返回这样的路径个数 function pathSum(root: TTreeNode; sum: integer): integer; end; procedure Main; implementation procedure Main; begin end; { TSolution } function TSolution.pathSum(root: TTreeNode; sum: integer): integer; begin if root = nil then Exit(0); Result := __findPath(root, sum) + __findPath(root.Left, sum) + __findPath(root.Right, sum); end; function TSolution.__findPath(node: TTreeNode; num: integer): integer; var res: integer; begin if node = nil then Exit(0); res := 0; if node.Val = num then res += 1; res += __findPath(node.Left, num - node.Val); res += __findPath(node.Right, num - node.Val); Result := res; end; end.
program DrawPrimitives; uses sgTypes, SwinGame; procedure Main(); var t: Timer; time: Integer; i: Integer; clipped: Boolean; begin OpenAudio(); OpenGraphicsWindow('Draw Primitives', 640, 480); t := CreateTimer(); StartTimer(t); ClearScreen(ColorWhite); clipped := false; repeat // The game loop... ProcessEvents(); if KeyTyped(FKey) then begin ToggleFullscreen(); WriteLn('Toggle Fullscreen'); end; if KeyTyped(SKey) then TakeScreenshot('test'); if KeyTyped(BKey) then ToggleWindowBorder(); if KeyTyped(CKey) then begin WriteLn('Centre pixel is ', GetPixelFromScreen(320, 240)); MoveMouse(320, 240); end; time := TimerTicks(t); if time < 1000 then begin FillEllipse(RandomColor(), Rnd(640), Rnd(480), -Rnd(200), -Rnd(200)); DrawEllipse(RandomColor(), Rnd(640), Rnd(480), -Rnd(200), -Rnd(200)); end else if time < 2000 then begin FillEllipse(RandomColor(), Rnd(640), Rnd(480), Rnd(200), Rnd(200)); DrawEllipse(RandomColor(), Rnd(640), Rnd(480), Rnd(200), Rnd(200)); end else if time < 4000 then begin DrawCircle(RandomColor(), Rnd(640), Rnd(480), Rnd(200)); FillCircle(RandomColor(), Rnd(640), Rnd(480), Rnd(200)); end else if time < 5000 then begin DrawRectangle(RandomColor(), Rnd(640), Rnd(480), Rnd(200), Rnd(200)); FillRectangle(RandomColor(), Rnd(640), Rnd(480), Rnd(200), Rnd(200)); end else if time < 6000 then begin DrawRectangle(RandomColor(), Rnd(640), Rnd(480), -Rnd(200), -Rnd(200)); FillRectangle(RandomColor(), Rnd(640), Rnd(480), -Rnd(200), -Rnd(200)); end else if time < 7500 then begin DrawLine(RandomColor(), Rnd(640), Rnd(480), Rnd(640), Rnd(480), OptionLineWidth(1 + Rnd(5))); end else if time < 9000 then begin for i := 0 to 999 do DrawPixel(RandomColor(), Rnd(640), Rnd(480)); end else if time < 11000 then begin DrawTriangle(RandomColor(), Rnd(640), Rnd(480), Rnd(640), Rnd(480), Rnd(640), Rnd(480)); FillTriangle(RandomColor(), Rnd(640), Rnd(480), Rnd(640), Rnd(480), Rnd(640), Rnd(480)); end else begin ResetTimer(t); if clipped then begin ResetClip(); clipped := False; end else begin ClearScreen(ColorWhite); FillRectangle(ColorGreen, 160, 50, 320, 240); SetClip(RectangleFrom(160, 50, 320, 240)); clipped := True; end; end; RefreshScreen(); until WindowCloseRequested(); ReleaseAllResources(); CloseAudio(); end; begin Main(); end.
(* Category: SWAG Title: MENU MANAGEMENT ROUTINES Original name: 0006.PAS Description: Re: Arrow Keys Author: PETER LOUWEN Date: 11-25-95 09:26 *) (* SB> i have a problem. I want it to show Three Choices Like This; SB> Choice #1 SB> Choice #2 SB> Choice #3 SB> SB> I want Choice #1 to be in White, and the others to be In Darkgray, if SB> they press down, it will make only #2 White, and the others Darkgray, SB> if they press Down again it will make only Choice #3 White, and it will SB> Tell Them Which Choice they choosed on each one if they press enter. SB> So if they press Enter while Choice #1 Was Highlighted, it would say SB> 'You Chose Choice Number 1'. and and it will Repeat when you Press the SB> arrow keys, untill they press Enter on anyone of the Choice Choices... The following should get you started: *) PROGRAM Seans_Menu; USES Crt; {FUNCTION readkeyword: word; ASSEMBLER;} { -- Assumes you have an extended (i.e. non-XT) keyboard. -- Returns both scancode and character with one call. } {ASM mov ah, $10 int $16 END;} CONST { -- Value returned by ReadKeyword for the down arrow key. } {Down = $5000; Up = $4800; Enter = $1C0D; Esc = $011B;} Down = #$50; Up = #$48; Enter = #$0D; Esc = #$1B; PROCEDURE menu(CONST nbr_of_choices: byte; VAR selected : byte; VAR accept : boolean); { -- Puts up a menu with NBR_OF_CHOICES choices. -- The user can use the up and down arrow keys to select a particular -- menu item. Enter then selects, and Esc exits immediately. -- On exit, if the user pressed Enter, ACCEPT will be TRUE, and SELECTED -- will hold the number of the selected item. If the user cancelled the -- selection (Esc pressed), ACCEPT will be FALSE, and SELECTED then is -- undefined. } CONST StartingCol = 5; { -- These two determine the top left corner of } StartingRow = 3; { -- your menu. } NormalColour = DarkGray; HiliteColour = White; Str = 'Choice #'; VAR j, TA: byte; PROCEDURE beep; BEGIN sound(700); delay(50); nosound END; PROCEDURE DrawCurrentlySelected; BEGIN gotoxy(StartingCol, StartingRow + selected - 1); write(Str, selected:1) END; PROCEDURE DoDown; BEGIN DrawCurrentlySelected; { -- Redraw current item in the normal, i.e. unselected, colour. } IF selected = nbr_of_choices THEN selected:=1 ELSE inc(selected); TextAttr:=HiliteColour; DrawCurrentlySelected; { -- Move cursor to newly selected item and redraw in the highlight, -- i.e. selected, colour. } TextAttr:=NormalColour END; PROCEDURE DoUp; BEGIN DrawCurrentlySelected; IF selected = 1 THEN selected:=nbr_of_choices ELSE dec(selected); TextAttr:=HiliteColour; DrawCurrentlySelected; TextAttr:=NormalColour END; PROCEDURE Process; { -- Keep reading keys until user decides s/he has had enough. } VAR finished: boolean; key : char; BEGIN finished:=FALSE; REPEAT key:=readkey; if key = #0 THEN key:=readkey; CASE key OF Down : DoDown; Up : DoUp; Enter: BEGIN finished:=TRUE; accept:=TRUE END; Esc : BEGIN finished:=TRUE; accept:=FALSE END; ELSE beep END UNTIL finished END; BEGIN (* menu *) gotoxy(StartingCol, StartingRow); TA:=TextAttr; { -- If you start messing with the screen colours, it is good -- manners to mark the current ones, so you can restore them -- when you're through. } { -- Now draw all items in the unselected colour: } TextAttr:=NormalColour; FOR j:=1 TO nbr_of_choices DO BEGIN gotoxy(StartingCol, StartingRow + j - 1); write(Str, j:1) END; { -- Do first item in selected colour: } TextAttr:=HiliteColour; selected:=1; DrawCurrentlySelected; TextAttr:=NormalColour; accept:=FALSE; Process; TextAttr:=TA END; PROCEDURE ColourClrscr(CONST Colour_U_Like: byte); { -- Clears the screen, colouring all positions. -- Not essential, just nice ... } VAR TA: byte; BEGIN TA:=TextAttr; TextAttr:=Colour_U_Like; clrscr; TextAttr:=TA END; { -- Main: } VAR choice: byte; ok : boolean; BEGIN ColourClrscr(Blue*16); menu(5, choice, ok); gotoxy(1, 20); IF ok THEN writeln('You chose nr. ', choice:1) ELSE writeln('You aborted ...') END.
unit Odontologia.Controlador.Estado.Cita; interface uses Data.DB, System.Generics.Collections, System.SysUtils, Odontologia.Modelo, Odontologia.Modelo.Entidades.Estado.Cita, Odontologia.Modelo.Estado.Cita.Interfaces, Odontologia.Controlador.Estado.Cita.Interfaces; type TControllerEstadoCita = class(TInterfacedObject, iControllerEstadoCita) private FModel: iModelEstadoCita; FDataSource: TDataSource; FEntidad: TFESTADO_CITA; public constructor Create; destructor Destroy; override; class function New: iControllerEstadoCita; function DataSource(aDataSource: TDataSource): iControllerEstadoCita; function Buscar: iControllerEstadoCita; function Insertar: iControllerEstadoCita; function Modificar: iControllerEstadoCita; function Eliminar: iControllerEstadoCita; function Entidad: TFESTADO_CITA; end; implementation { TControllerEstadoCita } function TControllerEstadoCita.Buscar: iControllerEstadoCita; begin Result := Self; FModel.DAO .SQL .Where('') .&End .Find; end; constructor TControllerEstadoCita.Create; begin FModel := TModel.New.EstadoCita; end; function TControllerEstadoCita.DataSource(aDataSource: TDataSource) : iControllerEstadoCita; begin Result := Self; FDataSource := aDataSource; FModel.DataSource(FDataSource); end; destructor TControllerEstadoCita.Destroy; begin FEntidad.Free; inherited; end; function TControllerEstadoCita.Eliminar: iControllerEstadoCita; begin Result := Self; FModel.DAO.Delete(FModel.Entidad); end; function TControllerEstadoCita.Entidad: TFESTADO_CITA; begin Result := FModel.Entidad; end; function TControllerEstadoCita.Insertar: iControllerEstadoCita; begin Result := Self; FModel.DAO.Insert(FModel.Entidad); end; function TControllerEstadoCita.Modificar: iControllerEstadoCita; begin Result := Self; FModel.DAO.Update(FModel.Entidad); end; class function TControllerEstadoCita.New: iControllerEstadoCita; begin Result := Self.Create; end; end.
namespace proholz.xsdparser; interface type UnsolvedReferenceItem = public class private // * // * A {@link UnsolvedReference} object that wasn't solved in the parsing process. This happened because its referred // * element isn't present in the files that were parsed. // // var unsolvedReference: UnsolvedReference; // * // * A list of parents which indicate all the places where the {@link UnsolvedReference} object was used, which cause // * every element present in this list to not be fully correct. // // var parents: List<XsdAbstractElement>; public constructor(aunsolvedReference: UnsolvedReference); method getUnsolvedReference: UnsolvedReference; virtual; method getParents: List<XsdAbstractElement>; virtual; end; implementation constructor UnsolvedReferenceItem(aunsolvedReference: UnsolvedReference); begin self.unsolvedReference := aunsolvedReference; self.parents := new List<XsdAbstractElement>(); self.parents.Add(unsolvedReference.getParent()); end; method UnsolvedReferenceItem.getUnsolvedReference: UnsolvedReference; begin exit unsolvedReference; end; method UnsolvedReferenceItem.getParents: List<XsdAbstractElement>; begin exit parents; end; end.
Unit ListarDispositivos; interface uses windows, SetupAPI, DeviceHelper, sysutils; const NumDevices = 500; Separador = '@@##&&'; var ClassImageListData: TSPClassImageListData; hAllDevices: HDEVINFO; DeviceHelper: TDeviceHelper; tvRoot: array [0..NumDevices] of string; LastRoot: integer = 0; procedure ReleaseDeviceList; procedure InitDeviceList(ShowHidden: boolean); function FillDeviceList(var DeviceClassesCount: integer; var DevicesCount: integer): string; function ShowDeviceAdvancedInfo(const DeviceIndex: Integer): string; function ShowDeviceInterfaces(const DeviceIndex: Integer): string; implementation function FindRootNode(ClassName: string): integer; var i: integer; begin result := -1; for i := 0 to NumDevices do begin if copy(tvroot[i], 1, pos(Separador, tvroot[i]) - 1) = ClassName then begin result := i; break; end; end; end; procedure ReleaseDeviceList; begin SetupDiDestroyDeviceInfoList(hAllDevices); end; procedure InitDeviceList(ShowHidden: boolean); const PINVALID_HANDLE_VALUE = Pointer(INVALID_HANDLE_VALUE); var dwFlags: DWORD; begin dwFlags := DIGCF_ALLCLASSES;// or DIGCF_DEVICEINTERFACE; if not ShowHidden then dwFlags := dwFlags or DIGCF_PRESENT; hAllDevices := SetupDiGetClassDevsExA(nil, nil, 0, dwFlags, nil, nil, nil); if hAllDevices = PINVALID_HANDLE_VALUE then RaiseLastOSError; DeviceHelper.DeviceListHandle := hAllDevices; end; function FillDeviceList(var DeviceClassesCount: integer; var DevicesCount: integer): string; var dwIndex: DWORD; DeviceInfoData: SP_DEVINFO_DATA; DeviceName, DeviceClassName: String; ClassGUID: TGUID; RootAtual, i: integer; TempStr: string; begin dwIndex := 0; DeviceClassesCount := 0; DevicesCount := 0; ZeroMemory(@DeviceInfoData, SizeOf(SP_DEVINFO_DATA)); DeviceInfoData.cbSize := SizeOf(SP_DEVINFO_DATA); while SetupDiEnumDeviceInfo(hAllDevices, dwIndex, DeviceInfoData) do begin DeviceHelper.DeviceInfoData := DeviceInfoData; DeviceName := DeviceHelper.FriendlyName; if DeviceName = '' then DeviceName := DeviceHelper.Description; ClassGUID := DeviceHelper.ClassGUID; DeviceClassName := DeviceHelper.DeviceClassDescription(ClassGUID); if length(DeviceClassName) > 1 then begin RootAtual := FindRootNode(DeviceClassName); if RootAtual = -1 then begin RootAtual := LastRoot; tvRoot[RootAtual] := tvRoot[RootAtual] + DeviceClassName + Separador; // DeviceType setstring(TempStr, pchar(@ClassGUID), sizeof(ClassGUID)); tvRoot[RootAtual] := tvRoot[RootAtual] + TempStr + '##' + separador; // ClassGUID para pegar a ImageIndex tvRoot[RootAtual] := tvRoot[RootAtual] + '-1' + separador + #13#10; // StateIndex Inc(DeviceClassesCount); end; if length(DeviceName) > 1 then begin tvRoot[RootAtual] := tvRoot[RootAtual] + '@@' + DeviceName + Separador; // DeviceName setstring(TempStr, pchar(@DeviceInfoData.ClassGuid), sizeof(DeviceInfoData.ClassGuid)); tvRoot[RootAtual] := tvRoot[RootAtual] + TempStr + '##' + separador; // ClassGUID para pegar a ImageIndex tvRoot[RootAtual] := tvRoot[RootAtual] + inttostr(Integer(dwIndex)) + Separador + #13#10; // StateIndex end; end; Inc(DevicesCount); Inc(LastRoot); Inc(dwIndex); end; for i := 0 to NumDevices do if tvRoot[i] <> '' then Result := Result + tvRoot[i]; end; function ShowDeviceAdvancedInfo(const DeviceIndex: Integer): string; var DeviceInfoData: SP_DEVINFO_DATA; EmptyGUID, AGUID: TGUID; dwData: DWORD; begin ZeroMemory(@EmptyGUID, SizeOf(TGUID)); ZeroMemory(@DeviceInfoData, SizeOf(SP_DEVINFO_DATA)); DeviceInfoData.cbSize := SizeOf(SP_DEVINFO_DATA); if not SetupDiEnumDeviceInfo(hAllDevices, DeviceIndex, DeviceInfoData) then Exit; DeviceHelper.DeviceInfoData := DeviceInfoData; if DeviceHelper.Description <> '' then result := result + 'Device Description: ' + Separador + DeviceHelper.Description + Separador + #13#10; if DeviceHelper.HardwareID <> '' then result := result + 'Hardware IDs: ' + Separador + DeviceHelper.HardwareID + Separador + #13#10; if DeviceHelper.CompatibleIDS <> '' then result := result + 'Compatible IDs: ' + Separador + DeviceHelper.CompatibleIDS + Separador + #13#10; if DeviceHelper.DriverName <> '' then result := result + 'Driver: ' + Separador + DeviceHelper.DriverName + Separador + #13#10; if DeviceHelper.DeviceClassName <> '' then result := result + 'Class name: ' + Separador + DeviceHelper.DeviceClassName + Separador + #13#10; if DeviceHelper.Manufacturer <> '' then result := result + 'Manufacturer: ' + Separador + DeviceHelper.Manufacturer + Separador + #13#10; if DeviceHelper.FriendlyName <> '' then result := result + 'Friendly Description: ' + Separador + DeviceHelper.FriendlyName + Separador + #13#10; if DeviceHelper.Location <> '' then result := result + 'Location Information: ' + Separador + DeviceHelper.Location + Separador + #13#10; if DeviceHelper.PhisicalDriverName <> '' then result := result + 'Device CreateFile Name: ' + Separador + DeviceHelper.PhisicalDriverName + Separador + #13#10; if DeviceHelper.Capabilities <> '' then result := result + 'Capabilities: ' + Separador + DeviceHelper.Capabilities + Separador + #13#10; if DeviceHelper.ConfigFlags <> '' then result := result + 'ConfigFlags: ' + Separador + DeviceHelper.ConfigFlags + Separador + #13#10; if DeviceHelper.UpperFilters <> '' then result := result + 'UpperFilters: ' + Separador + DeviceHelper.UpperFilters + Separador + #13#10; if DeviceHelper.LowerFilters <> '' then result := result + 'LowerFilters: ' + Separador + DeviceHelper.LowerFilters + Separador + #13#10; if DeviceHelper.LegacyBusType <> '' then result := result + 'LegacyBusType: ' + Separador + DeviceHelper.LegacyBusType + Separador + #13#10; if DeviceHelper.Enumerator <> '' then result := result + 'Enumerator: ' + Separador + DeviceHelper.Enumerator + Separador + #13#10; if DeviceHelper.Characteristics <> '' then result := result + 'Characteristics: ' + Separador + DeviceHelper.Characteristics + Separador + #13#10; if DeviceHelper.UINumberDecription <> '' then result := result + 'UINumberDecription: ' + Separador + DeviceHelper.UINumberDecription + Separador + #13#10; if DeviceHelper.RemovalPolicy <> '' then result := result + 'RemovalPolicy: ' + Separador + DeviceHelper.RemovalPolicy + Separador + #13#10; if DeviceHelper.RemovalPolicyHWDefault <> '' then result := result + 'RemovalPolicyHWDefault: ' + Separador + DeviceHelper.RemovalPolicyHWDefault + Separador + #13#10; if DeviceHelper.RemovalPolicyOverride <> '' then result := result + 'RemovalPolicyOverride: ' + Separador + DeviceHelper.RemovalPolicyOverride + Separador + #13#10; if DeviceHelper.InstallState <> '' then result := result + 'InstallState: ' + Separador + DeviceHelper.InstallState + Separador + #13#10; if not CompareMem(@EmptyGUID, @DeviceInfoData.ClassGUID, SizeOf(TGUID)) then result := result + 'Device GUID: ' + Separador + GUIDToString(DeviceInfoData.ClassGUID) + Separador + #13#10; AGUID := DeviceHelper.BusTypeGUID; if not CompareMem(@EmptyGUID, @AGUID, SizeOf(TGUID)) then result := result + 'Bus Type GUID: ' + Separador + GUIDToString(AGUID) + Separador + #13#10; dwData := DeviceHelper.UINumber; if dwData <> 0 then result := result + 'UI Number: ' + Separador + IntToStr(dwData) + Separador + #13#10; dwData := DeviceHelper.BusNumber; if dwData <> 0 then result := result + 'Bus Number: ' + Separador + IntToStr(dwData) + Separador + #13#10; dwData := DeviceHelper.Address; if dwData <> 0 then result := result + 'Device Address: ' + Separador + IntToStr(dwData) + Separador + #13#10; end; function ShowDeviceInterfaces(const DeviceIndex: Integer): string; var hInterfaces: HDEVINFO; DeviceInfoData: SP_DEVINFO_DATA; DeviceInterfaceData: TSPDeviceInterfaceData; I: Integer; begin ZeroMemory(@DeviceInfoData, SizeOf(SP_DEVINFO_DATA)); DeviceInfoData.cbSize := SizeOf(SP_DEVINFO_DATA); ZeroMemory(@DeviceInterfaceData, SizeOf(TSPDeviceInterfaceData)); DeviceInterfaceData.cbSize := SizeOf(TSPDeviceInterfaceData); if not SetupDiEnumDeviceInfo(hAllDevices, DeviceIndex, DeviceInfoData) then Exit; hInterfaces := SetupDiGetClassDevs(@DeviceInfoData.ClassGuid, nil, 0, DIGCF_PRESENT or DIGCF_INTERFACEDEVICE); if not Assigned(hInterfaces) then RaiseLastOSError; try I := 0; while SetupDiEnumDeviceInterfaces(hInterfaces, nil, DeviceInfoData.ClassGuid, I, DeviceInterfaceData) do begin case DeviceInterfaceData.Flags of SPINT_ACTIVE: result := result + 'Interface State: ' + Separador + 'SPINT_ACTIVE' + Separador + #13#10; SPINT_DEFAULT: result := result + 'Interface State: ' + Separador + 'SPINT_DEFAULT' + Separador + #13#10; SPINT_REMOVED: result := result + 'Interface State: ' + Separador + 'SPINT_REMOVED' + Separador + #13#10; else result := result + 'Interface State: ' + Separador + 'unknown 0x' + IntToHex(DeviceInterfaceData.Flags, 8) + Separador + #13#10; end; Inc(I); end; finally SetupDiDestroyDeviceInfoList(hInterfaces); end; end; initialization if not LoadSetupApi then RaiseLastOSError; DeviceHelper := TDeviceHelper.Create; InitDeviceList(true); finalization DeviceHelper.Free; ReleaseDeviceList; end.
{******************************************************************************} { } { Delphi OPENSSL Library } { Copyright (c) 2021 Lsuper } { https://github.com/delphilite/DelphiOpenSSL } { } {******************************************************************************} { } { 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. } { } {******************************************************************************} unit OpenSSL.HashUtils; // https://www.openssl.org/docs/man1.1.1/man3/MD4.html // https://www.openssl.org/docs/man1.1.1/man3/MD5.html // https://www.openssl.org/docs/man1.1.1/man3/SHA1.html // https://www.openssl.org/docs/man1.1.1/man3/SHA256.html interface uses System.SysUtils, System.Classes, OpenSSL.Api_11, OpenSSL.Core; type THashUtil = class(TOpenSSLBase) public // initialize Hash context for hashing procedure Init; virtual; abstract; // update the Hash context with some data procedure Update(ABuffer: Pointer; ASize: integer); virtual; abstract; // update the Hash context with stream data procedure UpdateStream(AStream: TStream; const ACount: Int64 = 0); // finalize and compute the resulting Hash hash Digest of all data // affected to Update() method procedure Final(out ADigest: TBytes); virtual; abstract; public // portal for stream class function Execute(AStream: TStream; const ACount: Int64 = 0): TBytes; overload; // portal for bytes class function Execute(const AData: TBytes): TBytes; overload; end; // handle MD4 hashing TMD4 = class(THashUtil) private FContext: MD4_CTX; public // initialize MD4 context for hashing procedure Init; override; // update the MD4 context with some data procedure Update(ABuffer: Pointer; ASize: integer); override; // finalize and compute the resulting MD4 hash Digest of all data // affected to Update() method procedure Final(out ADigest: TBytes); override; end; // handle MD5 hashing TMD5 = class(THashUtil) private FContext: MD5_CTX; public // initialize MD5 context for hashing procedure Init; override; // update the MD5 context with some data procedure Update(ABuffer: Pointer; ASize: integer); override; // finalize and compute the resulting MD5 hash Digest of all data // affected to Update() method procedure Final(out ADigest: TBytes); override; end; /// handle SHA1 hashing TSHA1 = class(THashUtil) private FContext: SHA_CTX; public // initialize SHA1 context for hashing procedure Init; override; // update the SHA1 context with some data procedure Update(ABuffer: Pointer; ASize: integer); override; // finalize and compute the resulting SHA1 hash Digest of all data // affected to Update() method procedure Final(out ADigest: TBytes); override; end; /// handle SHA256 hashing TSHA256 = class(THashUtil) private FContext: SHA256_CTX; public // initialize SHA256 context for hashing procedure Init; override; // update the SHA256 context with some data procedure Update(ABuffer: Pointer; ASize: integer); override; // finalize and compute the resulting SHA256 hash Digest of all data // affected to Update() method procedure Final(out ADigest: TBytes); override; end; /// handle SHA512 hashing TSHA512 = class(THashUtil) private FContext: SHA512_CTX; public // initialize SHA512 context for hashing procedure Init; override; // update the SHA512 context with some data procedure Update(ABuffer: Pointer; ASize: integer); override; // finalize and compute the resulting SHA512 hash Digest of all data // affected to Update() method procedure Final(out ADigest: TBytes); override; end; implementation uses System.Math; { THashUtil } class function THashUtil.Execute(const AData: TBytes): TBytes; begin with Self.Create do try Init; Update(Pointer(AData), Length(AData)); Final(Result); finally Free; end; end; class function THashUtil.Execute(AStream: TStream; const ACount: Int64): TBytes; begin with Self.Create do try Init; UpdateStream(AStream, ACount); Final(Result); finally Free; end; end; procedure THashUtil.UpdateStream(AStream: TStream; const ACount: Int64); const defBufferSize = 1024 * 1024; { 1m } var B: TBytes; L, R: Integer; C: Int64; begin if ACount = 0 then C := AStream.Size - AStream.Position else C := Min(ACount, AStream.Size - AStream.Position); SetLength(B, defBufferSize); while C > 0 do begin L := Min(C, defBufferSize); R := AStream.Read(Pointer(B)^, L); Update(Pointer(B), R); Dec(C, R); end; end; { TMD4 } procedure TMD4.Final(out ADigest: TBytes); begin SetLength(ADigest, MD4_DIGEST_LENGTH); MD4_Final(PByte(ADigest), @FContext); end; procedure TMD4.Init; begin MD4_Init(@FContext); end; procedure TMD4.Update(ABuffer: Pointer; ASize: integer); begin MD4_Update(@FContext, ABuffer, ASize); end; { TMD5 } procedure TMD5.Final(out ADigest: TBytes); begin SetLength(ADigest, MD5_DIGEST_LENGTH); MD5_Final(PByte(ADigest), @FContext); end; procedure TMD5.Init; begin MD5_Init(@FContext); end; procedure TMD5.Update(ABuffer: Pointer; ASize: integer); begin MD5_Update(@FContext, ABuffer, ASize); end; { TSHA1 } procedure TSHA1.Final(out ADigest: TBytes); begin SetLength(ADigest, SHA_DIGEST_LENGTH); SHA1_Final(PByte(ADigest), @FContext); end; procedure TSHA1.Init; begin SHA1_Init(@FContext); end; procedure TSHA1.Update(ABuffer: Pointer; ASize: integer); begin SHA1_Update(@FContext, ABuffer, ASize); end; { TSHA256 } procedure TSHA256.Final(out ADigest: TBytes); begin SetLength(ADigest, SHA256_DIGEST_LENGTH); SHA256_Final(PByte(ADigest), @FContext); end; procedure TSHA256.Init; begin SHA256_Init(@FContext); end; procedure TSHA256.Update(ABuffer: Pointer; ASize: integer); begin SHA256_Update(@FContext, ABuffer, ASize); end; { TSHA512 } procedure TSHA512.Final(out ADigest: TBytes); begin SetLength(ADigest, SHA512_DIGEST_LENGTH); SHA512_Final(PByte(ADigest), @FContext); end; procedure TSHA512.Init; begin SHA512_Init(@FContext); end; procedure TSHA512.Update(ABuffer: Pointer; ASize: integer); begin SHA512_Update(@FContext, ABuffer, ASize); end; end.
unit uFrmHistory; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, siComp; const HIST_TRANSACTION = 0; HIST_ERROR = 1; HIST_IMPORT = 2; type TFrmHistory = class(TForm) Panel1: TPanel; Bevel1: TBevel; memHistory: TMemo; siLang: TsiLang; Panel2: TPanel; BitBtn3: TBitBtn; BtnSave: TBitBtn; BitBtn2: TBitBtn; Panel3: TPanel; cbxHistory: TComboBox; btnEmail: TBitBtn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BitBtn3Click(Sender: TObject); procedure cbxHistoryChange(Sender: TObject); procedure btnEmailClick(Sender: TObject); private { Private declarations } procedure GetHistory(iType:Integer); procedure SetHistory(iType:Integer); public { Public declarations } function Start:Boolean; end; implementation uses uMainConf, uPOSServerConsts; {$R *.dfm} procedure TFrmHistory.GetHistory(iType:Integer); var sHistoryFile : String; sPath: String; begin sPath := ExtractFileDir(Application.ExeName) + '\'; case iType of HIST_TRANSACTION : sHistoryFile := sPath + HISTORY_FILE; HIST_ERROR : sHistoryFile := sPath + ERROR_FILE; HIST_IMPORT : sHistoryFile := sPath + IMPORT_FILE; end; memHistory.Lines.Clear; if FileExists(sHistoryFile) then memHistory.Lines.LoadFromFile(sHistoryFile); btnEmail.Enabled := (Trim(memHistory.Lines.Text) <> ''); memHistory.SelStart := 0; end; procedure TFrmHistory.SetHistory(iType:Integer); var sPath: String; begin sPath := ExtractFileDir(Application.ExeName) + '\'; case iType of HIST_TRANSACTION : memHistory.Lines.SaveToFile(sPath + HISTORY_FILE); HIST_ERROR : memHistory.Lines.SaveToFile(sPath + ERROR_FILE); HIST_IMPORT : memHistory.Lines.SaveToFile(sPath + IMPORT_FILE); end; end; function TFrmHistory.Start:boolean; begin GetHistory(HIST_TRANSACTION); ShowModal; Result := (ModalResult=mrOK); if Result then SetHistory(cbxHistory.ItemIndex); end; procedure TFrmHistory.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmHistory.BitBtn3Click(Sender: TObject); begin memHistory.Lines.Clear; BtnSave.Enabled := True; end; procedure TFrmHistory.cbxHistoryChange(Sender: TObject); begin GetHistory(cbxHistory.ItemIndex); end; procedure TFrmHistory.btnEmailClick(Sender: TObject); begin with FrmMain.Email do begin Recipients.Text := 'suporte@mainretai.com'; FromName := FrmMain.fIniConfig.ReadString('Local','Customer', ''); Subject := cbxHistory.Items.Text; Body := memHistory.Lines.Text; //Mostra o Email ShowDialog := True; SendMail; end; end; end.
unit ShaderBankItem; interface uses BasicFunctions, BasicMathsTypes, BasicDataTypes, dglOpenGL, SysUtils, Classes; type TShaderBankItem = class private Counter: longword; IsAuthorized,IsVertexCompiled,IsFragmentCompiled,IsLinked, IsRunning : boolean; ProgramID, VertexID, FragmentID : GLUInt; Attributes: AString; AttributeLocation: array of TGLInt; Uniforms: AString; UniformLocation: array of TGLInt; public // Constructor and Destructor constructor Create(const _VertexFilename, _FragmentFilename: string); overload; destructor Destroy; override; // Gets function GetID : GLInt; function IsProgramLinked: boolean; function IsVertexShaderCompiled: boolean; function IsFragmentShaderCompiled: boolean; // Sets procedure SetAuthorization(_value: boolean); // Uses procedure UseProgram; procedure DeactivateProgram; // Adds procedure AddAttribute(const _name: string); procedure AddUniform(const _name: string); // Counter function GetCount : integer; procedure IncCounter; procedure DecCounter; // OpenGL procedure glSendAttribute2f(_AttributeID: integer; const _Value: TVector2f); procedure glSendAttribute3f(_AttributeID: integer; const _Value: TVector3f); procedure glSendUniform1i(_UniformID: integer; const _Value: integer); end; PShaderBankItem = ^TShaderBankItem; implementation uses Dialogs; // Constructors and Destructors constructor TShaderBankItem.Create(const _VertexFilename, _FragmentFilename: string); var Stream : TStream; PPCharData : PPGLChar; PCharData,Log : PAnsiChar; CharData : array of ansichar; Size : GLInt; Compiled : PGLInt; Filename: string; begin Counter := 1; IsVertexCompiled := false; IsFragmentCompiled := false; IsLinked := false; IsRunning := false; IsAuthorized := false; VertexID := 0; FragmentID := 0; ProgramID := 0; SetLength(Attributes,0); // Let's load the vertex shader first. if FileExists(_VertexFilename) then begin Stream := TFileStream.Create(_VertexFilename,fmOpenRead); Size := Stream.Size; SetLength(CharData,Size+1); PCharData := Addr(CharData[0]); PPCharData := Addr(PCharData); Stream.Read(CharData[0],Size); CharData[High(CharData)] := #0; Stream.Free; VertexID := glCreateShader(GL_VERTEX_SHADER); glShaderSource(VertexID,1,PPCharData,nil); SetLength(CharData,0); glCompileShader(VertexID); GetMem(Compiled,4); glGetShaderiv(VertexID,GL_COMPILE_STATUS,Compiled); IsVertexCompiled := Compiled^ <> 0; FreeMem(Compiled); if not IsVertexCompiled then begin // If compile fails, generate the log. // Note: Here compiled will be the size of the error log GetMem(Compiled,4); glGetShaderiv(VertexID,GL_INFO_LOG_LENGTH,Compiled); if Compiled^ > 0 then begin Filename := copy(_VertexFilename,1,Length(_VertexFilename)-4) + '_error.log'; Stream := TFileStream.Create(Filename,fmCreate); GetMem(Log,Compiled^); glGetShaderInfoLog(VertexID,Compiled^,Size,Log); Stream.Write(Log^,Size); FreeMem(Log); Stream.Free; end; FreeMem(Compiled); end; end; // Let's load the fragment shader. if FileExists(_FragmentFilename) then begin Stream := TFileStream.Create(_FragmentFilename,fmOpenRead); Size := Stream.Size; SetLength(CharData,Size+1); PCharData := Addr(CharData[0]); PPCharData := Addr(PCharData); Stream.Read(CharData[0],Size); CharData[High(CharData)] := #0; Stream.Free; FragmentID := glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(FragmentID,1,PPCharData,nil); SetLength(CharData,0); glCompileShader(FragmentID); GetMem(Compiled,4); glGetShaderiv(FragmentID,GL_COMPILE_STATUS,Compiled); IsFragmentCompiled := Compiled^ <> 0; FreeMem(Compiled); if not IsFragmentCompiled then begin // If compile fails, generate the log. // Note: Here compiled will be the size of the error log GetMem(Compiled,4); glGetShaderiv(FragmentID,GL_INFO_LOG_LENGTH,Compiled); if Compiled^ > 0 then begin Filename := copy(_FragmentFilename,1,Length(_FragmentFilename)-4) + '_error.log'; Stream := TFileStream.Create(Filename,fmCreate); GetMem(Log,Compiled^); glGetShaderInfoLog(FragmentID,Compiled^,Size,Log); Stream.Write(Log^,Size); FreeMem(Log); Stream.Free; end; FreeMem(Compiled); end; end; // Time to create and link the program. if IsFragmentCompiled or isVertexCompiled then begin ProgramID := glCreateProgram(); if isVertexCompiled then glAttachShader(ProgramID,VertexID); if isFragmentCompiled then glAttachShader(ProgramID,FragmentID); glLinkProgram(ProgramID); GetMem(Compiled,4); glGetProgramiv(ProgramID,GL_LINK_STATUS,Compiled); IsLinked := Compiled^ <> 0; IsAuthorized := IsLinked; FreeMem(Compiled); if not IsLinked then begin // If compile fails, generate the log. // Note: Here compiled will be the size of the error log GetMem(Compiled,4); glGetProgramiv(ProgramID,GL_INFO_LOG_LENGTH,Compiled); if Compiled^ > 0 then begin if IsFragmentCompiled then Filename := IncludeTrailingPathDelimiter(ExtractFileDir(_FragmentFilename)) + 'link_error.log' else if IsVertexCompiled then Filename := IncludeTrailingPathDelimiter(ExtractFileDir(_VertexFilename)) + 'link_error.log'; Stream := TFileStream.Create(Filename,fmCreate); GetMem(Log,Compiled^); glGetProgramInfoLog(ProgramID,Compiled^,Size,Log); Stream.Write(Log^,Size); FreeMem(Log); Stream.Free; end; FreeMem(Compiled); end; end; end; destructor TShaderBankItem.Destroy; begin DeactivateProgram; if IsLinked then begin if IsVertexCompiled then begin glDetachShader(ProgramID,VertexID); end; if IsFragmentCompiled then begin glDetachShader(ProgramID,FragmentID); end; glDeleteProgram(ProgramID); end; if IsVertexCompiled then begin glDeleteShader(VertexID); end; if IsFragmentCompiled then begin glDeleteShader(FragmentID); end; SetLength(Attributes,0); inherited Destroy; end; // Gets function TShaderBankItem.GetID : GLInt; begin Result := ProgramID; end; function TShaderBankItem.IsProgramLinked: boolean; begin Result := IsLinked; end; function TShaderBankItem.IsVertexShaderCompiled: boolean; begin Result := IsVertexCompiled; end; function TShaderBankItem.IsFragmentShaderCompiled: boolean; begin Result := IsFragmentCompiled; end; // Sets procedure TShaderBankItem.SetAuthorization(_value: boolean); begin isAuthorized := _value; end; // Uses procedure TShaderBankItem.UseProgram; var i : integer; UniformName: Pchar; begin if IsLinked and (not IsRunning) and (isAuthorized) then begin glUseProgram(ProgramID); i := 0; while i <= High(Attributes) do begin glBindAttribLocation(ProgramID,i,PChar(Attributes[i])); AttributeLocation[i] := glGetAttribLocation(ProgramID,PChar(Attributes[i])); inc(i); end; i := 0; while i <= High(Uniforms) do begin UniformName := PChar(Uniforms[i]); UniformLocation[i] := glGetUniformLocation(ProgramID,UniformName); inc(i); end; IsRunning := true; end; end; procedure TShaderBankItem.DeactivateProgram; begin if IsRunning then begin glUseProgram(0); IsRunning := false; end; end; // Adds procedure TShaderBankItem.AddAttribute(const _name: string); //var // AttributeName : PChar; begin SetLength(Attributes,High(Attributes)+2); SetLength(AttributeLocation,High(Attributes)+1); Attributes[High(Attributes)] := copy(_name,1,Length(_name)); // AttributeName := StrCat(PChar(Attributes[High(Attributes)]),#0); // AttributeLocation[High(Attributes)] := glGetAttribLocation(ProgramID,PChar(Attributes[High(Attributes)])); end; procedure TShaderBankItem.AddUniform(const _name: string); //var // UniformName : PChar; begin SetLength(Uniforms,High(Uniforms)+2); SetLength(UniformLocation,High(Uniforms)+1); Uniforms[High(Uniforms)] := copy(_name,1,Length(_name)); // UniformName := StrCat(PChar(Uniforms[High(Uniforms)]),#0); // UniformLocation[High(Uniforms)] := glGetUniformLocation(ProgramID,UniformName); end; procedure TShaderBankItem.glSendAttribute2f(_AttributeID: integer; const _Value: TVector2f); begin glVertexAttrib2f(AttributeLocation[_AttributeID], _Value.U, _Value.V); end; procedure TShaderBankItem.glSendAttribute3f(_AttributeID: integer; const _Value: TVector3f); begin glVertexAttrib3f(AttributeLocation[_AttributeID], _Value.X, _Value.Y, _Value.Z); end; procedure TShaderBankItem.glSendUniform1i(_UniformID: integer; const _Value: integer); begin glUniform1i(UniformLocation[_UniformID], _Value); end; // Counter function TShaderBankItem.GetCount : integer; begin Result := Counter; end; procedure TShaderBankItem.IncCounter; begin inc(Counter); end; procedure TShaderBankItem.DecCounter; begin Dec(Counter); end; end.
(* Category: SWAG Title: DOS & ENVIRONMENT ROUTINES Original name: 0015.PAS Description: Demostrates EXEC Proc Author: SWAG SUPPORT TEAM Date: 08-17-93 08:41 *) {$M 8192,0,0} {* This memory directive is used to make certain there is enough memory left to execute the DOS shell and any other programs needed. *} Program EXEC_Demo; {* EXEC.PAS This program demonstrates the use of Pascal's EXEC function to execute either an individual DOS command or to move into a DOS Shell. You may enter any command you could normally enter at a DOS prompt and it will execute. You may also hit RETURN without entering anything and you will enter into a DOS Shell, from which you can exit by typing EXIT. The program stops when you hit a 'Q', upper or lower case. *} Uses Crt, Dos; Var Command : String; {**************************************} Procedure Do_Exec; {*******************} {Var Ch : Char;} Begin If Command <> '' Then Command := '/C' + Command Else Writeln('Type EXIT to return from the DOS Shell.'); {* The /C prefix is needed to execute any command other than the complete DOS Shell. *} SwapVectors; Exec(GetEnv('COMSPEC'), Command); {* GetEnv is used to read COMSPEC from the DOS environment so the program knows the correct path to COMMAND.COM. *} SwapVectors; Writeln; Writeln('DOS Error = ',DosError); If DosError <> 0 Then Writeln('Could not execute COMMAND.COM'); {* We're assuming that the only reason DosError would be something other than 0 is if it couldn't find the COMMAND.COM, but there are other errors that can occur, we just haven't provided for them here. *} Writeln; Writeln; Writeln('Hit any key to continue...'); {Ch := }ReadKey; End; Function Get_Command : String; Var {Count : Integer;} Cmnd : String; Begin Clrscr; Write('Enter DOS Command (or Q to Quit): '); Readln(Cmnd); Get_Command := Cmnd End; Begin Command := Get_Command; While NOT ((Command = 'Q') OR (Command = 'q')) Do Begin Do_Exec; Command := Get_Command End; End.
namespace Oxygene.Samples.SampleClasses; interface uses System, System.Collections; type Gender = (Male, Female); MaritalStatus = (Single, Married, Divorced, Widdowed); Person = class private fSpouse: Person; fMaritalStatus: MaritalStatus; fNickName: String; method set_Spouse(aValue: Person); method set_MaritalStatus(aValue: MaritalStatus); method set_NickName(aValue: String); public constructor (aName: String; aAge: Integer; aGender: Gender); virtual; method GenerateSSN: String; { Notice how Oxygene doesn't require the declaration of private fields to store property values, thus making the code more compact and easier to read } property Name: String; property Age: Integer; property Gender: Gender; property NickName: String read fNickName write set_NickName; property Address: PersonAddress := new PersonAddress(); property MaritalStatus: MaritalStatus read fMaritalStatus write set_MaritalStatus; property Spouse: Person read fSpouse write set_Spouse; public invariants { These conditions are guaranteed to always be respected at the end of the execution of a non-private method of the Person class } Age >= 0; length(Name) > 0; (fMaritalStatus = MaritalStatus.Married) implies assigned(Spouse); end; PersonClass = class of Person; Employee = class(Person) private protected method get_Salary: Double; public property Salary: Double read get_Salary; end; PersonCollection = class(CollectionBase) private protected { Type checking events } procedure OnInsert(aIndex: Integer; aValue: Object); override; procedure OnValidate(aValue: Object); override; { Other methods } function GetPersonsByIndex(aIndex: Integer): Person; function GetPersonsByName(aName: String): Person; public constructor; method Add(aName: String; aAge: Integer; aGender: Gender): Person; method Add(aPerson: Person): Integer; method IndexOf(aPerson: Person): Integer; procedure Remove(aPerson: Person); { Notice the use of overloaded array properties } property Persons[anIndex: Integer]: Person read GetPersonsByIndex; default; property Persons[aName: String]: Person read GetPersonsByName; default; end; PersonAddress = class public property City: String; property Street: String; property Zip: String; end; { ECustomException } ECustomException = class(Exception); implementation { Person } constructor Person(aName: string; aAge: integer; aGender: Gender); begin inherited constructor; Name := aName; Age := aAge; Gender := aGender; end; method Person.GenerateSSN: string; var lHashValue: Integer; begin { Generates a complex string with all the information we have and outputs a fake SSN using the String.Format method } lHashValue := (Age.ToString+'S'+Gender.ToString[2]+Name.GetHashCode.ToString).GetHashCode; if lHashValue < 0 then lHashValue := -lHashValue; result := String.Format('{0:000-00-0000}', lHashValue); end; method Person.set_NickName(aValue: string); require aValue <> ''; begin fNickName := aValue; ensure fNickName <> ''; end; method Person.set_MaritalStatus(aValue: MaritalStatus); begin if aValue <> fMaritalStatus then begin fMaritalStatus := aValue; if fMaritalStatus <> MaritalStatus.Married then Spouse := nil; end; end; method Person.set_Spouse(aValue: Person); begin if aValue <> fSpouse then begin fSpouse := aValue; if assigned(fSpouse) then MaritalStatus := MaritalStatus.Married else MaritalStatus := MaritalStatus.Single; end; end; { PersonCollection } constructor PersonCollection; begin inherited; end; method PersonCollection.Add(aName: string; aAge: integer; aGender: Gender): Person; begin result := new Person(aName, aAge, aGender); List.Add(result); end; method PersonCollection.Add(aPerson: Person): integer; begin result := List.Add(aPerson); end; method PersonCollection.IndexOf(aPerson: Person): integer; begin result := List.IndexOf(aPerson); end; procedure PersonCollection.Remove(aPerson: Person); begin List.Remove(aPerson); end; function PersonCollection.GetPersonsByIndex(aIndex: integer): Person; begin result := List[aIndex] as Person; end; function PersonCollection.GetPersonsByName(aName: string): Person; begin for each somebody: Person in List do if String.Compare(aName, somebody.Name, true) = 0 then exit(somebody); end; procedure PersonCollection.OnInsert(aIndex: integer; aValue: Object); begin OnValidate(aValue); end; procedure PersonCollection.OnValidate(aValue: Object); begin { Notice the use of the "is not" syntax } if (aValue is not Person) then raise new Exception('Not a Person'); end; { Employee } method Employee.get_Salary: Double; begin case Age of 0..15: Exit(0); 16..24: Exit(15000); 25..45: Exit(55000); else exit(75000); end; end; end.
unit uModelHelper; interface uses uModApp, uModPO, uModSO,uModSuplier,uModBarang, uModSatuan, System.SysUtils, uDMClient, uModDO, uClientClasses, Datasnap.DBClient, uDBUtils, System.Classes; type TModPOItemHelper = class helper for TModPOItem public procedure LoadBarang; procedure LoadUOM; end; TModPOHelper = class helper for TModPO public procedure LoadPO_SUPPLIER_MERCHAN_GRUP; procedure LoadSO; procedure LoadStatusPO; end; TModDOHelper = class helper for TModDO public procedure LoadPO; end; TModAppHelper = class helper for TModApp private protected public procedure CopyFrom(aModApp : TModApp); procedure Reload(LoadObjectList: Boolean = False); function ReloadByCode(aCode: String): Boolean; end; TCRUDObj = class private public class function RetrieveCode<T: class>(aCode: string): T; class function Retrieve<T: class>(aID: string; LoadObjectList: Boolean = True): T; end; function GetModAppRestID(aObject: TModApp): String; implementation uses System.Rtti, System.TypInfo, Vcl.Dialogs; function GetModAppRestID(aObject: TModApp): String; begin Result := 'null'; if aObject <> nil then Result := aObject.ID; end; procedure TModPOHelper.LoadPO_SUPPLIER_MERCHAN_GRUP; begin Self.PO_SUPPLIER_MERCHAN_GRUP := TModSuplierMerchanGroup(DMClient.CrudClient.Retrieve(TModSuplierMerchanGroup.ClassName, Self.PO_SUPPLIER_MERCHAN_GRUP.ID)); end; procedure TModPOHelper.LoadSO; begin Self.PO_SO := TModSO(DMClient.CrudClient.RetrieveSingle(TModSO.ClassName, Self.PO_SO.ID)); end; procedure TModPOHelper.LoadStatusPO; begin Self.PO_STATUS_PO := TModStatusPO(DMClient.CrudClient.RetrieveSingle(TModStatusPO.ClassName, Self.PO_STATUS_PO.ID)); end; procedure TModPOItemHelper.LoadBarang; begin Self.POD_BARANG := TModBarang(DMClient.CrudClient.RetrieveSingle(TModBarang.ClassName, Self.POD_BARANG.ID)); end; procedure TModPOItemHelper.LoadUOM; begin Self.POD_UOM := TModSatuan(DMClient.CrudClient.RetrieveSingle(TModSatuan.ClassName,Self.POD_UOM.ID)); end; procedure TModDOHelper.LoadPO; begin Self.PO := TModPO(DMClient.CrudPOClient.RetrieveSingle(TModPO.ClassName, Self.PO.ID)); end; procedure TModAppHelper.Reload(LoadObjectList: Boolean = False); var lModApp: TModApp; begin If Self.ID = '' then exit; if LoadObjectList then lModApp := DMClient.CrudClient.Retrieve(Self.ClassName, Self.ID) else lModApp := DMClient.CrudClient.RetrieveSingle(Self.ClassName, Self.ID); Try Self.CopyFrom(lModApp); Finally lModApp.Free; End; end; procedure TModAppHelper.CopyFrom(aModApp : TModApp); var ctx: TRttiContext; i: Integer; lAppClass: TModAppClass; lNewItem: TModApp; lNewObjList: TObject; lSrcItem: TModApp; lSrcObjList: TObject; meth: TRttiMethod; RttiType: TRttiType; Prop: TRttiProperty; rtItem: TRttiType; sGenericItemClassName: string; value: TValue; function SetPropertyFrom(AProp: TRttiProperty; ASource: TModApp): TModApp; var lSrcObj: TObject; begin Result := nil; lSrcObj := Prop.GetValue(ASource).AsObject; if not prop.PropertyType.AsInstance.MetaclassType.InheritsFrom(TModApp) then exit;; meth := prop.PropertyType.GetMethod('Create'); Result := TModApp(meth.Invoke(prop.PropertyType.AsInstance.MetaclassType, []).AsObject); if lSrcObj <> nil then TModApp(Result).CopyFrom(TModApp(lSrcObj)); end; begin RttiType := ctx.GetType(Self.ClassType); Try for Prop in RttiType.GetProperties do begin if not (Prop.IsReadable and Prop.IsWritable) then continue; // if prop.Visibility <> mvPublished then continue; If prop.PropertyType.TypeKind = tkClass then begin meth := prop.PropertyType.GetMethod('ToArray'); if Assigned(meth) then //object list begin lSrcObjList := prop.GetValue(aModApp).AsObject; lNewObjList := prop.GetValue(Self).AsObject; if lSrcObjList = nil then continue; value := meth.Invoke(prop.GetValue(aModApp), []); Assert(value.IsArray); sGenericItemClassName := StringReplace(lSrcObjList.ClassName, 'TOBJECTLIST<','', [rfIgnoreCase]); sGenericItemClassName := StringReplace(sGenericItemClassName, '>','', [rfIgnoreCase]); rtItem := ctx.FindType(sGenericItemClassName); meth := prop.PropertyType.GetMethod('Add'); if Assigned(meth) and Assigned(rtItem) then begin if not rtItem.AsInstance.MetaclassType.InheritsFrom(TModApp) then continue; lAppClass := TModAppClass( rtItem.AsInstance.MetaclassType ); for i := 0 to value.GetArrayLength - 1 do begin lSrcItem := TModApp(value.GetArrayElement(i).AsObject); lNewItem := lAppClass.Create; lNewItem.CopyFrom(lSrcItem); meth.Invoke(lNewObjList,[lNewItem]); end; end; prop.SetValue(Self, lNewObjList); end else begin prop.SetValue(Self, SetPropertyFrom(prop, aModApp)); end; end else Prop.SetValue(Self, Prop.GetValue(aModApp)); end; except ShowMessage(Self.ClassName + '.' + Prop.Name); raise; End; end; function TModAppHelper.ReloadByCode(aCode: String): Boolean; var lModApp: TModApp; begin lModApp := DMClient.CrudClient.RetrieveByCode(Self.ClassName, aCode); Try Self.CopyFrom(lModApp); Result := Self.ID <> ''; //not found Finally lModApp.Free; End; end; class function TCRUDObj.RetrieveCode<T>(aCode: string): T; var sClass: string; begin if (T = nil) then Raise Exception.Create('Type can''t be nil') else if not TClass(T).InheritsFrom(TModApp) then Raise Exception.Create('Type must inherti from TObjectModel') else begin sClass := T.ClassName; Result := T(DMClient.CrudClient.RetrieveByCode(sClass, aCode)) end; end; class function TCRUDObj.Retrieve<T>(aID: string; LoadObjectList: Boolean = True): T; var sClass: string; begin if (T = nil) then Raise Exception.Create('Type can''t be nil') else if not TClass(T).InheritsFrom(TModApp) then Raise Exception.Create('Type must inherti from TObjectModel') else begin sClass := T.ClassName; if LoadObjectList then Result := T(DMClient.CrudClient.Retrieve(sClass, aID)) else Result := T(DMClient.CrudClient.RetrieveSingle(sClass, aID)); end; end; end.
unit LuaObject; {$IFDEF FPC} {$mode objfpc}{$H+} {$ENDIF} {$I pLua.inc} interface uses Classes, SysUtils, lua, Variants, pLuaObject, pLua; type TLuaObject = class; { TLuaObject } TLuaObject = class protected L : PLua_State; FLuaReference : integer; FParent : TLuaObject; FChildren : TList; function GetLuaProp(PropName : AnsiString): Variant; procedure SetLuaProp(PropName : AnsiString; const AValue: Variant); function GetPropValue(propName : AnsiString): Variant; virtual; function GetPropObject(propName: AnsiString) : Boolean; virtual; function SetPropValue(PropName : AnsiString; const AValue: Variant) : Boolean; virtual; function SetPropObject(propName: AnsiString) : Boolean; virtual; function PropIsObject(propName : AnsiString): Boolean; virtual; procedure CommonCreate(LuaState : PLua_State; AParent : TLuaObject = nil); virtual; public constructor Create(LuaState : PLua_State; AParent : TLuaObject = nil); virtual; overload; constructor Create(LuaState: PLua_State; LuaClassName, LuaName: AnsiString); virtual; overload; destructor Destroy; override; procedure PushSelf; procedure CallEvent(EventName : AnsiString); overload; function CallEvent(EventName : AnsiString; args : Array of Variant; Results: PVariantArray = nil) : Integer; overload; function EventExists(EventName: AnsiString): Boolean; property LState : PLua_State read L; property LuaProp[PropName : AnsiString] : Variant read GetLuaProp write SetLuaProp; end; TLuaObjectRegisterMethodsCallback = procedure(L : Plua_State; classTable : Integer); TLuaObjectNewCallback = function(L : PLua_State; AParent : TLuaObject=nil):TLuaObject; var LuaObjects : TList; procedure ClearObjects; procedure LuaCopyTable(L: Plua_State; IdxFrom, IdxTo, MtTo : Integer); function LuaToTLuaObject(L: Plua_State; Idx : Integer) : TLuaObject; procedure RegisterLuaObject(L: Plua_State); procedure RegisterTLuaObject(L : Plua_State; ObjectName : AnsiString; CreateFunc : lua_CFunction; MethodsCallback : TLuaObjectRegisterMethodsCallback = nil); procedure RegisterObjectInstance(L : Plua_State; aClassName, InstanceName : AnsiString; ObjectInstance : TLuaObject); procedure RegisterMethod(L : Plua_State; TheMethodName : AnsiString; TheMethodAddress : lua_CFunction; classTable : Integer); function new_LuaObject(L : PLua_State; aClassName : AnsiString; NewCallback : TLuaObjectNewCallback) : Integer; extdecl; procedure PushTLuaObject(L : PLua_State; ObjectInstance : TLuaObject); function new_TLuaObject(L : PLua_State) : Integer; extdecl; function index_TLuaObject(L : PLua_State) : Integer; extdecl; function newindex_TLuaObject(L : PLua_State) : Integer; extdecl; function gc_TLuaObject(L : PLua_State) : Integer; extdecl; procedure RegisterClassTLuaObject(L : Plua_State); implementation uses typinfo; const LuaTLuaObjectClassName = 'TLuaObject'; constructor TLuaObject.Create(LuaState : PLua_State; AParent : TLuaObject = nil); begin CommonCreate(LuaState, nil); // Create a reference to the object table, this way lua won't GC its version FLuaReference := luaL_ref(L, LUA_REGISTRYINDEX); lua_rawgeti (L, LUA_REGISTRYINDEX, FLuaReference); LuaObjects.Add(Self); end; constructor TLuaObject.Create(LuaState: PLua_State; LuaClassName, LuaName: AnsiString); begin CommonCreate(LuaState, nil); RegisterObjectInstance(LuaState, LuaClassName, LuaName, self); end; destructor TLuaObject.Destroy; var lo : TLuaObject; begin LuaObjects.Remove(Self); if assigned(FParent) then FParent.FChildren.Remove(Self); while FChildren.Count > 0 do begin lo := TLuaObject(FChildren[FChildren.Count-1]); FChildren.Delete(FChildren.Count-1); lo.Free; end; FChildren.Free; luaL_unref(L, LUA_REGISTRYINDEX, FLuaReference); inherited Destroy; end; procedure TLuaObject.PushSelf; begin lua_rawgeti(L, LUA_REGISTRYINDEX, FLuaReference); end; procedure TLuaObject.CallEvent(EventName: AnsiString); begin CallEvent(EventName, []); end; function TLuaObject.CallEvent(EventName : AnsiString; args: array of Variant; Results: PVariantArray) : Integer; begin result := -1; if not EventExists(EventName) then exit; PushSelf; result := plua_callfunction(L, EventName, args, results, lua_gettop(L)); end; function TLuaObject.EventExists(EventName: AnsiString): Boolean; begin PushSelf; result := plua_functionexists(L, EventName, lua_gettop(L)); lua_pop(L, 1); end; function TLuaObject.GetLuaProp(PropName : AnsiString): Variant; var idx : Integer; begin lua_rawgeti (L, LUA_REGISTRYINDEX, FLuaReference); // Place our object on the stack idx := lua_gettop(L); lua_pushliteral(L, PChar(PropName)); // Place the event name on the stack lua_gettable(L, idx); // try to get the item result := plua_tovariant(L, lua_gettop(L)); lua_pop(L, 2); end; procedure TLuaObject.SetLuaProp(PropName : AnsiString; const AValue: Variant); var idx : Integer; begin lua_rawgeti (L, LUA_REGISTRYINDEX, FLuaReference); // Place our object on the stack idx := lua_gettop(L); lua_pushstring(L, PChar(propName)); plua_pushvariant(L, AValue); lua_rawset(L, idx); end; function TLuaObject.GetPropValue(propName: AnsiString): Variant; begin if IsPublishedProp(self, propName) then result := typinfo.GetPropValue(self, propName) else result := NULL; end; function TLuaObject.GetPropObject(propName: AnsiString) : Boolean; begin result := false; end; function TLuaObject.SetPropValue(PropName: AnsiString; const AValue: Variant) : Boolean; begin result := IsPublishedProp(self, propName); if result then typinfo.SetPropValue(self, propName, AValue); end; function TLuaObject.SetPropObject(propName: AnsiString) : Boolean; begin result := false; end; function TLuaObject.PropIsObject(propName: AnsiString): Boolean; begin result := false; end; procedure TLuaObject.CommonCreate(LuaState: PLua_State; AParent: TLuaObject); begin L := LuaState; FParent := AParent; if assigned(FParent) then FParent.FChildren.Add(Self); FChildren := TList.Create; end; { Global LUA Methods } procedure LuaCopyTable(L: Plua_State; IdxFrom, IdxTo, MtTo : Integer); var id:Integer; tbl : Integer; key, val : Variant; cf : lua_CFunction; begin lua_pushnil(L); while(lua_next(L, IdxFrom)<>0)do begin key := plua_tovariant(L, -2); if CompareText(key, '__') = 1 then tbl := MtTo else tbl := IdxTo; case lua_type(L, -1) of LUA_TFUNCTION : begin cf := lua_tocfunction(L, -1); plua_pushvariant(L, key); lua_pushcfunction(L, cf); lua_rawset(L, tbl); end; LUA_TTABLE : begin id := lua_gettop(L); LuaCopyTable(L, id, IdxTo, MtTo); end; else val := plua_tovariant(L, -1); plua_pushvariant(L, key); plua_pushvariant(L, val); lua_rawset(L, tbl); end; lua_pop(L, 1); end; end; function LuaToTLuaObject(L: Plua_State; Idx : Integer) : TLuaObject; begin result := nil; if lua_type(L, Idx) = LUA_TTABLE then begin Idx := plua_absindex(L, Idx); lua_pushstring(L, '_Self'); lua_gettable(L, Idx); result := TLuaObject(PtrUint(lua_tointeger(L, -1))); lua_pop(L, 1); end else luaL_error(L, PChar('Class table expected.')); end; procedure PushTLuaObject(L: PLua_State; ObjectInstance: TLuaObject); begin lua_rawgeti(L, LUA_REGISTRYINDEX, ObjectInstance.FLuaReference); end; function new_TLuaObject(L : PLua_State) : Integer; extdecl; var P, E : TLuaObject; n, idx, idx2, mt : Integer; begin n := lua_gettop(L); if lua_type(L, 1) <> LUA_TTABLE then lua_remove(L, 1); if n = 1 then P := LuaToTLuaObject(L, 1) else P := nil; lua_newtable(L); E := TLuaObject.Create(L, P); idx := lua_gettop(L); lua_pushliteral(L, '_Self'); lua_pushinteger(L, PtrUint(Pointer(E))); lua_rawset(L, idx); lua_newtable(L); mt := lua_gettop(L); lua_pushliteral(L, LuaTLuaObjectClassName); lua_gettable(L, LUA_GLOBALSINDEX); idx2 := lua_gettop(L); LuaCopyTable(L, idx2, idx, mt); lua_setmetatable(L, idx); lua_pop(L, 1); result := 1; end; function index_TLuaObject(L : PLua_State) : Integer; extdecl; var E : TLuaObject; propName : AnsiString; v : Variant; begin E := LuaToTLuaObject(L, 1); lua_remove(L, 1); if E = nil then begin result := 0; exit; end; propName := plua_tostring(L, 1); index_TLuaObject := 1; if E.PropIsObject(propName) then begin if not E.GetPropObject(propName) then index_TLuaObject := 0; end else begin v := E.GetPropValue(propName); if v = NULL then index_TLuaObject := 0 else plua_pushvariant(L, v); end; end; function newindex_TLuaObject(L : PLua_State) : Integer; extdecl; var TableIndex, ValueIndex : Integer; E : TLuaObject; propName : AnsiString; begin result := 0; E := LuaToTLuaObject(L, 1); if E = nil then begin exit; end; propName := plua_tostring(L, 2); if E.PropIsObject(propName) and E.SetPropObject(propName) then else if not E.SetPropValue(propName, plua_tovariant(L, 3)) then begin // This is a standard handler, no value was found in the object instance // so we push the value into the Lua Object reference. TableIndex := plua_absindex(L, 1); ValueIndex := plua_absindex(L, 3); lua_pushstring(L, PChar(propName)); lua_pushvalue(L, ValueIndex); lua_rawset(L, TableIndex); end; end; function gc_TLuaObject(L : PLua_State) : Integer; extdecl; var E : TLuaObject; begin E := LuaToTLuaObject(L, 1); // Release the object if assigned(E) then E.Free; result := 0; end; procedure RegisterObjectInstance(L: Plua_State; aClassName, InstanceName: AnsiString; ObjectInstance : TLuaObject); var idx, idx2, mt : Integer; begin lua_pushliteral(L, PChar(InstanceName)); lua_newtable(L); ObjectInstance.FLuaReference := luaL_ref(L, LUA_REGISTRYINDEX); lua_rawgeti (L, LUA_REGISTRYINDEX, ObjectInstance.FLuaReference); LuaObjects.Add(ObjectInstance); idx := lua_gettop(L); lua_pushliteral(L, '_Self'); lua_pushinteger(L, PtrUint(Pointer(ObjectInstance))); lua_rawset(L, idx); lua_newtable(L); mt := lua_gettop(L); lua_pushliteral(L, PChar(aClassName)); lua_gettable(L, LUA_GLOBALSINDEX); idx2 := lua_gettop(L); LuaCopyTable(L, idx2, idx, mt); lua_setmetatable(L, idx); lua_pop(L, 1); lua_settable(L, LUA_GLOBALSINDEX); end; procedure RegisterMethod(L : Plua_State; TheMethodName : AnsiString; TheMethodAddress : lua_CFunction; classTable : Integer); begin lua_pushliteral(L, PChar(TheMethodName)); lua_pushcfunction(L, TheMethodAddress); lua_rawset(L, classTable); end; function new_LuaObject(L : PLua_State; aClassName : AnsiString; NewCallback : TLuaObjectNewCallback): Integer; extdecl; var P, E : TLuaObject; n, idx, idx2, mt : Integer; begin n := lua_gettop(L); if lua_type(L, 1) <> LUA_TTABLE then lua_remove(L, 1); if n > 1 then P := LuaToTLuaObject(L, 2) else P := nil; lua_newtable(L); E := NewCallback(L, P); idx := lua_gettop(L); lua_pushliteral(L, '_Self'); lua_pushinteger(L, PtrUint(Pointer(E))); lua_rawset(L, idx); lua_newtable(L); mt := lua_gettop(L); lua_pushliteral(L, PChar(aClassName)); lua_gettable(L, LUA_GLOBALSINDEX); idx2 := lua_gettop(L); LuaCopyTable(L, idx2, idx, mt); lua_setmetatable(L, idx); lua_pop(L, 1); result := 1; end; procedure RegisterClassTLuaObject(L : Plua_State); var classTable : Integer; begin lua_pushstring(L, LuaTLuaObjectClassName); lua_newtable(L); classTable := lua_gettop(L); RegisterMethod(L, '__index', @index_TLuaObject, classTable); RegisterMethod(L, '__newindex', @newindex_TLuaObject, classTable); RegisterMethod(L, '__call', @new_TLuaObject, classTable); RegisterMethod(L, '__gc', @gc_TLuaObject, classTable); RegisterMethod(L, 'release', @gc_TLuaObject, classTable); RegisterMethod(L, 'new', @new_TLuaObject, classTable); lua_settable(L, LUA_GLOBALSINDEX); end; { Global Management Methods } procedure RegisterTLuaObject(L: Plua_State; ObjectName : AnsiString; CreateFunc : lua_CFunction; MethodsCallback: TLuaObjectRegisterMethodsCallback); var classTable : Integer; begin lua_pushstring(L, PChar(ObjectName)); lua_newtable(L); classTable := lua_gettop(L); RegisterMethod(L, '__index', @index_TLuaObject, classTable); RegisterMethod(L, '__newindex', @newindex_TLuaObject, classTable); RegisterMethod(L, '__call', CreateFunc, classTable); RegisterMethod(L, '__gc', @gc_TLuaObject, classTable); RegisterMethod(L, 'release', @gc_TLuaObject, classTable); RegisterMethod(L, 'new', CreateFunc, classTable); if Assigned(MethodsCallback) then MethodsCallback(L, classTable); lua_settable(L, LUA_GLOBALSINDEX); end; procedure ClearObjects; begin while LuaObjects.Count > 0 do TLuaObject(LuaObjects[LuaObjects.Count-1]).Free; end; procedure RegisterLuaObject(L: Plua_State); begin RegisterClassTLuaObject(L); end; initialization LuaObjects := TList.Create; finalization ClearObjects; LuaObjects.Free; end.
unit Adapt.EventDepot; //------------------------------------------------------------------------------ // модуль адаптера кэша для TClassEventDepot //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, ZConnection, ZDataset, Cache.Root, Cache.Elements, Adapter.MySQL, Event.Cnst; //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! //------------------------------------------------------------------------------ TEventDepotMySQL = class(TCacheAdapterMySQL) protected function MakeObjFromReadQuery( const AQuery: TZQuery ): TCacheDataObjectAbstract; override; public constructor Create( const AReadConnection: TZConnection; const AWriteConnection: TZConnection ); procedure Flush( const ACache: TCache ); override; procedure Add( const ACache: TCache; const AObj: TCacheDataObjectAbstract ); override; procedure Change( const ACache: TCache; const AObj: TCacheDataObjectAbstract ); override; end; //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ //! запросы //------------------------------------------------------------------------------ const CSQLInsert = 'INSERT INTO event_depot' + ' (IMEI, DepotID, DT, Duration, GUID)' + ' VALUES (:imei, :d_id, :dt, :dur, UUID_TO_BIN(:guid))'; CSQLUpdate = 'UPDATE event_depot' + ' SET Duration = :dur' + ' WHERE IMEI = :imei' + ' AND DepotID = :d_id' + ' AND DT = :dt'; CSQLReadBefore = 'SELECT MAX(DT) AS DT' + ' FROM event_depot' + ' WHERE IMEI = :imei' + ' AND DepotID = :d_id' + ' AND DT < :dt'; CSQLReadAfter = 'SELECT MIN(DT) AS DT' + ' FROM event_depot' + ' WHERE IMEI = :imei' + ' AND DepotID = :d_id' + ' AND DT > :dt'; CSQLReadRange = 'SELECT' + ' IMEI, DepotID, DT, Duration, BIN_TO_UUID(GUID) AS GUID' + ' FROM event_depot' + ' WHERE IMEI = :imei' + ' AND DepotID = :d_id' + ' AND DT >= :dt_from' + ' AND DT <= :dt_to'; CSQLDeleteRange = 'DELETE FROM event_depot' + ' WHERE IMEI = :imei' + ' AND DepotID = :d_id' + ' AND DT = :dt'; //------------------------------------------------------------------------------ // TEventDepotMySQL //------------------------------------------------------------------------------ constructor TEventDepotMySQL.Create( const AReadConnection: TZConnection; const AWriteConnection: TZConnection ); begin inherited Create( AReadConnection, AWriteConnection, CSQLInsert, CSQLUpdate, CSQLReadBefore, CSQLReadAfter, CSQLReadRange, CSQLDeleteRange ); end; procedure TEventDepotMySQL.Flush( const ACache: TCache ); //var // Iter: TCacheUnit; //------------------------------------------------------------------------------ begin // FillParamsFromKey(ACache.Key, FQueryInsert); // FillParamsFromKey(ACache.Key, FQueryUpdate); // for Iter in ACache do // begin // with TClassEventDepot(Iter) do // begin // if (Origin = ooNew) then // begin // FQueryInsert.ParamByName(CSQLParamDT).AsDateTime := DTMark; // FQueryInsert.ParamByName('dur').AsFloat := Duration; // FQueryInsert.ParamByName('inv').AsInteger := Ord(Inverse); // FQueryInsert.ExecSQL(); // Origin := ooLoaded; // Stored := Now(); // end // else // begin // if (Changed > Stored) then // begin // FQueryUpdate.ParamByName(CSQLParamDT).AsDateTime := DTMark; // FQueryUpdate.ParamByName('dur').AsFloat := Duration; // FQueryUpdate.ParamByName('inv').AsInteger := Ord(Inverse); // FQueryUpdate.ExecSQL(); // Stored := Now(); // end; // end; // end; // end; end; procedure TEventDepotMySQL.Add( const ACache: TCache; const AObj: TCacheDataObjectAbstract ); begin with TEventDepot(AObj) do begin FillParamsFromKey(ACache.Key, FInsertQry); FInsertQry.ParamByName(CSQLParamDT).AsDateTime := DTMark; FInsertQry.ParamByName('dur').AsFloat := Duration; FInsertQry.ParamByName('guid').AsString := GUID; FInsertQry.ExecSQL(); Origin := ooLoaded; Stored := Now(); end; end; procedure TEventDepotMySQL.Change( const ACache: TCache; const AObj: TCacheDataObjectAbstract ); begin with TEventDepot(AObj) do begin FillParamsFromKey(ACache.Key, FUpdateQry); // if (Changed > Stored) then // begin FUpdateQry.ParamByName(CSQLParamDT).AsDateTime := DTMark; FUpdateQry.ParamByName('dur').AsFloat := Duration; FUpdateQry.ExecSQL(); Stored := Now(); // end; end; end; function TEventDepotMySQL.MakeObjFromReadQuery( const AQuery: TZQuery ): TCacheDataObjectAbstract; begin with AQuery do begin Result := TEventDepot.Create( ooLoaded, FieldByName('IMEI').AsLargeInt, FieldByName('DepotID').AsInteger, FieldByName('DT').AsDateTime, FieldByName('Duration').AsFloat, '{' + FieldByName('GUID').AsString + '}' ); end; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, bsSkinCtrls, bsSkinData, Menus, bsSkinMenus, ActnList, StdCtrls, BusinessSkinForm, ExtCtrls, Mask, bsSkinBoxCtrls, FileCtrl, bsfilectrl, DropListBox,ShellAPI, ImgList, DB, DBClient,MainConst,MidasLib; type THideStyle = (hsHide,hsShow); TItemRec = record FileName:string; FilePath:string; IcoFile:TMemoryStream; end; PItemRec = ^TItemRec; TFrmMyTool = class(TForm) pnHead: TbsSkinPanel; pnMain: TbsSkinPanel; skinData: TbsSkinData; skinList: TbsCompressedSkinList; sbInfo: TbsSkinStatusBar; pp1: TbsSkinPopupMenu; N1: TMenuItem; Ubuntu1: TMenuItem; Aero1: TMenuItem; Office20101: TMenuItem; Office20102: TMenuItem; Win7Aero1: TMenuItem; Win8Aero1: TMenuItem; actlst1: TActionList; actSetTheme_Ubuntu: TAction; actSetTheme_SilverAero: TAction; actSetThemeOffice2010blue: TAction; actSetThemeOffice2010Silver: TAction; actSetThemeWin7Aero: TAction; actSetThemeWin8Aero: TAction; bsbsnsknfrm1: TbsBusinessSkinForm; tbSet: TbsSkinToolBar; pnQry: TbsSkinPanel; edtQry: TbsSkinEdit; imgQry: TImage; bsknpnl1: TbsSkinPanel; bsknpnl2: TbsSkinPanel; lbdt: TbsSkinLabel; tmr1: TTimer; lstContent: TbsSkinDropFileListBox; lbXQ: TbsSkinLabel; lbTime: TbsSkinLabel; il1: TImageList; ds1: TClientDataSet; tmr2: TTimer; tmr3: TTimer; ppList: TbsSkinPopupMenu; act_Delete: TAction; N2: TMenuItem; act_Set: TAction; ppMin: TbsSkinPopupMenu; act_showFrm: TAction; act_Exit: TAction; N3: TMenuItem; N4: TMenuItem; act_OffenUse: TAction; ilOffenUse: TImageList; N5: TMenuItem; bsSkinMenuSpeedButton1: TbsSkinMenuSpeedButton; ppSpeedButton: TbsSkinPopupMenu; act_DeleteSpeed: TAction; N6: TMenuItem; btn1: TbsSkinSpeedButton; bsknstspnl1: TbsSkinStatusPanel; procedure actSetTheme_UbuntuExecute(Sender: TObject); procedure actSetTheme_SilverAeroExecute(Sender: TObject); procedure actSetThemeOffice2010blueExecute(Sender: TObject); procedure actSetThemeOffice2010SilverExecute(Sender: TObject); procedure actSetThemeWin7AeroExecute(Sender: TObject); procedure actSetThemeWin8AeroExecute(Sender: TObject); procedure btnSetClick(Sender: TObject); procedure tmr1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lstContentDropFiles(Sender: TObject; FileNames: TStringList); procedure tmr2Timer(Sender: TObject); procedure tmr3Timer(Sender: TObject); //靠边缩进 procedure lstContentListBoxDblClick(Sender: TObject); procedure act_DeleteExecute(Sender: TObject); procedure act_ExitExecute(Sender: TObject); procedure act_OffenUseExecute(Sender: TObject); procedure act_DeleteSpeedExecute(Sender: TObject); private AppName:string; FBtnCount:Integer; procedure DateInit; procedure FreeDynamicBtn(sID:Integer); function GetFormNameAt(X,Y:Integer):string; procedure HideFrm(hs:THideStyle;hsSpped:Integer); procedure DynamicClick(Sender:TObject); procedure OpenLink(vID:Integer); { Private declarations } public { Public declarations } end; var FrmMyTool: TFrmMyTool; implementation {$R *.dfm} procedure TFrmMyTool.actSetThemeOffice2010blueExecute(Sender: TObject); begin skinData.SkinIndex := 2; end; procedure TFrmMyTool.actSetThemeOffice2010SilverExecute(Sender: TObject); begin skinData.SkinIndex := 3; end; procedure TFrmMyTool.actSetThemeWin7AeroExecute(Sender: TObject); begin skinData.SkinIndex := 4; end; procedure TFrmMyTool.actSetThemeWin8AeroExecute(Sender: TObject); begin skinData.SkinIndex := 5; end; procedure TFrmMyTool.actSetTheme_SilverAeroExecute(Sender: TObject); begin skinData.SkinIndex := 1; end; procedure TFrmMyTool.actSetTheme_UbuntuExecute(Sender: TObject); begin skinData.SkinIndex := 0; end; procedure TFrmMyTool.act_DeleteExecute(Sender: TObject); var CurIndex,I:Integer; btn:TComponent; begin //获取当前ID if lstContent.ItemIndex < 0 then begin ShowMessage('请选择要删除的记录!'); Exit; end; CurIndex := Integer(lstContent.Items.Objects[lstContent.ItemIndex]); try with ds1 do begin if Locate('ID',CurIndex,[]) then begin if FieldByName('OffenUse').AsBoolean then begin FreeDynamicBtn(CurIndex); end; //删除imagelist中对应图片 il1.Delete(lstContent.ItemIndex); //删除listbox中数据 lstContent.Items.Delete(lstContent.ItemIndex); //删除数据集中数据 Delete; SaveToFile(AppName); DateInit; end; end; except on E:Exception do ShowMessage(E.message); end; end; procedure TFrmMyTool.act_DeleteSpeedExecute(Sender: TObject); var CurIndex:Integer; begin //获取当前ID CurIndex := TbsSkinSpeedButton(TbsSkinPopupMenu(TMenuItem(TAction(Sender).ActionComponent).GetParentComponent).PopupComponent).Tag; with ds1 do begin if Locate('ID',CurIndex,[]) then begin Edit; FieldByName('OffenUse').AsBoolean := False; Post; TbsSkinSpeedButton(TbsSkinPopupMenu(TMenuItem(TAction(Sender).ActionComponent).GetParentComponent).PopupComponent).Destroy; SaveToFile(AppName); DateInit; end; end; end; procedure TFrmMyTool.act_ExitExecute(Sender: TObject); begin Self.Close; end; procedure TFrmMyTool.act_OffenUseExecute(Sender: TObject); var CurIndex:Integer; begin //获取当前ID if lstContent.ItemIndex < 0 then begin ShowMessage('请选择要添加的记录!'); Exit; end; CurIndex := Integer(lstContent.Items.Objects[lstContent.ItemIndex]); with ds1 do begin if Locate('ID',CurIndex,[]) then begin Edit; FieldByName('OffenUse').AsBoolean := True; Post; end; SaveToFile(AppName); end; DateInit; end; procedure TFrmMyTool.btnSetClick(Sender: TObject); var pc:TPoint; vValue : LongBool; begin GetCursorPos(pc); if Owner is TForm then SetForegroundWindow(TForm(Owner).Handle); pp1.Popup(pc.X,pc.Y); PostMessage( 0, 0, 0, 0 ); end; procedure TFrmMyTool.DateInit; var ico:TIcon; FileRec:PItemRec; begin lstContent.Clear; with ds1 do begin with FieldDefs do begin Close; Clear; Add('ID',ftInteger,0,True); Add('FileName',ftString,50,True); Add('FilePath',ftString,500,True); Add('OffenUse',ftBoolean); Add('Ico',ftBlob,0,True); end; CreateDataSet; FBtnCount := 0; //用于计算动态生成的按钮 il1.Clear; //清楚所有图片 ilOffenUse.Clear; if FileExists(AppName) then begin LoadFromFile(AppName); Open; FreeDynamicBtn(0); First; while not Eof do begin try try New(FileRec); ico := TIcon.Create; FileRec.IcoFile := TMemoryStream.Create; FileRec.FileName := FieldByName('FileName').AsString; TBlobField(FieldByName('Ico')).SaveToStream(FileRec.IcoFile); lstContent.Items.AddObject(filerec.FileName,TObject(FieldByName('ID').AsInteger)); FileRec.IcoFile.Position := 0; ico.LoadFromStream(FileRec.IcoFile); il1.AddIcon(ico); //添加常用软件 try if Assigned(FindField('OffenUse')) and FieldByName('OffenUse').AsBoolean then begin ilOffenUse.AddIcon(ico); with TbsSkinSpeedButton.Create(self) do begin Name := 'btn_' + IntToStr(FieldByName('ID').AsInteger); Parent := sbInfo; Width := Parent.Height; Height := Parent.Height; top := 0; Left := FBtnCount * Parent.Height ; Align := alNone; ImageList := ilOffenUse; ImageIndex := FBtnCount; Tag := FieldByName('ID').AsInteger; SkinData := skinData; OnClick := DynamicClick; PopupMenu := ppSpeedButton; BringToFront; end; FBtnCount := FBtnCount + 1; end; except ON e:Exception do ShowMessage(E.Message); end; except on E:Exception do ShowMessage(e.Message); end; finally FileRec.IcoFile.Free; ico.Free; Dispose(FileRec); end; Next; end; end; end; end; procedure TFrmMyTool.DynamicClick(Sender: TObject); begin OpenLink(TbsSkinSpeedButton(Sender).Tag); end; procedure TFrmMyTool.FormCreate(Sender: TObject); begin AppName := ExtractFilePath(Application.ExeName) + 'MyTools.dat'; ds1.FileName := AppName; DateInit; tmr1.Interval := 1000; tmr1.Enabled := True; tmr1Timer(tmr1); //由于skin控件禁止,这里手动在开启一次 DragAcceptFiles(lstContent.Handle,lstContent.DropEnabled); end; procedure TFrmMyTool.FreeDynamicBtn(sID: Integer); var I:integer; btn:TComponent; begin with ds1 do begin DisableControls; Filtered := False; if sID = 0 then Filter := 'OffenUse <> 0' else Filter := 'ID = ' + IntToStr(sID); Filtered := True; ds1.First; while not Eof do begin btn := Self.FindComponent('btn_' + FieldByName('ID').AsString); if Assigned(Btn) then TbsSkinSpeedButton(btn).Destroy; Next; end; Filtered := False; EnableControls; end; end; function TFrmMyTool.GetFormNameAt(X, Y: Integer): string; var P:TPoint; W:TWinControl; begin P.X := x; p.y := y; W := FindVCLWindow(P); if (W <> nil) then begin while w.Parent <> nil do begin w := w.Parent; end; Result := w.Name; end else Result := ''; end; procedure TFrmMyTool.HideFrm(hs: THideStyle; hsSpped: Integer); var finalHeight:Integer; begin if hs = hsHide then begin finalHeight := -(Self.height - 10); while Self.Top >= finalHeight do begin Self.Top := Self.Top - hsSpped; end; if Self.Top < finalHeight then Self.Top := finalHeight; SetWindowLong(Application.Handle,GWL_EXSTYLE,WS_EX_TOOLWINDOW); end; if hs = hsShow then begin finalHeight := 0; while Self.top < finalHeight do begin Self.Top := Self.Top + hsSpped; end; if Self.Top > finalHeight then Self.Top := finalHeight; end; end; procedure TFrmMyTool.lstContentDropFiles(Sender: TObject; FileNames: TStringList); var I,count: Integer; ico:TIcon; FileInfo:SHFILEINFO; FileRec:PItemRec; F:file of PItemRec; begin //提取exe图标 for I := 0 to FileNames.Count - 1 do begin try ico := TIcon.Create; count := SHGetFileInfo(PAnsiChar(FileNames[I]),0,FileInfo,SizeOf(FileInfo),SHGFI_ICON); ico.Handle := FileInfo.hIcon; il1.AddIcon(ico); //保存到文件 New(FileRec); try FileRec.FileName := ExtractFileName(FileNames[I]); FileRec.FilePath := FileNames[I]; FileRec.IcoFile := TMemoryStream.Create; ico.SaveToStream(FileRec.IcoFile); ds1.Append; ds1.FieldByName('ID').AsInteger := ds1.RecordCount + 1; ds1.FieldByName('FileName').AsString := FileRec.FileName; ds1.FieldByName('FilePath').AsString := FileRec.FilePath; TBlobField(ds1.FieldByName('Ico')).LoadFromStream(FileRec.IcoFile); ds1.Post; ds1.SaveToFile(AppName); lstContent.Items.AddObject(FileRec.FileName,TObject(ds1.FieldByName('ID').AsInteger)); finally FileRec.IcoFile.Free; Dispose(FileRec); end; finally ico.Free; end; end; end; procedure TFrmMyTool.lstContentListBoxDblClick(Sender: TObject); begin OpenLink(Integer(lstContent.Items.Objects[lstContent.ItemIndex])) end; procedure TFrmMyTool.OpenLink(vID: Integer); begin with ds1 do begin if Locate('ID',vID,[]) then begin ShellExecute(0,'open',PChar(FieldByName('FilePath').AsString),nil,nil,SW_NORMAL); end; end; end; procedure TFrmMyTool.tmr1Timer(Sender: TObject); var Date,XQ,Time:string; begin Date := FormatDateTime('yyyy年mm月dd日',now); case DayOfWeek(Now) - 1 of 1: XQ := '星期一'; 2: XQ := '星期二'; 3: XQ := '星期三'; 4: XQ := '星期四'; 5: XQ := '星期五'; 6: XQ := '星期六'; 7: XQ := '星期日'; end; time := FormatDateTime('hh:mm:ss',Now); lbdt.Caption := Date; lbXQ.Caption := XQ; lbTime.Caption := Time; end; procedure TFrmMyTool.tmr2Timer(Sender: TObject); var winPos:TPoint; begin if (Self.Top <= 3) or (Self.Left >= screen.Width - self.Width - 3) then begin GetCursorPos(winPos); if Self.Name = GetFormNameAt(winPos.X,winPos.y) then begin Self.tmr3.Enabled := False; HideFrm(hsShow,HideSpeed); end else tmr3.Enabled := True; end; end; procedure TFrmMyTool.tmr3Timer(Sender: TObject); begin if (Self.Top <= 20) and (Self.Top >= 0) then begin HideFrm(hsHide,HideSpeed); tmr3.Enabled := False; end; end; end.
unit findchip; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, dom, utilfunc, lazUTF8; type { TChipSearchForm } TChipSearchForm = class(TForm) Bevel1: TBevel; ChipSearchSelectButton: TButton; EditSearch: TEdit; Label1: TLabel; ListBoxChips: TListBox; procedure ChipSearchSelectButtonClick(Sender: TObject); procedure EditSearchChange(Sender: TObject); procedure ListBoxChipsDblClick(Sender: TObject); private { private declarations } public { public declarations } end; procedure FindChip(XMLfile: TXMLDocument; chipname: string; chipid: string = ''); procedure SelectChip(XMLfile: TXMLDocument; chipname: string); var ChipSearchForm: TChipSearchForm; implementation uses main, scriptsfunc; {$R *.lfm} //Ищет чип по имени. Если id не пустое то только по id. procedure FindChip(XMLfile: TXMLDocument; chipname: string; chipid: string = ''); var Node, ChipNode: TDOMNode; j, i: integer; cs: string; begin if XMLfile <> nil then begin Node := XMLfile.DocumentElement.FirstChild; while Assigned(Node) do begin //Node.NodeName; //Раздел(SPI, I2C...) // Используем свойство ChildNodes with Node.ChildNodes do try for j := 0 to (Count - 1) do begin //Item[j].NodeName; //Раздел Фирма for i := 0 to (Item[j].ChildNodes.Count - 1) do begin ChipNode := Item[j].ChildNodes.Item[i]; if chipid <> '' then begin if (ChipNode.HasAttributes) then if ChipNode.Attributes.GetNamedItem('id') <> nil then begin cs := UTF16ToUTF8(ChipNode.Attributes.GetNamedItem('id').NodeValue); //id if Upcase(cs) = Upcase(chipid) then ChipSearchForm.ListBoxChips.Items.Append(UTF16ToUTF8(ChipNode.NodeName)+' ('+ UTF16ToUTF8(Item[j].NodeName) +')'); end; end else begin cs := UTF16ToUTF8(ChipNode.NodeName); //Чип if pos(Upcase(chipname), Upcase(cs)) > 0 then ChipSearchForm.ListBoxChips.Items.Append(cs+' ('+ UTF16ToUTF8(Item[j].NodeName) +')'); end; end; end; finally Free; end; Node := Node.NextSibling; end; end; end; procedure SelectChip(XMLfile: TXMLDocument; chipname: string); var Node, ChipNode: TDOMNode; j, i: integer; cs: string; begin if XMLfile <> nil then begin Node := XMLfile.DocumentElement.FirstChild; while Assigned(Node) do begin //Node.NodeName; //Раздел(SPI, I2C...) // Используем свойство ChildNodes with Node.ChildNodes do try for j := 0 to (Count - 1) do begin //Item[j].NodeName; //Раздел Фирма for i := 0 to (Item[j].ChildNodes.Count - 1) do begin cs := UTF16ToUTF8(Item[j].ChildNodes.Item[i].NodeName); //Чип if Upcase(chipname) = Upcase(cs) then begin ChipNode := Item[j].ChildNodes.Item[i]; Main.CurrentICParam.Name:= UTF16ToUTF8(ChipNode.NodeName); if (ChipNode.HasAttributes) then begin if ChipNode.Attributes.GetNamedItem('spicmd') <> nil then begin if UpperCase(ChipNode.Attributes.GetNamedItem('spicmd').NodeValue) = 'KB'then Main.CurrentICParam.SpiCmd:= SPI_CMD_KB; if ChipNode.Attributes.GetNamedItem('spicmd').NodeValue = '45' then Main.CurrentICParam.SpiCmd:= SPI_CMD_45; if ChipNode.Attributes.GetNamedItem('spicmd').NodeValue = '25' then Main.CurrentICParam.SpiCmd:= SPI_CMD_25; if ChipNode.Attributes.GetNamedItem('spicmd').NodeValue = '95' then Main.CurrentICParam.SpiCmd:= SPI_CMD_95; MainForm.ComboSPICMD.ItemIndex := CurrentICParam.SpiCmd; MainForm.RadioSPI.Checked:= true; MainForm.RadioSPIChange(MainForm); end else //По дефолту spicmd25 if (ChipNode.Attributes.GetNamedItem('addrtype') = nil) and (ChipNode.Attributes.GetNamedItem('addrbitlen') = nil) then begin Main.CurrentICParam.SpiCmd:= SPI_CMD_25; MainForm.ComboSPICMD.ItemIndex := CurrentICParam.SpiCmd; MainForm.RadioSPI.Checked:= true; MainForm.RadioSPIChange(MainForm); end; if ChipNode.Attributes.GetNamedItem('addrbitlen') <> nil then begin MainForm.RadioMw.Checked:= true; Main.CurrentICParam.MWAddLen := StrToInt(UTF16ToUTF8(ChipNode.Attributes.GetNamedItem('addrbitlen').NodeValue)); end else Main.CurrentICParam.MWAddLen := 0; if ChipNode.Attributes.GetNamedItem('addrtype') <> nil then if IsNumber(UTF16ToUTF8(ChipNode.Attributes.GetNamedItem('addrtype').NodeValue)) then begin MainForm.RadioI2C.Checked:= true; Main.CurrentICParam.I2CAddrType := StrToInt(UTF16ToUTF8(ChipNode.Attributes.GetNamedItem('addrtype').NodeValue)); end; if ChipNode.Attributes.GetNamedItem('page') <> nil then begin if UpCase(UTF16ToUTF8(ChipNode.Attributes.GetNamedItem('page').NodeValue)) = 'SSTB' then Main.CurrentICParam.Page := -1 else if UpCase(UTF16ToUTF8(ChipNode.Attributes.GetNamedItem('page').NodeValue)) = 'SSTW' then Main.CurrentICParam.Page := -2 else Main.CurrentICParam.Page := StrToInt(UTF16ToUTF8(ChipNode.Attributes.GetNamedItem('page').NodeValue)); end else Main.CurrentICParam.Page := 0; if ChipNode.Attributes.GetNamedItem('size') <> nil then Main.CurrentICParam.Size:= StrToInt(UTF16ToUTF8(ChipNode.Attributes.GetNamedItem('size').NodeValue)) else Main.CurrentICParam.Size := 0; if ChipNode.Attributes.GetNamedItem('script') <> nil then begin Main.CurrentICParam.Script:= UTF16ToUTF8(ChipNode.Attributes.GetNamedItem('script').NodeValue); MainForm.ComboBox_chip_scriptrun.Items := scriptsfunc.GetScriptSectionsFromFile(Main.CurrentICParam.Script); MainForm.ComboBox_chip_scriptrun.ItemIndex := 0; end else begin Main.CurrentICParam.Script := ''; MainForm.ComboBox_chip_scriptrun.Items.Clear; end; MainForm.LabelChipName.Caption := CurrentICParam.Name; if CurrentICParam.MWAddLen > 0 then MainForm.ComboMWBitLen.Text := IntToStr(CurrentICParam.MWAddLen) else MainForm.ComboMWBitLen.Text := 'MW addr len'; MainForm.ComboAddrType.ItemIndex := CurrentICParam.I2CAddrType; if CurrentICParam.Page > 0 then MainForm.ComboPageSize.Text := IntToStr(CurrentICParam.Page) else if CurrentICParam.Page = -1 then MainForm.ComboPageSize.Text := 'SSTB' else if CurrentICParam.Page = -2 then MainForm.ComboPageSize.Text := 'SSTW' else MainForm.ComboPageSize.Text := 'Page size'; if CurrentICParam.Size > 0 then MainForm.ComboChipSize.Text := IntToStr(CurrentICParam.Size) else MainForm.ComboChipSize.Text := 'Chip size'; end; end; end; end; finally Free; end; Node := Node.NextSibling; end; end; end; { TChipSearchForm } procedure TChipSearchForm.EditSearchChange(Sender: TObject); begin ListBoxChips.Clear; FindChip(chiplistfile, EditSearch.Text); end; procedure TChipSearchForm.ChipSearchSelectButtonClick(Sender: TObject); begin ChipSearchForm.ListBoxChipsDblClick(Sender); ChipSearchForm.Hide; end; procedure TChipSearchForm.ListBoxChipsDblClick(Sender: TObject); var chipname: string; begin if ListBoxChips.ItemIndex >= 0 then begin chipname := ListBoxChips.Items[ListBoxChips.ItemIndex]; chipname := copy(chipname, 1, pos(' (', chipname)-1); //отрезаем фирму SelectChip(chiplistfile, chipname); end; end; end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps; type TFrmMain = class(TForm) Map: TTMSFNCMaps; procedure MapMapInitialized(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses IOUtils, Flix.Utils.Maps; procedure TFrmMain.FormCreate(Sender: TObject); var LKeys: TServiceAPIKeys; begin LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) ); try Map.APIKey := LKeys.GetKey( msGoogleMaps ); finally LKeys.Free; end; end; procedure TFrmMain.MapMapInitialized(Sender: TObject); var LBounds: TTMSFNCMapsBounds; LSeattle, LBaltimore : TTMSFNCMapsCoordinate; begin LSeattle := TTMSFNCMapsCoordinate.Create( 47.609722, -122.333056 ); LBaltimore := TTMSFNCMapsCoordinate.Create( 39.283333 ,-76.616667 ); LBounds := TTMSFNCMapsBounds.Create( LBaltimore.ToRec, LSeattle.ToRec ); try Map.ZoomToBounds( LBounds.ToRec ); Map.AddRectangle(LBounds.ToRec).FillOpacity := 0.3; Map.AddMarker( LBaltimore.ToRec ); Map.AddMarker( LSeattle.ToRec ); finally LSeattle.Free; LBaltimore.Free; LBounds.Free; end; end; end.
unit UnitSaveQueryThread; interface uses Generics.Collections, Winapi.Windows, Winapi.ActiveX, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Data.DB, Dmitry.CRC32, Dmitry.Utils.Files, uConstants, uDBUtils, uShellIntegration, uMemory, uTranslate, uDBThread, uDBConnection, uDBContext, uDBEntities, uDBManager, uResourceUtils, uThreadForm, uThreadEx, uMobileUtils, uTime, uLogger, uDBShellUtils, uRuntime, uProgramStatInfo, uFormInterfaces; type TSaveQueryThread = class(TThreadEx) private { Private declarations } FDBContext: IDBContext; FDestinationPath, DBFolder: string; FIntParam: Integer; FRegGroups: TGroups; FGroupsFound: TGroups; FSubFolders: Boolean; FFileList: TStrings; SaveToDBName: string; NewIcon: TIcon; OutIconName: string; OriginalIconLanguage: Integer; protected { Protected declarations } function GetThreadID: string; override; procedure Execute; override; procedure SetMaxValue(Value: integer); procedure SetMaxValueA; procedure SetProgress(Value: integer); procedure SetProgressA; Procedure Done; procedure LoadCustomDBName; procedure ReplaceIconAction; procedure SaveLocation(Src, Dest: TDataSet; MediaIds: TDictionary<Integer, Integer>); public { Public declarations } constructor Create(DBContext: IDBContext; DestinationPath : String; OwnerForm: TThreadForm; SubFolders: boolean; FileList: TStrings; State: TGUID); destructor Destroy; override; end; implementation uses UnitSavingTableForm; { TSaveQueryThread } constructor TSaveQueryThread.Create(DBContext: IDBContext;DestinationPath: string; OwnerForm: TThreadForm; SubFolders: Boolean; FileList: TStrings; State: TGUID); begin inherited Create(OwnerForm, State); FDBContext := DBContext; FSubFolders := SubFolders; FDestinationPath := DestinationPath; FFileList := TStringList.Create; FFileList.Assign(FileList); end; destructor TSaveQueryThread.Destroy; begin F(FFileList); inherited; end; procedure TSaveQueryThread.Done; begin ThreadForm.OnCloseQuery := nil; ThreadForm.Close; end; procedure LoadLocation(Query: TDataSet; Location: string; WithSubflders: Boolean); var LocationFolder: string; AndWhere, FromSQL: string; Crc: Cardinal; begin if FileExistsSafe(Location) then LocationFolder := ExtractFileDir(Location) else LocationFolder := Location; LocationFolder := ExcludeTrailingBackslash(LocationFolder); if not WithSubflders then begin AndWhere := ' and not (FFileName like :FolderB) '; CalcStringCRC32(AnsiLowerCase(LocationFolder), Crc); FromSQL := '(Select * from $DB$ where FolderCRC=' + Inttostr(Integer(Crc)) + ')'; end else begin FromSQL := '$DB$'; AndWhere := ''; end; SetSQL(Query, 'Select * From ' + FromSQL + ' where (FFileName Like :FolderA)' + AndWhere); LocationFolder := IncludeTrailingBackslash(LocationFolder); if FileExistsSafe(Location) then SetStrParam(Query, 0, '%' + AnsiLowerCase(Location) + '%') else SetStrParam(Query, 0, '%' + LocationFolder + '%'); if not WithSubflders then SetStrParam(Query, 1, '%' + LocationFolder + '%\%'); OpenDS(Query); end; procedure TSaveQueryThread.SaveLocation(Src, Dest: TDataSet; MediaIds: TDictionary<Integer, Integer>); begin if not Src.Eof then begin SetMaxValue(Src.RecordCount); Src.First; repeat if IsTerminated then Break; Dest.Append; CopyRecordsW(Src, Dest, True, False, DBFolder, FGroupsFound); Dest.Post; MediaIds.Add(Src.FieldByName('ID').AsInteger, Dest.FieldByName('ID').AsInteger); SetProgress(Src.RecNo); Src.Next; until Src.Eof; end; end; procedure TSaveQueryThread.Execute; var I, J: Integer; FDBFileName, FExeFileName: string; ImageSettings: TSettings; FQuery: TDataSet; FTable: TDataSet; Destination: IDBContext; SettingsRSrc, SettingsRDest: ISettingsRepository; GroupsSrc, GroupsDest: IGroupsRepository; PeopleSrc, PeopleDest: IPeopleRepository; MediaIds, PeopleIds: TDictionary<Integer, Integer>; MediaPair: TPair<Integer, Integer>; PersonAreas: TPersonAreaCollection; Person: TPerson; begin inherited; FreeOnTerminate := True; MediaIds := TDictionary<Integer, Integer>.Create; PeopleIds := TDictionary<Integer, Integer>.Create; try try CoInitializeEx(nil, COM_MODE); try SaveToDBName := GetFileNameWithoutExt(FDestinationPath); if SaveToDBName <> '' then if Length(SaveToDBName) > 1 then if SaveToDBName[2] = ':' then SaveToDBName := SaveToDBName[1] + '_drive'; SynchronizeEx(LoadCustomDBName); FDestinationPath := IncludeTrailingBackslash(FDestinationPath); FDBFileName := FDestinationPath + SaveToDBName + '.photodb'; if not TDBManager.CreateDBbyName(FDBFileName) then Exit; Destination := TDBContext.Create(FDBFileName); SettingsRSrc := FDBContext.Settings; SettingsRDest := Destination.Settings; ImageSettings := SettingsRSrc.Get; try SettingsRDest.Update(ImageSettings); finally F(ImageSettings); end; GroupsSrc := FDBContext.Groups; GroupsDest := Destination.Groups; PeopleSrc := FDBContext.People; PeopleDest := Destination.People; FTable := GetTable(FDBFileName, DB_TABLE_IMAGES); try OpenDS(FTable); DBFolder := ExtractFilePath(FDBFileName); FGroupsFound := TGroups.Create; try for I := 0 to FFileList.Count - 1 do begin FQuery := FDBContext.CreateQuery; try LoadLocation(FQuery, FFileList[I], FSubFolders); SaveLocation(FQuery, FTable, MediaIds); finally FreeDS(FQuery); end; end; SetMaxValue(FGroupsFound.Count); FRegGroups := GroupsSrc.GetAll(True, True); try for I := 0 to FGroupsFound.Count - 1 do begin if IsTerminated then Break; SetProgress(I); for J := 0 to FRegGroups.Count - 1 do if FRegGroups[J].GroupCode = FGroupsFound[I].GroupCode then begin GroupsDest.Add(FRegGroups[J]); Break; end; end; finally F(FRegGroups); end; for MediaPair in MediaIds do begin PersonAreas := PeopleSrc.GetAreasOnImage(MediaPair.Key); try for I := 0 to PersonAreas.Count - 1 do begin PersonAreas[I].ImageID := MediaPair.Value; if not PeopleIds.ContainsKey(PersonAreas[I].PersonID) then begin Person := PeopleSrc.GetPerson(PersonAreas[I].PersonID, True); try PeopleIds.Add(PersonAreas[I].PersonID, PeopleDest.CreateNewPerson(Person)); finally F(Person); end; end; PersonAreas[I].PersonID := PeopleIds[PersonAreas[I].PersonID]; PeopleDest.AddPersonForPhoto(nil, PersonAreas[I]); end; finally F(PersonAreas); end; end; finally F(FGroupsFound); end; finally FreeDS(FTable); end; TryRemoveConnection(Destination.CollectionFileName, True); TW.I.Check('Copy File'); FExeFileName := ExtractFilePath(FDBFileName) + SaveToDBName + '.exe'; CopyFile(PChar(Application.Exename), PChar(FExeFileName), False); TW.I.Check('Update File Resources'); UpdateExeResources(FExeFileName); TW.I.Check('Change File Icon'); NewIcon := TIcon.Create; try SynchronizeEx(ReplaceIconAction); if not NewIcon.Empty then begin NewIcon.SaveToFile(OutIconName); F(NewIcon); ReplaceIcon(FExeFileName, PWideChar(OutIconName)); if FileExistsSafe(OutIconName) then DeleteFile(OutIconName); end; finally F(NewIcon); end; //statistics ProgramStatistics.PortableUsed; finally CoUninitialize; end; finally F(MediaIds); F(PeopleIds); SynchronizeEx(Done); end; except on e: Exception do begin MessageBoxDB(0, E.Message, TA('Error'), TD_BUTTON_OK, TD_ICON_ERROR); EventLog(e); end; end; end; function TSaveQueryThread.GetThreadID: string; begin Result := 'Mobile'; end; procedure TSaveQueryThread.SetMaxValue(Value: Integer); begin FIntParam := Value; SynchronizeEx(SetMaxValueA); end; procedure TSaveQueryThread.SetMaxValueA; begin TSavingTableForm(ThreadForm).DmProgress1.MaxValue := FIntParam; end; procedure TSaveQueryThread.SetProgress(Value: Integer); begin FIntParam := Value; SynchronizeEx(SetProgressA); end; procedure TSaveQueryThread.SetProgressA; begin TSavingTableForm(ThreadForm).DmProgress1.Position := FIntParam; end; procedure TSaveQueryThread.LoadCustomDBName; var S: string; begin S := SaveToDBName; if StringPromtForm.Query(L('Collection name'), L('Please enter name for new collection') + ':', S) then if S <> '' then SaveToDBName := S; end; procedure TSaveQueryThread.ReplaceIconAction; begin if ID_YES = MessageBoxDB(0, TA('Do you want to change the icon for the final collection?', 'Mobile'), TA('Question'), TD_BUTTON_YESNO, TD_ICON_QUESTION) then GetIconForFile(NewIcon, OutIconName, OriginalIconLanguage); end; end.
unit InflatablesList_ShopSelectItemsArray; {$INCLUDE '.\InflatablesList_defs.inc'} {$INCLUDE '.\CountedDynArrays_defs.inc'} {$DEFINE CDA_FuncOverride_ItemCompare} interface uses AuxTypes, CountedDynArrays, InflatablesList_Item; type TILShopSelectItemEntry = record ItemObject: TILItem; Available: Boolean; Selected: Boolean; Index: Integer; Price: UInt32; end; TCDABaseType = TILShopSelectItemEntry; PCDABaseType = ^TCDABaseType; TILCountedDynArrayShopSelectItem = record {$DEFINE CDA_Structure} {$INCLUDE '.\CountedDynArrays.inc'} {$UNDEF CDA_Structure} end; PILCountedDynArrayShopSelectItem = ^TILCountedDynArrayShopSelectItem; // aliases TILCountedDynArrayOfShopSelectItem = TILCountedDynArrayShopSelectItem; PILCountedDynArrayOfShopSelectItem = PILCountedDynArrayShopSelectItem; TILShopSelectItemCountedDynArray = TILCountedDynArrayShopSelectItem; PILShopSelectItemCountedDynArray = PILCountedDynArrayShopSelectItem; TCDAArrayType = TILCountedDynArrayShopSelectItem; PCDAArrayType = PILCountedDynArrayShopSelectItem; {$DEFINE CDA_Interface} {$INCLUDE '.\CountedDynArrays.inc'} {$UNDEF CDA_Interface} Function CDA_IndexOfObject(Arr: TCDAArrayType; ItemObject: TILItem): Integer; implementation uses SysUtils, ListSorters; Function CDA_ItemCompare(const A,B: TCDABaseType): Integer; begin // first by selected, then by available, and at the end by index in the main list If (A.Selected = B.Selected) and (A.Available = B.Available) then Result := B.Index - A.Index else If A.Selected and not B.Selected then Result := +1 else If B.Selected and not A.Selected then Result := -1 else If A.Available and not B.Available then Result := +1 else If B.Available and not A.Available then Result := -1 else Result := 0; end; //------------------------------------------------------------------------------ Function CDA_IndexOfObject(Arr: TCDAArrayType; ItemObject: TILItem): Integer; var i: Integer; begin Result := -1; For i := CDA_Low(Arr) to CDA_High(Arr) do If Arr.Arr[i].ItemObject = ItemObject then begin Result := i; Break{For i}; end; end; //------------------------------------------------------------------------------ {$DEFINE CDA_Implementation} {$INCLUDE '.\CountedDynArrays.inc'} {$UNDEF CDA_Implementation} end.
unit Pospolite.View.HTML.Parser; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} {$modeswitch advancedrecords} interface uses Classes, SysUtils, math, Pospolite.View.Basics, Pospolite.View.HTML.Basics; type { TPLHTMLParserPosition } TPLHTMLParserPosition = record public Row, Column: SizeInt; constructor Create(const ARow, AColumn: SizeInt); class operator =(a, b: TPLHTMLParserPosition): TPLBool; inline; end; { TPLHTMLParserError } TPLHTMLParserError = record public Position: TPLHTMLParserPosition; Name: TPLString; constructor Create(const APosition: TPLHTMLParserPosition; const AName: TPLString); class operator =(a, b: TPLHTMLParserError): TPLBool; inline; end; { TPLHTMLParserErrors } TPLHTMLParserErrors = class(specialize TPLList<TPLHTMLParserError>) public function AllInOneString: TPLString; end; { IPLHTMLParser } IPLHTMLParser = interface ['{F939F08E-B228-44DD-AA3B-BEE2F82F4AF0}'] function GetErrors: TPLHTMLParserErrors; function GetHasCriticalError: TPLBool; function GetStrict: TPLBool; procedure SetStrict(AValue: TPLBool); procedure Parse(const ASource: TPLString; var ARoot: TPLHTMLRootObject); procedure CleanUp; property Strict: TPLBool read GetStrict write SetStrict; property Errors: TPLHTMLParserErrors read GetErrors; property HasCriticalError: TPLBool read GetHasCriticalError; end; { TPLHTMLParser } TPLHTMLParser = class(TInterfacedObject, IPLHTMLParser) private FSource: TPLString; FCurrent, FEnd: ^TPLChar; FPos: TPLHTMLParserPosition; FStrict: TPLBool; FRoot: TPLHTMLRootObject; FErrors: TPLHTMLParserErrors; function GetErrors: TPLHTMLParserErrors; function GetHasCriticalError: TPLBool; function GetStrict: TPLBool; procedure SetStrict(AValue: TPLBool); procedure MovePosToNextRow; procedure MovePosForward; function IsVoidElement(AName: TPLString): TPLBool; inline; function IsEOF: TPLBool; inline; procedure Consume(AChar: TPLChar; AMoveNext: TPLBool = true); procedure ConsumeWhitespace; function Position: SizeInt; inline; function ReadObject(AParent: TPLHTMLBasicObject): TPLHTMLBasicObject; function ReadVoidObject(AParent: TPLHTMLBasicObject; AStart, AEnd, AName: TPLString): TPLHTMLVoidObject; function ReadNormalObject(AParent: TPLHTMLBasicObject): TPLHTMLBasicObject; function ReadText(AChars: array of TPLString): TPLString; procedure ReadObjectAttribute(var AObject: TPLHTMLBasicObject); public constructor Create; destructor Destroy; override; procedure Parse(const ASource: TPLString; var ARoot: TPLHTMLRootObject); procedure CleanUp; property Strict: TPLBool read GetStrict write SetStrict; property Errors: TPLHTMLParserErrors read GetErrors; property HasCriticalError: TPLBool read GetHasCriticalError; end; implementation { TPLHTMLParserPosition } constructor TPLHTMLParserPosition.Create(const ARow, AColumn: SizeInt); begin Row := ARow; Column := AColumn; end; class operator TPLHTMLParserPosition.=(a, b: TPLHTMLParserPosition): TPLBool; begin Result := (a.Row = b.Row) and (a.Column = b.Column); end; { TPLHTMLParserError } constructor TPLHTMLParserError.Create(const APosition: TPLHTMLParserPosition; const AName: TPLString); begin Position := APosition; Name := AName; end; class operator TPLHTMLParserError.=(a, b: TPLHTMLParserError): TPLBool; begin Result := (a.Name = b.Name) and (a.Position = b.Position); end; { TPLHTMLParserErrors } function TPLHTMLParserErrors.AllInOneString: TPLString; var e: TPLHTMLParserError; begin Result := ''; for e in self do Result += '(%d, %d) %s'.Format([e.Position.Row, e.Position.Column, e.Name]) + LineEnding; end; { TPLHTMLParser } function TPLHTMLParser.GetErrors: TPLHTMLParserErrors; begin Result := FErrors; end; function TPLHTMLParser.GetHasCriticalError: TPLBool; var e: TPLHTMLParserError; begin Result := false; for e in FErrors do if e.Name.Exists('CRITICAL') then exit(true); end; function TPLHTMLParser.GetStrict: TPLBool; begin Result := FStrict; end; procedure TPLHTMLParser.SetStrict(AValue: TPLBool); begin FStrict := AValue; end; procedure TPLHTMLParser.MovePosToNextRow; begin FPos.Row += 1; FPos.Column := 1; end; procedure TPLHTMLParser.MovePosForward; begin if FCurrent^ = #10 then MovePosToNextRow else FPos.Column += 1; Inc(FCurrent); end; function TPLHTMLParser.IsVoidElement(AName: TPLString): TPLBool; begin Result := AName.ToLower in TPLHTMLObjectFactory.VoidElements; end; function TPLHTMLParser.IsEOF: TPLBool; begin Result := FCurrent > FEnd; end; procedure TPLHTMLParser.Consume(AChar: TPLChar; AMoveNext: TPLBool); //var // p: SizeInt; begin if IsEOF then begin FErrors.Add(TPLHTMLParserError.Create(FPos, 'CRITICAL: Unexpected end of file.')); exit; end; if FCurrent^ <> AChar then begin FErrors.Add(TPLHTMLParserError.Create(FPos, '"%s" expected but "%s" found.'.Format([AChar, FCurrent^]))); //Write('[^]'); //FCurrent := FEnd; //p := FSource.Find(AChar, Position); //if p > 0 then begin // while FCurrent^ <> AChar do MovePosForward; //end else begin // FCurrent := FEnd + 1; // FPos.Column := FSource.Length; //end; //exit; end; if AMoveNext then MovePosForward; end; procedure TPLHTMLParser.ConsumeWhitespace; begin while not IsEOF and FCurrent^.IsWhitespace do MovePosForward; end; function TPLHTMLParser.Position: SizeInt; begin Result := FCurrent - @FSource[1] + 1; end; function TPLHTMLParser.ReadObject(AParent: TPLHTMLBasicObject ): TPLHTMLBasicObject; begin Consume('<', false); if IsEOF then exit(nil); if FSource.SubStr(Position, 4) = '<!--' then Result := ReadVoidObject(AParent, '<!--', '-->', 'comment') else if FSource.SubStr(Position, 9) = '<!DOCTYPE' then Result := ReadVoidObject(AParent, '<!DOCTYPE', '>', 'DOCTYPE') else if FSource.SubStr(Position, 9) = '<!CDATA[' then Result := ReadVoidObject(AParent, '<!CDATA[', ']]>', 'CDATA') else if FSource.SubStr(Position, 2) = '<!' then Result := ReadVoidObject(AParent, '<!', '>', 'void') else Result := ReadNormalObject(AParent); end; function TPLHTMLParser.ReadVoidObject(AParent: TPLHTMLBasicObject; AStart, AEnd, AName: TPLString): TPLHTMLVoidObject; var pom: TPLChar; s, l: SizeInt; begin for pom in AStart do Consume(pom); s := Position; l := Length(AEnd); Result := nil; while not IsEOF and (FSource.SubStr(Position, l) <> AEnd) do MovePosForward; if FSource.SubStr(Position, l) = AEnd then begin Result := TPLHTMLVoidObject.Create(AParent); Result.Position := s; Result.Text := FSource.SubStr(s, Position - s).Trim; Result.Name := AName; case AName of 'comment': Result.NodeType := ontCommentNode; 'DOCTYPE': Result.NodeType := ontDocumentTypeNode; 'CDATA': Result.NodeType := ontCDataSectionNode; end; Inc(FCurrent, l); end else FErrors.Add(TPLHTMLParserError.Create(FPos, '"%s" tag ending expected but "%s" found.'.Format([AEnd, FSource.SubStr(Position, l)]))); end; function TPLHTMLParser.ReadNormalObject(AParent: TPLHTMLBasicObject ): TPLHTMLBasicObject; var obj: TPLHTMLBasicObject; un: TPLBool = false; eof: TPLBool; n, x: TPLString; s: ^TPLChar; arrc: specialize TArray<TPLString>; txt: TPLHTMLTextObject; begin Result := nil; arrc := TPLStringFuncs.NewArray(TPLString.WhitespacesArrayString) + TPLStringFuncs.NewArray(['/', '>']); Consume('<'); ConsumeWhitespace; n := ReadText(arrc).ToLower; ConsumeWhitespace; try Result := TPLHTMLObjectFactory.CreateObjectByTagName(n, AParent); Result.Position := Position; while not IsEOF and not (FCurrent^ in ['/', '>']) do begin ReadObjectAttribute(Result); ConsumeWhitespace; end; if n in TPLStringFuncs.NewArray(['script', 'style', 'code', 'pre', 'svg']) then begin Consume('>'); Result.Text := ''; while not IsEOF and (FSource.SubStr(Position, Length(n)+2).ToLower <> '</'+n) do begin Result.Text := Result.Text + FCurrent^; MovePosForward; end; FCurrent := FCurrent + Length('</'+n); ConsumeWhitespace; while FCurrent^ <> '>' do MovePosForward; Consume('>'); ConsumeWhitespace; end else if IsVoidElement(n) then begin ConsumeWhitespace; if FCurrent^ = '/' then Consume('/'); ConsumeWhitespace; Consume('>'); ConsumeWhitespace; end else begin if FCurrent^ = '>' then begin Consume('>'); repeat if IsEOF then break; x := ''; while (FCurrent < FEnd) and (FCurrent^ <> '<') do begin x += FCurrent^; MovePosForward; end; x := x.Trim; if not x.IsEmpty then begin txt := TPLHTMLObjectFactory.CreateObjectByTagName('internal_text_object', Result) as TPLHTMLTextObject; txt.Text := x; Result.Children.Add(txt); txt.Parent := Result; end; //ConsumeWhitespace; s := FCurrent; //ConsumeWhitespace; Consume('<'); //ConsumeWhitespace; eof := FCurrent^ = '/'; //ConsumeWhitespace; if eof then begin Consume('/'); n := ReadText(arrc).ToLower; if n <> Result.Name then begin un := true; FCurrent := s; end; end else if not FCurrent^.IsWhiteSpace then begin FCurrent := s; obj := ReadObject(Result); if Assigned(obj) then begin Result.Children.Add(obj); obj.Parent := Result; end; end; until eof; end; if not un then Consume('>'); end; except on e: Exception do begin if Assigned(Result) then FreeAndNil(Result); FErrors.Add(TPLHTMLParserError.Create(FPos, 'CRITICAL: Unexpected error: ' + e.Message)); end; end; end; function TPLHTMLParser.ReadText(AChars: array of TPLString): TPLString; begin Result := ''; while not IsEOF and not (FCurrent^ in TPLStringFuncs.NewArray(AChars)) do begin Result += FCurrent^; MovePosForward; end; if IsEOF or not (FCurrent^ in TPLStringFuncs.NewArray(AChars)) then Result := ''; end; procedure TPLHTMLParser.ReadObjectAttribute(var AObject: TPLHTMLBasicObject); var q: TPLChar; attr: TPLHTMLObjectAttribute; r: TPLBool; begin attr.Key := ReadText(['=']); ConsumeWhitespace; Consume('='); ConsumeWhitespace; if FCurrent^ in ['"', ''''] then q := FCurrent^ else begin if FStrict then FErrors.Add(TPLHTMLParserError.Create(FPos, '"%s" attribute value is not strict.'.Format([FCurrent^]))); q := #0; end; if q <> #0 then begin Consume(q); ConsumeWhitespace; attr.Value := ''; repeat attr.Value += ReadText([q]); ConsumeWhitespace; Consume(q); ConsumeWhitespace; r := FCurrent^ <> q; if not r then begin Consume(q); attr.Value += q; end; until r; end else if not FStrict then attr.Value := ReadText(TPLStringFuncs.NewArray(TPLString.WhitespacesArrayString) + TPLStringFuncs.NewArray(['/', '>'])) else exit; AObject.Attributes.Add(attr); end; constructor TPLHTMLParser.Create; begin inherited Create; FErrors := TPLHTMLParserErrors.Create; FStrict := false; CleanUp; end; destructor TPLHTMLParser.Destroy; begin FErrors.Free; inherited Destroy; end; procedure TPLHTMLParser.Parse(const ASource: TPLString; var ARoot: TPLHTMLRootObject ); var obj: TPLHTMLBasicObject; begin CleanUp; if Length(ASource) < 2 then exit; FSource := ASource; FCurrent := @FSource[1]; FEnd := @FSource[Length(FSource)]; FPos := TPLHTMLParserPosition.Create(1, 1); FRoot := ARoot; ConsumeWhitespace; while not IsEOF do begin obj := ReadObject(FRoot); if Assigned(obj) then begin FRoot.Children.Add(obj); obj.Parent := FRoot; end; ConsumeWhitespace; end; end; procedure TPLHTMLParser.CleanUp; begin FErrors.Clear; FSource := ''; FCurrent := nil; FEnd := nil; FPos := TPLHTMLParserPosition.Create(0, 0); end; end.
unit uStartForm; {$mode objfpc}{$H+} interface uses forms, sysutils, classes, controls, iStart, rtti_serializer_uXmlStore, rtti_serializer_uFactory, rtti_broker_iBroker, rtti_idebinder_iBindings, rtti_idebinder_uDesigner; type EMain = class(Exception) end; { TStartForm } TStartForm = class(TComponent, IStartContext, IRBBinderContext) private fSerialFactory: IRBFactory; fDataStore: IRBStore; fDesigner: IRBDesigner; fMainF: TForm; protected // IMainContext function GetDataStore: IRBStore; function GetSerialFactory: IRBFactory; function GetDataQuery: IRBDataQuery; function GetDesigner: IRBDesigner; function GetBinderContext: IRBBinderContext; protected function PrepareHomeDir(const AHomeSubdir: string): string; function OpenDataStore(const AFile: string; ACanCreate: Boolean): Boolean; procedure InitData(const AStorage: string = ''); procedure StartUp; procedure ShutDown; procedure RegisterClasses(const AClasses: array of TClass); procedure Go(const AFormClass: TFormClass; const ACtlClasses: array of TControlClass); public class procedure Run(const AFormClass: TFormClass; const AClasses: array of TClass; const ACtlClasses: array of TControlClass; AStorage: string = ''); property SerialFactory: IRBFactory read GetSerialFactory; property DataStore: IRBStore read GetDataStore; property DataQuery: IRBDataQuery read GetDataQuery; property Designer: IRBDesigner read GetDesigner; end; implementation { TStartForm } function TStartForm.GetDesigner: IRBDesigner; begin Result := fDesigner; end; function TStartForm.GetBinderContext: IRBBinderContext; begin Result := Self; end; function TStartForm.GetDataStore: IRBStore; begin Result := fDataStore; end; function TStartForm.GetSerialFactory: IRBFactory; begin Result := fSerialFactory; end; function TStartForm.GetDataQuery: IRBDataQuery; begin Result := fDataStore as IRBDataQuery; end; function TStartForm.PrepareHomeDir(const AHomeSubdir: string): string; begin {$IFDEF UNIX} Result := GetEnvironmentVariable('HOME') + PathDelim + AHomeSubdir + PathDelim; {$ENDIF UNIX} {$IFDEF WINDOWS} Result := GetEnvironmentVariable('APPDATA') + PathDelim + AHomeSubdir + PathDelim; {$ENDIF WINDOWS} if not DirectoryExists(Result) then begin if not ForceDirectories(Result) then raise EMain('Cannot create directory ' + Result); end; end; function TStartForm.OpenDataStore(const AFile: string; ACanCreate: Boolean): Boolean; begin Result := False; if FileExists(AFile) or ACanCreate then begin fDataStore := TXmlStore.Create(fSerialFactory, AFile); Result := True; end; end; procedure TStartForm.InitData(const AStorage: string = ''); var mStorage: string; begin fSerialFactory := TSerialFactory.Create; mStorage := AStorage; if mStorage = '' then mStorage := PrepareHomeDir('.' + ExtractFileName(ParamStr(0))) + 'data.xml'; if not OpenDataStore(mStorage, True) then raise EMain.Create('Cannot oper or create ' + mStorage); end; procedure TStartForm.StartUp; begin end; procedure TStartForm.ShutDown; begin fDataStore.Flush; end; procedure TStartForm.RegisterClasses(const AClasses: array of TClass); var i: integer; begin for i := 0 to Length(AClasses) - 1 do begin fSerialFactory.RegisterClass(AClasses[i]); end; end; procedure TStartForm.Go(const AFormClass: TFormClass; const ACtlClasses: array of TControlClass); begin RequireDerivedFormResource := True; Application.Initialize; Application.CreateForm(AFormClass, fMainF); fDesigner := TRBDesigner.Create; fDesigner.Bind(fMainF, fDataStore, fSerialFactory, DataQuery, {ACtlClasses}nil); if Supports(fMainF, IStartContextConnectable) then (fMainF as IStartContextConnectable).Connect(self); //Application.ShowMainForm := False; Application.Run; end; class procedure TStartForm.Run(const AFormClass: TFormClass; const AClasses: array of TClass; const ACtlClasses: array of TControlClass; AStorage: string = ''); var m: TStartForm; begin m := TStartForm.Create(nil); try m.StartUp; try m.InitData(AStorage); m.RegisterClasses(AClasses); m.Go(AFormClass, ACtlClasses); finally m.ShutDown; end; finally m.Free; end; end; end.
unit variables; {$mode objfpc}{$H+} interface uses Classes, SysUtils, RData, GData, surface; Type TIntegerFileFormat=(INT2S,INT4S); Rraster_3D = array of Rraster; const PDB : double = 0.0112372; // Pee Dee Belemnite (PDB) standard of 13C : 12C var //Raster filenames c14filename,c13filename,Cs137filename: String; dtmfilename,outfilename,prcfilename, RKCPfilename, ktcfilename, ktilfilename: String; outfilename_temp : String; Working_Dir : string; WATEREROS : RRaster; //water erosion per year (unit: m) TILEROS : RRaster; //tillage erosion per year (unit: m) RKCP : RRaster; // RUSLE R*K*C*P parameters ktc : GRaster; // transport capacity constant kg/m W_Export : RRaster; // export per cell (unit : m) A12_EROS : RRaster; //water active C erosion per year (unit: m * %) S12_EROS : RRaster; P12_EROS : RRaster; A13_EROS : RRaster; //water active C erosion per year (unit: m * %) S13_EROS : RRaster; P13_EROS : RRaster; A14_EROS : RRaster; //water active C erosion per year (unit: m * %) S14_EROS : RRaster; P14_EROS : RRaster; Clay_EROS : RRaster; //water active C erosion per year (unit: m * %) Silt_EROS : RRaster; Sand_EROS : RRaster; Rock_EROS : RRaster; Cs137_EROS : RRaster; // Unit kg/m2 C_STOCK : RRaster; C_STOCK_equili : RRaster; CS137_ACTIVITY : RRaster; PRC : GRaster; DTM,Slope,Aspect,Uparea,LS: Rraster; // note uparea is used for temporary maps after uparea calculation! BD, TFCA, KTIL, PDEPTH : integer; // BD kg/m3 TFCA (0-100) KTIL kg/m Pdepth in cm (!) MC_RKCP, MC_ktc : integer; // # of Monte carlo runs for rkcp and ktc maps Cal_Frac : boolean; // set to "1 or 0", do recursive calculation for fractional contribution of each gridcell to export, CPU/time intensive! McCool_factor : real; // default = 1, you can set this to 0.5 for low contribution of rill erosion,, or 2 for high contribution of rill Write_map : boolean; // set to "1 or 0", default = TRUE, write spatial output if true, set to false for no map output Write_txt : boolean; Write_detail_Exp : boolean; // set to "1 or 0", default = TRUE, write spatial output if true, set to false for no map output Parcel_File_Format : TIntegerFileFormat; // set to "INT2S" or "INT4S", default = INT2S, standard Idrisi smallint format INT2S, set to "INT4S" for INT4S format, ie integer ra : Troutingalgorithm; //type of routing sdra= steepest descent mfra=multiple flow erosion_start_year : integer; erosion_end_year : integer; time_equilibrium : integer; time_step : integer; depth_interval : integer; // unit cm depth : integer; // unit cm tillage_depth : integer; // unit cm layer_num : integer; deltaC13_ini_top : single; // unit per mille deltaC13_ini_bot : single; // unit per mille DeltaC14_ini_top : single; // unit per mille DeltaC14_ini_bot : single; // unit per mille k1 : single; k2 : single; k3 : single; hAS : single; hAP : single; hSP : single; C13_discri : single; C14_discri : single; deltaC13_input_default : single; deltaC14_input_default : single; Cs137_input_default : single; r0 : single; C_input : single; // Mg C ha-1 yr-1 C_input2 : single; // Mg C ha-1 yr-1 r_exp : single; // unit m-1 i_exp : single; // unit m-1 Sand_ini_top : single; // unit % Silt_ini_top : single; // unit % Clay_ini_top : single; // unit % Sand_ini_bot : single; // unit % Silt_ini_bot : single; // unit % Clay_ini_bot : single; // unit % A12, S12, P12: Rraster_3D; A13, S13, P13 : Rraster_3D; A14, S14, P14 : Rraster_3D; SAND, SILT, CLAY, ROCK : Rraster_3D; CS137: Rraster_3D; unstable: Boolean; K0,v0,kfzp,vfzp:single; //ER_ero,ER_depo: single; a_erero,b_erero,b_erdepo: single; Procedure Allocate_Memory; Procedure Release_Memory; implementation Procedure Allocate_Memory; var i: integer; begin // Create procedure to read in maps & allocate memory to global maps // Assign internal & global 2D maps SetDynamicRData(LS); //SetDynamicRData(SLOPE); //SetDynamicRData(ASPECT); SetDynamicRData(RKCP); SetDynamicGData(ktc); SetDynamicRData(W_Export); SetZeroR(W_Export); SetDynamicRData(WATEREROS); SetDynamicRData(TILEROS); SetDynamicRData(A12_EROS); SetDynamicRData(S12_EROS); SetDynamicRData(P12_EROS); SetDynamicRData(A13_EROS); SetDynamicRData(S13_EROS); SetDynamicRData(P13_EROS); SetDynamicRData(A14_EROS); SetDynamicRData(S14_EROS); SetDynamicRData(P14_EROS); SetDynamicRData(Clay_EROS); SetDynamicRData(Silt_EROS); SetDynamicRData(Sand_EROS); SetDynamicRData(Rock_EROS); SetDynamicRData(Cs137_EROS); SetDynamicRData(C_STOCK); SetDynamicRData(C_STOCK_equili); SetDynamicRData(CS137_ACTIVITY); Setlength(A12,layer_num+2); Setlength(S12,layer_num+2); Setlength(P12,layer_num+2); Setlength(A13,layer_num+2); Setlength(S13,layer_num+2); Setlength(P13,layer_num+2); Setlength(A14,layer_num+2); Setlength(S14,layer_num+2); Setlength(P14,layer_num+2); Setlength(CLAY,layer_num+2); Setlength(SILT,layer_num+2); Setlength(SAND,layer_num+2); Setlength(ROCK,layer_num+2); Setlength(CS137,layer_num+2); for i:=0 to layer_num+1 do begin SetDynamicRdata(A12[i]); SetDynamicRdata(S12[i]); SetDynamicRdata(P12[i]); SetDynamicRdata(A13[i]); SetDynamicRdata(S13[i]); SetDynamicRdata(P13[i]); SetDynamicRdata(A14[i]); SetDynamicRdata(S14[i]); SetDynamicRdata(P14[i]); SetDynamicRdata(CLAY[i]); SetDynamicRdata(SILT[i]); SetDynamicRdata(SAND[i]); SetDynamicRdata(ROCK[i]); SetDynamicRdata(CS137[i]); end; end; Procedure Release_Memory; var i: integer; begin // Release memory for input rasters DisposeDynamicRdata(DTM); DisposeDynamicGdata(PRC); // Release internal 2D rasters maps DisposeDynamicRdata(LS); //DisposeDynamicRdata(SLOPE); //DisposeDynamicRdata(ASPECT); DisposeDynamicRdata(RKCP); DisposeDynamicGdata(ktc); DisposeDynamicRdata(W_Export); DisposeDynamicRdata(WATEREROS); DisposeDynamicRdata(TILEROS); DisposeDynamicRdata(A12_EROS); DisposeDynamicRdata(S12_EROS); DisposeDynamicRdata(P12_EROS); DisposeDynamicRdata(A13_EROS); DisposeDynamicRdata(S13_EROS); DisposeDynamicRdata(P13_EROS); DisposeDynamicRdata(A13_EROS); DisposeDynamicRdata(S13_EROS); DisposeDynamicRdata(P13_EROS); DisposeDynamicRdata(Clay_EROS); DisposeDynamicRdata(Silt_EROS); DisposeDynamicRdata(Sand_EROS); DisposeDynamicRdata(Rock_EROS); DisposeDynamicRdata(Cs137_EROS); DisposeDynamicRdata(C_STOCK); DisposeDynamicRdata(C_STOCK_equili); DisposeDynamicRdata(CS137_ACTIVITY); for i:=0 to layer_num+1 do begin DisposeDynamicRdata(A12[i]); DisposeDynamicRdata(S12[i]); DisposeDynamicRdata(P12[i]); DisposeDynamicRdata(A13[i]); DisposeDynamicRdata(S13[i]); DisposeDynamicRdata(P13[i]); DisposeDynamicRdata(A14[i]); DisposeDynamicRdata(S14[i]); DisposeDynamicRdata(P14[i]); DisposeDynamicRdata(CLAY[i]); DisposeDynamicRdata(SILT[i]); DisposeDynamicRdata(SAND[i]); DisposeDynamicRdata(ROCK[i]); DisposeDynamicRdata(CS137[i]); end; ROW:=NIL; COLUMN:=NIL; end; end.
unit UFrmCadSetor; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.DBCtrls, Data.DB, Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.Imaging.pngimage; type TFrmCadSetor = class(TForm) Panel1: TPanel; Panel2: TPanel; Label1: TLabel; DataSource1: TDataSource; Label2: TLabel; DBEdit2: TDBEdit; Label3: TLabel; DBEdit3: TDBEdit; DBNavigator1: TDBNavigator; bbtSair: TBitBtn; bbtIncluir: TBitBtn; bbtEditar: TBitBtn; bbtRemover: TBitBtn; bbtCancelar: TBitBtn; bbtConfirmar: TBitBtn; DBText1: TDBText; Image1: TImage; DBGrid1: TDBGrid; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure TrataBotao; procedure bbtCancelarClick(Sender: TObject); procedure bbtConfirmarClick(Sender: TObject); procedure bbtEditarClick(Sender: TObject); procedure bbtIncluirClick(Sender: TObject); procedure bbtRemoverClick(Sender: TObject); procedure bbtSairClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmCadSetor: TFrmCadSetor; implementation uses UFrmDmEmpresa; {$R *.dfm} procedure TFrmCadSetor.bbtCancelarClick(Sender: TObject); begin DataModule1.tbSetor.Cancel; TrataBotao; end; procedure TFrmCadSetor.bbtConfirmarClick(Sender: TObject); begin DataModule1.tbSetor.Post; TrataBotao; end; procedure TFrmCadSetor.bbtEditarClick(Sender: TObject); begin DataModule1.tbSetor.Edit; TrataBotao; end; procedure TFrmCadSetor.bbtIncluirClick(Sender: TObject); var ProxNum:Integer; begin TrataBotao; DataModule1.tbSetor.Last; ProxNum := DataModule1.tbSetor.FieldByName('SET_SETOR_ID').AsInteger + 1; DataModule1.tbSetor.Append; DataModule1.tbSetor.FieldByName('SET_SETOR_ID').AsInteger := ProxNum; DBEdit2.SetFocus; end; procedure TFrmCadSetor.bbtRemoverClick(Sender: TObject); begin if DataModule1.tbSetor.RecordCount = 0 Then ShowMessage('Tabela Vazia!') else if DataModule1.tbFuncionario.Locate('SET_Setor_ID',DataModule1.TbSetor.FieldByName('SET_Setor_ID').AsInteger,[]) then ShowMessage('Este setor possui funcionários,'+#13+'favor realocá-los antes de deletar.') else if MessageDLG('Tem certeza que deseja remover o setor: '+#13+ DataModule1.TbSetor.FieldByName('Descricao').AsString +' ?',mtConfirmation, [mbYes, mbNo], 0) = mrYes then DataModule1.tbSetor.Delete; end; procedure TFrmCadSetor.bbtSairClick(Sender: TObject); begin FrmCadSetor.Close; end; procedure TFrmCadSetor.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if DataModule1.tbSetor.State in [dsEdit,dsInsert] then if MessageDlg('Existem Dados Pendentes.'+ #13 + 'Deseja salvá-lo?', mtConfirmation, [mbYes,mbNo],0) = mrYes then CanClose := False else begin DataModule1.tbFuncionario.Cancel; TrataBotao; CanClose := True; end; end; procedure TFrmCadSetor.TrataBotao; begin bbtIncluir.Enabled := not bbtIncluir.Enabled; BbtEditar.Enabled := not BbtEditar.Enabled; BbtRemover.Enabled := not BbtRemover.Enabled; BbtCancelar.Enabled := not BbtCancelar.Enabled; BbtConfirmar.Enabled := True; //:= not BbtConfirmar.Enabled; BbtSair.Enabled := not BbtSair.Enabled; end; end.
unit ComandLineHelpers; interface // Gets the application executable full path from command line function GetApplicationFullPath : String; // Gets the full path to the directory containing the application executable function GetApplicationFullDirectoryPath : String; implementation uses SysUtils; function GetApplicationFullPath : String; begin Result := ParamStr(0); end; function GetApplicationFullDirectoryPath : String; begin Result := ExtractFileDir(GetApplicationFullPath); end; end.
unit CrudExampleHorseServer.Controller.Cadastro; interface uses CrudExampleHorseServer.Model.Conexao.DB , Horse.ISAPI; type IControllerCadastro = interface ['{B5BF6E50-40B0-4805-8B29-0E6A08D0E747}'] function DoRequestsCadastro( aReq: THorseRequest; aRes: THorseResponse ): IControllerCadastro; end; TControllerCadastro = class(TInterfacedObject, IControllerCadastro) private { private declarations } FConexaoDB: IModelConexaoDB; procedure ListCadastro(aReq: THorseRequest; aRes: THorseResponse); procedure InsertCadastro(aReq: THorseRequest; aRes: THorseResponse); procedure UpdateCadastro(aReq: THorseRequest; aRes: THorseResponse); procedure DeleteCadastro(aReq: THorseRequest; aRes: THorseResponse); public { public declarations } class function New( const aConexaoDB: IModelConexaoDB ): IControllerCadastro; constructor Create( const aConexaoDB: IModelConexaoDB ); destructor Destroy; override; function DoRequestsCadastro( aReq: THorseRequest; aRes: THorseResponse ): IControllerCadastro; end; implementation uses JOSE.Types.JSON , CrudExampleHorseServer.Model.DAO.Cadastro , Horse.Commons , Web.HTTPApp , System.JSON ; const RestResource = '/user'; constructor TControllerCadastro.Create( const aConexaoDB: IModelConexaoDB ); begin FConexaoDB:=aConexaoDB; end; destructor TControllerCadastro.Destroy; begin inherited; end; function TControllerCadastro.DoRequestsCadastro( aReq: THorseRequest; aRes: THorseResponse ): IControllerCadastro; begin case aReq.MethodType of mtGet : ListCadastro( aReq, aRes ); mtPost : InsertCadastro( aReq, aRes ); mtPut : UpdateCadastro( aReq, aRes ); mtDelete : DeleteCadastro( aReq, aRes ); end end; class function TControllerCadastro.New( const aConexaoDB: IModelConexaoDB ): IControllerCadastro; begin Result := Self.Create( aConexaoDB ); end; procedure TControllerCadastro.ListCadastro(aReq: THorseRequest; aRes: THorseResponse); var lResultArray: TJSONArray; lResultObject: TJSONObject; lCountObjects: integer; begin if aReq.Params.Count=0 then begin lResultArray:=TDAOCadastro.New(FConexaoDB).Find; lCountObjects:=lResultArray.Count; aRes.Send<TJSONArray>( lResultArray ); end else begin lResultObject:=TDAOCadastro.New(FConexaoDB).Find( aReq.Params.Items['id'] ); lCountObjects:=lResultObject.Count; aRes.Send<TJSONObject>( lResultObject ); end; if lCountObjects=0 then aRes.Status(THTTPStatus.NotFound) end; procedure TControllerCadastro.InsertCadastro(aReq: THorseRequest; aRes: THorseResponse); var lResult: TJSONObject; begin lResult:=TDAOCadastro.New(FConexaoDB).Insert( aReq.Body<TJSONObject> ); aRes.Send<TJSONObject>( lResult ); if lResult.Count>0 then aRes.Status(THTTPStatus.Created); end; procedure TControllerCadastro.UpdateCadastro(aReq: THorseRequest; aRes: THorseResponse); var lResult: TJSONObject; lStatus: THTTPStatus; begin lStatus:=THTTPStatus.OK; lResult:=TDAOCadastro.New(FConexaoDB).Find( aReq.Body<TJSONObject>.GetValue('id').Value ); if lResult.Count=0 then lStatus:=THTTPStatus.NotFound else lResult:=TDAOCadastro.New(FConexaoDB).Update( aReq.Body<TJSONObject> ); aRes.Send<TJSONObject>( lResult ); aRes.Status(lStatus); end; procedure TControllerCadastro.DeleteCadastro(aReq: THorseRequest; aRes: THorseResponse); var lResult: TJSONObject; lStatus: THTTPStatus; begin lStatus:=THTTPStatus.OK; lResult:=TDAOCadastro.New(FConexaoDB).Find( aReq.Params.Items['id'] ); if lResult.Count=0 then lStatus:=THTTPStatus.NotFound else lResult:=TDAOCadastro.New(FConexaoDB).Delete( aReq.Params.Items['id'] ); aRes.Send<TJSONObject>( lResult ); aRes.Status(lStatus); end; end.
unit glCheckBox; interface uses {$IFDEF VER230} System.SysUtils, WinAPI.Windows, WinAPI.Messages {$ELSE} Windows, Messages, SysUtils {$ENDIF} , Classes, Controls, Graphics, glCustomObject, PNGImage; type TglCheckBox = class(TglCustomObject) private FOnChange: TNotifyEvent; fViewState: byte; fCheck, fFocus: Boolean; FOnDown, FOnEnter, FOnLeave, FOffDown, FOffEnter, FOffLeave: TPicture; procedure SetChecked(Value: Boolean); protected procedure Change; dynamic; procedure Paint; override; procedure MouseEnter(var Msg: TMessage); message cm_mouseEnter; procedure MouseLeave(var Msg: TMessage); message cm_mouseLeave; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure SetOnDown(Value: TPicture); virtual; procedure SetOnEnter(Value: TPicture); virtual; procedure SetOnLeave(Value: TPicture); virtual; procedure SetOffDown(Value: TPicture); virtual; procedure SetOffEnter(Value: TPicture); virtual; procedure SetOffLeave(Value: TPicture); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property ImageOnDown: TPicture read FOnDown write SetOnDown; property ImageOnEnter: TPicture read FOnEnter write SetOnEnter; property ImageOnLeave: TPicture read FOnLeave write SetOnLeave; property ImageOffDown: TPicture read FOffDown write SetOffDown; property ImageOffEnter: TPicture read FOffEnter write SetOffEnter; property ImageOffLeave: TPicture read FOffLeave write SetOffLeave; property Checked: Boolean read fCheck write SetChecked; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; procedure Register; implementation const vsOnLeave = 0; vsOnEnter = 1; vsOnDown = 2; vsOffLeave = 3; vsOffEnter = 4; vsOffDown = 5; procedure TglCheckBox.Change; begin if Assigned(FOnChange) then FOnChange(Self); if fCheck then fViewState := vsOnLeave else fViewState := vsOffLeave; repaint; end; constructor TglCheckBox.Create(AOwner: TComponent); begin inherited Create(AOwner); FOnLeave := TPicture.Create; FOnEnter := TPicture.Create; FOnDown := TPicture.Create; FOffLeave := TPicture.Create; FOffEnter := TPicture.Create; FOffDown := TPicture.Create; fCheck := false; fViewState := vsOffLeave; end; destructor TglCheckBox.Destroy; begin inherited Destroy; FOnLeave.Free; FOnEnter.Free; FOnDown.Free; FOffLeave.Free; FOffEnter.Free; FOffDown.Free; end; procedure TglCheckBox.Paint; begin case fViewState of 0: Canvas.Draw(0, 0, FOnLeave.Graphic); 1: begin if Assigned(FOnEnter.Graphic) then Canvas.Draw(0, 0, FOnEnter.Graphic) else Canvas.Draw(0, 0, FOnLeave.Graphic); end; 2: begin if Assigned(FOnDown.Graphic) then Canvas.Draw(0, 0, FOnDown.Graphic) else if Assigned(FOnEnter.Graphic) then Canvas.Draw(0, 0, FOnEnter.Graphic) else Canvas.Draw(0, 0, FOnLeave.Graphic); end; 3: Canvas.Draw(0, 0, FOffLeave.Graphic); 4: begin if Assigned(FOffEnter.Graphic) then Canvas.Draw(0, 0, FOffEnter.Graphic) else Canvas.Draw(0, 0, FOffLeave.Graphic); end; 5: begin if Assigned(FOffDown.Graphic) then Canvas.Draw(0, 0, FOffDown.Graphic) else if Assigned(FOffEnter.Graphic) then Canvas.Draw(0, 0, FOffEnter.Graphic) else Canvas.Draw(0, 0, FOffLeave.Graphic); end; end; inherited; end; procedure TglCheckBox.SetChecked(Value: Boolean); begin fCheck := Value; Change; end; procedure TglCheckBox.SetOnLeave(Value: TPicture); begin FOnLeave.Assign(Value); Invalidate; end; procedure TglCheckBox.SetOnEnter(Value: TPicture); begin FOnEnter.Assign(Value); Invalidate; end; procedure TglCheckBox.SetOnDown(Value: TPicture); begin FOnDown.Assign(Value); Invalidate; end; procedure TglCheckBox.SetOffLeave(Value: TPicture); begin FOffLeave.Assign(Value); Invalidate; end; procedure TglCheckBox.SetOffEnter(Value: TPicture); begin FOffEnter.Assign(Value); Invalidate; end; procedure TglCheckBox.SetOffDown(Value: TPicture); begin FOffDown.Assign(Value); Invalidate; end; procedure TglCheckBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if fCheck then fViewState := vsOnDown else fViewState := vsOffDown; repaint; end; procedure TglCheckBox.MouseEnter(var Msg: TMessage); begin inherited; fFocus := true; if fCheck then fViewState := vsOnEnter else fViewState := vsOffEnter; repaint; end; procedure TglCheckBox.MouseLeave(var Msg: TMessage); begin inherited; fFocus := false; if fCheck then fViewState := vsOnLeave else fViewState := vsOffLeave; repaint; end; procedure TglCheckBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if fCheck then begin if fFocus then fViewState := vsOffEnter else fViewState := vsOffLeave; fCheck := false; end else begin if fFocus then fViewState := vsOnEnter else fViewState := vsOnLeave; fCheck := true; end; repaint; end; procedure Register; begin RegisterComponents('Golden Line', [TglCheckBox]); end; end.
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF } { ANY KIND, either express or implied. See the License for the specific language governing rights } { and limitations under the License. } { } { The Original Code is JclDebugIdeImpl.pas. } { } { The Initial Developer of the Original Code is documented in the accompanying } { help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. } { } {**************************************************************************************************} { } { Unit owner: Petr Vones } { Last modified: August 28, 2002 } { } {**************************************************************************************************} unit JclDebugIdeImpl; {$I JCL.INC} {$IFDEF DELPHI4} {$DEFINE OldStyleExpert} {$ELSE DELPHI4} {$UNDEF OldStyleExpert} {$ENDIF DELPHI4} // Delphi 4 accepts OldStyleExpert only // Delphi 5 can use both kind of the expert // Delphi 6 can use New expert style only interface uses Windows, Classes, Menus, ActnList, SysUtils, Graphics, Dialogs, Controls, Forms, ToolsAPI, JclOtaUtils; type TJclDebugDataInfo = record ProjectName: string; ExecutableFileName: TFileName; MapFileSize, JclDebugDataSize: Integer; LinkerBugUnit: string; LineNumberErrors: Integer; Success: Boolean; end; TJclDebugExtension = class(TJclOTAExpert) private FBuildAllMenuItem: TMenuItem; FBuildAllAction: TAction; FBuildMenuItem: TMenuItem; FBuildAction: TAction; FBuildError: Boolean; {$IFNDEF OldStyleExpert} FCurrentProject: IOTAProject; {$ENDIF OldStyleExpert} FInsertDataItem: TMenuItem; FInsertDataAction: TAction; FResultInfo: array of TJclDebugDataInfo; {$IFNDEF DELPHI5_UP} FSaveAllAction: TAction; {$ENDIF DELPHI5_UP} {$IFNDEF OldStyleExpert} FSaveBuildProject: TAction; FSaveBuildProjectExecute: TNotifyEvent; FSaveBuildAllProjects: TAction; FSaveBuildAllProjectsExecute: TNotifyEvent; {$ENDIF OldStyleExpert} FStoreResults: Boolean; {$IFNDEF OldStyleExpert} FNotifierIndex: Integer; FOptionsModifiedState: Boolean; FSaveMapFile: Integer; {$ENDIF OldStyleExpert} Services: IOTAServices; procedure BeginStoreResults; {$IFNDEF OldStyleExpert} procedure BuildAllProjects(Sender: TObject); // (New) Build All Projects command hook procedure BuildProject(Sender: TObject); // (New) Build Project command hook {$ENDIF OldStyleExpert} {$IFDEF OldStyleExpert} procedure BuildActionExecute(Sender: TObject); // (Old) Build JCL Debug command procedure BuildActionUpdate(Sender: TObject); procedure BuildAllActionExecute(Sender: TObject); // (Old) Build JCL Debug All Projects command procedure BuildAllActionUpdate(Sender: TObject); {$ENDIF OldStyleExpert} procedure DisplayResults; procedure EndStoreResults; {$IFNDEF OldStyleExpert} procedure ExpertActive(Active: Boolean); procedure HookBuildActions(Enable: Boolean); procedure InsertDataExecute(Sender: TObject); procedure LoadExpertValues; procedure SaveExpertValues; {$ENDIF OldStyleExpert} {$IFDEF OldStyleExpert} function InsertDataToProject(const ActiveProject: IOTAProject): Boolean; {$ENDIF OldStyleExpert} public constructor Create; destructor Destroy; override; procedure AfterCompile(Succeeded: Boolean); procedure BeforeCompile(const Project: IOTAProject; var Cancel: Boolean); procedure RegisterCommand; procedure UnregisterCommand; end; {$IFNDEF OldStyleExpert} TIdeNotifier = class(TNotifierObject, IOTANotifier, IOTAIDENotifier, IOTAIDENotifier50) private FDebugExtension: TJclDebugExtension; protected procedure AfterCompile(Succeeded: Boolean); overload; procedure AfterCompile(Succeeded: Boolean; IsCodeInsight: Boolean); overload; procedure BeforeCompile(const Project: IOTAProject; var Cancel: Boolean); overload; procedure BeforeCompile(const Project: IOTAProject; IsCodeInsight: Boolean; var Cancel: Boolean); overload; procedure FileNotification(NotifyCode: TOTAFileNotification; const FileName: string; var Cancel: Boolean); public constructor Create(ADebugExtension: TJclDebugExtension); end; {$ENDIF OldStyleExpert} procedure Register; implementation {$R JclDebugIdeIcon.res} uses IniFiles, ImageHlp, JclBase, JclDebug, JclSysUtils, JclDebugIdeResult; procedure Register; begin RegisterPackageWizard(TJclDebugExtension.Create); end; //-------------------------------------------------------------------------------------------------- resourcestring {$IFDEF OldStyleExpert} RsActionCaption = 'Build JCL Debug %s'; RsBuildAllCaption = 'Build JCL Debug All Projects'; RsProjectNone = '[none]'; {$ELSE OldStyleExpert} RsCantInsertToInstalledPackage = 'JCL Debug IDE Expert: Can not insert debug information to installed package' + #13#10'%s'#13#10#10'Would you like to disable inserting JCL Debug data ?'; RsInsertDataCaption = 'Insert JCL Debug data'; {$ENDIF OldStyleExpert} RsExecutableNotFound = 'Executable file (*.exe or *.dll) not found.' + 'JCL debug data can''t be added to the project.'; const JclDebugEnabledName = 'JclDebugEnabled'; //================================================================================================== // TJclDebugExtension //================================================================================================== procedure TJclDebugExtension.AfterCompile(Succeeded: Boolean); {$IFDEF OldStyleExpert} begin end; {$ELSE OldStyleExpert} var ProjectFileName, MapFileName, ExecutableFileName: string; OutputDirectory, LinkerBugUnit: string; ProjOptions: IOTAProjectOptions; ExecutableNotFound, Succ: Boolean; MapFileSize, JclDebugDataSize, LineNumberErrors, C: Integer; procedure DeleteMapAndDrcFile; begin if FSaveMapFile <> MapFileOptionDetailed then begin // delete MAP and DRC file DeleteFile(MapFileName); DeleteFile(ChangeFileExt(ProjectFileName, DrcFileExtension)); end; end; begin if FInsertDataAction.Checked and Assigned(FCurrentProject) then begin ProjOptions := FCurrentProject.ProjectOptions; { if FSaveMapFile <> MapFileOptionDetailed then begin ProjOptions.Values[MapFileOptionName] := FSaveMapFile; ProjOptions.ModifiedState := FOptionsModifiedState; end;} { TODO -oPV : Temporarily removed due Delphi 6 IDE problems } ProjectFileName := FCurrentProject.FileName; OutputDirectory := GetOutputDirectory(FCurrentProject); MapFileName := GetMapFileName(FCurrentProject); if Succeeded then begin ExecutableNotFound := False; LinkerBugUnit := ''; LineNumberErrors := 0; Succ := FileExists(MapFileName); if Succ then begin Screen.Cursor := crHourGlass; try if FindExecutableName(MapFileName, OutputDirectory, ExecutableFileName) then begin Succ := InsertDebugDataIntoExecutableFile(ExecutableFileName, MapFileName, LinkerBugUnit, MapFileSize, JclDebugDataSize, LineNumberErrors); end else ExecutableNotFound := True; finally Screen.Cursor := crDefault; end; end; DeleteMapAndDrcFile; if FStoreResults then begin C := Length(FResultInfo); SetLength(FResultInfo, C + 1); FResultInfo[C].ProjectName := ExtractFileName(ProjectFileName); FResultInfo[C].ExecutableFileName := ExecutableFileName; FResultInfo[C].MapFileSize := MapFileSize; FResultInfo[C].JclDebugDataSize := JclDebugDataSize; FResultInfo[C].LinkerBugUnit := LinkerBugUnit; FResultInfo[C].LineNumberErrors := LineNumberErrors; FResultInfo[C].Success := Succ; end; if ExecutableNotFound then MessageDlg(Format(RsExecutableNotFound, [ProjectFileName]), mtError, [mbOk], 0); end else begin FBuildError := True; DeleteMapAndDrcFile; end; Pointer(FCurrentProject) := nil; end; end; {$ENDIF OldStyleExpert} //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.BeforeCompile(const Project: IOTAProject; var Cancel: Boolean); {$IFDEF OldStyleExpert} begin end; {$ELSE OldStyleExpert} var ProjOptions: IOTAProjectOptions; begin if FInsertDataAction.Checked then begin if IsInstalledPackage(Project) then begin if MessageDlg(Format(RsCantInsertToInstalledPackage, [Project.FileName]), mtError, [mbYes, mbNo], 0) = mrYes then ExpertActive(False); Cancel := True; end else begin FCurrentProject := Project; ProjOptions := Project.ProjectOptions; Assert(Assigned(ProjOptions), 'IOTAProjectOptions not available'); FOptionsModifiedState := ProjOptions.ModifiedState; FSaveMapFile := ProjOptions.Values[MapFileOptionName]; if FSaveMapFile <> MapFileOptionDetailed then ProjOptions.Values[MapFileOptionName] := MapFileOptionDetailed; end; end; end; {$ENDIF OldStyleExpert} //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.BeginStoreResults; begin FBuildError := False; FStoreResults := True; FResultInfo := nil; end; //-------------------------------------------------------------------------------------------------- {$IFDEF OldStyleExpert} procedure TJclDebugExtension.BuildActionExecute(Sender: TObject); begin BeginStoreResults; try if InsertDataToProject(ActiveProject) then DisplayResults; finally EndStoreResults; end; end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.BuildActionUpdate(Sender: TObject); var TempActiveProject: IOTAProject; ProjectName: string; begin TempActiveProject := ActiveProject; {$IFDEF DELPHI5_UP} FBuildAction.Enabled := Assigned(TempActiveProject); {$ELSE DELPHI5_UP} FBuildAction.Enabled := Assigned(TempActiveProject) and not FSaveAllAction.Enabled; {$ENDIF DELPHI5_UP} if Assigned(ActiveProject) then ProjectName := ExtractFileName(TempActiveProject.FileName) else ProjectName := RsProjectNone; FBuildAction.Caption := Format(RsActionCaption, [ProjectName]); end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.BuildAllActionExecute(Sender: TObject); var I: Integer; TempActiveProject: IOTAProject; TempProjectGroup: IOTAProjectGroup; Error: Boolean; begin TempProjectGroup := ProjectGroup; if not Assigned(TempProjectGroup) then Exit; Error := False; BeginStoreResults; try for I := 0 to TempProjectGroup.ProjectCount - 1 do begin TempActiveProject := TempProjectGroup.Projects[I]; TempProjectGroup.ActiveProject := TempActiveProject; Error := not InsertDataToProject(TempActiveProject); if Error then Break; end; if not Error then DisplayResults; finally EndStoreResults; end; end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.BuildAllActionUpdate(Sender: TObject); begin {$IFDEF DELPHI5_UP} FBuildAllAction.Enabled := ProjectGroup <> nil; {$ELSE DELPHI5_UP} FBuildAllAction.Enabled := (ProjectGroup <> nil) and not FSaveAllAction.Enabled; {$ENDIF DELPHI5_UP} end; {$ENDIF OldStyleExpert} //-------------------------------------------------------------------------------------------------- {$IFNDEF OldStyleExpert} procedure TJclDebugExtension.BuildAllProjects(Sender: TObject); begin BeginStoreResults; try FSaveBuildAllProjectsExecute(Sender); DisplayResults; finally EndStoreResults; end; end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.BuildProject(Sender: TObject); begin BeginStoreResults; try FSaveBuildProjectExecute(Sender); DisplayResults; finally EndStoreResults; end; end; {$ENDIF OldStyleExpert} //-------------------------------------------------------------------------------------------------- constructor TJclDebugExtension.Create; begin inherited Create; Services := BorlandIDEServices as IOTAServices; Assert(Assigned(Services), 'IOTAServices not available'); {$IFNDEF OldStyleExpert} FNotifierIndex := Services.AddNotifier(TIdeNotifier.Create(Self)); {$ENDIF OldStyleExpert} RegisterCommand; {$IFNDEF OldStyleExpert} LoadExpertValues; {$ENDIF OldStyleExpert} end; //-------------------------------------------------------------------------------------------------- destructor TJclDebugExtension.Destroy; begin {$IFNDEF OldStyleExpert} if FNotifierIndex <> -1 then Services.RemoveNotifier(FNotifierIndex); SaveExpertValues; {$ENDIF OldStyleExpert} UnregisterCommand; inherited; end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.DisplayResults; var I: Integer; begin if FBuildError or (Length(FResultInfo) = 0) then Exit; with TJclDebugResultForm.Create(Application) do try for I := 0 to Length(FResultInfo) - 1 do with ResultListView.Items.Add, FResultInfo[I] do begin Caption := ProjectName; if Success then begin SubItems.Add(IntToStr(MapFileSize)); SubItems.Add(IntToStr(JclDebugDataSize)); SubItems.Add(Format('%3.1f', [JclDebugDataSize * 100 / MapFileSize])); SubItems.Add(ExecutableFileName); SubItems.Add(LinkerBugUnit); if LineNumberErrors > 0 then SubItems.Add(IntToStr(LineNumberErrors)) else SubItems.Add(''); ImageIndex := 0; end else begin SubItems.Add(''); SubItems.Add(''); SubItems.Add(''); SubItems.Add(ExecutableFileName); SubItems.Add(LinkerBugUnit); SubItems.Add(''); ImageIndex := 1; end; end; ShowModal; finally Free; end; end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.EndStoreResults; begin FStoreResults := False; FResultInfo := nil; end; //-------------------------------------------------------------------------------------------------- {$IFNDEF OldStyleExpert} procedure TJclDebugExtension.ExpertActive(Active: Boolean); begin FInsertDataAction.Checked := Active; HookBuildActions(Active); end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.HookBuildActions(Enable: Boolean); begin if Enable then begin if Assigned(FSaveBuildProject) then FSaveBuildProject.OnExecute := BuildProject; if Assigned(FSaveBuildAllProjects) then FSaveBuildAllProjects.OnExecute := BuildAllProjects; end else begin if Assigned(FSaveBuildProject) then FSaveBuildProject.OnExecute := FSaveBuildProjectExecute; if Assigned(FSaveBuildAllProjects) then FSaveBuildAllProjects.OnExecute := FSaveBuildAllProjectsExecute; end; end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.InsertDataExecute(Sender: TObject); begin ExpertActive(not FInsertDataAction.Checked); SaveExpertValues; end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.LoadExpertValues; begin ExpertActive(JediIniFile.ReadBool(ClassName, JclDebugEnabledName, False)); end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.SaveExpertValues; begin JediIniFile.WriteBool(ClassName, JclDebugEnabledName, FInsertDataAction.Checked); end; {$ENDIF OldStyleExpert} //-------------------------------------------------------------------------------------------------- {$IFDEF OldStyleExpert} function TJclDebugExtension.InsertDataToProject(const ActiveProject: IOTAProject): Boolean; var BuildOk, Succ: Boolean; ProjOptions: IOTAProjectOptions; SaveMapFile: Variant; ProjectFileName, MapFileName, ExecutableFileName: string; OutputDirectory, LinkerBugUnit: string; MapFileSize, JclDebugDataSize, LineNumberErrors, C: Integer; ExecutableNotFound: Boolean; {$IFDEF DELPHI5_UP} OptionsModifiedState: Boolean; {$ENDIF DELPHI5_UP} begin Assert(Assigned(ActiveProject)); ProjectFileName := ActiveProject.FileName; ProjOptions := ActiveProject.ProjectOptions; // read output directory OutputDirectory := GetOutputDirectory(ActiveProject); MapFileName := GetMapFileName(ActiveProject); {$IFDEF DELPHI5_UP} OptionsModifiedState := ProjOptions.ModifiedState; {$ENDIF DELPHI5_UP} SaveMapFile := ProjOptions.Values[MapFileOptionName]; ProjOptions.Values[MapFileOptionName] := MapFileOptionDetailed; BuildOk := ActiveProject.ProjectBuilder.BuildProject(cmOTABuild, False); ProjOptions.Values[MapFileOptionName] := SaveMapFile; {$IFDEF DELPHI5_UP} ProjOptions.ModifiedState := OptionsModifiedState; {$ENDIF DELPHI5_UP} ExecutableNotFound := False; LinkerBugUnit := ''; LineNumberErrors := 0; if BuildOk then begin Succ := FileExists(MapFileName); if Succ then begin if FindExecutableName(MapFileName, OutputDirectory, ExecutableFileName) then begin Succ := InsertDebugDataIntoExecutableFile(ExecutableFileName, MapFileName, LinkerBugUnit, MapFileSize, JclDebugDataSize, LineNumberErrors); end else begin ExecutableNotFound := True; Succ := False; end; end; end else Succ := False; if SaveMapFile <> MapFileOptionDetailed then begin DeleteFile(MapFileName); DeleteFile(ChangeFileExt(ProjectFileName, DrcFileExtension)); end; Result := BuildOk and not ExecutableNotFound; C := Length(FResultInfo); SetLength(FResultInfo, C + 1); FResultInfo[C].ProjectName := ExtractFileName(ProjectFileName); FResultInfo[C].ExecutableFileName := ExecutableFileName; FResultInfo[C].MapFileSize := MapFileSize; FResultInfo[C].JclDebugDataSize := JclDebugDataSize; FResultInfo[C].LinkerBugUnit := LinkerBugUnit; FResultInfo[C].LineNumberErrors := LineNumberErrors; FResultInfo[C].Success := Succ; if ExecutableNotFound then MessageDlg(Format(RsExecutableNotFound, [ProjectFileName]), mtError, [mbOk], 0); end; {$ENDIF OldStyleExpert} //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.RegisterCommand; var IDEMainMenu: TMainMenu; IDEProjectItem: TMenuItem; IDEActionList: TActionList; I: Integer; ImageBmp: TBitmap; begin IDEActionList := TActionList((BorlandIDEServices as INTAServices).ActionList); IDEMainMenu := (BorlandIDEServices as INTAServices).MainMenu; ImageBmp := TBitmap.Create; try {$IFDEF OldStyleExpert} ImageBmp.LoadFromResourceName(FindResourceHInstance(HInstance), 'JCLDEBUG'); FBuildAction := TAction.Create(nil); FBuildAction.Caption := Format(RsActionCaption, [RsProjectNone]); FBuildAction.ImageIndex := (BorlandIDEServices as INTAServices).AddMasked(ImageBmp, clPurple); FBuildAction.Visible := True; FBuildAction.OnExecute := BuildActionExecute; FBuildAction.OnUpdate := BuildActionUpdate; FBuildAction.ActionList := IDEActionList; FBuildMenuItem := TMenuItem.Create(nil); FBuildMenuItem.Action := FBuildAction; FBuildAllAction := TAction.Create(nil); FBuildAllAction.Caption := RsBuildAllCaption; FBuildAllAction.ImageIndex := (BorlandIDEServices as INTAServices).AddMasked(ImageBmp, clPurple); FBuildAllAction.Visible := True; FBuildAllAction.OnExecute := BuildAllActionExecute; FBuildAllAction.OnUpdate := BuildAllActionUpdate; FBuildAllAction.ActionList := IDEActionList; FBuildAllMenuItem := TMenuItem.Create(nil); FBuildAllMenuItem.Action := FBuildAllAction; {$ELSE OldStyleExpert} FInsertDataAction := TAction.Create(nil); FInsertDataAction.Caption := RsInsertDataCaption; FInsertDataAction.Visible := True; FInsertDataAction.OnExecute := InsertDataExecute; FInsertDataAction.ActionList := IDEActionList; FInsertDataItem := TMenuItem.Create(nil); FInsertDataItem.Action := FInsertDataAction; {$ENDIF OldStyleExpert} finally ImageBmp.Free; end; IDEProjectItem := nil; with IDEMainMenu do for I := 0 to Items.Count - 1 do if Items[I].Name = 'ProjectMenu' then begin IDEProjectItem := Items[I]; Break; end; Assert(IDEProjectItem <> nil); {$IFDEF OldStyleExpert} with IDEProjectItem do for I := 0 to Count - 1 do if Items[I].Name = 'ProjectBuildItem' then begin IDEProjectItem.Insert(I + 1, FBuildMenuItem); System.Break; end; Assert(FBuildMenuItem.Parent <> nil); with IDEProjectItem do for I := 0 to Count - 1 do if Items[I].Name = 'ProjectBuildAllItem' then begin IDEProjectItem.Insert(I + 1, FBuildAllMenuItem); System.Break; end; Assert(FBuildMenuItem.Parent <> nil); {$IFNDEF DELPHI5_UP} FSaveAllAction := nil; with IDEActionList do for I := 0 to ActionCount - 1 do if Actions[I].Name = 'FileSaveAllCommand' then begin FSaveAllAction := TAction(Actions[I]); Break; end; Assert(FSaveAllAction <> nil); {$ENDIF DELPHI5_UP} {$ELSE OldStyleExpert} with IDEProjectItem do for I := 0 to Count - 1 do if Items[I].Name = 'ProjectOptionsItem' then begin IDEProjectItem.Insert(I + 1, FInsertDataItem); System.Break; end; Assert(FInsertDataItem.Parent <> nil); FSaveBuildProject := nil; with IDEActionList do for I := 0 to ActionCount - 1 do if Actions[I].Name = 'ProjectBuildCommand' then begin FSaveBuildProject := TAction(Actions[I]); FSaveBuildProjectExecute := Actions[I].OnExecute; Break; end; Assert(Assigned(FSaveBuildProject), 'Build action not found'); FSaveBuildAllProjects := nil; with IDEActionList do for I := 0 to ActionCount - 1 do if Actions[I].Name = 'ProjectBuildAllCommand' then begin FSaveBuildAllProjects := TAction(Actions[I]); FSaveBuildAllProjectsExecute := Actions[I].OnExecute; Break; end; Assert(Assigned(FSaveBuildAllProjects), 'Build All action not found'); {$ENDIF OldStyleExpert} end; //-------------------------------------------------------------------------------------------------- procedure TJclDebugExtension.UnregisterCommand; begin {$IFNDEF OldStyleExpert} HookBuildActions(False); {$ENDIF OldStyleExpert} FreeAndNil(FBuildMenuItem); FreeAndNil(FBuildAction); FreeAndNil(FBuildAllMenuItem); FreeAndNil(FBuildAllAction); FreeAndNil(FInsertDataItem); FreeAndNil(FInsertDataAction); end; //================================================================================================== // TIdeNotifier //================================================================================================== {$IFNDEF OldStyleExpert} procedure TIdeNotifier.AfterCompile(Succeeded: Boolean); begin end; //-------------------------------------------------------------------------------------------------- procedure TIdeNotifier.AfterCompile(Succeeded, IsCodeInsight: Boolean); begin if not IsCodeInsight then FDebugExtension.AfterCompile(Succeeded); end; //-------------------------------------------------------------------------------------------------- procedure TIdeNotifier.BeforeCompile(const Project: IOTAProject; IsCodeInsight: Boolean; var Cancel: Boolean); begin if not IsCodeInsight then FDebugExtension.BeforeCompile(Project, Cancel); end; //-------------------------------------------------------------------------------------------------- procedure TIdeNotifier.BeforeCompile(const Project: IOTAProject; var Cancel: Boolean); begin end; //-------------------------------------------------------------------------------------------------- constructor TIdeNotifier.Create(ADebugExtension: TJclDebugExtension); begin inherited Create; FDebugExtension := ADebugExtension; end; //-------------------------------------------------------------------------------------------------- procedure TIdeNotifier.FileNotification(NotifyCode: TOTAFileNotification; const FileName: string; var Cancel: Boolean); begin end; {$ENDIF OldStyleExpert} //-------------------------------------------------------------------------------------------------- end.
unit UUI; interface uses UTipe,math,sysutils; procedure writeError(asal : string; pesan : string); {Mengoutput pesan error} {I.S. : Terdefinisi pesan error dan asal pesan} {F.s. : Tercetak di layar pesan error} procedure writeLog(asal : string; pesan : string); {Mengoutput log} {I.S. : Terdefinisi pesan dan asal pesan} {F.S. : Terdetak di layar logging} procedure writeText(pesan:string); {Mengoutput teks} {I.S. : Terdefinisi pesan} {F.S. : Tercetak pesan} procedure writelnText(pesan:string); {Mengoutput teks} {I.S. : Terdefinisi pesan} {F.S. : Tercetak pesan diikuti new line} procedure readText(var pesan:string); {Membaca teks} {I.S. : diminta input} {F.S. : input ditaruh di pesan} procedure prompt(var Diketik:string; isSimulasiAktif:boolean); {I.S. : isSimulasiAktif terdefinisi} {F.S. : variabel userInput yang menyimpan masukan command dari pengguna terisi} procedure tanya(prompt:string;var jawaban:string); {I.S. : terdefinisi prompt dan variabel jawaban} {F.S. : Mengembalikan hasil jawaban dari user} procedure commandPredictor(input:string;Daftar:DaftarPerintah); {I.S. : Terdefinisi perintah-perintah yang mungkin} {F.S. : Dicetak ke layar command yang paling mirip} procedure formatUserInput(var Diketik:string); {I.S. : terdefinisi input Diketik} {F.S. : Mengubah menjadi format ProperCase} function bacaInput(Input:string):UserInput; {memecah Input ke perintah, opsi1,opsi2,dst} procedure writeTabel(Input:tabel;Ukuran:UkuranTabel;Judul:string); {I.S. : Terdefinisi tabel, ukuran, dan judulnya} {F.S. : Tercetak tabel sesuai spesifikasi} implementation procedure writeTabel(Input:tabel;Ukuran:UkuranTabel;Judul:string); {I.S. : Terdefinisi tabel, ukuran, dan judulnya} {F.S. : Tercetak tabel sesuai spesifikasi} {Kamus lokal} var LokasiJudul:integer; TotalLebar:integer; i,j:integer; {Algoritma - writeTabel} begin {Cari total lebar} TotalLebar:=0; for i:= 1 to Ukuran.Kolom do begin TotalLebar:=TotalLebar + Ukuran.Ukuran[i]; end; {Cari lokasi judul tabel} LokasiJudul := ceil((TotalLebar/2)-(length(Judul)/2)); {Cetak judul tabel} for i:=1 to LokasiJudul do begin write('-'); end; write(Judul); for i:=1 to LokasiJudul do begin write('-'); end; writeln(); {Cetak tabel} for i:=1 to Input.NBar do begin for j:=1 to Input.NKol do begin write(Format('%-'+IntToStr(Ukuran.Ukuran[j])+'s',[Input.Isi[i][j]])); end; writeln(); end; writeln(); end; procedure formatUserInput(var Diketik:string); {I.S. : terdefinisi input Diketik} {F.S. : Mengubah menjadi format ProperCase} var n: integer; begin if (length(Diketik) > 0) then begin Diketik[1] := UpCase(Diketik[1]); n := 2; while (n <= length(Diketik)) do begin Diketik[n] := LowerCase(Diketik[n]); if (Diketik[n] = ' ') then begin Diketik[n+1] := UpCase(Diketik[n+1]); n := n + 2; end else begin n := n + 1; end; end; end; end; function bacaInput(Input:string):UserInput; {memecah Input ke perintah, opsi1, dan opsi2} {Kamus lokal} var i: integer; Indeks: integer; Sementara: string; Hasil:UserInput; Separator:char; {Algoritma} begin Sementara:= ''; i:=1; Indeks:=1; Hasil.Perintah := ''; Hasil.Neff:=0; Separator:=' '; {Looping semua input} while (i<=length(Input)) do begin {Jika separator, data biasa, atau habis} if ((Input[i]='"')and(Separator=' '))then begin Separator:='"'; end else if ((Input[i]=Separator) or (i=length(Input))) then begin {Jika habis langsung tambahkan input terakhir} if(i=length(Input))then begin {tambahkan kecuali jika "} if (Separator<>'"')then begin Sementara := Sementara + Input[i]; end; end; {Masukkan ke tempat yang benar} if (Indeks=1)then begin Hasil.Perintah:=Sementara; end else begin Hasil.Neff:=Hasil.Neff+1; Hasil.Opsi[Hasil.Neff]:=Sementara; end; Indeks:=Indeks+1; Sementara:=''; {Skip satu jika separator menggunakan "} if (Separator='"')then begin Separator:=' '; i:=i+1; end; end else begin Sementara:=Sementara + Input[i]; end; i:=i+1; end; bacaInput:=Hasil; end; procedure commandPredictor(input:string;Daftar:DaftarPerintah); {I.S. : Terdefinisi perintah-perintah yang mungkin} {F.S. : Dicetak ke layar command yang paling mirip} {KAMUS LOKAL} const MINCOCOK=0.49; var Kecocokan : real; i,j:integer; Total:integer; Sama:integer; MaxCocok:real; IndeksCocok:array[1..NMAX]of integer; Neff:integer; begin {search} MaxCocok:=MINCOCOK; Neff:=1; for i:=1 to Daftar.Neff do begin sama:=0; total:=Length(input); for j:=1 to total do begin {Jika panjang input lebih dari perintah, dianggap ketidaksesuain} if(j<=Length(Daftar.Isi[i]))then begin {Jika huruf sama, tambah kesesuaian} if(Daftar.Isi[i][j]=input[j])then begin sama:=sama+1; end; end; end; {Cari persentase kesesuaian} Kecocokan:=sama/total; if(Kecocokan>MaxCocok)then begin MaxCocok:=Kecocokan; IndeksCocok[Neff]:=i; end; end; {Output yang cocok} if((MaxCocok-MINCOCOK)>0.0001)then begin writelnText('Mungkin yang dimaksud :'); for i:=1 to Neff do begin writelnText(Daftar.Isi[IndeksCocok[i]]); end; end; end; procedure tanya(prompt:string;var jawaban:string); {I.S. : terdefinisi prompt dan variabel jawaban} {F.S. : Mengembalikan hasil jawaban dari user} begin write(prompt,' : '); readln(jawaban); end; procedure prompt(var Diketik:string; isSimulasiAktif:boolean); {I.S. : isSimulasiAktif terdefinisi} {F.S. : variabel userInput yang menyimpan masukan command dari pengguna terisi} begin if (isSimulasiAktif = false) then begin write('> '); readln(Diketik); end else begin write('>> '); readln(Diketik); end; end; procedure writeError(asal : string; pesan : string); {Mengoutput pesan error} {I.S. : Terdefinisi pesan error dan asal pesan} {F.s. : Tercetak di layar pesan error} {Algoritma - writeError} begin write('ERROR : '); write(asal); write(' -> '); writeln(pesan); end; procedure writeLog(asal : string; pesan : string); {Mengoutput log} {I.S. : Terdefinisi pesan dan asal pesan} {F.S. : Terdetak di layar logging} {Algoritma - writeLog} begin write('LOG : '); write(asal); write(' -> '); writeln(pesan); end; procedure writeText(pesan:string); {Mengoutput teks} {I.S. : Terdefinisi pesan} {F.S. : Tercetak pesan} {Algoritma - writeText} begin write(pesan); end; procedure writelnText(pesan:string); {Mengoutput teks} {I.S. : Terdefinisi pesan} {F.S. : Tercetak pesan diikuti new line} {Algoritma - writelnText} begin writeln(pesan); end; procedure readText(var pesan:string); {Membaca teks} {I.S. : diminta input} {F.S. : input ditaruh di pesan} {Algoritma - readText} begin readln(pesan); end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.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. } { } {***************************************************************************} unit DPM.Core.Repository.DPMGithub; interface uses Generics.Defaults, VSoft.Awaitable, Spring.Collections, DPM.Core.Types, DPM.Core.Dependency.Version, DPM.Core.Logging, DPM.Core.Options.Search, DPM.Core.Package.Interfaces, DPM.Core.Configuration.Interfaces, DPM.Core.Repository.Interfaces, DPM.Core.Repository.BaseGitHub; type TDPMGithubPackageRepository = class(TGithubBasePackageRepository, IPackageRepository) private protected function DownloadPackage(const cancellationToken : ICancellationToken; const packageIdentity : IPackageIdentity; const localFolder : string; var fileName : string) : Boolean; function GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo; function GetPackageVersions(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const preRelease : boolean) : IList<TPackageVersion>; function GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const versionRange : TVersionRange; const preRelease : Boolean) : IList<IPackageInfo>; function GetPackageLatestVersions(const cancellationToken: ICancellationToken; const ids: IList<IPackageId>; const platform: TDPMPlatform; const compilerVersion: TCompilerVersion; const preRelease: Boolean): IDictionary<string, TPackageVersion>; function List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageIdentity>; overload; //ui function GetPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const configuration : IConfiguration = nil) : IList<IPackageSearchResultItem>; function GetPackageIcon(const cancelToken : ICancellationToken; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon; public constructor Create(const logger : ILogger); override; end; implementation uses System.SysUtils, VSoft.HttpClient, JsonDataObjects; const cGithubDPMRepositorySearch = 'search/repositories?q=topic:dpmpackage+archived:false'; cGithubDPMSpecSearchFormat = '/search/code?q=extension:dspec+repo:%s'; // add repo to search in { TDPMGithubPackageRepository } constructor TDPMGithubPackageRepository.Create(const logger : ILogger); begin inherited Create(logger); end; function TDPMGithubPackageRepository.DownloadPackage(const cancellationToken : ICancellationToken; const packageIdentity : IPackageIdentity; const localFolder : string; var fileName : string) : Boolean; begin result := false; end; function TDPMGithubPackageRepository.GetPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const configuration : IConfiguration) : IList<IPackageSearchResultItem>; begin result := TCollections.CreateList<IPackageSearchResultItem>; end; function TDPMGithubPackageRepository.GetPackageIcon(const cancelToken : ICancellationToken; const packageId, packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon; begin result := nil; end; function TDPMGithubPackageRepository.GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo; begin result := nil; end; function TDPMGithubPackageRepository.GetPackageLatestVersions(const cancellationToken: ICancellationToken; const ids: IList<IPackageId>; const platform: TDPMPlatform; const compilerVersion: TCompilerVersion; const preRelease: Boolean): IDictionary<string, TPackageVersion>; begin result := TCollections.CreateDictionary<string, TPackageVersion>; end; function TDPMGithubPackageRepository.GetPackageVersions(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const preRelease : boolean) : IList<TPackageVersion>; begin result := TCollections.CreateList<TPackageVersion>; end; function TDPMGithubPackageRepository.GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const versionRange : TVersionRange; const preRelease : Boolean) : IList<IPackageInfo>; begin result := TCollections.CreateList<IPackageInfo>; end; function TDPMGithubPackageRepository.List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageIdentity>; var pageSize : string; pageNo : string; resource : string; request : IHttpRequest; response : IHttpResponse; jsonObj : TJsonObject; items : TJsonArray; repoItem : TJsonObject; i, j : integer; repoId : string; specSearchJson : TJSonObject; specItems : TJsonArray; // specItem : TJDOJsonObject; specUrl : string; begin result := TCollections.CreateList<IPackageIdentity>; if options.Take > 0 then pageSize := 'per_page=' + IntToStr(options.Take); if options.Skip > 0 then begin if options.Take = 0 then options.Take := 10; pageNo := 'page=' + IntToStr(options.Skip div options.Take); end; resource := cGithubDPMRepositorySearch; if pageSize <> '' then resource := resource + '&' + pageSize; if pageNo <> '' then resource := resource + '&' + pageNo; request := THttpClientFactory.CreateRequest(resource); request.Accept := cTopicSearchAccept; response := HttpClient.Get(request, cancellationToken); //if we get no response object, that means the cancellation token was cancelled. if response = nil then begin Logger.Error('request cancelled.'); exit; end; if response.ResponseCode <> HTTP_OK then begin Logger.Error('Error getting list of possible repos from github : ' + response.ErrorMessage); end; jsonObj := TJsonObject.ParseFromStream(response.ResponseStream) as TJsonObject; try items := jsonObj.ExtractArray('items'); for i := 0 to items.Count - 1 do begin repoItem := items.O[i]; repoId := repoItem.S['full_name']; resource := 'search/code?q=extension:dspec+repo:' + repoId; Logger.Debug(resource); request := THttpClientFactory.CreateRequest(resource); request.Accept := cGithubv3Accept; response := HttpClient.Get(request, cancellationToken); //if we get no response object, that means the cancellation token was cancelled. if response = nil then begin Logger.Error('request cancelled.'); exit; end; if response.ResponseCode <> HTTP_OK then begin Logger.Error('Error getting list of possible repos from github : ' + response.ErrorMessage); end; specSearchJson := TJsonObject.ParseFromStream(response.ResponseStream) as TJsonObject; try specItems := specSearchJson.ExtractArray('items'); for j := 0 to specItems.Count - 1 do begin specUrl := specItems.O[j].S['html_url']; Logger.Debug(specUrl); end; finally specSearchJson.Free; end; end; finally jsonObj.Free; end; end; end.
unit TB97Ctls; { Toolbar97 Copyright (C) 1998-2004 by Jordan Russell http://www.jrsoftware.org/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. TToolbarButton97 & TEdit97 $jrsoftware: tb97/Source/TB97Ctls.pas,v 1.9 2004/02/23 22:53:00 jr Exp $ } interface {$I TB97Ver.inc} uses Windows, Messages, Classes, Controls, Forms, Menus, Graphics, Buttons, {$IFDEF TB97D4} ImgList, ActnList, {$ENDIF} StdCtrls, ExtCtrls, Types, TB97Vers; const DefaultDropdownArrowWidth = 9; type { TToolbarButton97 } TButtonDisplayMode = (dmBoth, dmGlyphOnly, dmTextOnly); TButtonState97 = (bsUp, bsDisabled, bsDown, bsExclusive, bsMouseIn); TNumGlyphs97 = 1..5; TButtonDropdownEvent = procedure(Sender: TObject; var ShowMenu, RemoveClicks: Boolean) of object; TToolbarButton97 = class(TGraphicControl) private FAllowAllUp: Boolean; FAlignment: TAlignment; FCancel: Boolean; FDefault: Boolean; FDisplayMode: TButtonDisplayMode; FDown: Boolean; FDropdownAlways: Boolean; FDropdownArrow: Boolean; FDropdownArrowWidth: Integer; FDropdownCombo: Boolean; FDropdownMenu: TPopupMenu; FFlat: Boolean; FGlyph: Pointer; FGroupIndex: Integer; FHelpContext: THelpContext; FHighlightWhenDown: Boolean; FLayout: TButtonLayout; FMargin: Integer; FModalResult: TModalResult; FNoBorder: Boolean; FOldDisabledStyle: Boolean; FOpaque: Boolean; FRepeating: Boolean; FRepeatDelay, FRepeatInterval: Integer; FShowBorderWhenInactive: Boolean; FSpacing: Integer; FWordWrap: Boolean; FOnDropdown: TButtonDropdownEvent; FOnMouseEnter, FOnMouseExit: TNotifyEvent; { Internal } FInClick: Boolean; FMouseInControl: Boolean; FMouseIsDown: Boolean; FMenuIsDown: Boolean; FUsesDropdown: Boolean; FRepeatTimer: TTimer; procedure GlyphChanged(Sender: TObject); procedure UpdateExclusive; procedure SetAlignment (Value: TAlignment); procedure SetAllowAllUp (Value: Boolean); function GetCallDormant: Boolean; procedure SetCallDormant (Value: Boolean); procedure SetDown (Value: Boolean); procedure SetDisplayMode (Value: TButtonDisplayMode); procedure SetDropdownAlways (Value: Boolean); procedure SetDropdownArrow (Value: Boolean); procedure SetDropdownArrowWidth (Value: Integer); procedure SetDropdownCombo (Value: Boolean); procedure SetDropdownMenu (Value: TPopupMenu); procedure SetFlat (Value: Boolean); function GetGlyph: TBitmap; procedure SetGlyph (Value: TBitmap); function GetGlyphMask: TBitmap; procedure SetGlyphMask (Value: TBitmap); procedure SetGroupIndex (Value: Integer); procedure SetHighlightWhenDown (Value: Boolean); function GetImageIndex: Integer; procedure SetImageIndex (Value: Integer); function GetImages: TCustomImageList; procedure SetImages (Value: TCustomImageList); procedure SetLayout (Value: TButtonLayout); procedure SetMargin (Value: Integer); procedure SetNoBorder (Value: Boolean); function GetNumGlyphs: TNumGlyphs97; procedure SetNumGlyphs (Value: TNumGlyphs97); procedure SetOldDisabledStyle (Value: Boolean); procedure SetOpaque (Value: Boolean); procedure SetSpacing (Value: Integer); function GetVersion: TToolbar97Version; procedure SetVersion (const Value: TToolbar97Version); procedure SetWordWrap (Value: Boolean); procedure RemoveButtonMouseTimer; procedure Redraw (const Erase: Boolean); function PointInButton (X, Y: Integer): Boolean; procedure ButtonMouseTimerHandler (Sender: TObject); procedure RepeatTimerHandler (Sender: TObject); {$IFDEF TB97D4} function IsCheckedStored: Boolean; function IsHelpContextStored: Boolean; function IsImageIndexStored: Boolean; {$ENDIF} procedure WMLButtonDblClk (var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK; procedure CMEnabledChanged (var Message: TMessage); message CM_ENABLEDCHANGED; procedure CMDialogChar (var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CMDialogKey (var Message: TCMDialogKey); message CM_DIALOGKEY; procedure CMFontChanged (var Message: TMessage); message CM_FONTCHANGED; procedure CMTextChanged (var Message: TMessage); message CM_TEXTCHANGED; procedure CMSysColorChange (var Message: TMessage); message CM_SYSCOLORCHANGE; procedure WMCancelMode (var Message: TWMCancelMode); message WM_CANCELMODE; protected FState: TButtonState97; function GetPalette: HPALETTE; override; procedure Loaded; override; procedure Notification (AComponent: TComponent; Operation: TOperation); override; procedure MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove (Shift: TShiftState; X, Y: Integer); override; procedure MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; {$IFDEF TB97D4} procedure ActionChange (Sender: TObject; CheckDefaults: Boolean); override; function GetActionLinkClass: TControlActionLinkClass; override; procedure AssignTo (Dest: TPersistent); override; {$ENDIF} public property Canvas; property CallDormant: Boolean read GetCallDormant write SetCallDormant; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Click; override; procedure MouseEntered; procedure MouseLeft; published {$IFDEF TB97D4} property Action; {$ENDIF} property Alignment: TAlignment read FAlignment write SetAlignment default taCenter; property AllowAllUp: Boolean read FAllowAllUp write SetAllowAllUp default False; {$IFDEF TB97D4} property Anchors; {$ENDIF} property Cancel: Boolean read FCancel write FCancel default False; property Color default clBtnFace; {$IFDEF TB97D4} property Constraints; {$ENDIF} property GroupIndex: Integer read FGroupIndex write SetGroupIndex default 0; property Default: Boolean read FDefault write FDefault default False; property DisplayMode: TButtonDisplayMode read FDisplayMode write SetDisplayMode default dmBoth; property Down: Boolean read FDown write SetDown {$IFDEF TB97D4} stored IsCheckedStored {$ENDIF} default False; property DragCursor; property DragMode; property DropdownAlways: Boolean read FDropdownAlways write SetDropdownAlways default False; property DropdownArrow: Boolean read FDropdownArrow write SetDropdownArrow default True; property DropdownArrowWidth: Integer read FDropdownArrowWidth write SetDropdownArrowWidth default DefaultDropdownArrowWidth; property DropdownCombo: Boolean read FDropdownCombo write SetDropdownCombo default False; property DropdownMenu: TPopupMenu read FDropdownMenu write SetDropdownMenu; property Caption; property Enabled; property Flat: Boolean read FFlat write SetFlat default True; property Font; property Glyph: TBitmap read GetGlyph write SetGlyph; property GlyphMask: TBitmap read GetGlyphMask write SetGlyphMask; property HelpContext: THelpContext read FHelpContext write FHelpContext {$IFDEF TB97D4} stored IsHelpContextStored {$ENDIF} default 0; property HighlightWhenDown: Boolean read FHighlightWhenDown write SetHighlightWhenDown default True; property ImageIndex: Integer read GetImageIndex write SetImageIndex {$IFDEF TB97D4} stored IsImageIndexStored {$ENDIF} default -1; property Images: TCustomImageList read GetImages write SetImages; property Layout: TButtonLayout read FLayout write SetLayout default blGlyphLeft; property Margin: Integer read FMargin write SetMargin default -1; property ModalResult: TModalResult read FModalResult write FModalResult default 0; property NoBorder: Boolean read FNoBorder write SetNoBorder default False; property NumGlyphs: TNumGlyphs97 read GetNumGlyphs write SetNumGlyphs default 1; property OldDisabledStyle: Boolean read FOldDisabledStyle write SetOldDisabledStyle default False; property Opaque: Boolean read FOpaque write SetOpaque default True; property ParentFont; property ParentColor default False; property ParentShowHint; property Repeating: Boolean read FRepeating write FRepeating default False; property RepeatDelay: Integer read FRepeatDelay write FRepeatDelay default 400; property RepeatInterval: Integer read FRepeatInterval write FRepeatInterval default 100; property ShowBorderWhenInactive: Boolean read FShowBorderWhenInactive write FShowBorderWhenInactive default False; property ShowHint; property Spacing: Integer read FSpacing write SetSpacing default 4; property Version: TToolbar97Version read GetVersion write SetVersion stored False; property Visible; property WordWrap: Boolean read FWordWrap write SetWordWrap default False; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDropdown: TButtonDropdownEvent read FOnDropdown write FOnDropdown; property OnEndDrag; property OnMouseDown; property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter; property OnMouseExit: TNotifyEvent read FOnMouseExit write FOnMouseExit; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; { TToolButtonActionLink } {$IFDEF TB97D4} TToolbarButton97ActionLink = class(TControlActionLink) protected FClient: TToolbarButton97; procedure AssignClient (AClient: TObject); override; function IsCheckedLinked: Boolean; override; function IsHelpContextLinked: Boolean; override; function IsImageIndexLinked: Boolean; override; procedure SetChecked (Value: Boolean); override; procedure SetHelpContext (Value: THelpContext); override; procedure SetImageIndex (Value: Integer); override; end; TToolbarButton97ActionLinkClass = class of TToolbarButton97ActionLink; {$ENDIF} { TEdit97 } TEdit97 = class(TCustomEdit) private MouseInControl: Boolean; function GetVersion: TToolbar97Version; procedure SetVersion (const Value: TToolbar97Version); procedure DrawNCArea (const DrawToDC: Boolean; const ADC: HDC; const Clip: HRGN); procedure NewAdjustHeight; procedure CMEnabledChanged (var Message: TMessage); message CM_ENABLEDCHANGED; procedure CMFontChanged (var Message: TMessage); message CM_FONTCHANGED; procedure CMMouseEnter (var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave (var Message: TMessage); message CM_MOUSELEAVE; procedure WMKillFocus (var Message: TWMKillFocus); message WM_KILLFOCUS; procedure WMNCCalcSize (var Message: TWMNCCalcSize); message WM_NCCALCSIZE; procedure WMNCPaint (var Message: TMessage); message WM_NCPAINT; procedure WMPrint (var Message: TMessage); message WM_PRINT; procedure WMPrintClient (var Message: TMessage); message WM_PRINTCLIENT; procedure WMSetFocus (var Message: TWMSetFocus); message WM_SETFOCUS; protected procedure Loaded; override; public constructor Create (AOwner: TComponent); override; destructor Destroy; override; published property AutoSelect; {$IFDEF TB97D4} property Anchors; {$ENDIF} property Align; {$IFDEF TB97D4} property BiDiMode; {$ENDIF} property CharCase; {$IFDEF TB97D4} property Constraints; {$ENDIF} property DragCursor; {$IFDEF TB97D4} property DragKind; {$ENDIF} property DragMode; property Enabled; property Font; property HideSelection; {$IFDEF TB97D3} property ImeMode; property ImeName; {$ENDIF} property MaxLength; property OEMConvert; {$IFDEF TB97D4} property ParentBiDiMode; {$ENDIF} property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PasswordChar; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Text; property Version: TToolbar97Version read GetVersion write SetVersion stored False; property Visible; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; {$IFDEF TB97D4} property OnEndDock; {$ENDIF} property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; {$IFDEF TB97D4} property OnStartDock; {$ENDIF} property OnStartDrag; end; var ButtonsStayDown: Boolean = True; ButtonMouseInControl: TToolbarButton97 = nil; function ControlIs97Control (AControl: TControl): Boolean; procedure Register97ControlClass (AClass: TClass); procedure Unregister97ControlClass (AClass: TClass); implementation uses SysUtils, Consts, CommCtrl, TB97Cmn; var { See TToolbarButton97.ButtonMouseTimerHandler for info on this } ButtonMouseTimer: TTimer = nil; Control97List: TList = nil; Edit97Count: Integer = 0; const DropdownComboSpace = 2; function ControlIs97Control (AControl: TControl): Boolean; var I: Integer; begin Result := False; if Assigned(AControl) and Assigned(Control97List) then for I := 0 to Control97List.Count-1 do if AControl is TClass(Control97List[I]) then begin Result := True; Break; end; end; procedure Register97ControlClass (AClass: TClass); begin if Control97List = nil then Control97List := TList.Create; Control97List.Add (AClass); end; procedure Unregister97ControlClass (AClass: TClass); begin if Assigned(Control97List) then begin Control97List.Remove (AClass); if Control97List.Count = 0 then begin Control97List.Free; Control97List := nil; end; end; end; { TToolbarButton97ActionLink - internal } {$IFDEF TB97D4} procedure TToolbarButton97ActionLink.AssignClient (AClient: TObject); begin inherited AssignClient(AClient); FClient := AClient as TToolbarButton97; end; function TToolbarButton97ActionLink.IsCheckedLinked: Boolean; begin Result := inherited IsCheckedLinked and (FClient.Down = (Action as TCustomAction).Checked); end; function TToolbarButton97ActionLink.IsHelpContextLinked: Boolean; begin Result := inherited IsHelpContextLinked and (FClient.HelpContext = (Action as TCustomAction).HelpContext); end; function TToolbarButton97ActionLink.IsImageIndexLinked: Boolean; begin Result := inherited IsImageIndexLinked and (FClient.ImageIndex = (Action as TCustomAction).ImageIndex); end; procedure TToolbarButton97ActionLink.SetChecked (Value: Boolean); begin if IsCheckedLinked then FClient.Down := Value; end; procedure TToolbarButton97ActionLink.SetHelpContext (Value: THelpContext); begin if IsHelpContextLinked then FClient.HelpContext := Value; end; procedure TToolbarButton97ActionLink.SetImageIndex (Value: Integer); begin if IsImageIndexLinked then FClient.ImageIndex := Value; end; {$ENDIF} { TToolbarButton97 - internal } type TGlyphList = class(TImageList) private Used: TBits; FCount: Integer; function AllocateIndex: Integer; public constructor CreateSize (AWidth, AHeight: Integer); destructor Destroy; override; function Add (Image, Mask: TBitmap): Integer; function AddMasked (Image: TBitmap; MaskColor: TColor): Integer; procedure Delete (Index: Integer); property Count: Integer read FCount; end; TGlyphCache = class private GlyphLists: TList; public constructor Create; destructor Destroy; override; function GetList(AWidth, AHeight: Integer): TGlyphList; procedure ReturnList(List: TGlyphList); function Empty: Boolean; end; TBoolInt = record B: Boolean; I: Integer; end; TCustomImageListAccess = class(TCustomImageList); TButtonGlyph = class private FOriginal, FOriginalMask: TBitmap; FCallDormant: Boolean; FGlyphList: array[Boolean] of TGlyphList; FImageIndex: Integer; FImageList: TCustomImageList; FImageChangeLink: TChangeLink; FIndexs: array[Boolean, TButtonState97] of Integer; FTransparentColor: TColor; FNumGlyphs: TNumGlyphs97; FOnChange: TNotifyEvent; FOldDisabledStyle: Boolean; procedure GlyphChanged (Sender: TObject); procedure SetGlyph (Value: TBitmap); procedure SetGlyphMask (Value: TBitmap); procedure SetNumGlyphs (Value: TNumGlyphs97); procedure UpdateNumGlyphs; procedure Invalidate; function CreateButtonGlyph (State: TButtonState97): TBoolInt; procedure DrawButtonGlyph (Canvas: TCanvas; const GlyphPos: TPoint; State: TButtonState97); procedure DrawButtonText (Canvas: TCanvas; const Caption: string; TextBounds: TRect; WordWrap: Boolean; Alignment: TAlignment; State: TButtonState97); procedure DrawButtonDropArrow (Canvas: TCanvas; const X, Y, AWidth: Integer; State: TButtonState97); procedure CalcButtonLayout (Canvas: TCanvas; const Client: TRect; const Offset: TPoint; DrawGlyph, DrawCaption: Boolean; const Caption: string; WordWrap: Boolean; Layout: TButtonLayout; Margin, Spacing: Integer; DropArrow: Boolean; DropArrowWidth: Integer; var GlyphPos, ArrowPos: TPoint; var TextBounds: TRect); public constructor Create; destructor Destroy; override; { returns the text rectangle } function Draw (Canvas: TCanvas; const Client: TRect; const Offset: TPoint; DrawGlyph, DrawCaption: Boolean; const Caption: string; WordWrap: Boolean; Alignment: TAlignment; Layout: TButtonLayout; Margin, Spacing: Integer; DropArrow: Boolean; DropArrowWidth: Integer; State: TButtonState97): TRect; property Glyph: TBitmap read FOriginal write SetGlyph; property GlyphMask: TBitmap read FOriginalMask write SetGlyphMask; property NumGlyphs: TNumGlyphs97 read FNumGlyphs write SetNumGlyphs; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; { TGlyphList } constructor TGlyphList.CreateSize(AWidth, AHeight: Integer); begin inherited CreateSize (AWidth, AHeight); Used := TBits.Create; end; destructor TGlyphList.Destroy; begin Used.Free; inherited; end; function TGlyphList.AllocateIndex: Integer; begin Result := Used.OpenBit; if Result >= Used.Size then begin Result := inherited Add(nil, nil); Used.Size := Result + 1; end; Used[Result] := True; end; function TGlyphList.Add (Image, Mask: TBitmap): Integer; begin Result := AllocateIndex; Replace (Result, Image, Mask); Inc (FCount); end; function TGlyphList.AddMasked (Image: TBitmap; MaskColor: TColor): Integer; procedure BugfreeReplaceMasked (Index: Integer; NewImage: TBitmap; MaskColor: TColor); procedure CheckImage (Image: TGraphic); begin if Image = nil then Exit; if (Image.Height < Height) or (Image.Width < Width) then raise EInvalidOperation.Create({$IFNDEF TB97D3}LoadStr{$ENDIF}(SInvalidImageSize)); end; var TempIndex: Integer; Image, Mask: TBitmap; begin if HandleAllocated then begin CheckImage(NewImage); TempIndex := inherited AddMasked(NewImage, MaskColor); if TempIndex <> -1 then try Image := nil; Mask := nil; try Image := TBitmap.Create; Image.Height := Height; Image.Width := Width; Mask := TBitmap.Create; Mask.Monochrome := True; { ^ Prevents the "invisible glyph" problem when used with certain color schemes. (Fixed in Delphi 3.01) } Mask.Height := Height; Mask.Width := Width; ImageList_Draw (Handle, TempIndex, Image.Canvas.Handle, 0, 0, ILD_NORMAL); ImageList_Draw (Handle, TempIndex, Mask.Canvas.Handle, 0, 0, ILD_MASK); if not ImageList_Replace(Handle, Index, Image.Handle, Mask.Handle) then raise EInvalidOperation.Create({$IFNDEF TB97D3}LoadStr{$ENDIF}(SReplaceImage)); finally Image.Free; Mask.Free; end; finally inherited Delete(TempIndex); end else raise EInvalidOperation.Create({$IFNDEF TB97D3}LoadStr{$ENDIF}(SReplaceImage)); end; Change; end; begin Result := AllocateIndex; { This works two very serious bugs in the Delphi 2/BCB and Delphi 3 implementations of the ReplaceMasked method. In the Delphi 2 and BCB versions of the ReplaceMasked method, it incorrectly uses ILD_NORMAL as the last parameter for the second ImageList_Draw call, in effect causing all white colors to be considered transparent also. And in the Delphi 2/3 and BCB versions it doesn't set Monochrome to True on the Mask bitmap, causing the bitmaps to be invisible on certain color schemes. } BugfreeReplaceMasked (Result, Image, MaskColor); Inc (FCount); end; procedure TGlyphList.Delete (Index: Integer); begin if Used[Index] then begin Dec(FCount); Used[Index] := False; end; end; { TGlyphCache } constructor TGlyphCache.Create; begin inherited; GlyphLists := TList.Create; end; destructor TGlyphCache.Destroy; begin GlyphLists.Free; inherited; end; function TGlyphCache.GetList(AWidth, AHeight: Integer): TGlyphList; var I: Integer; begin for I := GlyphLists.Count - 1 downto 0 do begin Result := GlyphLists[I]; with Result do if (AWidth = Width) and (AHeight = Height) then Exit; end; Result := TGlyphList.CreateSize(AWidth, AHeight); GlyphLists.Add(Result); end; procedure TGlyphCache.ReturnList(List: TGlyphList); begin if List = nil then Exit; if List.Count = 0 then begin GlyphLists.Remove(List); List.Free; end; end; function TGlyphCache.Empty: Boolean; begin Result := GlyphLists.Count = 0; end; var GlyphCache: TGlyphCache = nil; Pattern: TBitmap = nil; PatternBtnFace, PatternBtnHighlight: TColor; ButtonCount: Integer = 0; procedure CreateBrushPattern; var X, Y: Integer; begin PatternBtnFace := GetSysColor(COLOR_BTNFACE); PatternBtnHighlight := GetSysColor(COLOR_BTNHIGHLIGHT); Pattern := TBitmap.Create; with Pattern do begin Width := 8; Height := 8; with Canvas do begin Brush.Style := bsSolid; Brush.Color := clBtnFace; FillRect (Rect(0, 0, Width, Height)); for Y := 0 to 7 do for X := 0 to 7 do if Odd(Y) = Odd(X) then { toggles between even/odd pixels } Pixels[X, Y] := clBtnHighlight; { on even/odd rows } end; end; end; { TButtonGlyph } constructor TButtonGlyph.Create; var B: Boolean; I: TButtonState97; begin inherited; FCallDormant := True; FImageIndex := -1; FOriginal := TBitmap.Create; FOriginal.OnChange := GlyphChanged; FOriginalMask := TBitmap.Create; FOriginalMask.OnChange := GlyphChanged; FNumGlyphs := 1; for B := False to True do for I := Low(I) to High(I) do FIndexs[B, I] := -1; if GlyphCache = nil then GlyphCache := TGlyphCache.Create; end; destructor TButtonGlyph.Destroy; begin FOriginalMask.Free; FOriginal.Free; FImageChangeLink.Free; Invalidate; if Assigned(GlyphCache) and GlyphCache.Empty then begin GlyphCache.Free; GlyphCache := nil; end; inherited; end; procedure TButtonGlyph.Invalidate; var B: Boolean; I: TButtonState97; begin for B := False to True do begin for I := Low(I) to High(I) do if FIndexs[B, I] <> -1 then begin FGlyphList[B].Delete (FIndexs[B, I]); FIndexs[B, I] := -1; end; GlyphCache.ReturnList (FGlyphList[B]); FGlyphList[B] := nil; end; end; procedure TButtonGlyph.GlyphChanged (Sender: TObject); begin if (Sender = FOriginal) and (FOriginal.Width <> 0) and (FOriginal.Height <> 0) then FTransparentColor := FOriginal.Canvas.Pixels[0, FOriginal.Height-1] or $02000000; Invalidate; if Assigned(FOnChange) then FOnChange (Self); end; procedure TButtonGlyph.UpdateNumGlyphs; var Glyphs: Integer; begin if (FOriginal.Width <> 0) and (FOriginal.Height <> 0) and (FOriginal.Width mod FOriginal.Height = 0) then begin Glyphs := FOriginal.Width div FOriginal.Height; if Glyphs > High(TNumGlyphs97) then Glyphs := 1; end else Glyphs := 1; SetNumGlyphs (Glyphs); end; procedure TButtonGlyph.SetGlyph (Value: TBitmap); begin Invalidate; FOriginal.Assign (Value); UpdateNumGlyphs; end; procedure TButtonGlyph.SetGlyphMask (Value: TBitmap); begin Invalidate; FOriginalMask.Assign (Value); end; procedure TButtonGlyph.SetNumGlyphs (Value: TNumGlyphs97); begin Invalidate; if (FImageList <> nil) or (Value < Low(TNumGlyphs97)) or (Value > High(TNumGlyphs97)) then FNumGlyphs := 1 else FNumGlyphs := Value; GlyphChanged (nil); end; function TButtonGlyph.CreateButtonGlyph (State: TButtonState97): TBoolInt; const ROP_DSPDxax = $00E20746; ROP_PSDPxax = $00B8074A; ROP_DSna = $00220326; { D & ~S } procedure GenerateMaskBitmapFromDIB (const MaskBitmap, SourceBitmap: TBitmap; const SourceOffset, SourceSize: TPoint; TransColors: array of TColor); { This a special procedure meant for generating monochrome masks from >4 bpp color DIB sections. Because each video driver seems to sport its own interpretation of how to handle DIB sections, a workaround procedure like this was necessary. } type TColorArray = array[0..536870910] of TColorRef; var Info: packed record Header: TBitmapInfoHeader; Colors: array[0..1] of TColorRef; end; W, H: Integer; I, Y, X: Integer; Pixels: ^TColorArray; Pixel: ^TColorRef; MonoPixels: Pointer; MonoPixel, StartMonoPixel: ^Byte; MonoScanLineSize, CurBit: Integer; DC: HDC; MaskBmp: HBITMAP; begin W := SourceBitmap.Width; H := SourceBitmap.Height; MonoScanLineSize := SourceSize.X div 8; if SourceSize.X mod 8 <> 0 then Inc (MonoScanLineSize); if MonoScanLineSize mod 4 <> 0 then { Compensate for scan line boundary } MonoScanLineSize := (MonoScanLineSize and not 3) + 4; MonoPixels := AllocMem(MonoScanLineSize * SourceSize.Y); { AllocMem is used because it initializes to zero } try GetMem (Pixels, W * H * 4); try FillChar (Info, SizeOf(Info), 0); with Info do begin with Header do begin biSize := SizeOf(TBitmapInfoHeader); biWidth := W; biHeight := -H; { negative number makes it a top-down DIB } biPlanes := 1; biBitCount := 32; {biCompression := BI_RGB;} { implied due to the FillChar zeroing } end; {Colors[0] := clBlack;} { implied due to the FillChar zeroing } Colors[1] := clWhite; end; DC := CreateCompatibleDC(0); GetDIBits (DC, SourceBitmap.Handle, 0, H, Pixels, PBitmapInfo(@Info)^, DIB_RGB_COLORS); DeleteDC (DC); for I := 0 to High(TransColors) do if TransColors[I] = -1 then TransColors[I] := Pixels[W * (H-1)] and $FFFFFF; { ^ 'and' operation is necessary because the high byte is undefined } MonoPixel := MonoPixels; for Y := SourceOffset.Y to SourceOffset.Y+SourceSize.Y-1 do begin StartMonoPixel := MonoPixel; CurBit := 7; Pixel := @Pixels[(Y * W) + SourceOffset.X]; for X := 0 to SourceSize.X-1 do begin for I := 0 to High(TransColors) do if Pixel^ and $FFFFFF = Cardinal(TransColors[I]) then begin { ^ 'and' operation is necessary because the high byte is undefined } MonoPixel^ := MonoPixel^ or (1 shl CurBit); Break; end; Dec (CurBit); if CurBit < 0 then begin Inc (MonoPixel); CurBit := 7; end; Inc (Pixel, SizeOf(Longint)); { proceed to the next pixel } end; {$POINTERMATH ON} MonoPixel := StartMonoPixel + MonoScanLineSize; {$POINTERMATH OFF} end; finally FreeMem (Pixels); end; { Write new bits into a new HBITMAP, and assign this handle to MaskBitmap } MaskBmp := CreateBitmap(SourceSize.X, SourceSize.Y, 1, 1, nil); with Info.Header do begin biWidth := SourceSize.X; biHeight := -SourceSize.Y; { negative number makes it a top-down DIB } biPlanes := 1; biBitCount := 1; end; DC := CreateCompatibleDC(0); SetDIBits (DC, MaskBmp, 0, SourceSize.Y, MonoPixels, PBitmapInfo(@Info)^, DIB_RGB_COLORS); DeleteDC (DC); finally FreeMem (MonoPixels); end; MaskBitmap.Handle := MaskBmp; end; procedure GenerateMaskBitmap (const MaskBitmap, SourceBitmap: TBitmap; const SourceOffset, SourceSize: TPoint; const TransColors: array of TColor); { Returns handle of a monochrome bitmap, with pixels in SourceBitmap of color TransColor set to white in the resulting bitmap. All other colors of SourceBitmap are set to black in the resulting bitmap. This uses the regular ROP_DSPDxax BitBlt method. } var CanvasHandle: HDC; SaveBkColor: TColorRef; DC: HDC; MaskBmp, SaveBmp: HBITMAP; I: Integer; const ROP: array[Boolean] of DWORD = (SRCPAINT, SRCCOPY); begin CanvasHandle := SourceBitmap.Canvas.Handle; MaskBmp := CreateBitmap(SourceSize.X, SourceSize.Y, 1, 1, nil); DC := CreateCompatibleDC(0); SaveBmp := SelectObject(DC, MaskBmp); SaveBkColor := GetBkColor(CanvasHandle); for I := 0 to High(TransColors) do begin SetBkColor (CanvasHandle, ColorToRGB(TransColors[I])); BitBlt (DC, 0, 0, SourceSize.X, SourceSize.Y, CanvasHandle, SourceOffset.X, SourceOffset.Y, ROP[I = 0]); end; SetBkColor (CanvasHandle, SaveBkColor); SelectObject (DC, SaveBmp); DeleteDC (DC); MaskBitmap.Handle := MaskBmp; end; procedure ReplaceBitmapColorsFromMask (const MaskBitmap, DestBitmap: TBitmap; const DestOffset, DestSize: TPoint; const ReplaceColor: TColor); var DestDC: HDC; SaveBrush: HBRUSH; SaveTextColor, SaveBkColor: TColorRef; begin DestDC := DestBitmap.Canvas.Handle; SaveBrush := SelectObject(DestDC, CreateSolidBrush(ColorToRGB(ReplaceColor))); SaveTextColor := SetTextColor(DestDC, clBlack); SaveBkColor := SetBkColor(DestDC, clWhite); BitBlt (DestDC, DestOffset.X, DestOffset.Y, DestSize.X, DestSize.Y, MaskBitmap.Canvas.Handle, 0, 0, ROP_DSPDxax); SetBkColor (DestDC, SaveBkColor); SetTextColor (DestDC, SaveTextColor); DeleteObject (SelectObject(DestDC, SaveBrush)); end; function CopyBitmapToDDB (const SourceBitmap: TBitmap): TBitmap; { Makes a device-dependent duplicate of SourceBitmap. The color palette, if any, is preserved. } var SB: HBITMAP; SavePalette: HPALETTE; DC: HDC; BitmapInfo: packed record Header: TBitmapInfoHeader; Colors: array[0..255] of TColorRef; end; Bits: Pointer; begin Result := TBitmap.Create; try Result.Palette := CopyPalette(SourceBitmap.Palette); Result.Width := SourceBitmap.Width; Result.Height := SourceBitmap.Height; SB := SourceBitmap.Handle; if SB = 0 then Exit; { it would have a null handle if its width or height was zero } SavePalette := 0; DC := CreateCompatibleDC(0); try if Result.Palette <> 0 then begin SavePalette := SelectPalette(DC, Result.Palette, False); RealizePalette (DC); end; BitmapInfo.Header.biSize := SizeOf(TBitmapInfoHeader); BitmapInfo.Header.biBitCount := 0; { instructs GetDIBits not to fill in the color table } { First retrieve the BitmapInfo header only } if GetDIBits(DC, SB, 0, 0, nil, PBitmapInfo(@BitmapInfo)^, DIB_RGB_COLORS) <> 0 then begin GetMem (Bits, BitmapInfo.Header.biSizeImage); try { Then read the actual bits } if GetDIBits(DC, SB, 0, SourceBitmap.Height, Bits, PBitmapInfo(@BitmapInfo)^, DIB_RGB_COLORS) <> 0 then { And copy them to the resulting bitmap } SetDIBits (DC, Result.Handle, 0, SourceBitmap.Height, Bits, PBitmapInfo(@BitmapInfo)^, DIB_RGB_COLORS); finally FreeMem (Bits); end; end; finally if SavePalette <> 0 then SelectPalette (DC, SavePalette, False); DeleteDC (DC); end; except Result.Free; raise; end; end; const ROPs: array[Boolean] of DWORD = (ROP_PSDPxax, ROP_DSPDxax); var OriginalBmp, OriginalMaskBmp, TmpImage, DDB, MonoBmp, MaskBmp, UseMaskBmp: TBitmap; I: TButtonState97; B: Boolean; AddPixels, IWidth, IHeight, IWidthA, IHeightA: Integer; IRect, IRectA, SourceRect, R: TRect; DC: HDC; UsesMask: Boolean; {$IFDEF TB97D3} IsHighColorDIB: Boolean; {$ELSE} const IsHighColorDIB = False; {$ENDIF} begin if (State <> bsDisabled) and (Ord(State) >= NumGlyphs) then State := bsUp; Result.B := True; Result.I := FIndexs[True, State]; if Result.I = -1 then begin Result.B := False; Result.I := FIndexs[False, State]; end; if Result.I <> -1 then Exit; if FImageList = nil then begin if (FOriginal.Width = 0) or (FOriginal.Height = 0) then Exit; UsesMask := (FOriginalMask.Width <> 0) and (FOriginalMask.Height <> 0); end else begin if (FImageIndex < 0) or (FImageIndex >= FImageList.Count) then Exit; UsesMask := False; end; B := State <> bsDisabled; { + AddPixels is to make sure the highlight color on generated disabled glyphs doesn't get cut off } if FImageList = nil then begin IWidthA := FOriginal.Width div FNumGlyphs; IHeightA := FOriginal.Height; end else begin IWidthA := TCustomImageListAccess(FImageList).Width; IHeightA := TCustomImageListAccess(FImageList).Height; end; IRectA := Rect(0, 0, IWidthA, IHeightA); AddPixels := Ord(State = bsDisabled); IWidth := IWidthA + AddPixels; IHeight := IHeightA + AddPixels; IRect := Rect(0, 0, IWidth, IHeight); if FGlyphList[B] = nil then begin if GlyphCache = nil then GlyphCache := TGlyphCache.Create; FGlyphList[B] := GlyphCache.GetList(IWidth, IHeight); end; {$IFDEF TB97D3} IsHighColorDIB := (FImageList = nil) and (FOriginal.PixelFormat > pf4bit); {$ENDIF} OriginalBmp := nil; OriginalMaskBmp := nil; TmpImage := nil; MaskBmp := nil; try OriginalBmp := TBitmap.Create; OriginalBmp.Assign (FOriginal); OriginalMaskBmp := TBitmap.Create; OriginalMaskBmp.Assign (FOriginalMask); TmpImage := TBitmap.Create; TmpImage.Width := IWidth; TmpImage.Height := IHeight; TmpImage.Canvas.Brush.Color := clBtnFace; if FImageList = nil then TmpImage.Palette := CopyPalette(OriginalBmp.Palette); I := State; if Ord(I) >= NumGlyphs then I := bsUp; SourceRect := Bounds(Ord(I) * IWidthA, 0, IWidthA, IHeightA); if FImageList <> nil then begin MaskBmp := TBitmap.Create; MaskBmp.Monochrome := True; MaskBmp.Width := IWidthA; MaskBmp.Height := IHeightA; ImageList_Draw (FImageList.Handle, FImageIndex, MaskBmp.Canvas.Handle, 0, 0, ILD_MASK); end; if State <> bsDisabled then begin if FImageList = nil then begin TmpImage.Canvas.CopyRect (IRectA, OriginalBmp.Canvas, SourceRect); if not UsesMask then begin {$IFDEF TB97D3} { Use clDefault instead of FTransparentColor whereever possible to ensure compatibility with all video drivers when using high-color (> 4 bpp) DIB glyphs } FIndexs[B, State] := FGlyphList[B].AddMasked(TmpImage, clDefault); {$ELSE} FIndexs[B, State] := FGlyphList[B].AddMasked(TmpImage, FTransparentColor); {$ENDIF} end else begin MonoBmp := TBitmap.Create; try MonoBmp.Monochrome := True; MonoBmp.Width := IWidth; MonoBmp.Height := IHeight; MonoBmp.Canvas.CopyRect (IRectA, OriginalMaskBmp.Canvas, SourceRect); FIndexs[B, State] := FGlyphList[B].Add(TmpImage, MonoBmp); finally MonoBmp.Free; end; end; end else begin ImageList_Draw (FImageList.Handle, FImageIndex, TmpImage.Canvas.Handle, 0, 0, ILD_NORMAL); FIndexs[B, State] := FGlyphList[B].Add(TmpImage, MaskBmp); end; end else begin MonoBmp := nil; DDB := nil; try MonoBmp := TBitmap.Create; { Uses the CopyBitmapToDDB to work around a Delphi 3 flaw. If you copy a DIB to a second bitmap via Assign, change the HandleType of the second bitmap to bmDDB, then try to read the Handle property, Delphi converts it back to a DIB. } if FImageList = nil then DDB := CopyBitmapToDDB(OriginalBmp) else begin DDB := TBitmap.Create; DDB.Width := IWidthA; DDB.Height := IHeightA; ImageList_Draw (FImageList.Handle, FImageIndex, DDB.Canvas.Handle, 0, 0, ILD_NORMAL); end; if NumGlyphs > 1 then with TmpImage.Canvas do begin CopyRect (IRectA, DDB.Canvas, SourceRect); { Convert white to clBtnHighlight } if not IsHighColorDIB then GenerateMaskBitmap (MonoBmp, DDB, SourceRect.TopLeft, IRectA.BottomRight, [GetNearestColor(OriginalBmp.Canvas.Handle, clWhite)]) else GenerateMaskBitmapFromDIB (MonoBmp, OriginalBmp, SourceRect.TopLeft, IRectA.BottomRight, [clWhite]); ReplaceBitmapColorsFromMask (MonoBmp, TmpImage, IRectA.TopLeft, IRectA.BottomRight, clBtnHighlight); { Convert gray to clBtnShadow } if not IsHighColorDIB then GenerateMaskBitmap (MonoBmp, DDB, SourceRect.TopLeft, IRectA.BottomRight, [GetNearestColor(OriginalBmp.Canvas.Handle, clGray)]) else GenerateMaskBitmapFromDIB (MonoBmp, OriginalBmp, SourceRect.TopLeft, IRectA.BottomRight, [clGray]); ReplaceBitmapColorsFromMask (MonoBmp, TmpImage, IRectA.TopLeft, IRectA.BottomRight, clBtnShadow); if not UsesMask then begin { Generate the transparent mask in MonoBmp. The reason why it doesn't just use a mask color is because the mask needs to be of the glyph -before- the clBtnHighlight/Shadow were translated } if not IsHighColorDIB then GenerateMaskBitmap (MonoBmp, DDB, SourceRect.TopLeft, IRectA.BottomRight, FTransparentColor) else GenerateMaskBitmapFromDIB (MonoBmp, OriginalBmp, SourceRect.TopLeft, IRectA.BottomRight, [-1]); end else MonoBmp.Canvas.CopyRect (IRectA, OriginalMaskBmp.Canvas, SourceRect); with MonoBmp do begin Width := Width + AddPixels; Height := Height + AddPixels; { Set the additional bottom and right row on disabled glyph masks to white so that it always shines through, since the bottom and right row on TmpImage was left uninitialized } Canvas.Pen.Color := clWhite; Canvas.PolyLine ([Point(0, Height-1), Point(Width-1, Height-1), Point(Width-1, -1)]); end; FIndexs[B, State] := FGlyphList[B].Add(TmpImage, MonoBmp); end else begin { Create a disabled version } if FOldDisabledStyle then begin { "Old" TSpeedButton style } if FImageList = nil then begin if not UsesMask then begin if IsHighColorDIB then GenerateMaskBitmapFromDIB (MonoBmp, OriginalBmp, SourceRect.TopLeft, IRectA.BottomRight, [clBlack]) else begin with MonoBmp do begin Assign (DDB); { must be a DDB for this to work right } Canvas.Brush.Color := clBlack; Monochrome := True; end; end; end else begin MonoBmp.Assign (DDB); { must be a DDB for this to work right } with TBitmap.Create do try Monochrome := True; Width := OriginalMaskBmp.Width; Height := OriginalMaskBmp.Height; R := Rect(0, 0, Width, Height); Canvas.CopyRect (R, OriginalMaskBmp.Canvas, R); DC := Canvas.Handle; with MonoBmp.Canvas do begin BitBlt (Handle, 0, 0, IWidthA, IHeightA, DC, SourceRect.Left, SourceRect.Top, ROP_DSna); BitBlt (Handle, 0, 0, IWidthA, IHeightA, DC, SourceRect.Left, SourceRect.Top, SRCPAINT); end; finally Free; end; MonoBmp.Canvas.Brush.Color := clBlack; MonoBmp.Monochrome := True; end end else begin with MonoBmp do begin Width := IWidthA; Height := IHeightA; Canvas.Brush.Color := clWhite; Canvas.FillRect (IRectA); ImageList_Draw (FImageList.Handle, FImageIndex, Canvas.Handle, 0, 0, ILD_TRANSPARENT); Canvas.Brush.Color := clBlack; Monochrome := True; end; end; end else begin { The new Office 97 / MFC look } if not UsesMask and (FImageList = nil) then begin with TmpImage.Canvas do begin if not IsHighColorDIB then GenerateMaskBitmap (MonoBmp, DDB, IRectA.TopLeft, IRectA.BottomRight, [FTransparentColor, clWhite, clSilver]) else GenerateMaskBitmapFromDIB (MonoBmp, OriginalBmp, SourceRect.TopLeft, IRectA.BottomRight, [-1, clWhite, clSilver]); end; end else begin { Generate the mask in MonoBmp. Make clWhite and clSilver transparent. } if not IsHighColorDIB then GenerateMaskBitmap (MonoBmp, DDB, SourceRect.TopLeft, IRectA.BottomRight, [clWhite, clSilver]) else GenerateMaskBitmapFromDIB (MonoBmp, OriginalBmp, SourceRect.TopLeft, IRectA.BottomRight, [clWhite, clSilver]); if FImageList = nil then UseMaskBmp := OriginalMaskBmp else UseMaskBmp := MaskBmp; { and all the white colors in UseMaskBmp } with TBitmap.Create do try Monochrome := True; Width := UseMaskBmp.Width; Height := UseMaskBmp.Height; R := Rect(0, 0, Width, Height); Canvas.CopyRect (R, UseMaskBmp.Canvas, R); DC := Canvas.Handle; with MonoBmp.Canvas do begin BitBlt (Handle, 0, 0, IWidthA, IHeightA, DC, SourceRect.Left, SourceRect.Top, ROP_DSna); BitBlt (Handle, 0, 0, IWidthA, IHeightA, DC, SourceRect.Left, SourceRect.Top, SRCPAINT); end; finally Free; end; end; end; with TmpImage.Canvas do begin Brush.Color := clBtnFace; FillRect (IRect); Brush.Color := clBtnHighlight; DC := Handle; SetTextColor (DC, clBlack); SetBkColor (DC, clWhite); BitBlt (DC, 1, 1, IWidthA, IHeightA, MonoBmp.Canvas.Handle, 0, 0, ROPs[FOldDisabledStyle]); Brush.Color := clBtnShadow; DC := Handle; SetTextColor (DC, clBlack); SetBkColor (DC, clWhite); BitBlt (DC, 0, 0, IWidthA, IHeightA, MonoBmp.Canvas.Handle, 0, 0, ROPs[FOldDisabledStyle]); end; FIndexs[B, State] := FGlyphList[B].AddMasked(TmpImage, clBtnFace); end; finally DDB.Free; MonoBmp.Free; end; end; finally MaskBmp.Free; TmpImage.Free; OriginalMaskBmp.Free; OriginalBmp.Free; end; Result.B := B; Result.I := FIndexs[B, State]; { Note: Due to a bug in graphics.pas, Delphi 2's VCL crashes if Dormant is called on an empty bitmap, so to prevent this it must check Width/Height first } if {$IFNDEF TB97D3} (FOriginal.Width <> 0) and (FOriginal.Height <> 0) and {$ENDIF} FCallDormant then FOriginal.Dormant; {$IFNDEF TB97D3} if (FOriginalMask.Width <> 0) and (FOriginalMask.Height <> 0) then {$ENDIF} FOriginalMask.Dormant; end; procedure TButtonGlyph.DrawButtonGlyph (Canvas: TCanvas; const GlyphPos: TPoint; State: TButtonState97); var Index: TBoolInt; begin Index := CreateButtonGlyph(State); if Index.I <> -1 then ImageList_DrawEx (FGlyphList[Index.B].Handle, Index.I, Canvas.Handle, GlyphPos.X, GlyphPos.Y, 0, 0, CLR_NONE, CLR_NONE, ILD_TRANSPARENT); end; procedure TButtonGlyph.DrawButtonText (Canvas: TCanvas; const Caption: string; TextBounds: TRect; WordWrap: Boolean; Alignment: TAlignment; State: TButtonState97); const AlignmentFlags: array[TAlignment] of UINT = (DT_LEFT, DT_RIGHT, DT_CENTER); var Format: UINT; begin Format := DT_VCENTER or AlignmentFlags[Alignment]; if not WordWrap then Format := Format or DT_SINGLELINE else Format := Format or DT_WORDBREAK; with Canvas do begin Brush.Style := bsClear; if State = bsDisabled then begin OffsetRect (TextBounds, 1, 1); Font.Color := clBtnHighlight; DrawText (Handle, PChar(Caption), Length(Caption), TextBounds, Format); OffsetRect (TextBounds, -1, -1); Font.Color := clBtnShadow; DrawText (Handle, PChar(Caption), Length(Caption), TextBounds, Format); end else DrawText (Handle, PChar(Caption), Length(Caption), TextBounds, Format); end; end; procedure TButtonGlyph.DrawButtonDropArrow (Canvas: TCanvas; const X, Y, AWidth: Integer; State: TButtonState97); var X2: Integer; begin with Canvas do begin X2 := X + AWidth div 2; if State = bsDisabled then begin Pen.Color := clBtnHighlight; Brush.Color := clBtnHighlight; Polygon ([Point(X2-1, Y+1), Point(X2+3, Y+1), Point(X2+1, Y+3)]); Pen.Color := clBtnShadow; Brush.Color := clBtnShadow; Polygon ([Point(X2-2, Y), Point(X2+2, Y), Point(X2, Y+2)]); end else begin Pen.Color := Font.Color; Brush.Color := Font.Color; Polygon ([Point(X2-2, Y), Point(X2+2, Y), Point(X2, Y+2)]); end; end; end; procedure TButtonGlyph.CalcButtonLayout (Canvas: TCanvas; const Client: TRect; const Offset: TPoint; DrawGlyph, DrawCaption: Boolean; const Caption: string; WordWrap: Boolean; Layout: TButtonLayout; Margin, Spacing: Integer; DropArrow: Boolean; DropArrowWidth: Integer; var GlyphPos, ArrowPos: TPoint; var TextBounds: TRect); var TextPos: TPoint; ClientSize, GlyphSize, TextSize, ArrowSize: TPoint; HasGlyph: Boolean; TotalSize: TPoint; Format: UINT; Margin1, Spacing1: Integer; LayoutLeftOrRight: Boolean; begin { calculate the item sizes } ClientSize := Point(Client.Right-Client.Left, Client.Bottom-Client.Top); GlyphSize.X := 0; GlyphSize.Y := 0; if DrawGlyph then begin if FImageList = nil then begin if FOriginal <> nil then begin GlyphSize.X := FOriginal.Width div FNumGlyphs; GlyphSize.Y := FOriginal.Height; end; end else begin GlyphSize.X := TCustomImageListAccess(FImageList).Width; GlyphSize.Y := TCustomImageListAccess(FImageList).Height; end; end; HasGlyph := (GlyphSize.X <> 0) and (GlyphSize.Y <> 0); if DropArrow then begin ArrowSize.X := DropArrowWidth; ArrowSize.Y := 3; end else begin ArrowSize.X := 0; ArrowSize.Y := 0; end; LayoutLeftOrRight := Layout in [blGlyphLeft, blGlyphRight]; if not LayoutLeftOrRight and not HasGlyph then begin Layout := blGlyphLeft; LayoutLeftOrRight := True; end; if DrawCaption and (Caption <> '') then begin TextBounds := Rect(0, 0, Client.Right-Client.Left, 0); if LayoutLeftOrRight then Dec (TextBounds.Right, ArrowSize.X); Format := DT_CALCRECT; if WordWrap then begin Format := Format or DT_WORDBREAK; Margin1 := 4; if LayoutLeftOrRight and HasGlyph then begin if Spacing = -1 then Spacing1 := 4 else Spacing1 := Spacing; Dec (TextBounds.Right, GlyphSize.X + Spacing1); if Margin <> -1 then Margin1 := Margin else if Spacing <> -1 then Margin1 := Spacing; end; Dec (TextBounds.Right, Margin1 * 2); end; DrawText (Canvas.Handle, PChar(Caption), Length(Caption), TextBounds, Format); TextSize := Point(TextBounds.Right - TextBounds.Left, TextBounds.Bottom - TextBounds.Top); end else begin TextBounds := Rect(0, 0, 0, 0); TextSize := Point(0,0); end; { If the layout has the glyph on the right or the left, then both the text and the glyph are centered vertically. If the glyph is on the top or the bottom, then both the text and the glyph are centered horizontally.} if LayoutLeftOrRight then begin GlyphPos.Y := (ClientSize.Y - GlyphSize.Y + 1) div 2; TextPos.Y := (ClientSize.Y - TextSize.Y + 1) div 2; end else begin GlyphPos.X := (ClientSize.X - GlyphSize.X - ArrowSize.X + 1) div 2; TextPos.X := (ClientSize.X - TextSize.X + 1) div 2; if not HasGlyph then ArrowPos.X := TextPos.X + TextSize.X else ArrowPos.X := GlyphPos.X + GlyphSize.X; end; { if there is no text or no bitmap, then Spacing is irrelevant } if (TextSize.X = 0) or (TextSize.Y = 0) or not HasGlyph then Spacing := 0; { adjust Margin and Spacing } if Margin = -1 then begin if Spacing = -1 then begin TotalSize := Point(GlyphSize.X + TextSize.X + ArrowSize.X, GlyphSize.Y + TextSize.Y); if LayoutLeftOrRight then Margin := (ClientSize.X - TotalSize.X) div 3 else Margin := (ClientSize.Y - TotalSize.Y) div 3; Spacing := Margin; end else begin TotalSize := Point(GlyphSize.X + Spacing + TextSize.X + ArrowSize.X, GlyphSize.Y + Spacing + TextSize.Y); if LayoutLeftOrRight then Margin := (ClientSize.X - TotalSize.X + 1) div 2 else Margin := (ClientSize.Y - TotalSize.Y + 1) div 2; end; end else begin if Spacing = -1 then begin TotalSize := Point(ClientSize.X - (Margin + GlyphSize.X + ArrowSize.X), ClientSize.Y - (Margin + GlyphSize.Y)); if LayoutLeftOrRight then Spacing := (TotalSize.X - TextSize.X) div 2 else Spacing := (TotalSize.Y - TextSize.Y) div 2; end; end; case Layout of blGlyphLeft: begin GlyphPos.X := Margin; TextPos.X := GlyphPos.X + GlyphSize.X + Spacing; ArrowPos.X := TextPos.X + TextSize.X; end; blGlyphRight: begin ArrowPos.X := ClientSize.X - Margin - ArrowSize.X; GlyphPos.X := ArrowPos.X - GlyphSize.X; TextPos.X := GlyphPos.X - Spacing - TextSize.X; end; blGlyphTop: begin GlyphPos.Y := Margin; TextPos.Y := GlyphPos.Y + GlyphSize.Y + Spacing; end; blGlyphBottom: begin GlyphPos.Y := ClientSize.Y - Margin - GlyphSize.Y; TextPos.Y := GlyphPos.Y - Spacing - TextSize.Y; end; end; Inc (ArrowPos.X); if not HasGlyph then ArrowPos.Y := TextPos.Y + (TextSize.Y - ArrowSize.Y) div 2 else ArrowPos.Y := GlyphPos.Y + (GlyphSize.Y - ArrowSize.Y) div 2; { fixup the result variables } Inc (GlyphPos.X, Client.Left + Offset.X); Inc (GlyphPos.Y, Client.Top + Offset.Y); Inc (ArrowPos.X, Client.Left + Offset.X); Inc (ArrowPos.Y, Client.Top + Offset.Y); OffsetRect (TextBounds, TextPos.X + Client.Left + Offset.X, TextPos.Y + Client.Top + Offset.X); end; function TButtonGlyph.Draw (Canvas: TCanvas; const Client: TRect; const Offset: TPoint; DrawGlyph, DrawCaption: Boolean; const Caption: string; WordWrap: Boolean; Alignment: TAlignment; Layout: TButtonLayout; Margin, Spacing: Integer; DropArrow: Boolean; DropArrowWidth: Integer; State: TButtonState97): TRect; var GlyphPos, ArrowPos: TPoint; begin CalcButtonLayout (Canvas, Client, Offset, DrawGlyph, DrawCaption, Caption, WordWrap, Layout, Margin, Spacing, DropArrow, DropArrowWidth, GlyphPos, ArrowPos, Result); if DrawGlyph then DrawButtonGlyph (Canvas, GlyphPos, State); if DrawCaption then DrawButtonText (Canvas, Caption, Result, WordWrap, Alignment, State); if DropArrow then DrawButtonDropArrow (Canvas, ArrowPos.X, ArrowPos.Y, DropArrowWidth, State); end; { TDropdownList } {$IFNDEF TB97D4} type TDropdownList = class(TComponent) private List: TList; Window: HWND; procedure WndProc (var Message: TMessage); protected procedure Notification (AComponent: TComponent; Operation: TOperation); override; public constructor Create (AOwner: TComponent); override; destructor Destroy; override; procedure AddMenu (Menu: TPopupMenu); end; var DropdownList: TDropdownList; constructor TDropdownList.Create (AOwner: TComponent); begin inherited; List := TList.Create; end; destructor TDropdownList.Destroy; begin inherited; if Window <> 0 then DeallocateHWnd (Window); List.Free; end; procedure TDropdownList.WndProc (var Message: TMessage); { This procedure is based on code from TPopupList.WndProc (menus.pas) } var I: Integer; MenuItem: TMenuItem; FindKind: TFindItemKind; ContextID: Integer; begin try with List do case Message.Msg of WM_COMMAND: for I := 0 to Count-1 do if TPopupMenu(Items[I]).DispatchCommand(TWMCommand(Message).ItemID) then Exit; WM_INITMENUPOPUP: for I := 0 to Count-1 do if TPopupMenu(Items[I]).DispatchPopup(TWMInitMenuPopup(Message).MenuPopup) then Exit; WM_MENUSELECT: with TWMMenuSelect(Message) do begin FindKind := fkCommand; if MenuFlag and MF_POPUP <> 0 then FindKind := fkHandle; for I := 0 to Count-1 do begin MenuItem := TPopupMenu(Items[I]).FindItem(IDItem, FindKind); if MenuItem <> nil then begin Application.Hint := MenuItem.Hint; Exit; end; end; Application.Hint := ''; end; WM_HELP: with TWMHelp(Message).HelpInfo^ do begin for I := 0 to Count-1 do if TPopupMenu(Items[I]).Handle = hItemHandle then begin ContextID := TPopupMenu(Items[I]).GetHelpContext(iCtrlID, True); if ContextID = 0 then ContextID := TPopupMenu(Items[I]).GetHelpContext(hItemHandle, False); if Screen.ActiveForm = nil then Exit; if (biHelp in Screen.ActiveForm.BorderIcons) then Application.HelpCommand (HELP_CONTEXTPOPUP, ContextID) else Application.HelpContext (ContextID); Exit; end; end; end; with Message do Result := DefWindowProc(Window, Msg, wParam, lParam); except Application.HandleException (Self); end; end; procedure TDropdownList.AddMenu (Menu: TPopupMenu); begin if List.IndexOf(Menu) = -1 then begin if Window = 0 then Window := AllocateHWnd(WndProc); Menu.FreeNotification (Self); List.Add (Menu); end; end; procedure TDropdownList.Notification (AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then begin List.Remove (AComponent); if (List.Count = 0) and (Window <> 0) then begin DeallocateHWnd (Window); Window := 0; end; end; end; {$ENDIF} { TToolbarButton97 } procedure ButtonHookProc (Code: THookProcCode; Wnd: HWND; WParam: WPARAM; LParam: LPARAM); var P: TPoint; begin case Code of hpSendActivateApp: if (WParam = 0) and Assigned(ButtonMouseInControl) and not ButtonMouseInControl.FShowBorderWhenInactive then ButtonMouseInControl.MouseLeft; hpPostMouseMove: begin if Assigned(ButtonMouseInControl) then begin GetCursorPos (P); if FindDragTarget(P, True) <> ButtonMouseInControl then ButtonMouseInControl.MouseLeft; end; end; end; end; constructor TToolbarButton97.Create (AOwner: TComponent); begin inherited; if ButtonMouseTimer = nil then begin ButtonMouseTimer := TTimer.Create(nil); ButtonMouseTimer.Enabled := False; ButtonMouseTimer.Interval := 125; { 8 times a second } end; InstallHookProc (ButtonHookProc, [hpSendActivateApp, hpPostMouseMove], csDesigning in ComponentState); SetBounds (Left, Top, 23, 22); ControlStyle := [csCaptureMouse, csDoubleClicks, csOpaque]; Color := clBtnFace; FGlyph := TButtonGlyph.Create; TButtonGlyph(FGlyph).OnChange := GlyphChanged; ParentFont := True; FAlignment := taCenter; FFlat := True; FHighlightWhenDown := True; FOpaque := True; FSpacing := 4; FMargin := -1; FLayout := blGlyphLeft; FDropdownArrow := True; FDropdownArrowWidth := DefaultDropdownArrowWidth; FRepeatDelay := 400; FRepeatInterval := 100; Inc (ButtonCount); end; destructor TToolbarButton97.Destroy; begin RemoveButtonMouseTimer; TButtonGlyph(FGlyph).Free; { The Notification method, which is sometimes called while the component is being destroyed, reads FGlyph and expects it to be valid, so it must be reset to nil } FGlyph := nil; UninstallHookProc (ButtonHookProc); Dec (ButtonCount); if ButtonCount = 0 then begin Pattern.Free; Pattern := nil; ButtonMouseTimer.Free; ButtonMouseTimer := nil; end; inherited; end; procedure TToolbarButton97.Paint; const EdgeStyles: array[Boolean, Boolean] of UINT = ( (EDGE_RAISED, EDGE_SUNKEN), (BDR_RAISEDINNER, BDR_SUNKENOUTER)); FlagStyles: array[Boolean] of UINT = (BF_RECT or BF_SOFT or BF_MIDDLE, BF_RECT); var UseBmp: Boolean; Bmp: TBitmap; DrawCanvas: TCanvas; PaintRect, R: TRect; Offset: TPoint; StateDownOrExclusive, DropdownComboShown, UseDownAppearance, DrawBorder: Boolean; begin UseBmp := FOpaque or not FFlat; if UseBmp then Bmp := TBitmap.Create else Bmp := nil; try if UseBmp then begin Bmp.Width := Width; Bmp.Height := Height; DrawCanvas := Bmp.Canvas; with DrawCanvas do begin Brush.Color := Color; FillRect (ClientRect); end; end else DrawCanvas := Canvas; DrawCanvas.Font := Self.Font; PaintRect := Rect(0, 0, Width, Height); StateDownOrExclusive := FState in [bsDown, bsExclusive]; DropdownComboShown := FDropdownCombo and FUsesDropdown; UseDownAppearance := (FState = bsExclusive) or ((FState = bsDown) and (not DropdownComboShown or not FMenuIsDown)); DrawBorder := (csDesigning in ComponentState) or (not FNoBorder and (not FFlat or StateDownOrExclusive or (FMouseInControl and (FState <> bsDisabled)))); if DropdownComboShown then begin if DrawBorder then begin R := PaintRect; Dec (R.Right, DropdownComboSpace); R.Left := R.Right - DropdownArrowWidth; DrawEdge (DrawCanvas.Handle, R, EdgeStyles[FFlat, StateDownOrExclusive and FMenuIsDown], FlagStyles[FFlat]); end; Dec (PaintRect.Right, DropdownArrowWidth + DropdownComboSpace); end; if DrawBorder then DrawEdge (DrawCanvas.Handle, PaintRect, EdgeStyles[FFlat, UseDownAppearance], FlagStyles[FFlat]); if not FNoBorder then begin if FFlat then InflateRect (PaintRect, -1, -1) else InflateRect (PaintRect, -2, -2); end; if UseDownAppearance then begin if (FState = bsExclusive) and (not FFlat or not FMouseInControl) and not FMenuIsDown and FHighlightWhenDown then begin if Pattern = nil then CreateBrushPattern; DrawCanvas.Brush.Bitmap := Pattern; DrawCanvas.FillRect(PaintRect); end; Offset.X := 1; Offset.Y := 1; end else begin Offset.X := 0; Offset.Y := 0; end; TButtonGlyph(FGlyph).Draw (DrawCanvas, PaintRect, Offset, FDisplayMode <> dmTextOnly, FDisplayMode <> dmGlyphOnly, Caption, FWordWrap, FAlignment, FLayout, FMargin, FSpacing, FDropdownArrow and not FDropdownCombo and FUsesDropdown, DropdownArrowWidth, FState); if DropdownComboShown then TButtonGlyph(FGlyph).DrawButtonDropArrow (DrawCanvas, Width-DropdownArrowWidth-2, Height div 2 - 1, DropdownArrowWidth, FState); if UseBmp then Canvas.Draw (0, 0, Bmp); finally Bmp.Free; end; end; procedure TToolbarButton97.RemoveButtonMouseTimer; begin if ButtonMouseInControl = Self then begin ButtonMouseTimer.Enabled := False; ButtonMouseInControl := nil; end; end; (* no longer used procedure TToolbarButton97.UpdateTracking; var P: TPoint; begin if Enabled then begin GetCursorPos (P); { Use FindDragTarget instead of PtInRect since we want to check based on the Z order } FMouseInControl := not (FindDragTarget(P, True) = Self); if FMouseInControl then MouseLeft else MouseEntered; end; end; *) procedure TToolbarButton97.Loaded; var State: TButtonState97; begin inherited; if Enabled then State := bsUp else State := bsDisabled; TButtonGlyph(FGlyph).CreateButtonGlyph (State); end; procedure TToolbarButton97.Notification (AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then begin if AComponent = DropdownMenu then DropdownMenu := nil; if Assigned(FGlyph) and (AComponent = Images) then Images := nil; end; end; function TToolbarButton97.PointInButton (X, Y: Integer): Boolean; begin Result := (X >= 0) and (X < ClientWidth-((DropdownArrowWidth+DropdownComboSpace) * Ord(FDropdownCombo and FUsesDropdown))) and (Y >= 0) and (Y < ClientHeight); end; procedure TToolbarButton97.MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if not Enabled then begin inherited; Exit; end; if Button <> mbLeft then begin MouseEntered; inherited; end else begin { We know mouse has to be over the control if the mouse went down. } MouseEntered; FMenuIsDown := FUsesDropdown and (not FDropdownCombo or (X >= Width-(DropdownArrowWidth+DropdownComboSpace))); try if not FDown then begin FState := bsDown; Redraw (True); end else if FAllowAllUp then Redraw (True); if not FMenuIsDown then FMouseIsDown := True; inherited; if FMenuIsDown then Click else if FRepeating then begin Click; if not Assigned(FRepeatTimer) then FRepeatTimer := TTimer.Create(Self); FRepeatTimer.Enabled := False; FRepeatTimer.Interval := FRepeatDelay; FRepeatTimer.OnTimer := RepeatTimerHandler; FRepeatTimer.Enabled := True; end; finally FMenuIsDown := False; end; end; end; procedure TToolbarButton97.MouseMove (Shift: TShiftState; X, Y: Integer); var P: TPoint; NewState: TButtonState97; PtInButton: Boolean; begin inherited; { Check if mouse just entered the control. It works better to check this in MouseMove rather than using CM_MOUSEENTER, since the VCL doesn't send a CM_MOUSEENTER in all cases Use FindDragTarget instead of PtInRect since we want to check based on the Z order } P := ClientToScreen(Point(X, Y)); if (ButtonMouseInControl <> Self) and (FindDragTarget(P, True) = Self) then begin if Assigned(ButtonMouseInControl) then ButtonMouseInControl.MouseLeft; { Like Office 97, only draw the active borders when the application is active } if FShowBorderWhenInactive or ApplicationIsActive then begin ButtonMouseInControl := Self; ButtonMouseTimer.OnTimer := ButtonMouseTimerHandler; ButtonMouseTimer.Enabled := True; MouseEntered; end; end; if FMouseIsDown then begin PtInButton := PointInButton(X, Y); if PtInButton and Assigned(FRepeatTimer) then FRepeatTimer.Enabled := True; if FDown then NewState := bsExclusive else begin if PtInButton then NewState := bsDown else NewState := bsUp; end; if NewState <> FState then begin FState := NewState; Redraw (True); end; end; end; procedure TToolbarButton97.RepeatTimerHandler (Sender: TObject); var P: TPoint; begin FRepeatTimer.Interval := FRepeatInterval; GetCursorPos (P); P := ScreenToClient(P); if Repeating and FMouseIsDown and MouseCapture and PointInButton(P.X, P.Y) then Click else FRepeatTimer.Enabled := False; end; procedure TToolbarButton97.WMCancelMode (var Message: TWMCancelMode); begin FRepeatTimer.Free; FRepeatTimer := nil; if FMouseIsDown then begin FMouseIsDown := False; MouseLeft; end; { Delphi's default processing of WM_CANCELMODE sends a "fake" WM_LBUTTONUP message to the control, so inherited must only be called after setting FMouseIsDown to False } inherited; end; procedure TToolbarButton97.MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FRepeatTimer.Free; FRepeatTimer := nil; { Remove active border when right button is clicked } if (Button = mbRight) and Enabled then begin FMouseIsDown := False; MouseLeft; end; inherited; if (Button = mbLeft) and FMouseIsDown then begin FMouseIsDown := False; if PointInButton(X, Y) and not FRepeating then Click else MouseLeft; end; end; procedure TToolbarButton97.Click; {$IFNDEF TB97D4} const { TPM_RIGHTBUTTON works better on Windows 3.x } ButtonFlags: array[Boolean] of UINT = (TPM_RIGHTBUTTON, TPM_LEFTBUTTON); AlignFlags: array[TPopupAlignment] of UINT = (TPM_LEFTALIGN, TPM_RIGHTALIGN, TPM_CENTERALIGN); {$ENDIF} var Popup, ShowMenu, RemoveClicks: Boolean; SaveAlignment: TPopupAlignment; {$IFDEF TB97D4} SaveTrackButton: TTrackButton; {$ENDIF} PopupPt: TPoint; RepostList: TList; {pointers to TMsg's} Msg: TMsg; Repost: Boolean; I: Integer; P: TPoint; Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF}; DockPos: TGetToolbarDockPosType; begin if FRepeating and not FMenuIsDown then begin inherited; Exit; end; FInClick := True; try if (GroupIndex <> 0) and not FMenuIsDown then SetDown (not FDown); Popup := FUsesDropdown and (not FDropdownCombo or FMenuIsDown); if ButtonsStayDown or Popup then begin if FState in [bsUp, bsMouseIn] then begin FState := bsDown; Redraw (True); end; end else begin if FState = bsDown then begin if FDown and (FGroupIndex <> 0) then FState := bsExclusive else FState := bsUp; Redraw (True); end; end; { Stop tracking } MouseLeft; if not Popup then begin Form := GetParentForm(Self); if Form <> nil then Form.ModalResult := ModalResult; inherited; end else begin if not FDropdownCombo then inherited; { It must release its capture before displaying the popup menu since this control uses csCaptureMouse. If it doesn't, the VCL seems to get confused and think the mouse is still captured even after the popup menu is displayed, causing mouse problems after the menu is dismissed. } MouseCapture := False; ShowMenu := Assigned(FDropdownMenu); RemoveClicks := True; if Assigned(FOnDropdown) then FOnDropdown (Self, ShowMenu, RemoveClicks); try if Assigned(FDropdownMenu) and ShowMenu then begin SaveAlignment := DropdownMenu.Alignment; {$IFDEF TB97D4} SaveTrackButton := DropdownMenu.TrackButton; {$ENDIF} try DropdownMenu.Alignment := paLeft; PopupPt := Point(0, Height); if Assigned(GetToolbarDockPosProc) then begin DockPos := GetToolbarDockPosProc(Parent); { Drop out right or left side } case DockPos of gtpLeft: PopupPt := Point(Width, 0); gtpRight: begin PopupPt := Point(0, 0); DropdownMenu.Alignment := paRight; end; end; end; PopupPt := ClientToScreen(PopupPt); with DropdownMenu do begin PopupComponent := Self; { In Delphi versions prior to 4 it avoids using the Popup method of TPopupMenu because it always uses the "track right button" flag (which disallowed the "click and drag" selecting motion many people are accustomed to). Delphi 4 has a TrackButton property to control the tracking button, so it can use the Popup method. } {$IFNDEF TB97D4} if (ClassType = TPopupMenu) and Assigned(DropdownList) then begin if Assigned(OnPopup) then OnPopup (DropdownMenu); TrackPopupMenu (Handle, AlignFlags[Alignment] or ButtonFlags[NewStyleControls], PopupPt.X, PopupPt.Y, 0, DropdownList.Window, nil) end else begin {$ELSE} if NewStyleControls then TrackButton := tbLeftButton else TrackButton := tbRightButton; {$ENDIF} Popup (PopupPt.X, PopupPt.Y); {$IFNDEF TB97D4} end; {$ENDIF} end; finally DropdownMenu.Alignment := SaveAlignment; {$IFDEF TB97D4} DropdownMenu.TrackButton := SaveTrackButton; {$ENDIF} end; end; finally if RemoveClicks then begin { To prevent a mouse click from redisplaying the menu, filter all mouse up/down messages, and repost the ones that don't need removing. This is sort of bulky, but it's the only way I could find that works perfectly and like Office 97. } RepostList := TList.Create; try while PeekMessage(Msg, 0, WM_LBUTTONDOWN, WM_MBUTTONDBLCLK, PM_REMOVE or PM_NOYIELD) do { ^ The WM_LBUTTONDOWN to WM_MBUTTONDBLCLK range encompasses all of the DOWN and DBLCLK messages for the three buttons } with Msg do begin Repost := True; case Message of WM_QUIT: begin { Throw back any WM_QUIT messages } PostQuitMessage (wParam); Break; end; WM_LBUTTONDOWN, WM_LBUTTONDBLCLK, WM_RBUTTONDOWN, WM_RBUTTONDBLCLK, WM_MBUTTONDOWN, WM_MBUTTONDBLCLK: begin P := SmallPointToPoint(TSmallPoint(UInt32(lParam))); Windows.ClientToScreen (hwnd, P); if FindDragTarget(P, True) = Self then Repost := False; end; end; if Repost then begin RepostList.Add (AllocMem(SizeOf(TMsg))); PMsg(RepostList.Last)^ := Msg; end; end; finally for I := 0 to RepostList.Count-1 do begin with PMsg(RepostList[I])^ do PostMessage (hwnd, message, wParam, lParam); FreeMem (RepostList[I]); end; RepostList.Free; end; end; end; end; finally FInClick := False; if FState = bsDown then FState := bsUp; { Need to check if it's destroying in case the OnClick handler freed the button. If it doesn't check this here, it can sometimes cause an access violation } if not(csDestroying in ComponentState) then begin Redraw (True); MouseLeft; end; end; end; function TToolbarButton97.GetPalette: HPALETTE; begin Result := Glyph.Palette; end; function TToolbarButton97.GetGlyph: TBitmap; begin Result := TButtonGlyph(FGlyph).Glyph; end; procedure TToolbarButton97.SetGlyph (Value: TBitmap); begin TButtonGlyph(FGlyph).Glyph := Value; Redraw (True); end; function TToolbarButton97.GetGlyphMask: TBitmap; begin Result := TButtonGlyph(FGlyph).GlyphMask; end; procedure TToolbarButton97.SetGlyphMask (Value: TBitmap); begin TButtonGlyph(FGlyph).GlyphMask := Value; Redraw (True); end; procedure TToolbarButton97.SetHighlightWhenDown (Value: Boolean); begin if FHighlightWhenDown <> Value then begin FHighlightWhenDown := Value; if Down then Redraw (True); end; end; function TToolbarButton97.GetImageIndex: Integer; begin Result := TButtonGlyph(FGlyph).FImageIndex; end; procedure TToolbarButton97.SetImageIndex (Value: Integer); begin if TButtonGlyph(FGlyph).FImageIndex <> Value then begin TButtonGlyph(FGlyph).FImageIndex := Value; if Assigned(TButtonGlyph(FGlyph).FImageList) then TButtonGlyph(FGlyph).GlyphChanged (nil); end; end; function TToolbarButton97.GetImages: TCustomImageList; begin Result := TButtonGlyph(FGlyph).FImageList; end; procedure TToolbarButton97.SetImages (Value: TCustomImageList); begin with TButtonGlyph(FGlyph) do if FImageList <> Value then begin if FImageList <> nil then FImageList.UnRegisterChanges (FImageChangeLink); FImageList := Value; if FImageList <> nil then begin if FImageChangeLink = nil then begin FImageChangeLink := TChangeLink.Create; FImageChangeLink.OnChange := GlyphChanged; end; FImageList.RegisterChanges (FImageChangeLink); FImageList.FreeNotification (Self); end else begin FImageChangeLink.Free; FImageChangeLink := nil; end; UpdateNumGlyphs; end; end; function TToolbarButton97.GetNumGlyphs: TNumGlyphs97; begin Result := TButtonGlyph(FGlyph).NumGlyphs; end; procedure TToolbarButton97.SetNumGlyphs (Value: TNumGlyphs97); begin if Value < Low(TNumGlyphs97) then Value := Low(TNumGlyphs97) else if Value > High(TNumGlyphs97) then Value := High(TNumGlyphs97); if Value <> TButtonGlyph(FGlyph).NumGlyphs then begin TButtonGlyph(FGlyph).NumGlyphs := Value; Redraw (True); end; end; procedure TToolbarButton97.GlyphChanged(Sender: TObject); begin Redraw (True); end; procedure TToolbarButton97.UpdateExclusive; var I: Integer; Ctl: TControl; begin if (FGroupIndex <> 0) and (Parent <> nil) then with Parent do for I := 0 to ControlCount-1 do begin Ctl := Controls[I]; if (Ctl <> Self) and (Ctl is TToolbarButton97) then with TToolbarButton97(Ctl) do if FGroupIndex = Self.FGroupIndex then begin if Self.Down and FDown then begin FDown := False; FState := bsUp; Redraw (True); end; FAllowAllUp := Self.AllowAllUp; end; end; end; procedure TToolbarButton97.SetDown (Value: Boolean); begin if FGroupIndex = 0 then Value := False; if Value <> FDown then begin if FDown and (not FAllowAllUp) then Exit; FDown := Value; if not Enabled then FState := bsDisabled else begin if Value then FState := bsExclusive else FState := bsUp; end; Redraw (True); if Value then UpdateExclusive; end; end; procedure TToolbarButton97.SetFlat (Value: Boolean); begin if FFlat <> Value then begin FFlat := Value; if FOpaque or not FFlat then ControlStyle := ControlStyle + [csOpaque] else ControlStyle := ControlStyle - [csOpaque]; Redraw (True); end; end; procedure TToolbarButton97.SetGroupIndex (Value: Integer); begin if FGroupIndex <> Value then begin FGroupIndex := Value; UpdateExclusive; end; end; procedure TToolbarButton97.SetLayout (Value: TButtonLayout); begin if FLayout <> Value then begin FLayout := Value; Redraw (True); end; end; procedure TToolbarButton97.SetMargin (Value: Integer); begin if (FMargin <> Value) and (Value >= -1) then begin FMargin := Value; Redraw (True); end; end; procedure TToolbarButton97.SetNoBorder (Value: Boolean); begin if FNoBorder <> Value then begin FNoBorder := Value; Invalidate; end; end; procedure TToolbarButton97.SetOldDisabledStyle (Value: Boolean); begin if FOldDisabledStyle <> Value then begin FOldDisabledStyle := Value; with TButtonGlyph(FGlyph) do begin FOldDisabledStyle := Value; Invalidate; end; Redraw (True); end; end; procedure TToolbarButton97.SetOpaque (Value: Boolean); begin if FOpaque <> Value then begin FOpaque := Value; if FOpaque or not FFlat then ControlStyle := ControlStyle + [csOpaque] else ControlStyle := ControlStyle - [csOpaque]; Invalidate; end; end; procedure TToolbarButton97.Redraw (const Erase: Boolean); var AddedOpaque: Boolean; begin if FOpaque or not FFlat or not Erase then begin { Temporarily add csOpaque to the style. This prevents Invalidate from erasing, which isn't needed when Erase is false. } AddedOpaque := False; if not(csOpaque in ControlStyle) then begin AddedOpaque := True; ControlStyle := ControlStyle + [csOpaque]; end; try Invalidate; finally if AddedOpaque then ControlStyle := ControlStyle - [csOpaque]; end; end else if not(FOpaque or not FFlat) then Invalidate; end; procedure TToolbarButton97.SetSpacing (Value: Integer); begin if Value <> FSpacing then begin FSpacing := Value; Redraw (True); end; end; procedure TToolbarButton97.SetAllowAllUp (Value: Boolean); begin if FAllowAllUp <> Value then begin FAllowAllUp := Value; UpdateExclusive; end; end; procedure TToolbarButton97.SetDropdownMenu (Value: TPopupMenu); var NewUsesDropdown: Boolean; begin if FDropdownMenu <> Value then begin FDropdownMenu := Value; if Assigned(Value) then begin Value.FreeNotification (Self); {$IFNDEF TB97D4} if DropdownList = nil then DropdownList := TDropdownList.Create(nil); DropdownList.AddMenu (Value); {$ENDIF} end; NewUsesDropdown := FDropdownAlways or Assigned(Value); if FUsesDropdown <> NewUsesDropdown then begin FUsesDropdown := NewUsesDropdown; if FDropdownArrow or FDropdownCombo then Redraw (True); end; end; end; procedure TToolbarButton97.SetWordWrap (Value: Boolean); begin if FWordWrap <> Value then begin FWordWrap := Value; Redraw (True); end; end; procedure TToolbarButton97.SetAlignment (Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; Redraw (True); end; end; procedure TToolbarButton97.SetDropdownAlways (Value: Boolean); var NewUsesDropdown: Boolean; begin if FDropdownAlways <> Value then begin FDropdownAlways := Value; NewUsesDropdown := Value or Assigned(FDropdownMenu); if FUsesDropdown <> NewUsesDropdown then begin FUsesDropdown := NewUsesDropdown; if FDropdownArrow or FDropdownCombo then Redraw (True); end; end; end; procedure TToolbarButton97.SetDropdownArrow (Value: Boolean); begin if FDropdownArrow <> Value then begin FDropdownArrow := Value; Redraw (True); end; end; procedure TToolbarButton97.SetDropdownArrowWidth (Value: Integer); var Diff: Integer; begin if Value < 7 then Value := 7; if FDropdownArrowWidth <> Value then begin Diff := Value - FDropdownArrowWidth; FDropdownArrowWidth := Value; if not(csLoading in ComponentState) and FDropdownCombo then Width := Width + Diff; Redraw (True); end; end; procedure TToolbarButton97.SetDropdownCombo (Value: Boolean); var W: Integer; begin if FDropdownCombo <> Value then begin FDropdownCombo := Value; if not(csLoading in ComponentState) then begin if Value then Width := Width + (DropdownArrowWidth + DropdownComboSpace) else begin W := Width - (DropdownArrowWidth + DropdownComboSpace); if W < 1 then W := 1; Width := W; end; end; Redraw (True); end; end; procedure TToolbarButton97.SetDisplayMode (Value: TButtonDisplayMode); begin if FDisplayMode <> Value then begin FDisplayMode := Value; Redraw (True); end; end; function TToolbarButton97.GetCallDormant: Boolean; begin Result := TButtonGlyph(FGlyph).FCallDormant; end; procedure TToolbarButton97.SetCallDormant (Value: Boolean); begin TButtonGlyph(FGlyph).FCallDormant := Value; end; function TToolbarButton97.GetVersion: TToolbar97Version; begin Result := Toolbar97VersionPropText; end; procedure TToolbarButton97.SetVersion (const Value: TToolbar97Version); begin { write method required for the property to show up in Object Inspector } end; {$IFDEF TB97D4} function TToolbarButton97.IsCheckedStored: Boolean; begin Result := (ActionLink = nil) or not TToolbarButton97ActionLink(ActionLink).IsCheckedLinked; end; function TToolbarButton97.IsHelpContextStored: Boolean; begin Result := (ActionLink = nil) or not TToolbarButton97ActionLink(ActionLink).IsHelpContextLinked; end; function TToolbarButton97.IsImageIndexStored: Boolean; begin Result := (ActionLink = nil) or not TToolbarButton97ActionLink(ActionLink).IsImageIndexLinked; end; procedure TToolbarButton97.ActionChange (Sender: TObject; CheckDefaults: Boolean); begin inherited; if Sender is TCustomAction then with TCustomAction(Sender) do begin if not CheckDefaults or (Self.Down = False) then Self.Down := Checked; if not CheckDefaults or (Self.HelpContext = 0) then Self.HelpContext := HelpContext; if not CheckDefaults or (Self.ImageIndex = -1) then Self.ImageIndex := ImageIndex; end; end; function TToolbarButton97.GetActionLinkClass: TControlActionLinkClass; begin Result := TToolbarButton97ActionLink; end; procedure TToolbarButton97.AssignTo (Dest: TPersistent); begin inherited; if Dest is TCustomAction then TCustomAction(Dest).Checked := Self.Down; end; {$ENDIF} procedure TToolbarButton97.WMLButtonDblClk (var Message: TWMLButtonDblClk); begin inherited; if FDown then DblClick; end; procedure TToolbarButton97.CMEnabledChanged (var Message: TMessage); begin if not Enabled then begin FState := bsDisabled; FMouseInControl := False; FMouseIsDown := False; RemoveButtonMouseTimer; Perform (WM_CANCELMODE, 0, 0); end else if FState = bsDisabled then if FDown and (FGroupIndex <> 0) then FState := bsExclusive else FState := bsUp; Redraw (True); end; procedure TToolbarButton97.CMDialogChar (var Message: TCMDialogChar); begin with Message do if IsAccel(CharCode, Caption) and Assigned(Parent) and Parent.CanFocus and Enabled and Visible and (DisplayMode <> dmGlyphOnly) then begin { NOTE: There is a bug in TSpeedButton where accelerator keys are still processed even when the button is not visible. The 'and Visible' corrects it, so TToolbarButton97 doesn't have this problem. } Click; Result := 1; end else inherited; end; procedure TToolbarButton97.CMDialogKey (var Message: TCMDialogKey); begin with Message do if (((CharCode = VK_RETURN) and FDefault) or ((CharCode = VK_ESCAPE) and FCancel)) and (KeyDataToShiftState(Message.KeyData) = []) and Assigned(Parent) and Parent.CanFocus and Enabled and Visible then begin Click; Result := 1; end else inherited; end; procedure TToolbarButton97.CMFontChanged (var Message: TMessage); begin Redraw (True); end; procedure TToolbarButton97.CMTextChanged (var Message: TMessage); begin Redraw (True); end; procedure TToolbarButton97.CMSysColorChange (var Message: TMessage); begin inherited; if Assigned(Pattern) and ((PatternBtnFace <> TColor(GetSysColor(COLOR_BTNFACE))) or (PatternBtnHighlight <> TColor(GetSysColor(COLOR_BTNHIGHLIGHT)))) then begin Pattern.Free; Pattern := nil; end; with TButtonGlyph(FGlyph) do begin Invalidate; CreateButtonGlyph (FState); end; end; procedure TToolbarButton97.MouseEntered; begin if Enabled and not FMouseInControl then begin FMouseInControl := True; if FState = bsUp then FState := bsMouseIn; if FFlat or (NumGlyphs >= 5) then Redraw (FDown or (NumGlyphs >= 5)); if Assigned(FOnMouseEnter) then FOnMouseEnter (Self); end; end; procedure TToolbarButton97.MouseLeft; var OldState: TButtonState97; begin if Enabled and FMouseInControl and not FMouseIsDown then begin FMouseInControl := False; RemoveButtonMouseTimer; OldState := FState; if (FState = bsMouseIn) or (not FInClick and (FState = bsDown)) then begin if FDown and (FGroupIndex <> 0) then FState := bsExclusive else FState := bsUp; end; if FFlat or ((NumGlyphs >= 5) or ((OldState = bsMouseIn) xor (FState <> OldState))) then Redraw (True); if Assigned(FOnMouseExit) then FOnMouseExit (Self); end; end; procedure TToolbarButton97.ButtonMouseTimerHandler (Sender: TObject); var P: TPoint; begin { The button mouse timer is used to periodically check if mouse has left. Normally it receives a CM_MOUSELEAVE, but the VCL does not send a CM_MOUSELEAVE if the mouse is moved quickly from the button to another application's window. For some reason, this problem doesn't seem to occur on Windows NT 4 -- only 95 and 3.x. The timer (which ticks 8 times a second) is only enabled when the application is active and the mouse is over a button, so it uses virtually no processing power. For something interesting to try: If you want to know just how often this is called, try putting a Beep call in here } GetCursorPos (P); if FindDragTarget(P, True) <> Self then MouseLeft; end; { TEdit97 - internal } constructor TEdit97.Create (AOwner: TComponent); begin inherited; AutoSize := False; Ctl3D := False; BorderStyle := bsNone; ControlStyle := ControlStyle - [csFramed]; {fixes a VCL bug with Win 3.x} Height := 19; if Edit97Count = 0 then Register97ControlClass (TEdit97); Inc (Edit97Count); end; destructor TEdit97.Destroy; begin Dec (Edit97Count); if Edit97Count = 0 then Unregister97ControlClass (TEdit97); inherited; end; procedure TEdit97.CMMouseEnter (var Message: TMessage); begin inherited; MouseInControl := True; DrawNCArea (False, 0, 0); end; procedure TEdit97.CMMouseLeave (var Message: TMessage); begin inherited; MouseInControl := False; DrawNCArea (False, 0, 0); end; procedure TEdit97.NewAdjustHeight; var DC: HDC; SaveFont: HFONT; Metrics: TTextMetric; begin DC := GetDC(0); SaveFont := SelectObject(DC, Font.Handle); GetTextMetrics (DC, Metrics); SelectObject (DC, SaveFont); ReleaseDC (0, DC); Height := Metrics.tmHeight + 6; end; procedure TEdit97.Loaded; begin inherited; if not(csDesigning in ComponentState) then NewAdjustHeight; end; procedure TEdit97.CMEnabledChanged (var Message: TMessage); const EnableColors: array[Boolean] of TColor = (clBtnFace, clWindow); begin inherited; Color := EnableColors[Enabled]; { Ensure non-client area is invalidated as well } if HandleAllocated then RedrawWindow (Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE or RDW_ERASE or RDW_NOCHILDREN); end; procedure TEdit97.CMFontChanged (var Message: TMessage); begin inherited; if not((csDesigning in ComponentState) and (csLoading in ComponentState)) then NewAdjustHeight; end; procedure TEdit97.WMSetFocus (var Message: TWMSetFocus); begin inherited; if not(csDesigning in ComponentState) then DrawNCArea (False, 0, 0); end; procedure TEdit97.WMKillFocus (var Message: TWMKillFocus); begin inherited; if not(csDesigning in ComponentState) then DrawNCArea (False, 0, 0); end; procedure TEdit97.WMNCCalcSize (var Message: TWMNCCalcSize); begin InflateRect (Message.CalcSize_Params^.rgrc[0], -3, -3); end; procedure TEdit97.WMNCPaint (var Message: TMessage); begin DrawNCArea (False, 0, HRGN(Message.WParam)); end; procedure TEdit97.DrawNCArea (const DrawToDC: Boolean; const ADC: HDC; const Clip: HRGN); var DC: HDC; R: TRect; BtnFaceBrush, WindowBrush: HBRUSH; begin if not DrawToDC then DC := GetWindowDC(Handle) else DC := ADC; try { Use update region } if not DrawToDC then SelectNCUpdateRgn (Handle, DC, Clip); { This works around WM_NCPAINT problem described at top of source code } {no! R := Rect(0, 0, Width, Height);} GetWindowRect (Handle, R); OffsetRect (R, -R.Left, -R.Top); BtnFaceBrush := GetSysColorBrush(COLOR_BTNFACE); WindowBrush := GetSysColorBrush(COLOR_WINDOW); if ((csDesigning in ComponentState) and Enabled) or (not(csDesigning in ComponentState) and (Focused or (MouseInControl and not ControlIs97Control(Screen.ActiveControl)))) then begin DrawEdge (DC, R, BDR_SUNKENOUTER, BF_RECT or BF_ADJUST); with R do begin FillRect (DC, Rect(Left, Top, Left+1, Bottom-1), BtnFaceBrush); FillRect (DC, Rect(Left, Top, Right-1, Top+1), BtnFaceBrush); end; DrawEdge (DC, R, BDR_SUNKENINNER, BF_BOTTOMRIGHT); InflateRect (R, -1, -1); FrameRect (DC, R, WindowBrush); end else begin FrameRect (DC, R, BtnFaceBrush); InflateRect (R, -1, -1); FrameRect (DC, R, BtnFaceBrush); InflateRect (R, -1, -1); FrameRect (DC, R, WindowBrush); end; finally if not DrawToDC then ReleaseDC (Handle, DC); end; end; procedure EditNCPaintProc (Wnd: HWND; DC: HDC; AppData: Longint); begin TEdit97(AppData).DrawNCArea (True, DC, 0); end; procedure TEdit97.WMPrint (var Message: TMessage); begin HandleWMPrint (Handle, Message, EditNCPaintProc, Longint(Self)); end; procedure TEdit97.WMPrintClient (var Message: TMessage); begin HandleWMPrintClient (Self, Message); end; function TEdit97.GetVersion: TToolbar97Version; begin Result := Toolbar97VersionPropText; end; procedure TEdit97.SetVersion (const Value: TToolbar97Version); begin { write method required for the property to show up in Object Inspector } end; {$IFNDEF TB97D4} initialization finalization DropdownList.Free; {$ENDIF} end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmTrackBar Purpose : An enhanced Trackbar allowing for multiple new styles Date : 12-01-1998 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmTrackBar; interface {$I CompilerDefines.INC} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, extctrls, rmLibrary; type TMarkPosition = (mpTopLeft, mpBottomRight, mpNone); TTrackOrientation = (toHorizontal, toVertical); TTrackPosition = (tpCenter, tpTopLeft, tpBottomRight); TrmTrackBar = class(TCustomControl) private { Private declarations } fTrackOrientation : TTrackOrientation; fTrackSize : integer; fTrackColor : TColor; fMinValue : integer; fMaxValue : integer; fThumbPosition : integer; fTrackPosition : TTrackPosition; fPageSize : integer; fMarkFrequency : integer; fMarkSpacing : integer; fMarkPosition : TMarkPosition; fThumb : tbitmap; fChanged : TNotifyEvent; fMarkData : TStrings; fmouseon : boolean; fShowFocus: boolean; fShowMarks: boolean; function ptinthumb(x,y:integer):boolean; function ptintrack(x,y:integer):boolean; procedure SetTrackOrientation(value:TTrackOrientation); procedure SetTrackSize(value:integer); procedure SetTrackColor(value:TColor); procedure SetMinValue(value:integer); procedure SetMaxValue(value:integer); procedure SetThumbPos(value:integer); procedure SetTrackPosition(value:TTrackPosition); procedure SetThumb(value:tbitmap); procedure SetMarkData(value:TStrings); procedure setmarkfrequency(value:integer); procedure SetMarkPosition(value:TMarkPosition); procedure SetPagesize(value:integer); procedure SetMarkSpacing(value:integer); function GetTrackRect:TRect; function PointPosition(x,y:integer):integer; procedure wmSetFocus(var msg:TWMSetFocus); message wm_setfocus; procedure wmKillFocus(var msg:TWMKillFocus); message wm_killfocus; procedure wmEraseBkGnd(var msg:TWMEraseBkgnd); message wm_erasebkgnd; procedure wmGetDLGCode(var msg:TWMGetDLGCode); message wm_GetDLGCode; procedure wmMouseActivate(var msg:TWMMouseActivate); message wm_MouseActivate; procedure SetshowFocus(const Value: boolean); procedure SetShowMarks(const Value: boolean); protected { Protected declarations } procedure paint; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public { Public declarations } constructor create(aowner:TComponent); override; destructor destroy; override; published { Published declarations } property Align; property Color; property Font; property ShowFocus : boolean read fShowFocus write SetshowFocus default true; property MarkFrequency:integer read fmarkfrequency write setmarkfrequency default 1; property MarkPosition : TMarkPosition read fMarkPosition write SetMarkPosition default mpTopLeft; property MarkSpacing : integer read fmarkspacing write setmarkspacing default 2; property MaxValue : integer read fMaxValue write SetMaxValue default 10; property MinValue : integer read fminvalue write SetMinValue default 0; property PageSize:integer read fpagesize write setpagesize default 2; property ShowMarks : boolean read fShowMarks write SetShowMarks default true; property TabStop; property TabOrder; property Thumb : tbitmap read fthumb write SetThumb stored true; property ThumbPosition : integer read fThumbPosition write SetThumbPos default 0; property TrackColor : TColor read ftrackcolor write SetTrackColor default clWindow; property TrackOrientation : TTrackOrientation read fTrackOrientation write SetTrackOrientation default toHorizontal; property TrackPosition : TTrackPosition read ftrackposition write SetTrackPosition default tpcenter; property TrackSize : integer read ftracksize write SetTrackSize default 8; property OnChange:TNotifyEvent read fchanged write fchanged; property MarkData : TStrings read fMarkData write SetMarkData stored true; end; implementation { TrmTrackBar } {$R rmTrackBar.res} constructor TrmTrackBar.create(aowner:TComponent); begin inherited create(aowner); fmouseon := false; ControlStyle := [csCaptureMouse,csClickEvents]; fThumb := tbitmap.create; fMarkData := TStringList.Create; height := 50; width := 150; fmarkspacing := 2; fTrackOrientation := toHorizontal; fMarkPosition := mpTopLeft; ftracksize := 8; ftrackcolor := clwindow; ftrackposition := tpcenter; fminvalue := 0; fmaxvalue := 10; fThumbPosition := 0; fPageSize := 1; tabstop := true; fmarkfrequency := 1; fShowFocus := true; fShowMarks := true; Thumb := nil; end; destructor TrmTrackBar.destroy; begin fMarkData.free; fThumb.free; inherited; end; procedure TrmTrackBar.Paint; var wr, wRect : TRect; hcenter, vcenter : integer; loop : integer; xstart, xend, xadj, xwidth, ystart, yend, yadj, yheight, calcstep : single; wmaxvalue, wminvalue, wmarkfrequency, wTextMeasure : integer; newimage : tbitmap; xspacing, yspacing : integer; wText : string; begin newimage := tbitmap.create; try newimage.height := height; newimage.width := width; if fmarkdata.count > 0 then begin wmaxvalue := fmarkdata.count-1; wminvalue := 0; wmarkfrequency := 1; end else begin wmaxvalue := fmaxvalue; wminvalue := fminvalue; wmarkfrequency := fmarkfrequency; end; calcstep := (wmaxvalue - wminvalue) / wmarkfrequency; newimage.canvas.font := font; newimage.canvas.brush.color := color; newimage.canvas.fillrect(GetClientRect); wr := GetTrackRect; ystart := 0; xstart := 0; xwidth := 0; yheight := 0; hcenter := 0; vcenter := 0; if fTrackOrientation = tovertical then begin if fmarkposition = mptopleft then begin xstart := wr.Left-3; xwidth := -5; end else if fmarkposition = mpbottomright then begin xstart := wr.Right+2; xwidth := 5; end; xend := xstart; xadj := 0; ystart :=wr.top + 2; yend := wr.bottom - 2; yadj := (yend - ystart) / calcstep; yheight := 0; hcenter := wr.left + ((wr.right-wr.left) shr 1); if (fThumbPosition >= wminvalue) and (fThumbPosition <= wmaxvalue) then vcenter := round( ystart + round ( (yend-ystart) * ( (fThumbPosition - wminvalue) / (wmaxvalue - wminvalue) ) ) ) else if (fThumbPosition < wminvalue) then vcenter := round(ystart) else if (fThumbPosition > wmaxvalue) then vcenter := round(yend); end else begin if fmarkposition = mptopleft then begin ystart := wr.Top - 3; yheight := 5; end else if fmarkposition = mpbottomright then begin ystart := wr.Bottom + 2; yheight := -5; end; yend := ystart; yadj := 0; xstart := wr.Left+2; xend := wr.right-2; xadj := (xend - xstart) / calcstep; xwidth := 0; vcenter := wr.top + ((wr.bottom-wr.top) shr 1); if (fThumbPosition >= wminvalue) and (fThumbPosition <= wmaxvalue) then hcenter := round( xstart + round ( (xend-xstart) * ( (fThumbPosition - wminvalue) / (wmaxvalue - wminvalue) ) ) ) else if (fThumbPosition > wmaxvalue) then hcenter := round(xend) else if (fThumbPosition < wminvalue) then hcenter := round(xstart); end; if fmarkposition <> mpNone then begin if fmarkdata.count > 0 then begin if fTrackOrientation = tovertical then begin xspacing := fmarkspacing; yspacing := -(newimage.canvas.TextHeight('X') shr 1); end else begin if fMarkPosition = mpTopLeft then yStart := yStart - newimage.Canvas.TextHeight('X'); xspacing := -(newimage.canvas.TextHeight('X') shr 1); yspacing := fmarkspacing; end; loop := 0; while loop < fmarkdata.count do begin wText := fmarkdata[loop]; if fTrackOrientation = toHorizontal then begin { Case MarkRotationAngle of ra0, ra180 : begin } wTextMeasure := (newimage.Canvas.TextWidth(wText) div 2); wRect.Left := (round(xstart) + xspacing) - wTextMeasure; wRect.Right := (round(xstart) + xspacing) + wTextMeasure; if fMarkPosition = mpTopLeft then begin wRect.Top := round(ystart) - yspacing; wRect.Bottom := round(ystart) - yspacing + newimage.Canvas.TextHeight(wText); end else begin wRect.Top := round(ystart) + yspacing; wRect.Bottom := round(ystart) + yspacing + newimage.Canvas.TextHeight(wText); end { end; ra90, ra270 : begin wTextMeasure := newimage.Canvas.TextHeight(wText); wRect.Left := (round(xstart) + xspacing) - wTextMeasure; wRect.Right := (round(xstart) + xspacing) + wTextMeasure; wRect.Top := round(ystart) + yspacing; wRect.Bottom := round(ystart) + yspacing + newimage.Canvas.TextWidth(wText); end; end;} end else begin { Case MarkRotationAngle of ra0, ra180 : begin} wTextMeasure := (newimage.Canvas.TextHeight(wText) div 2); wRect.Top := round(ystart) + yspacing + wTextMeasure; wRect.Bottom := round(ystart) + yspacing + wTextMeasure; if MarkPosition = mpTopLeft then begin wRect.Left := (round(xstart) - xspacing) - newimage.Canvas.TextWidth(wText); wRect.Right := (round(xstart) - xspacing); end else begin wRect.Left := (round(xstart) + xspacing) ; wRect.Right := (round(xstart) + xspacing) + newimage.Canvas.TextWidth(wText); end; { end; ra90, ra270 : begin wTextMeasure := newimage.Canvas.TextHeight(wText); wRect.Left := (round(xstart) + xspacing) - wTextMeasure; wRect.Right := (round(xstart) + xspacing) + wTextMeasure; wRect.Top := round(ystart) + yspacing; wRect.Bottom := round(ystart) + yspacing + newimage.Canvas.TextWidth(wText); end; end;} end; // RotateText(wText,frotationangle,newimage.canvas,wRect); RotateText(newimage.canvas,wText,wRect,0); xstart := xstart+xadj; ystart := ystart+yadj; inc(loop); end; end else begin if fTrackOrientation = toHorizontal then begin ystart := yStart - yheight; yend := yend - yheight; end; newimage.canvas.Pen.color := clbtntext; loop := 0; while loop < round(calcstep) do begin newimage.canvas.moveto(round(xstart), round(ystart)); newimage.canvas.lineto(round(xstart+xwidth), round(ystart+yheight)); xstart := xstart+xadj; ystart := ystart+yadj; inc(loop); end; newimage.canvas.moveto(round(xend), round(yend)); newimage.canvas.lineto(round(xend+xwidth), round(yend+yheight)); end; end; frame3d(newimage.canvas,wr,clBtnShadow,clBtnhighlight,1); frame3d(newimage.canvas,wr,cl3ddkshadow,cl3dlight,1); newimage.canvas.brush.color := ftrackColor; newimage.canvas.FillRect(wr); fThumb.Transparent := true; if not fThumb.Empty then begin newimage.canvas.draw(hcenter-(fThumb.Width shr 1),vcenter-(fThumb.height shr 1),fThumb); end; canvas.Draw(0,0,newimage); if Focused and fShowFocus then canvas.drawfocusrect(GetClientRect); finally newimage.free; end; end; procedure TrmTrackBar.SetTrackOrientation(value:TTrackOrientation); begin if value <> fTrackOrientation then begin fTrackOrientation := value; if not Thumb.transparent then Thumb := nil; end; invalidate; end; procedure TrmTrackBar.SetMarkPosition(value:TMarkPosition); begin if value <> fMarkPosition then begin fMarkPosition := value; invalidate; end; end; procedure TrmTrackBar.SetTrackSize(value:integer); begin if value <> ftracksize then begin ftracksize := value; invalidate; end; end; procedure TrmTrackBar.SetTrackColor(value:TColor); begin if value <> ftrackcolor then begin ftrackcolor := value; invalidate; end; end; procedure TrmTrackBar.SetMinValue(value:integer); begin if fmarkdata.count > 0 then exit; if value >= fmaxvalue then exit; if value <> fminvalue then begin fminvalue := value; invalidate; end; end; procedure TrmTrackBar.SetMaxValue(value:integer); begin if fmarkdata.count > 0 then exit; if value <= fminvalue then exit; if value <> fmaxvalue then begin fmaxvalue := value; invalidate; end; end; procedure TrmTrackBar.SetThumbPos(value:integer); begin if fmarkdata.count > 0 then begin if value < 0 then value := 0; if value >= fmarkdata.count then value := fmarkdata.count-1; end else begin if value < fminvalue then value := fminvalue; if value > fmaxvalue then value := fmaxvalue; end; if value <> fThumbPosition then begin fThumbPosition := value; invalidate; if assigned(fchanged) then fchanged(self); end; end; procedure TrmTrackBar.SetMarkSpacing(value:integer); begin if value <> fmarkspacing then begin fmarkspacing := value; invalidate; end; end; procedure TrmTrackBar.SetTrackPosition(value:TTrackPosition); begin if value <> ftrackposition then begin ftrackposition := value; invalidate; end; end; procedure TrmTrackBar.SetPageSize(value:integer); begin if value <= 0 then exit; if value <> fPageSize then begin fPageSize := value; invalidate; end; end; procedure TrmTrackBar.SetThumb(value:tbitmap); begin if value = nil then fThumb.LoadFromResourceName(HInstance, 'RMTRACKBAR') else fThumb.assign(value); fThumb.Transparent := true; invalidate; end; procedure TrmTrackBar.SetMarkData(value:TStrings); begin if value.Count = 1 then begin showmessage('More than one point is required'); exit; end; fmarkdata.assign(value); invalidate; end; procedure TrmTrackBar.setmarkfrequency(value:integer); begin if value <= 0 then exit; if fmarkdata.count > 0 then exit; if value <> fmarkfrequency then begin fmarkfrequency := value; invalidate; end; end; function TrmTrackBar.GetTrackRect:TRect; var wr : TRect; TCenter : integer; fVerticalIndent, fHorizontalIndent : integer; begin fVerticalIndent := GreaterThanInt(Thumb.Height, Canvas.TextHeight('X')); fHorizontalIndent := GreaterThanInt(Thumb.Width, Canvas.TextWidth('X')); wr := Rect(0,0,width,height); if fTrackOrientation = tovertical then begin wr.top := wr.top + fVerticalindent; wr.bottom := wr.bottom - fVerticalIndent; case ftrackposition of tpcenter: begin tcenter := (wr.left + ((wr.right-wr.left) shr 1)); wr.left := tcenter - (ftracksize shr 1); wr.right := tcenter + (ftracksize shr 1); end; tpTopLeft: begin wr.left := wr.left + fHorizontalIndent; wr.right := wr.left + ftracksize; end; tpBottomRight: begin wr.right := wr.right - fHorizontalIndent; wr.left := wr.right - ftracksize; end; end; end else begin wr.left := wr.left + fHorizontalIndent; wr.right := wr.Right - fHorizontalIndent; case ftrackposition of tpcenter: begin tcenter := (wr.top + ((wr.bottom-wr.top) shr 1)); wr.top := tcenter - (ftracksize shr 1); wr.bottom := tcenter + (ftracksize shr 1); end; tpTopLeft: begin wr.top := wr.top + fVerticalIndent; wr.bottom := wr.top + ftracksize; end; tpBottomRight: begin wr.bottom := wr.bottom - fVerticalIndent; wr.top := wr.bottom - ftracksize; end; end; end; result := wr; end; procedure TrmTrackBar.KeyDown(var Key: Word; Shift: TShiftState); begin case key of vk_down :if fTrackOrientation = tovertical then ThumbPosition := ThumbPosition + 1; vk_up :if fTrackOrientation = tovertical then ThumbPosition := ThumbPosition - 1; vk_right :if fTrackOrientation = tohorizontal then ThumbPosition := ThumbPosition + 1; vk_left :if fTrackOrientation = tohorizontal then ThumbPosition := ThumbPosition - 1; vk_next :ThumbPosition := ThumbPosition + fpagesize; vk_prior :ThumbPosition := ThumbPosition - fpagesize; vk_Home :begin if fMarkData.count > 0 then ThumbPosition := 0 else ThumbPosition := fminvalue; end; vk_end :begin if fMarkData.count > 0 then ThumbPosition := fmarkdata.count-1 else ThumbPosition := fmaxvalue; end; end; end; procedure TrmTrackBar.wmSetFocus(var msg:TWMSetFocus); begin msg.result := 0; invalidate; end; procedure TrmTrackBar.wmKillFocus(var msg:TWMKillFocus); begin msg.result := 0; invalidate; end; procedure TrmTrackBar.wmEraseBkGnd(var msg:TWMEraseBkGnd); begin msg.result := 1; end; procedure TrmTrackBar.wmGetDLGCode(var msg:TWMGetDLGCode); begin inherited; msg.Result := msg.Result or DLGC_WANTARROWS; end; procedure TrmTrackBar.wmMouseActivate(var msg:TWMMouseActivate); begin inherited; msg.Result := msg.result or MA_ACTIVATE; if not (csdesigning in componentstate) then setfocus; end; procedure TrmTrackBar.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if (csLButtonDown in controlstate) and (fmouseon) then thumbposition := pointposition(x,y); end; procedure TrmTrackBar.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var mousepos : integer; begin inherited; if button = mbleft then if ptinThumb(x,y) then begin thumbposition := pointposition(x,y); fmouseon := true; end else if ptinTrack(x,y) then begin mousepos := pointposition(x,y); if thumbposition > mousepos then thumbposition := thumbposition - fpagesize else thumbposition := thumbposition + fpagesize; end; end; procedure TrmTrackBar.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; fmouseon := false; end; function TrmTrackBar.PointPosition(x,y:integer):integer; var wr : TRect; wmaxvalue, wminvalue: integer; calcpos : integer; pstart, pend : integer; begin if fmarkdata.count > 0 then begin wmaxvalue := fmarkdata.count-1; wminvalue := 0; end else begin wmaxvalue := fmaxvalue; wminvalue := fminvalue; end; wr := GetTrackRect; if fTrackOrientation = tovertical then begin pstart :=wr.top + 2; pend := wr.bottom - 2; calcpos := round((((y-pstart)/(pend-pstart))*(wmaxvalue - wminvalue)))+wminvalue; end else begin pstart := wr.Left+2; pend := wr.right-2; calcpos := round((((x-pstart)/(pend-pstart))*(wmaxvalue - wminvalue)))+wminvalue; end; result := calcpos; end; function TrmTrackBar.ptinthumb(x,y:integer):boolean; var wr : TRect; hcenter, vcenter : integer; xstart, xend, ystart, yend : single; wmaxvalue, wminvalue : integer; begin if fmarkdata.count > 0 then begin wmaxvalue := fmarkdata.count-1; wminvalue := 0; end else begin wmaxvalue := fmaxvalue; wminvalue := fminvalue; end; wr := GetTrackRect; hcenter := 0; vcenter := 0; if fTrackOrientation = tovertical then begin ystart :=wr.top + 2; yend := wr.bottom - 2; hcenter := wr.left + ((wr.right-wr.left) shr 1); if (fThumbPosition >= wminvalue) and (fThumbPosition <= wmaxvalue) then vcenter := round( ystart + round ( (yend-ystart) * ( (fThumbPosition - wminvalue) / (wmaxvalue - wminvalue) ) ) ) else if (fThumbPosition < wminvalue) then vcenter := round(ystart) else if (fThumbPosition > wmaxvalue) then vcenter := round(yend); end else begin xstart := wr.Left+2; xend := wr.right-2; vcenter := wr.top + ((wr.bottom-wr.top) shr 1); if (fThumbPosition >= wminvalue) and (fThumbPosition <= wmaxvalue) then hcenter := round( xstart + round ( (xend-xstart) * ( (fThumbPosition - wminvalue) / (wmaxvalue - wminvalue) ) ) ) else if (fThumbPosition > wmaxvalue) then hcenter := round(xend) else if (fThumbPosition < wminvalue) then hcenter := round(xstart); end; wr.top := vcenter-round(fThumb.height / 2); wr.left := hcenter-round(fThumb.Width / 2); wr.bottom := wr.top+fThumb.height; wr.right := wr.left+fThumb.Width; result := ptinrect(wr,point(x,y)); end; function TrmTrackBar.ptintrack(x,y:integer):boolean; begin result := ptinrect(gettrackrect,point(x,y)); end; procedure TrmTrackBar.SetshowFocus(const Value: boolean); begin fShowFocus := Value; Invalidate; end; procedure TrmTrackBar.SetShowMarks(const Value: boolean); begin fShowMarks := Value; Invalidate; end; end.
unit restore; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type Trestorefrm = class(TForm) Label1: TLabel; GroupBox1: TGroupBox; Label2: TLabel; SpeedButton1: TSpeedButton; Label3: TLabel; Path_Edit: TEdit; BitBtn1: TBitBtn; BitBtn2: TBitBtn; OpenDialog1: TOpenDialog; procedure BitBtn2Click(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); function RestoreFile: Boolean; procedure BitBtn1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var restorefrm: Trestorefrm; implementation {$R *.dfm} procedure Trestorefrm.BitBtn2Click(Sender: TObject); begin Hide; end; function TRestorefrm.RestoreFile: Boolean; var ExePath: string; begin ExePath := ExtractFilePath(Application.ExeName); if Path_Edit.Text = '' then begin Application.MessageBox('选择恢复路径及文件名!', '提示', Mb_ok or Mb_IconWarning); Exit; end; if UpperCase(ExtractFileExt(Path_Edit.Text)) <> '.JXC' then begin Application.MessageBox('请选择正确的备份文件!', '提示', Mb_ok or Mb_IconWarning); Exit; end; if Application.MessageBox('恢复数据将导致现在的数据文件被覆盖,你确认吗?', '提示', Mb_YesNo or Mb_IconQuestion) = IdYes then begin try CopyFile(Pchar(Path_Edit.Text), Pchar(ExePath + 'mdb\' + 'JXCGL.mdb'), False); Result := True; Application.MessageBox('恢复成功,请重新启动本软件!', '提示', Mb_ok or Mb_Iconinformation); Application.Terminate; except Result := False; Application.MessageBox('恢复失败!', '提示', Mb_ok or Mb_Iconerror); end; end; end; procedure Trestorefrm.SpeedButton1Click(Sender: TObject); begin if OpenDialog1.Execute then begin Path_Edit.Text := OpenDialog1.FileName; end; end; procedure Trestorefrm.BitBtn1Click(Sender: TObject); begin RestoreFile; end; end.