text
stringlengths
14
6.51M
{ 14/02/2007 08:39:25 (GMT+0:00) > [Akadamia] checked in } { 14/02/2007 08:39:10 (GMT+0:00) > [Akadamia] checked out /} { 12/02/2007 10:18:00 (GMT+0:00) > [Akadamia] checked in } { 08/02/2007 14:10:47 (GMT+0:00) > [Akadamia] checked in } {----------------------------------------------------------------------------- Unit Name: WSU Author: ken.adam Date: 15-Jan-2007 Purpose: Translation of Weather Station example to Delphi Requests weather data from the nearest weather station to the user aircraft, every 10 seconds History: -----------------------------------------------------------------------------} unit WSU; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls, ActnList, ComCtrls, SimConnect, StdActns; const // Define a user message for message driven version of the example WM_USER_SIMCONNECT = WM_USER + 2; type // Use enumerated types to create unique IDs as required TGroupId = (Group6); TInputId = (Input6); TEventID = (EventSimStart); TDataDefineId = (DefinitionLla); TDataRequestId = (RequestLla, RequestWeather); PStruct7 = ^TStruct7; TStruct7 = record Altitude: double; Latitude: double; Longitude: double; end; // The form TSetDataForm = class(TForm) StatusBar: TStatusBar; ActionManager: TActionManager; ActionToolBar: TActionToolBar; Images: TImageList; Memo: TMemo; StartPoll: TAction; FileExit: TFileExit; StartEvent: TAction; procedure StartPollExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure SimConnectMessage(var Message: TMessage); message WM_USER_SIMCONNECT; procedure StartEventExecute(Sender: TObject); private { Private declarations } RxCount: integer; // Count of Rx messages Quit: boolean; // True when signalled to quit hSimConnect: THandle; // Handle for the SimConection public { Public declarations } procedure DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext: Pointer); end; var SetDataForm: TSetDataForm; implementation resourcestring StrRx6d = 'Rx: %6d'; {$R *.dfm} {----------------------------------------------------------------------------- Procedure: MyDispatchProc Wraps the call to the form method in a simple StdCall procedure Author: ken.adam Date: 11-Jan-2007 Arguments: pData: PSimConnectRecv cbData: DWORD pContext: Pointer -----------------------------------------------------------------------------} procedure MyDispatchProc(pData: PSimConnectRecv; cbData: DWORD; pContext: Pointer); stdcall; begin SetDataForm.DispatchHandler(pData, cbData, pContext); end; {----------------------------------------------------------------------------- Procedure: DispatchHandler Handle the Dispatched callbacks in a method of the form. Note that this is used by both methods of handling the interface. Author: ken.adam Date: 11-Jan-2007 Arguments: pData: PSimConnectRecv cbData: DWORD pContext: Pointer -----------------------------------------------------------------------------} procedure TSetDataForm.DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext: Pointer); var hr: HRESULT; Evt: PSimconnectRecvEvent; OpenData: PSimConnectRecvOpen; pObjData: PSimConnectRecvSimObjectData; ps: PStruct7; pszMetar: PChar; pWxData: PSimConnectRecvWeatherObservation; begin // Maintain a display of the message count Inc(RxCount); StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]); // Only keep the last 200 lines in the Memo while Memo.Lines.Count > 200 do Memo.Lines.Delete(0); // Handle the various types of message case TSimConnectRecvId(pData^.dwID) of SIMCONNECT_RECV_ID_OPEN: begin StatusBar.Panels[0].Text := 'Opened'; OpenData := PSimConnectRecvOpen(pData); with OpenData^ do begin Memo.Lines.Add(''); Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', [szApplicationName, dwApplicationVersionMajor, dwApplicationVersionMinor, dwApplicationBuildMajor, dwApplicationBuildMinor])); Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', ['SimConnect', dwSimConnectVersionMajor, dwSimConnectVersionMinor, dwSimConnectBuildMajor, dwSimConnectBuildMinor])); Memo.Lines.Add(''); end; end; SIMCONNECT_RECV_ID_EVENT: begin evt := PSimconnectRecvEvent(pData); case TEventId(evt^.uEventID) of EventSimStart: begin // Start requesting lat/lon data every 10 seconds hr := SimConnect_RequestDataOnSimObject(hSimConnect, Ord(RequestLla), Ord(DefinitionLla), SIMCONNECT_OBJECT_ID_USER, SIMCONNECT_PERIOD_SECOND, 0, 0, 10, 0); end; end; end; SIMCONNECT_RECV_ID_SIMOBJECT_DATA: begin pObjData := PSimConnectRecvSimObjectData(pData); Memo.Lines.Add('Object data received'); case TDataRequestId(pObjData^.dwRequestID) of RequestLla: begin pS := PStruct7(@pObjData^.dwData); Memo.Lines.Add(Format('Lat=%f Lon=%f IndAlt=%f', [pS^.latitude, pS^.longitude, pS^.altitude])); // Now request the weather data - this will also be requested every 10 seconds hr := SimConnect_WeatherRequestObservationAtNearestStation( hSimConnect, Ord(RequestWeather), pS^.latitude, pS^.longitude); end; end; end; SIMCONNECT_RECV_ID_WEATHER_OBSERVATION: begin pWxData := PSimConnectRecvWeatherObservation(pData); pszMetar := pWxData^.szMetar; case TDataRequestId(pWxData^.dwRequestID) of RequestWeather: Memo.Lines.Add(Format('Weather Observation : %s', [pszMetar])); end; end; SIMCONNECT_RECV_ID_QUIT: begin Quit := True; StatusBar.Panels[0].Text := 'FS X Quit'; end else Memo.Lines.Add(Format('Unknown dwID: %d', [pData.dwID])); end; end; {----------------------------------------------------------------------------- Procedure: FormCloseQuery Ensure that we can signal "Quit" to the busy wait loop Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject var CanClose: Boolean Result: None -----------------------------------------------------------------------------} procedure TSetDataForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin Quit := True; CanClose := True; end; {----------------------------------------------------------------------------- Procedure: FormCreate We are using run-time dynamic loading of SimConnect.dll, so that the program will execute and fail gracefully if the DLL does not exist. Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject Result: None -----------------------------------------------------------------------------} procedure TSetDataForm.FormCreate(Sender: TObject); begin if InitSimConnect then StatusBar.Panels[2].Text := 'SimConnect.dll Loaded' else begin StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND'; StartPoll.Enabled := False; StartEvent.Enabled := False; end; Quit := False; hSimConnect := 0; StatusBar.Panels[0].Text := 'Not Connected'; RxCount := 0; StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]); end; {----------------------------------------------------------------------------- Procedure: SimConnectMessage This uses CallDispatch, but could probably avoid the callback and use SimConnect_GetNextDispatch instead. Author: ken.adam Date: 11-Jan-2007 Arguments: var Message: TMessage -----------------------------------------------------------------------------} procedure TSetDataForm.SimConnectMessage(var Message: TMessage); begin SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil); end; {----------------------------------------------------------------------------- Procedure: StartEventExecute Opens the connection for Event driven handling. If successful sets up the data requests and hooks the system event "SimStart". Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject -----------------------------------------------------------------------------} procedure TSetDataForm.StartEventExecute(Sender: TObject); var hr: HRESULT; begin if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', Handle, WM_USER_SIMCONNECT, 0, 0))) then begin StatusBar.Panels[0].Text := 'Connected'; // Set up the data definition, note this matches the order in Struct_7 hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionLla), 'Indicated Altitude', 'feet'); hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionLla), 'Plane Latitude', 'degrees'); hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionLla), 'Plane Longitude', 'degrees'); // Request a flight loaded event hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart), 'SimStart'); StartEvent.Enabled := False; StartPoll.Enabled := False; end; end; {----------------------------------------------------------------------------- Procedure: StartPollExecute Opens the connection for Polled access. If successful sets up the data requests and hooks the system event "SimStart", and then loops indefinitely on CallDispatch. Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject -----------------------------------------------------------------------------} procedure TSetDataForm.StartPollExecute(Sender: TObject); var hr: HRESULT; begin if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', 0, 0, 0, 0))) then begin StatusBar.Panels[0].Text := 'Connected'; // Set up the data definition, note this matches the order in Struct_7 hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionLla), 'Indicated Altitude', 'feet'); hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionLla), 'Plane Latitude', 'degrees'); hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionLla), 'Plane Longitude', 'degrees'); // Request a flight loaded event hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart), 'SimStart'); StartEvent.Enabled := False; StartPoll.Enabled := False; while not Quit do begin SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil); Application.ProcessMessages; Sleep(1); end; hr := SimConnect_Close(hSimConnect); end; end; end.
unit caMath; {$INCLUDE ca.inc} interface uses // Standard Delphi units Classes, Sysutils, // ca units caClasses; type //--------------------------------------------------------------------------- // IcaValidNum //--------------------------------------------------------------------------- IcaValidNumType = (vtInteger, vtFloat); IcaValidNum = interface ['{EF66F544-E5E5-438F-9C4B-5140E94AB183}'] function GetIsValid: Boolean; function GetNumType: IcaValidNumType; function GetNumString: String; procedure SetNumType(const Value: IcaValidNumType); procedure SetNumString(const Value: String); property IsValid: Boolean read GetIsValid; property NumType: IcaValidNumType read GetNumType write SetNumType; property NumString: String read GetNumString write SetNumString; end; //--------------------------------------------------------------------------- // TcaValidNum //--------------------------------------------------------------------------- TcaValidNum = class(TInterfacedObject, IcaValidNum) private FIsValid: Boolean; FNumString: String; FNumType: IcaValidNumType; FValidChars: set of Char; FValidated: Boolean; function GetIsValid: Boolean; function GetNumString: String; function GetNumType: IcaValidNumType; procedure SetNumString(const Value: String); procedure SetNumType(const Value: IcaValidNumType); procedure UpdateValidChars; public constructor Create(ANumType: IcaValidNumType); property IsValid: Boolean read GetIsValid; property NumType: IcaValidNumType read GetNumType write SetNumType; property NumString: String read GetNumString write SetNumString; end; implementation //--------------------------------------------------------------------------- // TcaValidNum //--------------------------------------------------------------------------- constructor TcaValidNum.Create(ANumType: IcaValidNumType); begin inherited Create; SetNumType(ANumType); end; function TcaValidNum.GetIsValid: Boolean; var Index: Integer; begin if FValidated then Result := FIsValid else begin Result := True; for Index := 1 to Length(FNumString) do if not (FNumString[Index] in FValidChars) then begin FIsValid := False; Result := FIsValid; FValidated := True; Break; end; end; end; function TcaValidNum.GetNumType: IcaValidNumType; begin Result := FNumType; end; function TcaValidNum.GetNumString: String; begin Result := FNumString; end; procedure TcaValidNum.SetNumType(const Value: IcaValidNumType); begin if Value <> FNumType then begin FNumType := Value; UpdateValidChars; end; end; procedure TcaValidNum.SetNumString(const Value: String); begin if Value <> FNumString then begin FNumString := Value; FValidated := False; end; end; procedure TcaValidNum.UpdateValidChars; begin case FNumType of vtInteger: FValidChars := ['+', '-', '0'..'9']; vtFloat: FValidChars := [DecimalSeparator, '+', '-', '0'..'9', 'E', 'e']; end; end; end.
unit IdCoderQuotedPrintable; {9-17-2001 - J. Peter Mugaas made the interpretation of =20 + EOL to mean a hard line break soft line breaks are now ignored. It does not make much sense in plain text. Soft breaks do not indicate the end of paragraphs unlike hard line breaks that do end paragraphs. 3-24-2001 - J. Peter Mugaas Rewrote the Decoder according to a new design. 3-25-2001 - J. Peter Mugaas Rewrote the Encoder according to the new design} interface uses Classes, IdCoder; type TIdDecoderQuotedPrintable = class(TIdDecoder) public procedure DecodeToStream(AIn: string; ADest: TStream); override; end; TIdEncoderQuotedPrintable = class(TIdEncoder) public function Encode(ASrcStream: TStream; const ABytes: integer = MaxInt): string; override; end; implementation uses IdGlobal, SysUtils; { TIdDecoderQuotedPrintable } procedure TIdDecoderQuotedPrintable.DecodeToStream(AIn: string; ADest: TStream); var Buffer, Line, Hex : String; i : Integer; b : Byte; const Numbers = '01234567890ABCDEF'; {Do not Localize} procedure StripEOLChars; var j : Integer; begin for j := 1 to 2 do begin if (Length(Buffer) > 0) and (Pos(Buffer[1],EOL) > 0) then begin Delete(Buffer,1,1); end else begin break; end; end; end; function TrimRightWhiteSpace(const Str : String) : String; var i : integer; LSaveStr : String; begin SetLength(LSaveStr,0); i := Length(Str); while (i > 0) and (Str[i] in [#9,#32]+[#10,#13]) do begin if Str[i] in [#10,#13] then begin Insert(Str[i],LSaveStr,1); end; dec(i); end; result := Copy(Str,1,i) + LSaveStr; end; begin Line := ''; {Do not Localize} { when decoding a Quoted-Printable body, any trailing white space on a line must be deleted, - RFC 1521} Buffer := TrimRightWhiteSpace(AIn); while Length(Buffer) > 0 do begin Line := Line + Fetch(Buffer,'='); {Do not Localize} // process any following hexidecimal represntation if Length(Buffer) > 0 then begin Hex := ''; {Do not Localize} for i := 0 to 1 do begin If IndyPos(UpperCase(Buffer[1]),Numbers) <> 0 then begin Hex := Hex + Copy(Buffer,1,1); Delete(Buffer,1,1); end else begin break; end; end; if (Length(Hex) > 0) then begin b := StrToInt('$'+Hex); {Do not Localize} //if =20 + EOL, this is a hard line break after a space if (b = 32) and (Length(Buffer) > 0) and (Pos(Buffer[1],EOL) > 0) then begin Line := Line + Char(b) + EOL; StripEOLChars; end else begin Line := Line + Char(b); end; end else begin //ignore soft line breaks - StripEOLChars; end; end; end; if Length(Line) > 0 then begin ADest.Write(Line[1],Length(Line)); end; end; { TIdEncoderQuotedPrintable } function TIdEncoderQuotedPrintable.Encode(ASrcStream: TStream; const ABytes: integer): string; //TODO: Change this to be more efficient - dont read the whole data in ahead of time as it may // be quite large const BUF_SIZE = 8192; var i, LDataSize, LBytesRead, LBufSize : Integer; Buffer : Array [1..BUF_SIZE] of char; Line : String; st : TStrings; s : String; Procedure NewLine; begin Line := Line + '='; {Do not Localize} st.Add(Line); Line := ''; {Do not Localize} end; Function QPHex(c : Char) : String; begin Result := '='+ IntToHex(Ord(c),2); {Do not Localize} end; begin st := TStringList.Create; try Result := ''; {Do not Localize} Line := ''; {Do not Localize} LBytesRead := 0; LDataSize := ASrcStream.Size - ASrcStream.Position; if LDataSize > ABytes then begin LDataSize := ABytes; end; if (LDataSize > 0) then begin while LBytesRead < LDataSize do begin if (LDataSize - LBytesRead) > BUF_SIZE then begin LBufSize := BUF_SIZE end else begin LBufSize := LDataSize - LBytesRead; end; ASrcStream.Read(Buffer[1],LBufSize); LBytesRead := LBytesRead + LBufSize; For i := 1 to LBufSize do begin case Buffer[i] of {TODO: Strange problem. Temp var needed in between. Check.} ' ', TAB : {Do not Localize} If (i < Length(Buffer)) and (Buffer[i+1] in [#10,#13]) then // If (Length(Line) > 71) then begin //Modified by Dennies Chang. //Line := Line + QPHex(Buffer[i]); s := QPHex(Buffer[i]); Line := Line + s; end else Line := Line + Buffer[i]; '=' : {Do not Localize} begin //Modified by Dennies Chang. //Line := Line + QPHex(Buffer[i]); s := QPHex(Buffer[i]); Line := Line + s; end else begin if ((Buffer[i] >= #33 ) and (Buffer[i] <= #60 )) or ((Buffer[i] >= #62) and (Buffer[i] <= #126 )) then begin Line := Line + Buffer[i]; end else begin if Buffer[i] in [#10,#13] then begin Line := Line + Buffer[i] end else begin Line := Line + QPHex(Buffer[i]); end; end; //...else end; //..else end; //case buffer[i] of if Length(Line) > 71 then begin NewLine; end; //if Length(Line > 71 then end; //For i := 1 to LBufSize do end; //while LBytesRead < LDataSize do end; //if (LDataSize > 0) then {This ensures that the remaining is added to the TStrings} if Length(Line) >0 then begin st.Add(Line); end; Result := st.Text; //Delete an extra system EOL that was added by the TStrings itself //The EOL varies from system to system i := Length(sLineBreak); if (Length(Result)>i) then begin Delete(Result,Length(Result) - i+1,i); end; finally FreeAndNil(st); end; end; end.
// auteur : Djebien Tarik // date : Mai 2010 // objet : Unite pour la structure de donnée linéaire de LISTE SIMPLEMENT CHAINEE. UNIT U_Liste; INTERFACE uses SysUtils; (*=============================== DEFINITION DU TYPE LISTE =========================================*) (* _ _____________ _ *) (* LISTE = |_|--->|______|______|--->|_| = LISTE *) (* info suivant *) TYPE // Un element de la liste est un mot du dictionnaire ELEMENT = STRING; // donc une chaine de caractere. // Une LISTE est un pointeur de CELLULE LISTE = ^CELLULE; // Chaque CELLULE possedant CELLULE = record // une tete contenant le mot tete : ELEMENT; // et un reste contenant un pointeur sur la cellule suivante. reste : LISTE; end {CELLULE}; ListeVide = class(SysUtils.Exception); const // Une liste Vide est un pointeur initialisé à NIL. LISTE_VIDE : LISTE = NIL; (* Constructeur *) // ajouteEnTete(l,x) = < l;x > // ajoute un nouvel élément x au debut de la liste l function ajouterEnTete(const l : LISTE; const x : ELEMENT): LISTE; (* Sélecteurs *) // tete(l) = le premier élement de la liste l // CU : leve une exception si la liste l est vide. function tete(l : LISTE) : ELEMENT; // reste(l) = la liste qui suit le premier élement de la liste l // CU : leve une exception si la liste l est vide. function reste(l : LISTE) : LISTE; (* Opérations modificatrices *) // modifierTete(l,x) modifie la valeur de l'element en tete de l // CU : leve une exception si la liste l est vide. procedure modifierTete(var l : LISTE; x : ELEMENT); // modifierReste(l,ll) modifie la valeur du reste de la liste l // en lui attribuant la liste ll // CU : leve une exception si la liste l est vide. procedure modifierReste(var l : LISTE; const ll : LISTE); (* Prédicat *) // estListeVide(l) <=> l est vide function estListeVide(l : LISTE): BOOLEAN; (* Afficheur *) // Affiche les élements de la liste L avec les parentheses // exemple : (babar,ane,barbe...) procedure AfficherListe(const L: LISTE); (* Constructeur de copie *) // cloner(L) duplique la liste L function cloner(L: LISTE): LISTE; IMPLEMENTATION function ajouterEnTete(const l : LISTE; const x : ELEMENT): LISTE; var res : LISTE = NIL; begin new(res); res.tete := x; res.reste := l; ajouterEnTete := res; end {ajouterEnTete}; function tete(l : LISTE) : ELEMENT; begin if l = LISTE_VIDE then raise ListeVide.create('Impossible d acceder a la tete'); tete := l.tete; end {tete}; function reste(l : LISTE) : LISTE; begin if l = LISTE_VIDE then raise ListeVide.create('Impossible d acceder a la tete'); reste := l.reste; end {reste}; function estListeVide(l : LISTE): BOOLEAN; begin estListeVide := l = LISTE_VIDE; end {estListeVide}; procedure modifierTete(var l : LISTE; x : ELEMENT); begin if l = LISTE_VIDE then raise ListeVide.create('Impossible d acceder a la tete'); l.tete := x; end {modifierTete}; procedure modifierReste(var l : LISTE; const ll : LISTE); begin if l = LISTE_VIDE then raise ListeVide.create('Impossible d acceder a la tete'); l.reste := ll; end {modifierReste}; // Affiche les élements de la liste sans les parentheses procedure afficherElementListe(const L: LISTE); begin if not(estListeVide(L)) then begin write(tete(L)); if not(estListeVide(reste(L))) then begin write(','); afficherElementListe(reste(L)); end{if}; end{if}; end{afficherElementListe}; // Affiche les élements de la liste avec les parentheses procedure AfficherListe(const L: LISTE); begin write('('); AfficherElementListe(L); write(')'); end{AfficherListe}; // constructeur de copie de la liste L function cloner(L: LISTE): LISTE; var anc,nouv,debut: LISTE; begin if estListeVide(L) then cloner:= nil else begin new(debut); debut^.tete := L^.tete; anc:= debut; anc^.reste:= nil; L:= L^.reste; while ( not estListeVide(L) ) do begin new(nouv); nouv^.tete:= L^.tete; nouv^.reste:= nil; anc^.reste:= nouv; anc:= nouv; L:= L^.reste; end; cloner:= debut; end; end{cloner}; INITIALIZATION (* UNITE MANIPULATION DE LISTE SIMPLEMENT CHAINEE *) (* ANNEXE : Prototypes *) (* CONSTRUCTEURS function ajouteEnTete(l: LISTE ; const x : ELEMENT): LISTE; (* CONSTRUCTEUR DE COPIE function cloner(L: LISTE): LISTE; (* SELECTEURS function tete(l: LISTE): ELEMENT; function reste(l: LISTE): LISTE; (* PREDICATS function estListeVide(l: LISTE): BOOLEAN; (* MODIFICATEURS procedure modifierTete(const l: LISTE ; const x : ELEMENT); procedure modifierReste(const l: LISTE ; const ll: LISTE); (* AFFICHEUR procedure AfficherListe(const L: LISTE); *) FINALIZATION (* Auteur, Djebien Tarik *) END {U_Liste}.
unit dXML; interface uses Classes, SysUtils, ExtCtrls, ACBrNFe, ACBrMail, ACBrNFeDANFeRLClass, db, ACBrDFe, ACBrDFeSSL, Data.FMTBcd, Data.SqlExpr, ACBrNFeDANFEClass, ACBrBase, DbxSqlite, Forms, Datasnap.DBClient, Datasnap.Provider, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Comp.Client, FireDAC.Comp.DataSet, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Phys.SQLite, FireDAC.Phys.FB, FireDAC.Phys.FBDef; type { Tdtmxml } Tdtmxml = class(TDataModule) ACBrMail1: TACBrMail; ACBrNFe1: TACBrNFe; ACBrNFeDANFeRL1: TACBrNFeDANFeRL; AutoExec: TTimer; qXmlDfe: TFDQuery; qXmlNfe: TFDQuery; qXmlRes: TFDQuery; qXmlCfg: TFDQuery; Conn: TFDConnection; pXmlCfg: TDataSetProvider; XmlCfg: TClientDataSet; pXmlRes: TDataSetProvider; XmlRes: TClientDataSet; pXmlDfe: TDataSetProvider; XmlDfe: TClientDataSet; pXmlNfe: TDataSetProvider; XmlNfe: TClientDataSet; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; FDGUIxWaitCursor1: TFDGUIxWaitCursor; FDSQLiteValidate1: TFDSQLiteValidate; XmlCfgIDDFE: TIntegerField; XmlCfgULTNSU: TIntegerField; XmlCfgUF: TStringField; XmlCfgTIMEINTERVAL: TIntegerField; XmlCfgNUMEROSERIE: TStringField; XmlCfgIDDFEAUTOINC: TIntegerField; XmlCfgSENHA: TStringField; XmlCfgARQUIVOPFX: TStringField; XmlCfgPATHDB: TStringField; XmlCfgSSLLIB: TStringField; XmlCfgAUTOEXECUTE: TIntegerField; XmlCfgAUTOTIMER: TIntegerField; XmlResIDDFE: TIntegerField; XmlResXNUMERONFE: TStringField; XmlResXSERIE: TStringField; XmlResCHNFE: TStringField; XmlResCNPJCPF: TStringField; XmlResXNOME: TStringField; XmlResIE: TStringField; XmlResDHEMI: TSQLTimeStampField; XmlResTPNF: TIntegerField; XmlResVNF: TBCDField; XmlResDIGVAL: TStringField; XmlResDHRECBTO: TSQLTimeStampField; XmlResNPROT: TStringField; XmlResCSITNFE: TIntegerField; XmlResNSU: TIntegerField; XmlResNFE: TStringField; XmlResDFE: TStringField; procedure AutoExecTimer(Sender: TObject); procedure xmlcfgAfterPost(DataSet: TDataSet); procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure XmlCfgAfterOpen(DataSet: TDataSet); procedure pXmlCfgUpdateData(Sender: TObject; DataSet: TCustomClientDataSet); procedure pXmlResUpdateData(Sender: TObject; DataSet: TCustomClientDataSet); procedure XmlCfgNewRecord(DataSet: TDataSet); private public procedure SetaConfiguracoes; function GetPathXMLNFe(const ADataEmissao: TDateTime; const AChaveNFe: String): String; function GetPathPDFNFe(const ADataEmissao: TDateTime; const AChaveNFe: String): String; end; var dtmxml: Tdtmxml; implementation uses uXML, ACBrUtil; {$R *.dfm} { Tdtmxml } function Tdtmxml.GetPathXMLNFe(const ADataEmissao: TDateTime; const AChaveNFe: String): String; begin Result := PathWithDelim(ACbrNFe1.Configuracoes.Arquivos.DownloadNFe.PathDownload) + PathWithDelim(FormatDateTime('YYYYMM', ADataEmissao)) + PathWithDelim('Down') + AChaveNFe + '-nfe.xml'; end; function Tdtmxml.GetPathPDFNFe(const ADataEmissao: TDateTime; const AChaveNFe: String): String; begin Result := PathWithDelim(dtmxml.ACBrNFe1.DANFE.PathPDF) + PathWithDelim(FormatDateTime('YYYYMM', ADataEmissao)) + AChaveNFe + '-nfe.pdf'; end; procedure Tdtmxml.DataModuleCreate(Sender: TObject); var sDirEXE: String; sdirNFe: String; begin sDirEXE := ExtractFilePath(Application.ExeName); sdirNFe := IncludeTrailingPathDelimiter(sDirEXE + 'Documentos'); // diretorios ACbrNFe1.Configuracoes.Arquivos.PathSchemas := sDirEXE + 'Schemas\nfe'; ACbrNFe1.Configuracoes.Arquivos.PathEvento := sdirNFe + 'Eventos\'; ACbrNFe1.Configuracoes.Arquivos.PathInu := sdirNFe + 'Inu\'; ACbrNFe1.Configuracoes.Arquivos.PathNFe := sdirNFe + 'NFe\'; ACbrNFe1.Configuracoes.Arquivos.PathSalvar := sdirNFe + 'Salvar\'; // diretorio de padfs ACbrNFe1.DANFE.PathPDF := sdirNFe + 'PDF'; // arquivos baixados ACbrNFe1.Configuracoes.Arquivos.DownloadNFe.PathDownload := sdirNFe + 'Download\'; // selects gerais xmlcfg.CommandText := 'select * from xmlcfg'; xmldfe.CommandText := 'select * from xmlnfe where NFe = ''F'''; xmlnfe.CommandText := 'select * from xmlnfe where NFe = ''T'''; xmlres.CommandText := 'select * from xmlnfe where idDFe = -1'; // arquivo de bancos de dados, usa o mesmo nome do aplicativo porem com extensão .DB Conn.Params.Database := 'C:\Sisconet18\Exec\Dados\DADOS.FDB'; //fabricio // manutenção da base de dados FDSQLiteValidate1.Database := Conn.Params.Database; // FDSQLiteValidate1.Sweep; // FDSQLiteValidate1.Analyze; Conn.Connected := True; xmlcfg.Open; end; procedure Tdtmxml.xmlcfgAfterPost(DataSet: TDataSet); begin xmlcfg.ApplyUpdates(0); SetaConfiguracoes; end; procedure Tdtmxml.XmlCfgNewRecord(DataSet: TDataSet); begin XmlCfg.FieldByName('idDFe').Value := 1; XmlCfg.FieldByName('TimeInterval').Value := 1000; XmlCfg.FieldByName('idDFeAutoInc').Value := 0; XmlCfg.FieldByName('SSLLib').Value := '01'; XmlCfg.FieldByName('AutoExecute').Value := '0'; XmlCfg.FieldByName('AutoTimer').Value := 1000; end; procedure Tdtmxml.AutoExecTimer(Sender: TObject); begin frmxml.AutoExecuteProcessos; end; procedure Tdtmxml.DataModuleDestroy(Sender: TObject); begin Conn.Connected := False; xmlcfg.Close; end; procedure Tdtmxml.pXmlCfgUpdateData(Sender: TObject; DataSet: TCustomClientDataSet); begin XmlCfg.FieldByName('idDFe').ProviderFlags := [pfInKey]; end; procedure Tdtmxml.pXmlResUpdateData(Sender: TObject; DataSet: TCustomClientDataSet); begin XmlCfg.FieldByName('idDFe').ProviderFlags := [pfInKey]; end; procedure Tdtmxml.SetaConfiguracoes; begin // Atribui as configurações ao componente if XmlCfg.FieldByName('SSLLib').AsString = '01' then begin ACBrNFe1.Configuracoes.Geral.SSLLib := libWinCrypt; ACBrNFe1.Configuracoes.Certificados.NumeroSerie := xmlcfg.FieldByName('NumeroSerie').AsString end else begin ACBrNFe1.Configuracoes.Geral.SSLLib := libOpenSSL; ACBrNFe1.Configuracoes.Certificados.ArquivoPFX := xmlcfg.FieldByName('ArquivoPFX').AsString; end; ACBrNFe1.Configuracoes.Geral.SSLXmlSignLib := xsMsXml; ACBrNFe1.Configuracoes.WebServices.UF := xmlcfg.FieldByName('UF').AsString; ACBrNFe1.Configuracoes.Certificados.Senha := xmlcfg.FieldByName('Senha').AsAnsiString; AutoExec.Enabled := Boolean(xmlcfg.FieldByName('AutoExecute').AsInteger); AutoExec.Interval := xmlcfg.FieldByName('AutoTimer').AsInteger * 60000; end; procedure Tdtmxml.XmlCfgAfterOpen(DataSet: TDataSet); begin SetaConfiguracoes; end; end.
unit URegraCRUDProximaVacina; interface uses URegraCRUD , URepositorioDB , URepositorioProximaVacina , UEntidade , UProximaVacina ; type TRegraCRUDProximaVacina = class(TRegraCRUD) protected procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override; public constructor Create; override; end; implementation { TRegraCRUDCidade } uses SysUtils , UUtilitarios , UMensagens , UConstantes ; constructor TRegraCRUDProximaVacina.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioProximaVacina.Create); end; procedure TRegraCRUDProximaVacina.ValidaInsercao(const coENTIDADE: TENTIDADE); begin inherited; //if Trim(TPROXIMAVACINA(coENTIDADE).SUS_CODIGO) = EmptyStr Then //raise EValidacaoNegocio.Create(STR_CODIGO_SUS_NAO_INFORMADO); if (TPROXIMAVACINA(coENTIDADE).NOME) = EmptyStr then raise EValidacaoNegocio.Create (STR_VACINA_NAO_INFORMADA); //if Trim(TPROXIMAVACINA(coENTIDADE).DATA_RETORNO) = EmptyStr Then //raise EValidacaoNegocio.Create(STR_DATA_RETORNO_NAO_INFORMADA); if Trim(TPROXIMAVACINA(coENTIDADE).VACINA_RETORNO) = EmptyStr Then raise EValidacaoNegocio.Create(STR_VACINA_RETORNO_NAO_INFORMADA); end; end.
unit untEasyDesignerPivotOLAPDataSourceReg; {$I cxVer.inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, cxCustomPivotGrid, cxPivotGridOLAPDataSource, cxButtons, ExtCtrls, cxGeometry, ComCtrls, CommCtrl, cxGraphics, cxControls, ImgList, Types, DesignIntf, DesignEditors, VCLEditors, cxPivotGrid, cxPivotGridReg, ADOReg; procedure DesignerPivotOLAPDataSourceRegister; implementation type { TcxPivotGridFieldUniqueNameProperty } TcxPivotGridFieldUniqueNameProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; function GetDataSource: TcxPivotGridOLAPDataSource; procedure Edit; override; end; TcxPivotGridOLAPDataSourceAccess = class(TcxPivotGridOLAPDataSource); TcxPivotGridEditUniqueNameDialog = class(TForm) private FBtnCancel: TcxButton; FBtnOk: TcxButton; FCurrentItem: string; FHierarchySite: TGroupBox; FHierarchyTree: TTreeView; FOLAPDataSource: TcxPivotGridOLAPDataSource; FPivotGrid: TcxCustomPivotGrid; FSelectedItem: TTreeNode; FTimer: TcxTimer; FUniqueNames: TStringList; function GetCurrentItem: WideString; procedure SetOLAPDataSource(AValue: TcxPivotGridOLAPDataSource); procedure SetCurrentItem(AValue: WideString); protected function AddHierarchyNode(AParent: Pointer; const ACaption: string; const ANameIndex, AImageIndex: Integer): Pointer; procedure CreateControls; procedure DoShow; override; procedure FillHierarchy; procedure TimerHandler(Sender: TObject); public constructor CreateEx(APivotGrid: TcxCustomPivotGrid); virtual; destructor Destroy; override; property CurrentItem: WideString read GetCurrentItem write SetCurrentItem; property OLAPSource: TcxPivotGridOLAPDataSource read FOLAPDataSource write SetOLAPDataSource; property PivotGrid: TcxCustomPivotGrid read FPivotGrid write FPivotGrid; end; constructor TcxPivotGridEditUniqueNameDialog.CreateEx(APivotGrid: TcxCustomPivotGrid); begin inherited CreateNew(nil); FPivotGrid := APivotGrid; {$IFDEF DELPHI9} PopupMode := pmAuto; {$ENDIF} Position := poDesigned; BorderStyle := bsSizeToolWin; Width := 300; Height := 400; Constraints.MinWidth := 300; Constraints.MinHeight := 400; CreateControls; AutoScroll := False; ChangeScale(PixelsPerInch, 96); FUniqueNames := TStringList.Create; FTimer := TcxTimer.Create(Self); FTimer.Interval := 100; FTimer.OnTimer := TimerHandler; FHierarchyTree.OnClick := TimerHandler; end; destructor TcxPivotGridEditUniqueNameDialog.Destroy; begin FreeAndNil(FUniqueNames); inherited Destroy; end; function TcxPivotGridEditUniqueNameDialog.AddHierarchyNode(AParent: Pointer; const ACaption: string; const ANameIndex, AImageIndex: Integer): Pointer; begin Result := FHierarchyTree.Items.AddChild(TTreeNode(AParent), ACaption); with TTreeNode(Result) do begin ImageIndex := AImageIndex; SelectedIndex := AImageIndex; Data := Pointer(ANameIndex); end; if SameText(FUniqueNames[FUniqueNames.Count - 1], FCurrentItem) then FSelectedItem := Result; end; procedure TcxPivotGridEditUniqueNameDialog.CreateControls; begin // Caption := 'Field Chooser'; // FHierarchySite := TGroupBox.Create(Self); FHierarchyTree := TTreeView.Create(Self); FBtnOk := TcxButton.Create(Self); FBtnCancel := TcxButton.Create(Self); // FBtnCancel.Caption := 'Cancel'; FBtnCancel.Cancel := True; FBtnCancel.BoundsRect := cxRectOffset(FBtnCancel.BoundsRect, ClientWidth - FBtnCancel.Width - 8, ClientHeight - FBtnCancel.Height - 8); FBtnCancel.Anchors := [akBottom, akRight]; FBtnCancel.ModalResult := mrCancel; // FBtnOk.Caption := 'Ok'; FBtnOk.BoundsRect := cxRectOffset(FBtnOk.BoundsRect, FBtnCancel.Left - FBtnOk.Width - 8, ClientHeight - FBtnOk.Height - 8); FBtnOk.ModalResult := mrOk; FBtnOk.Default := True; FBtnOk.Anchors := [akBottom, akRight]; // FHierarchySite.Caption := 'Structure:'; FHierarchySite.BoundsRect := Rect(8, 8, ClientWidth - 8, FBtnOk.Top - 8); FHierarchySite.Anchors := [akLeft..akBottom]; // FHierarchyTree.Align := alClient; FHierarchyTree.Images := cxPivotGridHierarchyImages; // place to FHierarchySite.Parent := Self; FHierarchyTree.Parent := FHierarchySite; FBtnOk.Parent := Self; FBtnCancel.Parent := Self; ActiveControl := FHierarchyTree; // end; procedure TcxPivotGridEditUniqueNameDialog.DoShow; var P: TPoint; begin FillHierarchy; FHierarchyTree.FullExpand; inherited DoShow; P := PivotGrid.ClientToScreen(Point((PivotGrid.Width - Width) div 2, (PivotGrid.Height - Height) div 2)); Left := P.X; Top := P.Y; if FHierarchyTree.Items.Count > 0 then FHierarchyTree.TopItem := FHierarchyTree.Items[0]; if FSelectedItem <> nil then begin FSelectedItem.Selected := True; FSelectedItem.Focused := True; FSelectedItem.MakeVisible; end; end; procedure TcxPivotGridEditUniqueNameDialog.FillHierarchy; begin with FHierarchyTree.Items do try BeginUpdate; Clear; FSelectedItem := nil; TcxPivotGridOLAPDataSourceAccess(FOLAPDataSource). ExtractStructure(AddHierarchyNode, FUniqueNames); finally EndUpdate; TimerHandler(nil); end; end; procedure TcxPivotGridEditUniqueNameDialog.TimerHandler(Sender: TObject); begin with FHierarchyTree do FBtnOk.Enabled := (Selected <> nil) and (Selected.Count = 0); end; function TcxPivotGridEditUniqueNameDialog.GetCurrentItem: WideString; begin Result := ''; if FHierarchyTree.Selected <> nil then Result := FUniqueNames[Integer(FHierarchyTree.Selected.Data)]; end; procedure TcxPivotGridEditUniqueNameDialog.SetOLAPDataSource( AValue: TcxPivotGridOLAPDataSource); begin FOLAPDataSource := AValue; end; procedure TcxPivotGridEditUniqueNameDialog.SetCurrentItem( AValue: WideString); begin FCurrentItem := AValue; end; { TcxPivotGridFieldUniqueNameProperty } function TcxPivotGridFieldUniqueNameProperty.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes; if GetDataSource <> nil then Result := Result + [paDialog]; end; function TcxPivotGridFieldUniqueNameProperty.GetDataSource: TcxPivotGridOLAPDataSource; begin Result := TcxPivotGridOLAPDataSource(TcxPivotGrid(TcxPivotGridField(GetComponent(0)).PivotGrid).OLAPDataSource); if (Result <> nil) and not Result.Active then Result := nil; end; procedure TcxPivotGridFieldUniqueNameProperty.Edit; var AEditDlg: TcxPivotGridEditUniqueNameDialog; begin if GetDataSource = nil then Exit; AEditDlg := TcxPivotGridEditUniqueNameDialog.CreateEx(TcxPivotGridField(GetComponent(0)).PivotGrid); try AEditDlg.OLAPSource := GetDataSource; AEditDlg.CurrentItem := GetValue; if AEditDlg.ShowModal = mrOk then SetValue(AEditDlg.CurrentItem); finally AEditDlg.Free; end; end; procedure DesignerPivotOLAPDataSourceRegister; begin {$IFDEF DELPHI9} ForceDemandLoadState(dlDisable); {$ENDIF} RegisterComponents('Easy Grid', [TcxPivotGridOLAPDataSource]); RegisterClasses([TcxPivotGridOLAPDataSource]); RegisterComponentEditor(TcxPivotGridOLAPDataSource, cxPivotGridCustomComponentEditor); RegisterPropertyEditor(TypeInfo(WideString), TcxPivotGridOLAPDataSource, 'ConnectionString', TConnectionStringProperty); RegisterPropertyEditor(TypeInfo(WideString), TcxPivotGridField, 'UniqueName', TcxPivotGridFieldUniqueNameProperty); end; initialization DesignerPivotOLAPDataSourceRegister; end.
unit Financas.Model.Connections.Factory.DataSet; interface uses Financas.Model.Connections.Interfaces, Financas.Model.Connections.TableFiredac; Type TModelConnectionFactoryDataSet = class(TInterfacedObject, iModelFactoryDataSet) private public constructor Create; destructor Destroy; override; class function New: iModelFactoryDataSet; function DataSetFiredac(Connection: iModelConnection): iModelDataSet; end; implementation { TModelConnectionFactoryDataSet } constructor TModelConnectionFactoryDataSet.Create; begin end; function TModelConnectionFactoryDataSet.DataSetFiredac(Connection: iModelConnection): iModelDataSet; begin Result := TModelConnectionsTableFiredac.New(Connection); end; destructor TModelConnectionFactoryDataSet.Destroy; begin inherited; end; class function TModelConnectionFactoryDataSet.New: iModelFactoryDataSet; begin Result := Self.Create; end; end.
unit TemplateResItems; interface uses Windows, Messages, SysUtils, Variants, Classes, Contnrs, SyncObjs; type TTemplateResources = class; TTemplateResourceItem = class private FName: string; FTemplate: PChar; FTemplateLength: Integer; FType: PChar; FOwner: TTemplateResources; function GetTemplate: PChar; function GetTemplateLength: Integer; public constructor Create(AOwner: TTemplateResources; const AName: string; AType: PChar); destructor Destroy; override; property Name: string read FName; property Template: PChar read GetTemplate; property TemplateLength: Integer read GetTemplateLength; property ResType: PChar read FType; end; TTemplateResources = class(TObject) private FCriticalSection: TCriticalSection; FItems: TObjectList; FResInstance: THandle; procedure Lock; procedure Unlock; function GetItemCount: Integer; function GetItem(I: Integer): TTemplateResourceItem; public constructor Create(AHInstance: LongWord); destructor Destroy; override; procedure Add(const AResName: string; AType: PChar); function IndexOfItem(const AResName: string): Integer; function FindItem(const AResName: string): TTemplateResourceItem; property ResInstance: THandle read FResInstance; property ItemCount: Integer read GetItemCount; property Items[I: Integer]: TTemplateResourceItem read GetItem; end; TTemplateResourceItemStream = class(TCustomMemoryStream) public constructor Create(AItem: TTemplateResourceItem); function Write(const Buffer; Count: Longint): Longint; override; end; function TemplateFileStreamFromResource(ATemplateResources: TTemplateResources; const AFileName: string; var AStream: TStream; var AOwned: Boolean): Boolean; function EnumResourceNamesCallback(hModule: HMODULE; lpType, lpName: PAnsiChar; lParam: Longint): BOOL; stdcall; export; const RT_HTML = MakeIntResource(23); RT_XSL = MakeIntResource(24); implementation function TemplateFileStreamFromResource(ATemplateResources: TTemplateResources; const AFileName: string; var AStream: TStream; var AOwned: Boolean): Boolean; var ResourceItem: TTemplateResourceItem; begin ResourceItem := ATemplateResources.FindItem(ChangeFileExt(ExtractFileName(AFileName), '')); if ResourceItem <> nil then begin AStream := TTemplateResourceItemStream.Create(ResourceItem); AOwned := True; Result := True; end else begin raise Exception.CreateFmt('Resource not found for file: %s', [AFileName]); Result := False; end; end; function EnumResourceNamesCallback(hModule: HMODULE; lpType, lpName: PAnsiChar; lParam: Longint): BOOL; var S: TStrings; begin S := TStrings(lParam); S.Add(lpName); Result := True; end; { TTemplateResources } procedure TTemplateResources.Add(const AResName: string; AType: PChar); begin FItems.Add(TTemplateResourceItem.Create(Self, AResName, AType)); end; constructor TTemplateResources.Create(AHInstance: LongWord); var S: TStrings; I: Integer; begin inherited Create; FItems := TObjectList.Create(True {Owned} ); FCriticalSection := TCriticalSection.Create; FResInstance := FindResourceHInstance(AHInstance); S := TStringList.Create; try EnumResourceNames(FResInstance, RT_HTML, @EnumResourceNamesCallback, Integer(Pointer(S))); for I := 0 to S.Count - 1 do Add(S[I], RT_HTML); S.Clear; EnumResourceNames(FResInstance, RT_XSL, @EnumResourceNamesCallback, Integer(Pointer(S))); for I := 0 to S.Count - 1 do Add(S[I], RT_XSL); finally S.Free; end; end; destructor TTemplateResources.Destroy; begin FCriticalSection.Free; FItems.Free; inherited Destroy; end; function TTemplateResources.FindItem( const AResName: string): TTemplateResourceItem; var I: Integer; begin I := IndexOfItem(AResName); if I >= 0 then Result := Items[I] else Result := nil; end; function TTemplateResources.GetItem(I: Integer): TTemplateResourceItem; begin Result := TTemplateResourceItem(FItems[I]); end; function TTemplateResources.GetItemCount: Integer; begin Result := FItems.Count; end; function TTemplateResources.IndexOfItem(const AResName: string): Integer; var I: Integer; begin for I := 0 to ItemCount - 1 do begin if CompareText(Items[I].Name, AResName) = 0 then begin Result := I; Exit; end; end; Result := -1; end; procedure TTemplateResources.Lock; begin FCriticalSection.Enter; end; procedure TTemplateResources.Unlock; begin FCriticalSection.Leave; end; { TTemplateResourceItem } constructor TTemplateResourceItem.Create(AOwner: TTemplateResources; const AName: string; AType: PChar); begin FOwner := AOwner; FName := AName; FType := AType; end; destructor TTemplateResourceItem.Destroy; begin inherited; if FTemplate <> nil then StrDispose(FTemplate); end; function TTemplateResourceItem.GetTemplate: PChar; var hResInfo: HRSRC; P: PChar; begin if FTemplate = nil then begin FOwner.Lock; try hResInfo := FindResource(FOwner.ResInstance, PChar(FName), FType); if hResInfo <> 0 then begin FTemplateLength := SizeofResource(FOwner.ResInstance, hResInfo); P := PChar(LockResource(LoadResource(FOwner.ResInstance, hResInfo))); FTemplate := StrMove(StrAlloc(FTemplateLength+1), P, FTemplateLength); FTemplate[FTemplateLength] := Char(0); end; finally FOwner.Unlock; end; end; Result := FTemplate; end; function TTemplateResourceItem.GetTemplateLength: Integer; begin GetTemplate; Result := FTemplateLength; end; { TTemplateResourceItemStream } constructor TTemplateResourceItemStream.Create(AItem: TTemplateResourceItem); begin SetPointer(AItem.Template, AItem.TemplateLength); inherited Create; end; function TTemplateResourceItemStream.Write(const Buffer; Count: Integer): Longint; begin // Write not supported Assert(False); Result := 0; end; end.
(** This module contains a class / interface for managaing message in the application. @Author David Hoyle @Version 1.0 @Date 05 Jan 2018 **) Unit ITHelper.MessageManager; Interface {$INCLUDE 'CompilerDefinitions.inc'} Uses Classes, ITHelper.Interfaces, ITHelper.Types; Type (** A class which implements the IITHMessageManager interface for managing messages in the plug-in. **) TITHMessageManager = Class(TInterfacedObject, IITHMessageManager) Strict Private FGlobalOps : IITHGlobalOptions; FMsgs : TInterfaceList; FParentMsg : IITHCustomMessage; FLastMessage : Int64; Strict Protected // IITHMessageManager Function GetCount : Integer; Function GetItem(Const iIndex : Integer) : IITHCustomMessage; Function GetLastMessage : Int64; Function GetParentMsg : IITHCustomMessage; Procedure SetParentMsg(Const ParentMsg : IITHCustomMessage); Procedure Clear; Function AddMsg(Const strText: String; Const eFontName : TITHFontNames; Const eFont : TITHFonts; Const ptrParentMsg : Pointer = Nil): IITHCustomMessage; Public Constructor Create(Const GlobalOps : IITHGlobalOptions); Destructor Destroy; Override; End; Implementation Uses {$IFDEF CODESITE} CodeSiteLogging, {$ENDIF} SysUtils, Windows, ToolsAPI, ITHelper.CustomMessages, ITHelper.ResourceStrings; (** This method adds a custom message to the IDE and returns a POINTER to that message. @precon ptrParent must be a POINTER to another message not a reference. @postcon Adds a custom message to the IDE and returns a POINTER to that message. @param strText as a String as a constant @param eFontName as a TITHFontNames as a constant @param eFont as a TITHFonts as a constant @param ptrParentMsg as a Pointer as a constant @return an IITHCustomMessage **) Function TITHMessageManager.AddMsg(Const strText: String; Const eFontName : TITHFontNames; Const eFont : TITHFonts; Const ptrParentMsg : Pointer = Nil): IITHCustomMessage; Var MS : IOTAMessageServices; G: IOTAMessageGroup; Begin Result := Nil; If Supports(BorlandIDEServices, IOTAMessageServices, MS) Then Begin Result := TITHCustomMessage.Create(strText, FGlobalOps.FontName[eFontName], FGlobalOps.FontColour[eFont], FGlobalOps.FontStyles[eFont]); FMsgs.Add(Result); If Not Assigned(ptrParentMsg) Then Begin G := Nil; If FGlobalOps.GroupMessages Then G := MS.AddMessageGroup(strITHelperGroup) Else G := MS.GetMessageGroup(0); If FGlobalOps.AutoScrollMessages <> G.AutoScroll Then G.AutoScroll := FGlobalOps.AutoScrollMessages; Result.MessagePntr := MS.AddCustomMessagePtr(Result, G); End Else MS.AddCustomMessage(Result, ptrParentMsg); FLastMessage := GetTickCount; End; End; (** This method clears all the messages from the manager. @precon None. @postcon All the messages are cleared from the managers internal collection (they still remain in the message view). **) Procedure TITHMessageManager.Clear; Begin FMsgs.Clear; End; (** A constructor for the TITHMessageManager class. @precon None. @postcon Stores references to the Global Options and creates a message list. @param GlobalOps as an IITHGlobalOptions as a constant **) Constructor TITHMessageManager.Create(Const GlobalOps: IITHGlobalOptions); Begin FGlobalOps := GlobalOps; FMsgs := TInterfaceList.Create; End; (** A destructor for the TITHMessageManager class. @precon None. @postcon Frees the message list. **) Destructor TITHMessageManager.Destroy; Begin FMsgs.Free; Inherited Destroy; End; (** This is a getter method for the Count property. @precon None. @postcon Returns the number of items in the internal message list. @return an Integer **) Function TITHMessageManager.GetCount: Integer; Begin Result := FMsgs.Count; End; (** This is a getter method for the Item property. @precon None. @postcon Returns the indexed message from the internal list. @param iIndex as an Integer as a constant @return an IITHCustomMessage **) Function TITHMessageManager.GetItem(Const iIndex: Integer): IITHCustomMessage; Begin Result := FMsgs[iIndex] As IITHCustomMessage; End; (** This is a getter method for the LastMessage property. @precon None. @postcon Returns the tickcount of the last message created. @return an Int64 **) Function TITHMessageManager.GetLastMessage: Int64; Begin Result := FLastMessage; End; (** This is a getter method for the ParentMsg property. @precon None. @postcon Returns the current parent message. @return an IITHCustomMessage **) Function TITHMessageManager.GetParentMsg: IITHCustomMessage; Begin Result := FParentMsg; End; (** This is a setter method for the ParentMsg property. @precon None. @postcon Sets the current ParentMsg referernce. @param ParentMsg as an IITHCustomMessage as a constant **) Procedure TITHMessageManager.SetParentMsg(Const ParentMsg: IITHCustomMessage); Begin If FParentMsg <> ParentMsg Then FParentMsg := ParentMsg; End; End.
unit MainFrm; { MemoEdit is a simple OLE Automation enabled MDI-style text editor. The application contains the following units: MainFrm The MDI main form. EditFrm The MDI child form class and its automation class. MemoAuto The Application automation object. To register the MemoEdit application as an OLE Automation server, run it using the command line "MemoEdit /regserver". To unregister the application, use "MemoEdit /unregserver". You may also do this by running the application from the IDE by specifying the command line parameters using the Run|Parameters dialog. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, EditFrm; type TMainForm = class(TForm) MainMenu: TMainMenu; FileMenu: TMenuItem; FileNewItem: TMenuItem; FileOpenItem: TMenuItem; FileExitItem: TMenuItem; WindowMenu: TMenuItem; WindowCascadeItem: TMenuItem; WindowTileItem: TMenuItem; WindowArrangeIconsItem: TMenuItem; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; procedure FileNewItemClick(Sender: TObject); procedure FileOpenItemClick(Sender: TObject); procedure FileExitItemClick(Sender: TObject); procedure WindowTileItemClick(Sender: TObject); procedure WindowCascadeItemClick(Sender: TObject); procedure WindowArrangeIconsItemClick(Sender: TObject); public Local: Boolean; NewFileName: string; function CreateMemo(const FileName: string): TEditForm; function CreateMemoLocal(const FileName: string): TEditForm; end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.FileNewItemClick(Sender: TObject); begin CreateMemoLocal(''); end; procedure TMainForm.FileOpenItemClick(Sender: TObject); begin OpenDialog.FileName := ''; if OpenDialog.Execute then CreateMemo(OpenDialog.FileName); end; procedure TMainForm.FileExitItemClick(Sender: TObject); begin Close; end; procedure TMainForm.WindowTileItemClick(Sender: TObject); begin Tile; end; procedure TMainForm.WindowCascadeItemClick(Sender: TObject); begin Cascade; end; procedure TMainForm.WindowArrangeIconsItemClick(Sender: TObject); begin ArrangeIcons; end; function TMainForm.CreateMemo(const FileName: string): TEditForm; begin NewFileName := ExpandFileName(FileName); Result := TEditForm.Create(Application); end; function TMainForm.CreateMemoLocal(const FileName: string): TEditForm; begin Local := true; NewFileName := ExpandFileName(FileName); Result := TEditForm.Create(Application); end; end.
(* Name: initprog Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 20 Jun 2006 Modified Date: 23 Jun 2015 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 20 Jun 2006 - mcdurdin - Initial version 01 Aug 2006 - mcdurdin - Rework for Keyman 7 02 Aug 2006 - mcdurdin - Timeout when Beta expires 04 Dec 2006 - mcdurdin - Add -activate, locale functionality, icons 04 Jan 2007 - mcdurdin - Add help support 04 Jan 2007 - mcdurdin - Workaround Vista button refresh issue in Delphi 30 May 2007 - mcdurdin - Add -w to show welcome at any time 20 Jun 2007 - mcdurdin - I838 - Fix shadow keyboards (usually from KM6) 23 Aug 2007 - mcdurdin - I933 - Use Unicode application title 05 Nov 2007 - mcdurdin - I869 - Add -nowelcome for elevated keyboard install 05 Nov 2007 - mcdurdin - I937, I1128 - Repair COM object if it fails at startup 06 Nov 2007 - mcdurdin - I1140 - Support -configure-addin for elevated addin configuration 27 Mar 2008 - mcdurdin - I1201 - Admin required uninstalling package 27 Mar 2008 - mcdurdin - I1248 - Redesign Welcome 14 Jun 2008 - mcdurdin - Support installing multiple files at once 28 Aug 2008 - mcdurdin - I1616 - Upgrade keyboards from 6.x 16 Jan 2009 - mcdurdin - I1730 - Check update of keyboards 27 Jan 2009 - mcdurdin - Improve startup and shutdown performance 30 Jan 2009 - mcdurdin - I1826 - Fix performance starting and closing help 07 Sep 2009 - mcdurdin - I2051 - Crash in kmshell when -h parameter used with no page parameter 12 Mar 2010 - mcdurdin - I2226 - Include link to Text Editor in Keyman Menu 29 Mar 2010 - mcdurdin - I2260 - "Start Text Editor" should not start in Tutorial mode 25 May 2010 - mcdurdin - I1694 - UI language option accessibility 25 May 2010 - mcdurdin - I2392 - Activation Client integration 30 Nov 2010 - mcdurdin - I2548 - Support for upgrading Desktop 7 to Desktop 8 10 Dec 2010 - mcdurdin - I2548 - Consolidate -upgradekeyboards switch 17 Dec 2010 - mcdurdin - I2548 - Fix bugs with upgrade 30 Dec 2010 - mcdurdin - I2562 - Start Keyman install properties 30 Dec 2010 - mcdurdin - I2604 - Upgrade to Pro from Character Map is incomplete 31 Dec 2010 - mcdurdin - I2605 - Crash starting Keyman Desktop after upgrade when using non-default locale 18 Feb 2011 - mcdurdin - I2702 - "Getting Started" link not working 21 Feb 2011 - mcdurdin - I2651 - Setup does not set desired default options 22 Feb 2011 - mcdurdin - I2753 - Firstrun crashes because start with windows and auto update check options are set in Engine instead of Desktop 28 Feb 2011 - mcdurdin - I2720 - Prevent Keyman Desktop splash from showing multiple copies 18 Mar 2011 - mcdurdin - I2807 - Enable/disable addins 18 Mar 2011 - mcdurdin - I2782 - Unminimize configuration when bringing it to foreground 18 May 2012 - mcdurdin - I3306 - V9.0 - Remove TntControls + Win9x support 02 Feb 2012 - mcdurdin - I2975 - VistaAltFixUnit can crash on shutdown 01 Dec 2012 - mcdurdin - I3613 - V9.0 - System shadow keyboards obsolete, strip out remaining code 01 Jan 2013 - mcdurdin - I3624 - V9.0 - Install keyboard language profiles from Keyman COM API 16 Apr 2014 - mcdurdin - I4169 - V9.0 - Mnemonic layouts should be recompiled to positional based on user-selected base keyboard 03 Jun 2014 - mcdurdin - I4248 - V9.0 - Refactor of kmtip 16 Jun 2014 - mcdurdin - I4185 - V9.0 - Upgrade V8.0 keyboards to 9.0 03 Sep 2014 - mcdurdin - I4400 - V9.0 - Add HKCU FEATURE_BROWSER_EMULATION 9000 for kmshell.exe 10 Oct 2014 - mcdurdin - I4436 - V9.0 - browser emulation control for kmshell breaks downlevel versions of Keyman 31 Dec 2014 - mcdurdin - I4553 - V9.0 - Upgrade to 476 or later requires recompile of all mnemonic layouts 23 Jun 2015 - mcdurdin - I4773 - Keyman needs to rebuild its language profiles if they are inadvertently deleted *) unit initprog; // I3306 // I4248 interface uses System.UITypes, Windows, Controls, SysUtils, Classes, ErrorControlledRegistry, Forms, MessageIdentifiers, MessageIdentifierConsts, keymanapi_TLB; procedure Run; procedure Main(Owner: TComponent = nil); type TKMShellMode = (fmUndefined, fmInstall, fmView, fmUninstall, fmAbout, fmUninstallKeyboard, fmInstallKeyboardLanguage, fmUninstallKeyboardLanguage, // I3624 fmUninstallPackage, fmRegistryAdd, fmRegistryRemove, fmMain, fmHelp, fmHelpKMShell, fmMigrate, fmSplash, fmStart, fmUpgradeKeyboards, fmOnlineUpdateCheck,// I2548 fmOnlineUpdateAdmin, fmTextEditor, fmFirstRun, // I2562 fmKeyboardWelcome, // I2569 fmKeyboardPrint, // I2329 fmBaseKeyboard, // I4169 fmUpgradeMnemonicLayout, // I4553 fmRepair, fmKeepInTouch); // I4773 var ApplicationRunning: Boolean = False; UnRegCRC: LongWord = 0; FMode: TKMShellMode; implementation uses custinterfaces, DebugPaths, Dialogs, FixupLocaleDoctype, GetOsVersion, help, HTMLHelpViewer, KeymanPaths, KLog, kmint, KeymanMutex, OnlineUpdateCheck, ExternalExceptionHandler, RegistryKeys, UfrmBaseKeyboard, UfrmKeymanBase, UfrmInstallKeyboard, UfrmInstallKeyboardLanguage, //UfrmSelectLanguage, UfrmSplash, UfrmHTML, UfrmKeepInTouch, UfrmMain, UfrmPrintOSK, UfrmTextEditor, UfrmWebContainer, UImportOlderVersionSettings, UImportOlderVersionKeyboards8, UImportOlderVersionKeyboards9, UILanguages, uninstall, UpgradeMnemonicLayout, utilfocusappwnd, utilkmshell, KeyboardTIPCheck, ValidateKeymanInstalledSystemKeyboards, VisualKeyboard, WideStrings, extctrls, stdctrls, comctrls; procedure FirstRun(FQuery: string); forward; // I2562 procedure ShowKeyboardWelcome(PackageName: WideString); forward; // I2569 procedure PrintKeyboard(KeyboardName: WideString); forward; // I2329 procedure Main(Owner: TComponent = nil); var frmMain: TfrmMain; begin if not Assigned(Owner) then begin UfrmWebContainer.CreateForm(TfrmMain, frmMain); ApplicationRunning := True; Application.Run; ApplicationRunning := False; FreeAndNil(frmMain); end else if not FocusConfiguration then // I2720 begin with TfrmMain.Create(Owner) do try ShowModal; finally Free; end; end; end; function Show_frmHTML(AParent: TComponent; const ACaption, AText, AFileName: string; AHelpContext: Integer): Integer; begin with TfrmHTML.Create(AParent) do try Caption := ACaption; HelpContext := AHelpContext; if AText <> '' then Text := AText else ShowFile(AFileName); Result := ShowModal; finally Free; end; end; function Init(var FMode: TKMShellMode; KeyboardFileNames: TWideStrings; var FSilent, FForce, FNoWelcome: Boolean; var FQuery: string): Boolean; var s: string; i: Integer; begin Result := False; FSilent := False; FForce := False; FNoWelcome := False; FQuery := ''; FMode := fmStart; KeyboardFileNames.Clear; i := 1; while i <= ParamCount do begin if (ParamStr(i) <> '') and (ParamStr(i)[1] = '-') then begin s := LowerCase(ParamStr(i)); if s = '-s' then FSilent := True else if s = '-f' then FForce := True else if s = '-c' then FMode := fmMain else if s = '-m' then FMode := fmMigrate else if s = '-i' then FMode := fmInstall else if s = '-ikl' then FMode := fmInstallKeyboardLanguage // I3624 //else if s = '-i+' then begin FMode := fmInstall; FNoWelcome := True; end; else if s = '-v' then FMode := fmView else if s = '-u' then FMode := fmUninstall else if s = '-uk' then FMode := fmUninstallKeyboard { I1201 - Fix crash uninstalling admin-installed keyboards and packages } else if s = '-ukl' then FMode := fmUninstallKeyboardLanguage // I3624 else if s = '-up' then FMode := fmUninstallPackage { I1201 - Fix crash uninstalling admin-installed keyboards and packages } else if s = '-ou' then FMode := fmOnlineUpdateAdmin { I1730 - Check update of keyboards (admin elevation) } else if s = '-a' then FMode := fmAbout else if s = '-ra' then FMode := fmRegistryAdd else if s = '-rr' then FMode := fmRegistryRemove else if s = '-splash' then FMode := fmSplash else if s = '-?' then FMode := fmHelpKMShell else if s = '-h' then FMode := fmHelp else if s = '-t' then FMode := fmTextEditor else if s = '-ouc' then FMode := fmOnlineUpdateCheck else if s = '-basekeyboard' then FMode := fmBaseKeyboard // I4169 else if s = '-nowelcome' then FNoWelcome := True else if s = '-kw' then FMode := fmKeyboardWelcome // I2569 else if s = '-kp' then FMode := fmKeyboardPrint // I2329 else if Copy(s,1,Length('-firstrun')) = '-firstrun' then begin FMode := fmFirstRun; FQuery := Copy(s,Length('-firstrun')+2,MAXINT); end // I2562 else if Copy(s,1,Length('-upgradekeyboards')) = '-upgradekeyboards' then begin FMode := fmUpgradeKeyboards; FQuery := Copy(s,Length('-upgradekeyboards')+2,MAXINT); end // I2548 else if s = '-upgrademnemoniclayout' then FMode := fmUpgradeMnemonicLayout // I4553 else if s = '-repair' then FMode := fmRepair // I4773 else if s = '-keepintouch' then FMode := fmKeepInTouch else if s = '-q' then begin FQuery := ''; Inc(i); while i <= ParamCount do begin FQuery := FQuery + ParamStr(i) + ' '; Inc(i); end; FQuery := Trim(FQuery); end else if Copy(s, 1, 3) = '-ur' then UnRegCRC := StrToIntDef('$'+Copy(s, 4, 8), 0) else Exit; end else begin KeyboardFileNames.Add(ParamStr(i)); end; Inc(i); end; if FMode in [fmInstall, fmInstallKeyboardLanguage, fmView, fmUninstallKeyboard, fmUninstallKeyboardLanguage, fmUninstallPackage] then // I2807 // I3624 if KeyboardFileNames.Count = 0 then Exit; Result := FMode <> fmUndefined; end; procedure RegisterControlClasses; begin RegisterClasses([TImage, TCheckBox, TLabel, TButton, TPanel, TGroupBox, TPageControl, TTabSheet]); end; procedure RunKMCOM(FMode: TKMShellMode; KeyboardFileNames: TWideStrings; FSilent, FForce, FNoWelcome: Boolean; FQuery: string); forward; procedure Run; var KeyboardFileNames: TWideStrings; FQuery: string; FSilent: Boolean; FNoWelcome: Boolean; FForce: Boolean; begin RegisterControlClasses; with TRegistryErrorControlled.Create do // I4400 try if OpenKey(SRegKey_InternetExplorerFeatureBrowserEmulation, True) then // I4436 begin WriteInteger(TKeymanPaths.S_KMShell, 9000); WriteInteger(TKeymanPaths.S_KeymanExe, 9000); end; finally Free; end; //FRunFolder := GetCurrentDir; //raise Exception.Create('Error Message'); KeyboardFileNames := TWideStringList.Create; try if not Init(FMode, KeyboardFileNames, FSilent, FForce, FNoWelcome, FQuery) then begin //TODO: TUtilExecute.Shell(PChar('hh.exe mk:@MSITStore:'+ExtractFilePath(KMShellExe)+'keyman.chm::/context/keyman_usage.html'), SW_SHOWNORMAL); Exit; end; if not LoadKMCOM then Exit; try RunKMCOM(FMode, KeyboardFileNames, FSilent, FForce, FNoWelcome, FQuery); finally kmcom := nil; end; finally KeyboardFileNames.Free; end; end; procedure RunKMCOM(FMode: TKMShellMode; KeyboardFileNames: TWideStrings; FSilent, FForce, FNoWelcome: Boolean; FQuery: string); var FIcon: string; FMutex: TKeymanMutex; // I2720 function FirstKeyboardFileName: WideString; begin if KeyboardFileNames.Count = 0 then Result := '' else Result := KeyboardFileNames[0]; end; function SecondKeyboardFileName: WideString; // I3624 begin if KeyboardFileNames.Count < 2 then Result := '' else Result := KeyboardFileNames[1]; end; begin kmcom.AutoApply := True; FMutex := nil; // I2720 { Locate the appropriate product } UILanguages.CreateUILanguages; Application.HelpFile := GetCHMPath; // may change if language changes Application.Title := MsgFromId(SKApplicationTitle); if GetOS in [osOther] then begin ShowMessage(MsgFromId(SKOSNotSupported)); Exit; end; if not FSilent or (FMode = fmUpgradeMnemonicLayout) then // I4553 begin // Note: will elevate and re-run if required // Upgrades mnemonic layouts to fix bugs in existing layouts TUpgradeMnemonicLayout.Run; if FMode = fmUpgradeMnemonicLayout then Exit; end; if not FSilent and (FMode <> fmRepair) then // I4773 begin if not TKeyboardTIPCheck.CheckKeyboardTIPInstallStatus then begin if MessageDlg('Some keyboard profiles have been damaged. Correct these now?', mtConfirmation, mbOkCancel, 0) = mrOk then WaitForElevatedConfiguration(0, '-repair', True); end; end; // I1818 - remove start mode change if FMode = fmStart then FIcon := 'appicon.ico' else FIcon := 'cfgicon.ico'; FIcon := GetDebugPath(FIcon, ExtractFilePath(ParamStr(0)) + FIcon, False); if FileExists(FIcon) then Application.Icon.LoadFromFile(FIcon); case FMode of fmKeyboardWelcome: // I2569 ShowKeyboardWelcome(FirstKeyboardFileName); fmKeyboardPrint: // I2329 PrintKeyboard(FirstKeyboardFileName); fmFirstRun: // I2562 FirstRun(FQuery); fmOnlineUpdateAdmin: OnlineUpdateAdmin(FirstKeyboardFileName); fmOnlineUpdateCheck: with TOnlineUpdateCheck.Create(FForce, FSilent) do try Run; finally Free; end; fmUpgradeKeyboards:// I2548 begin ImportOlderVersionKeyboards8(Pos('admin', FQuery) > 0); // I4185 ImportOlderVersionKeyboards9(Pos('admin', FQuery) > 0); // I4185 DeleteLegacyKeymanInstalledSystemKeyboards; // I3613 end; fmMigrate: ; fmHelp: if KeyboardFileNames.Count > 0 then OpenHelp(KeyboardFileNames[0]) else OpenHelp(''); fmHelpKMShell: ; ////TODO: TUtilExecute.Shell(PChar('hh.exe mk:@MSITStore:'+ExtractFilePath(KMShellExe)+'keyman.chm::/context/keyman_usage.html'), SW_SHOWNORMAL); fmStart: begin // I2720 StartKeyman(False, FSilent); end; fmSplash: ShowSplash; fmMain, fmAbout: begin // I2720 FMutex := TKeymanMutex.Create('KeymanConfiguration'); if FMutex.MutexOwned then Main else FocusConfiguration; end; fmTextEditor: begin // I2720 FMutex := TKeymanMutex.Create('KeymanTextEditor'); if FMutex.MutexOwned then OpenTextEditor(nil) else FocusTextEditor; end; fmBaseKeyboard: // I4169 if ConfigureBaseKeyboard then ExitCode := 0 else ExitCode := 1; fmInstall: if KeyboardFileNames.Count > 1 then begin if InstallFiles(nil, KeyboardFileNames, FSilent) then ExitCode := 0 else ExitCode := 1; end else if InstallFile(nil, FirstKeyboardFileName, FSilent, FNoWelcome) then ExitCode := 0 else ExitCode := 1; fmUninstallKeyboard: { I1201 - Fix crash uninstalling admin-installed keyboards and packages } if UninstallKeyboard(nil, FirstKeyboardFileName, FSilent) then ExitCode := 0 else ExitCode := 1; fmInstallKeyboardLanguage: // I3624 if InstallKeyboardLanguage(nil, FirstKeyboardFileName, SecondKeyboardFileName, FSilent) then ExitCode := 0 else ExitCode := 1; fmUninstallKeyboardLanguage: // I3624 if UninstallKeyboardLanguage(nil, FirstKeyboardFileName, FSilent) then ExitCode := 0 else ExitCode := 1; fmUninstallPackage: { I1201 - Fix crash uninstalling admin-installed keyboards and packages } if UninstallPackage(nil, FirstKeyboardFileName, FSilent) then ExitCode := 0 else ExitCode := 1; fmRepair: // I4773 if not TKeyboardTIPCheck.CheckKeyboardTIPInstallStatus then begin if not FSilent then begin if MessageDlg('Some of the keyboard profiles have been damaged. Correct these now?', mtConfirmation, mbOkCancel, 0) = mrOk then WaitForElevatedConfiguration(0, '-repair', True); ExitCode := 0; end else ExitCode := 1; end else ExitCode := 0; fmKeepInTouch: ShowKeepInTouchForm(True); // I4658 end; if FMode <> fmMain then begin if kmcom.SystemInfo.RebootRequired then RunReboot('Windows must be restarted for changes to complete. Restart now?', 'Windows did not initiate the restart successfully. You will need to restart manually.'); ApplicationRunning := True; Application.Run; ApplicationRunning := False; end; FreeAndNil(FMutex); // I2720 end; procedure FirstRun(FQuery: string); // I2562 var DoAdmin: Boolean; begin DoAdmin := kmcom.SystemInfo.IsAdministrator; if not DoAdmin then begin // I2651 - options not matching, case sensitivity, 8.0.309.0 FirstRunInstallDefaults(Pos('installdefaults', FQuery) > 0, Pos('startwithwindows', FQuery) > 0, Pos('checkforupdates', FQuery) > 0); // I2651, I2753 end; UpdateAllLocaleDoctypes; // I2605 end; procedure ShowKeyboardWelcome(PackageName: WideString); // I2569 var n: Integer; begin n := kmcom.Packages.IndexOf(PackageName); if n >= 0 then DoShowPackageWelcome(kmcom.Packages[n], True); end; procedure PrintKeyboard(KeyboardName: WideString); // I2329 var n: Integer; begin n := kmcom.Keyboards.IndexOf(KeyboardName); if n >= 0 then with TfrmPrintOSK.Create(nil) do try PrintKeyboard(kmcom.Keyboards[n]); finally Free; end; end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX_Platform; {$I FMX_Defines.inc} (*$HPPEMIT '#if defined(WIN32) && defined(CreateWindow)'*) (*$HPPEMIT ' #define __SAVE_CREATEWINDOW CreateWindow'*) (*$HPPEMIT ' #undef CreateWindow'*) (*$HPPEMIT '#endif'*) (*$HPPEMIT END '#if defined(__SAVE_CREATEWINDOW)'*) (*$HPPEMIT END ' #define CreateWindow __SAVE_CREATEWINDOW'*) (*$HPPEMIT END ' #undef __SAVE_CREATEWINDOW'*) (*$HPPEMIT END '#endif'*) interface uses Classes, SysUtils, Types, UITypes, FMX_Types, FMX_Forms, FMX_Menus, FMX_Dialogs; type EInvalidFmxHandle = class(Exception); { Abstract platform class } { TPlatform } TPlatform = class(TComponent) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Application } procedure Run; virtual; abstract; procedure Terminate; virtual; abstract; function HandleMessage: Boolean; virtual; abstract; procedure WaitMessage; virtual; abstract; { System Metrics } function GetDefaultFontFamilyName: WideString; virtual; abstract; { Timer } function CreateTimer(Interval: Integer; TimerFunc: TTimerProc): TFmxHandle; virtual; abstract; function DestroyTimer(Timer: TFmxHandle): Boolean; virtual; abstract; function GetTick: Single; virtual; abstract; { Window } function FindForm(AHandle: TFmxHandle): TCommonCustomForm; virtual; abstract; function CreateWindow(AForm: TCommonCustomForm): TFmxHandle; virtual; abstract; procedure DestroyWindow(AForm: TCommonCustomForm); virtual; abstract; procedure ReleaseWindow(AForm: TCommonCustomForm); virtual; abstract; procedure SetWindowState(AForm: TCommonCustomForm; const AState: TWindowState); virtual; abstract; procedure ShowWindow(AForm: TCommonCustomForm); virtual; abstract; procedure HideWindow(AForm: TCommonCustomForm); virtual; abstract; function ShowWindowModal(AForm: TCommonCustomForm): TModalResult; virtual; abstract; procedure InvalidateWindowRect(AForm: TCommonCustomForm; R: TRectF); virtual; abstract; procedure SetWindowRect(AForm: TCommonCustomForm; ARect: TRectF); virtual; abstract; function GetWindowRect(AForm: TCommonCustomForm): TRectF; virtual; abstract; function GetClientSize(AForm: TCommonCustomForm): TPointF; virtual; abstract; procedure SetClientSize(AForm: TCommonCustomForm; const ASize: TPointF); virtual; abstract; procedure SetWindowCaption(AForm: TCommonCustomForm; const ACaption: WideString); virtual; abstract; procedure SetCapture(AForm: TCommonCustomForm); virtual; abstract; procedure ReleaseCapture(AForm: TCommonCustomForm); virtual; abstract; function ClientToScreen(AForm: TCommonCustomForm; const Point: TPointF): TPointF; virtual; abstract; function ScreenToClient(AForm: TCommonCustomForm; const Point: TPointF): TPointF; virtual; abstract; { Menus } procedure StartMenuLoop(const AView: IMenuView); virtual; abstract; function ShortCutToText(ShortCut: TShortCut): WideString; virtual; abstract; procedure ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState); virtual; abstract; function TextToShortCut(Text: WideString): integer; virtual; abstract; procedure CreateOSMenu(AForm: TCommonCustomForm; const AMenu: IItemsContainer); virtual; abstract; procedure UpdateMenuItem(const AItem: TMenuItem); virtual; abstract; { Drag and Drop } procedure BeginDragDrop(AForm: TCommonCustomForm; const Data: TDragObject; ABitmap: TBitmap); virtual; abstract; { Clipboard } procedure SetClipboard(Value: Variant); virtual; abstract; function GetClipboard: Variant; virtual; abstract; { Cursor } procedure SetCursor(AForm: TCommonCustomForm; const ACursor: TCursor); virtual; abstract; { Mouse } function GetMousePos: TPointF; virtual; abstract; { Screen } function GetScreenSize: TPointF; virtual; abstract; { International } function GetCurrentLangID: WideString; virtual; abstract; function GetLocaleFirstDayOfWeek: WideString; virtual; abstract; { Dialogs } function DialogOpenFiles(var FileName: TFileName; const AInitDir, ADefaultExt, AFilter, ATitle: WideString; var AFilterIndex: Integer; var AFiles: TWideStrings; var AOptions: TOpenOptions): Boolean; virtual; abstract; function DialogPrint(var ACollate, APrintToFile: Boolean; var AFromPage, AToPage, ACopies: Integer; AMinPage, AMaxPage: Integer; var APrintRange: TPrintRange; AOptions: TPrintDialogOptions): Boolean; virtual; abstract; function PageSetupGetDefaults(var AMargin, AMinMargin: TRect; var APaperSize: TPointF; AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean; virtual; abstract; function DialogPageSetup(var AMargin, AMinMargin: TRect; var APaperSize: TPointF; var AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean; virtual; abstract; function DialogSaveFiles(var AFileName: TFileName; const AInitDir, ADefaultExt, AFilter, ATitle: WideString; var AFilterIndex: Integer; var AFiles: TWideStrings; var AOptions: TOpenOptions): Boolean; virtual; abstract; function DialogPrinterSetup: Boolean; virtual; abstract; { Keyboard } function ShowVirtualKeyboard(AControl: TFmxObject): Boolean; virtual; function HideVirtualKeyboard: Boolean; virtual; { Text Service } function GetTextServiceClass: TTextServiceClass; virtual; abstract; end; TPlatformClass = class of TPlatform; function PlatformClass: TPlatformClass; var Platform: TPlatform = nil; implementation {$IFDEF IOS} uses FMX_Platform_iOS, FMX_Canvas_iOS, FMX_Context_GLES; {$ENDIF} {$IFDEF MACOS} uses FMX_Platform_Mac, FMX_Canvas_Mac, FMX_Context_Mac; {$ENDIF} {$IFDEF MSWINDOWS} uses FMX_Platform_Win, FMX_Context_DX9; {$ENDIF} function PlatformClass: TPlatformClass; begin Result := ActualPlatformClass; end; { TPlatform } constructor TPlatform.Create; begin inherited; end; destructor TPlatform.Destroy; begin inherited; end; function TPlatform.ShowVirtualKeyboard(AControl: TFmxObject): Boolean; begin Result := False; end; function TPlatform.HideVirtualKeyboard: Boolean; begin Result := False; end; end.
{----------------------------------------------------------------------------- Unit Name: StrConsts Author: n0mad Version: 1.2.8.x Creation: 06.08.2003 Purpose: Standard contants History: -----------------------------------------------------------------------------} unit StrConsts; interface const // ------------------------------------------------------------------------- c_Null_Terminator: Char = #0; c_Tab: Char = #9; c_Quote: Char = ''''; c_Space: Char = ' '; c_CR: Char = #13; c_LF: Char = #10; c_CRLF: string = #13#10; c_White_Space: string = #13#10#9; c_Separator_20: string = '--------------------'; // ------------------------------------------------------------------------- c_Menu_In_Str: string = ' ::::: '; c_Valuta: string = 'тенге'; // ------------------------------------------------------------------------- BoolYesNo: array[Boolean] of Char = ('N', 'Y'); c_Boolean: array[Boolean] of string = ('Нет (No)', 'Да (Yes)'); c_Bool2Int: array[Boolean] of Integer = (0, 1); // ------------------------------------------------------------------------- implementation end.
(* Deklarasi nama program*) program HelloWorld; (* Deklarasi library*) uses crt; (* Ini adalah komentar, tidak dieksekusi oleh komputer. Program ini untuk menampilkan kalimat "Hello, World!" di layar. *) (* Program utama selalu dimulai dengan "begin" dan diakhiri dengan "end"*) begin writeln('Hello, World!'); readkey; end.
unit FC.Trade.Trader.MACross3; {$I Compiler.inc} interface uses Classes, Math,Graphics, Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions, StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators, Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage; type //Пока здесь объявлен. Потом как устоится, вынести в Definitions IStockTraderMACross3 = interface ['{1933A182-D3E9-4A1C-A69E-C87B7E4D4B1C}'] end; TStockTraderMACross3 = class (TStockTraderBase,IStockTraderMACross3) private FBarHeightD1 : ISCIndicatorBarHeight; FSMA21_H1,FSMA55_H1: ISCIndicatorMA; //FLWMA21_H1,FLWMA55_H1: ISCIndicatorMA; //FMA84_H1,FMA220_H1: ISCIndicatorMA; FLastOpenOrderTime : TDateTime; FPropFullBarsOnly : TPropertyYesNo; FPropMaxPriceAndMAGap : TPropertyInt; protected function CreateBarHeightD1(const aChart: IStockChart): ISCIndicatorBarHeight; function CreateMA_H1(const aChart: IStockChart; aPeriod: integer; aMethod: TSCIndicatorMAMethod): ISCIndicatorMA; //Считает, на какой примерно цене сработает Stop Loss или Trailing Stop function GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber; //Считает, какой убыток будет, если закроется по StopLoss или Trailing Stop function GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber; procedure CloseProfitableOrders(aKind: TSCOrderKind;const aComment: string); procedure CloseAllOrders(aKind: TSCOrderKind;const aComment: string); function GetRecommendedLots: TStockOrderLots; override; procedure SetTP(const aOrder: IStockOrder; const aTP: TStockRealNumber; const aComment: string); function GetMainTrend(index: integer): TSCRealNumber; function GetFastTrend(index: integer): TSCRealNumber; function GetCross(index: integer): integer; function PriceToPoint(const aPrice: TSCRealNumber): integer; function GetCurrentBid: TSCRealNumber; function OpenPendingOrder(aOrderType:TStockOrderKind; aLevel: TSCRealNumber): IStockOrder; public procedure SetProject(const aValue : IStockProject); override; procedure OnBeginWorkSession; override; //Посчитать procedure UpdateStep2(const aTime: TDateTime); override; function OpenOrder(aKind: TStockOrderKind;const aComment: string=''): IStockOrder; constructor Create; override; destructor Destroy; override; procedure Dispose; override; end; implementation uses DateUtils,Variants,Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message, StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory, FC.DataUtils; { TStockTraderMACross3 } procedure TStockTraderMACross3.CloseAllOrders(aKind: TSCOrderKind;const aComment: string); var i: Integer; aOrders : IStockOrderCollection; begin aOrders:=GetOrders; for i := aOrders.Count- 1 downto 0 do begin if (aOrders[i].GetKind=aKind) and (aOrders[i].GetState=osOpened) then CloseOrder(aOrders[i],aComment); end; end; procedure TStockTraderMACross3.CloseProfitableOrders(aKind: TSCOrderKind;const aComment: string); var i: Integer; aOrders : IStockOrderCollection; begin aOrders:=GetOrders; for i := aOrders.Count- 1 downto 0 do begin if (aOrders[i].GetKind=aKind) and (aOrders[i].GetCurrentProfit>0) then CloseOrder(aOrders[i],aComment); end; end; constructor TStockTraderMACross3.Create; begin inherited Create; FPropFullBarsOnly := TPropertyYesNo.Create('Method','Full Bars Only',self); FPropFullBarsOnly.Value:=true; FPropMaxPriceAndMAGap:=TPropertyInt.Create('Method','Max gap between price and MA level',self); FPropMaxPriceAndMAGap.Value:=200; RegisterProperties([FPropFullBarsOnly,FPropMaxPriceAndMAGap]); //UnRegisterProperties([PropLotDefaultRateSize,PropLotDynamicRate]); end; function TStockTraderMACross3.CreateBarHeightD1(const aChart: IStockChart): ISCIndicatorBarHeight; var aCreated: boolean; begin result:=CreateOrFindIndicator(aChart,ISCIndicatorBarHeight,'BarHeightD1',true, aCreated) as ISCIndicatorBarHeight; //Ничего не нашли, создадим нового эксперта if aCreated then begin Result.SetPeriod(3); Result.SetBarHeight(bhHighLow); end; end; function TStockTraderMACross3.CreateMA_H1(const aChart: IStockChart;aPeriod: integer; aMethod: TSCIndicatorMAMethod): ISCIndicatorMA; var aCreated: boolean; begin result:=CreateOrFindIndicator(aChart,ISCIndicatorMA,'MA'+IntToStr(integer(aMethod))+'_'+IntToStr(aPeriod)+'_H1',true, aCreated) as ISCIndicatorMA; //Ничего не нашли, создадим нового эксперта if aCreated then begin Result.SetMAMethod(aMethod); Result.SetPeriod(aPeriod); end; end; destructor TStockTraderMACross3.Destroy; begin inherited; end; procedure TStockTraderMACross3.Dispose; begin inherited; end; function TStockTraderMACross3.GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber; begin result:=aOrder.GetStopLoss; if aOrder.GetState=osOpened then if aOrder.GetKind=okBuy then result:=max(result,aOrder.GetBestPrice-aOrder.GetTrailingStop) else result:=min(result,aOrder.GetBestPrice+aOrder.GetTrailingStop); end; function TStockTraderMACross3.GetFastTrend(index: integer): TSCRealNumber; begin result:=0;//FLWMA21_H1.GetValue(index)-FLWMA55_H1.GetValue(index); end; function TStockTraderMACross3.GetRecommendedLots: TStockOrderLots; var aDayVolatility,aDayVolatilityM,k: TStockRealNumber; begin if not PropLotDynamicRate.Value then exit(inherited GetRecommendedLots); aDayVolatility:=FBarHeightD1.GetValue(FBarHeightD1.GetInputData.Count-1); //Считаем какая волатильность в деньгах у нас была последние дни aDayVolatilityM:=GetBroker.PriceToMoney(GetSymbol,aDayVolatility,1); //Считаем, сколько таких волатильностей вынесет наш баланс k:=(GetBroker.GetEquity/aDayVolatilityM); //Теперь берем допустимый процент result:=RoundTo(k*PropLotDynamicRateSize.Value/100,-2); end; function TStockTraderMACross3.GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber; begin if aOrder.GetKind=okBuy then result:=aOrder.GetOpenPrice-GetExpectedStopLossPrice(aOrder) else result:=GetExpectedStopLossPrice(aOrder) - aOrder.GetOpenPrice; end; procedure TStockTraderMACross3.SetProject(const aValue: IStockProject); begin if GetProject=aValue then exit; inherited; if aValue <> nil then begin //Создае нужных нам экспертов FBarHeightD1:=CreateBarHeightD1(aValue.GetStockChart(sti1440)); FSMA21_H1:= CreateMA_H1(aValue.GetStockChart(sti60),21,mamSimple); FSMA55_H1:= CreateMA_H1(aValue.GetStockChart(sti60),55,mamSimple); // FLWMA21_H1:= CreateMA_H1(aValue.GetStockChart(sti60),21,mamLinearWeighted); // FLWMA55_H1:= CreateMA_H1(aValue.GetStockChart(sti60),55,mamLinearWeighted); // FMA84_H1:= CreateMA_H1(aValue.GetStockChart(sti60),84,mamSimple); //FMA220_H1:= CreateMA_H1(aValue.GetStockChart(sti60),220,mamSimple); end; end; procedure TStockTraderMACross3.SetTP(const aOrder: IStockOrder;const aTP: TStockRealNumber; const aComment: string); var aNew : TStockRealNumber; begin aNew:=GetBroker.RoundPrice(aOrder.GetSymbol,aTP); if not SameValue(aNew,aOrder.GetTakeProfit) then begin if aComment<>'' then GetBroker.AddMessage(aOrder,aComment); aOrder.SetTakeProfit(aNew); end; end; function TStockTraderMACross3.GetMainTrend(index: integer): TSCRealNumber; begin result:=0;//FMA84_H1.GetValue(index)-FMA220_H1.GetValue(index); end; function TStockTraderMACross3.GetCross(index: integer): integer; var x1,x2: integer; begin x1:=Sign(FSMA21_H1.GetValue(index)-FSMA55_H1.GetValue(index)); x2:=Sign(FSMA21_H1.GetValue(index-1)-FSMA55_H1.GetValue(index-1)); if x1=x2 then exit(0); result:=x1; end; function TStockTraderMACross3.GetCurrentBid: TSCRealNumber; begin result:=GetBroker.GetCurrentPrice(GetSymbol,bpkBid); end; procedure TStockTraderMACross3.UpdateStep2(const aTime: TDateTime); var idx60: integer; aInputData : ISCInputDataCollection; aChart : IStockChart; aDataOpen,aDataClose : TSCRealNumber; aTime60 : TDateTime; //aFastTrend : TSCRealNumber; //aPrice : TSCRealNumber; aMALevel : TSCRealNumber; aBid,aAsk: TSCRealNumber; begin aTime60:=TStockDataUtils.AlignTimeToLeft(aTime,sti60); if SameTime(FLastOpenOrderTime,aTime60) then exit; //Брокер может закрыть ордера и без нас. У нас в списке они останутся, //но будут уже закрыты. Если их не убрать, то открываться в этоу же сторону мы не //сможем, пока не будет сигнала от эксперта. Если же их удалить, сигналы //от эксперта в эту же сторону опять можно отрабатывать RemoveClosedOrders; //Анализируем экcпертные оценки aChart:=GetParentStockChart(FSMA21_H1); aInputData:=aChart.GetInputData; idx60:=aChart.FindBar(aTime); if (idx60<>-1) and (idx60>=FSMA55_H1.GetPeriod) then begin aMALevel:=FSMA21_H1.GetValue(idx60); aBid:=GetBroker.GetCurrentPrice(GetSymbol,bpkBid); aAsk:=GetBroker.GetCurrentPrice(GetSymbol,bpkAsk); aDataOpen:=aInputData.DirectGetItem_DataOpen(idx60-1); aDataClose:=aInputData.DirectGetItem_DataClose(idx60); //Поднимаемся вверх if (aBid<aMALevel) and (aDataClose>aDataOpen) then begin OpenPendingOrder(okBuy,aMALevel) end; //Опускаемся вниз if (aAsk>aMALevel) and (aDataClose<aDataOpen) then begin OpenPendingOrder(okSell,aMALevel) end; if (aBid)>aMALevel then begin //CloseAllOrders(okSell,'Cross up'); end; if (aAsk)<aMALevel then begin //CloseAllOrders(okBuy,'Cross down'); end; end; end; procedure TStockTraderMACross3.OnBeginWorkSession; begin inherited; FLastOpenOrderTime:=0; end; function TStockTraderMACross3.OpenOrder(aKind: TStockOrderKind; const aComment: string): IStockOrder; begin Result:=inherited OpenOrder(aKind,aComment); end; function TStockTraderMACross3.OpenPendingOrder(aOrderType: TStockOrderKind;aLevel: TSCRealNumber): IStockOrder; var i: integer; aOrder: IStockOrder; begin aLevel:=GetBroker.RoundPrice(GetSymbol,aLevel); for i := 0 to GetOrders.Count-1 do begin aOrder:=GetOrders.Items[i]; if (aOrder.GetState=osPending) and (aOrder.GetKind=aOrderType) then begin result:=aOrder; break; end; end; try if result=nil then result:=OpenOrderAt(aOrderType,aLevel) else result.SetPendingOpenPrice(aLevel); except end; end; function TStockTraderMACross3.PriceToPoint(const aPrice: TSCRealNumber): integer; begin result:=GetBroker.PriceToPoint(GetSymbol,aPrice); end; initialization FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','MA Cross 3',TStockTraderMACross3,IStockTraderMACross3); end.
// ################################## // # TPLVisor - Michel Kunkler 2013 # // ################################## (* Turingmaschine Befehle werden beim Interpretieren der Befehlsobjekte aufgerufen. Hat ein Magnetband als Attribut. Kann das Magnetband als String speichern oder laden. *) unit TPLTuringmaschine; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Menus, TPLMagnetband, TPLZeichen; type TTuringmaschine = class private Form : TObject; procedure ZeichenAnfuegen; public Magnetband : TMagnetband; Panel : TPanel; Constructor Create(Form : TObject); Destructor Destroy; Reintroduce; procedure PanelResize(Sender: TObject); procedure BefehlLinks; procedure BefehlRechts; procedure BefehlSchreibe(Wert : char); function BefehlSpringeWenn(Wert : char; Ziel : integer) : boolean; function BefehlHole : char; function MagnetbandToString : string; procedure StringToMagnetband(Text : string); end; implementation uses TPLVisorMain; { TTuringmaschine } Constructor TTuringmaschine.Create(Form : TObject); begin self.Form := TTPLVisorForm(Form); self.Panel := TTPLVisorForm(self.Form).Band; self.Magnetband := TMagnetband.Create(self.Form); TTPLVisorForm(Form).Band.OnResize := self.PanelResize; self.PanelResize(Nil); //self.CreateMagnetkopf; end; Destructor TTuringmaschine.Destroy; begin self.Magnetband.Destroy; end; procedure TTuringmaschine.ZeichenAnfuegen; begin self.Magnetband.ErweitereRechts; end; procedure TTuringmaschine.PanelResize(Sender: TObject); begin // Magnetband nach rechts auffüllen while self.Magnetband.GetRechtsMax < self.Panel.Width do self.ZeichenAnfuegen; end; procedure TTuringmaschine.BefehlLinks; begin self.Magnetband.links; end; procedure TTuringmaschine.BefehlRechts; begin self.Magnetband.rechts; end; procedure TTuringmaschine.BefehlSchreibe(Wert : char); begin self.Magnetband.Position.Zeichen.ZEdit.Text := Wert; end; function TTuringmaschine.BefehlSpringeWenn(Wert : char; Ziel : integer) : boolean; begin Result := False; if self.Magnetband.Position.Zeichen.ZEdit.Text = Wert then Result := True; end; function TTuringmaschine.BefehlHole : char; begin Result := self.Magnetband.hole; end; function TTuringmaschine.MagnetbandToString : string; var Position : TZeichenKette; begin Position := self.Magnetband.ErstesZeichen; Result := ''; while Position <> nil do begin Result := Result+Position.Zeichen.ZEdit.Text; Position := TZeichenKette(Position.Naechstes); end; end; procedure TTuringmaschine.StringToMagnetband(Text : string); var i : integer; Position : TZeichenKette; begin self.Magnetband.Destroy; self.Magnetband := TMagnetband.Create(self.Form); Position := self.Magnetband.ErstesZeichen; for i:=1 to Length(Text) do begin Position.Zeichen.ZEdit.Text := Text[i]; self.Magnetband.ErweitereRechts; Position := TZeichenKette(Position.Naechstes); end; self.PanelResize(nil); end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} { Useful URLs: MSHTML Command Identifiers http://msdn.microsoft.com/library/default.asp?url=/workshop/browser/mshtml/reference/commandids.asp Command Identifiers (DHTML) http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/commandids.asp other supported commands IDM_INSERTOBJECT IDM_PRINT IDM_IFRAME IDM_REMOVEFORMAT } unit IEActions; interface uses System.SysUtils, Winapi.Windows, Vcl.Forms, System.Classes, Vcl.ActnList, Vcl.StdActns, Vcl.Dialogs, Winapi.ActiveX, WebBrowserEx, WBComp, Vcl.StdCtrls, Vcl.Graphics, MSHTML; type { TWebBrowserAction } TWebActionOption = (woDoDefault, woPromptUser, woDontPrompt, woShowHelp); TWebActionApplyOption = (applyRootDocument, applyAllDocuments, applyActiveDocument); TCustomWebBrowserAction = class(TCustomAction) private FControl: TWebBrowserEx; FCmdStr: string; FCmdID: TOleEnum; FHTMLTag: string; FUseexecCommand: Boolean; FUpdateChecked: Boolean; FCommandUpdater: TWebBrowserCommandUpdater; FCmdGroup: TGUID; FWebActionApplyOption: TWebActionApplyOption; procedure SetCmdID(const Value: TOleEnum); procedure SetCommandUpdater(const Value: TWebBrowserCommandUpdater); protected FCommandState: TCommandStates; FInParam: OleVariant; FOutParam: OleVariant; FOption: TWebActionOption; FShowUI: WordBool; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure UpdateCheckedState; property Control: TWebBrowserEx read FControl; property Option: TWebActionOption read FOption write FOption; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ExecuteTarget(Target: TObject); override; function HandlesTarget(Target: TObject): Boolean; override; procedure UpdateTarget(Target: TObject); override; property ApplyOption: TWebActionApplyOption read FWebActionApplyOption write FWebActionApplyOption; property CmdID: TOleEnum read FCmdID write SetCmdID; property CmdGroup: TGUID read FCmdGroup write FCmdGroup; property CommandUpdater: TWebBrowserCommandUpdater read FCommandUpdater write SetCommandUpdater; property UseexecCommand: Boolean read FUseexecCommand write FUseexecCommand; property UpdateChecked: Boolean read FUpdateChecked write FUpdateChecked; end; TWebBrowserAction = class(TCustomWebBrowserAction) published property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; TBrowserAction = class(TCustomWebBrowserAction) published property AutoCheck; property CommandUpdater; property Caption; property Checked; property CmdID; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property Option; property UseexecCommand; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property Visible; end; TWebBrowserUndoAction = class(TCustomWebBrowserAction) private FAllowBatchUndo: Boolean; protected procedure BeforeAction(Target: TObject); virtual; procedure DoAction(Target: TObject; Data: Integer); virtual; procedure AfterAction(Target: TObject); virtual; public constructor Create(AOwner: TComponent); override; procedure ExecuteTarget(Target: TObject); override; property AllowBatchUndo: Boolean read FAllowBatchUndo write FAllowBatchUndo default True; end; TWebBrowserToggleAction = class(TWebBrowserAction) private FNotInParam: Boolean; public constructor Create(AOwner: TComponent); override; procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; property NotInParam: Boolean read FNotInParam write FNotInParam; end; TWebBrowserOverrideCursor = class(TWebBrowserToggleAction) public constructor Create(AOwner: TComponent); override; end; { Edit Actions } TWebBrowserCut = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; procedure ExecuteTarget(Target: TObject); override; end; TWebBrowserCopy = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; procedure ExecuteTarget(Target: TObject); override; end; TWebBrowserPaste = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowserSelectAll = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowserSelectAllControls = class(TWebBrowserAction) public procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; end; // Currently documented as an unsupported command but works in (at least) IE 6.0 TWebBrowserUndo = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; // Currently documented as an unsupported command but works in (at least) IE 6.0 TWebBrowserRedo = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowserDelete = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; //procedure UpdateTarget(Target: TObject); override; end; TWebBrowserClearSelection = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowserMultiSelect = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserAtomicSelect = class(TWebBrowserToggleAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserKeepSelection = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; { Formatting operations } TWebBrowserFormatAction = class(TWebBrowserAction) public procedure UpdateTarget(Target: TObject); override; end; TWebBrowserBold = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserItalic = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserUnderLine = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserSuperscript = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserSubscript = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserAlignLeft = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserAlignRight = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserAlignCenter = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; // Currently documented as an unsupported command but works in IE 6.0 TWebBrowserAlignFull = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserIndent = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowserUnindent = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowserFont = class(TWebBrowserFormatAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowserColor = class(TWebBrowserFormatAction) private FDialog: TColorDialog; FExecuteResult: Boolean; FOnAccept: TNotifyEvent; FOnCancel: TNotifyEvent; FBeforeExecute: TNotifyEvent; function GetColor: TColor; procedure SetColor(const Value: TColor); protected procedure DoAccept; virtual; procedure DoCancel; virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetupDialog; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ExecuteTarget(Target: TObject); override; property Color: TColor read GetColor write SetColor; property Dialog: TColorDialog read FDialog write FDialog; property ExecuteResult: Boolean read FExecuteResult; property BeforeExecute: TNotifyEvent read FBeforeExecute write FBeforeExecute; property OnAccept: TNotifyEvent read FOnAccept write FOnAccept; property OnCancel: TNotifyEvent read FOnCancel write FOnCancel; end; TWebBrowserBackColor = class(TWebBrowserColor) public constructor Create(AOwner: TComponent); override; published property Dialog; end; TWebBrowserForeColor = class(TWebBrowserColor) public constructor Create(AOwner: TComponent); override; published property Dialog; end; { HTML Elements } TWebBrowserOrderedList = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserUnorderedList = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; { HTML Element actions } TWebBrowserCreateURL = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; procedure UpdateTarget(Target: TObject); override; end; TWebBrowserRemoveURL = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowser2DPosition = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserAbsolutePosition = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; { Page actions } TWebBrowserDesignMode = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; end; TWebBrowserPrint = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowserPrintPreview = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowserRefresh = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; TWebBrowserSaveAs = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; published property Option; end; TWebBrowserAddFavorites = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; { Design mode } TWebBrowserZeroBorder = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; procedure UpdateTarget(Target: TObject); override; published property UpdateChecked default True; end; // The TWebBrowserShowTags action only works with the default glyphs // provided with Internet Explorer. TShowTags = (stAll, stAlignedSiteTags, stScript, stStyle, stComment, stArea, stUnknown, stMisc); TWebBrowserShowTags = class(TWebBrowserAction) private FShowTags: TShowTags; procedure SetShowTags(const Value: TShowTags); public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; property ShowTags: TShowTags read FShowTags write SetShowTags default stAll; end; TWebBrowserLiveResize = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserRespectVisiblity = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; TWebBrowserAutoURLDetect = class(TWebBrowserToggleAction) public constructor Create(AOwner: TComponent); override; published property UpdateChecked default True; end; { Navigation } TWebBrowserBack = class(TWebBrowserAction) public procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; end; TWebBrowserForward = class(TWebBrowserAction) public procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; end; TWebBrowserHome = class(TWebBrowserAction) public procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; end; // Browses to the default search site TWebBrowserSearch = class(TWebBrowserAction) public procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; end; { Search/Replace } TWebBrowserSearchAction = class(TCommonDialogAction) protected FControl: TWebBrowserEx; FFindFirst: Boolean; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public function HandlesTarget(Target: TObject): Boolean; override; procedure Search(Sender: TObject); virtual; procedure UpdateTarget(Target: TObject); override; procedure ExecuteTarget(Target: TObject); override; end; { TWebBrowserSearchFind } TWebBrowserSearchFind = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; { TWebBrowserSearchFind = class(TWebBrowserSearchAction) private function GetFindDialog: TFindDialog; protected function GetDialogClass: TCommonDialogClass; override; published property Caption; property Dialog: TFindDialog read GetFindDialog; property Enabled; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property ShortCut; property SecondaryShortCuts; property Visible; property BeforeExecute; property OnAccept; property OnCancel; property OnHint; end;} TWebBrowserSearchReplace = class(TWebBrowserSearchAction) private procedure Replace(Sender: TObject); function GetReplaceDialog: TReplaceDialog; protected function GetDialogClass: TCommonDialogClass; override; public procedure ExecuteTarget(Target: TObject); override; published property Caption; property Dialog: TReplaceDialog read GetReplaceDialog; property Enabled; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property ShortCut; property SecondaryShortCuts; property Visible; property BeforeExecute; property OnAccept; property OnCancel; property OnHint; end; TWebBrowserSearchFindFirst = class(TWebBrowserSearchFind) public constructor Create(AOwner: TComponent); override; end; TWebBrowserSearchFindNext = class(TCustomAction) private FSearchFind: TWebBrowserSearchFind; public constructor Create(AOwner: TComponent); override; function HandlesTarget(Target: TObject): Boolean; override; procedure UpdateTarget(Target: TObject); override; procedure ExecuteTarget(Target: TObject); override; published property Caption; property Enabled; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property SearchFind: TWebBrowserSearchFind read FSearchFind write FSearchFind; property ShortCut; property SecondaryShortCuts; property Visible; property OnHint; end; { Frame Actions } TWebBrowserFrameAction = class(TWebBrowserUndoAction) public procedure UpdateTarget(Target: TObject); override; end; TWebBrowserSeamlessJoin = class(TWebBrowserFrameAction) protected procedure DoAction(Target: TObject; Data: Integer); override; public constructor Create(AOwner: TComponent); override; procedure UpdateTarget(Target: TObject); override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; TWebBrowserDeleteFrame = class(TWebBrowserFrameAction) protected procedure DoAction(Target: TObject; Data: Integer); override; public function HandlesTarget(Target: TObject): Boolean; override; procedure UpdateTarget(Target: TObject); override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; { Element Actions for actions on the element at the current caret position } TWebBrowserElementAction = class(TWebBrowserUndoAction) protected function GetElement: IHTMLElement; virtual; function IsTargetElement: Boolean; virtual; public procedure UpdateTarget(Target: TObject); override; property Element: IHTMLElement read GetElement; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; { HTML Control Action } TWebBrowserControlAction = class(TWebBrowserElementAction) protected function GetElement: IHTMLElement; override; end; { Input Action } TWebBrowserInputAction = class(TWebBrowserControlAction) protected function IsTargetElement: Boolean; override; end; { Image Actions } TWebBrowserImageAction = class(TWebBrowserControlAction) protected function IsTargetElement: Boolean; override; end; { Table Actions } TWebBrowserTableAction = class(TWebBrowserControlAction) protected function IsTargetElement: Boolean; override; end; TWebBrowserTableDelete = class(TWebBrowserTableAction) protected procedure DoAction(Target: TObject; Data: Integer); override; function GetElement: IHTMLElement; override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; TWebBrowserTableCellAction = class(TWebBrowserElementAction) protected function IsTargetElement: Boolean; override; function GetElement: IHTMLElement; override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; TWebBrowserTableInsertRow = class(TWebBrowserTableCellAction) private FInsertAbove: Boolean; protected procedure DoAction(Target: TObject; Data: Integer); override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property InsertAbove: Boolean read FInsertAbove write FInsertAbove default False; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; TWebBrowserTableDeleteRow = class(TWebBrowserTableCellAction) public procedure DoAction(Target: TObject; Data: Integer); override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; TWebBrowserTableMoveRow = class(TWebBrowserTableCellAction) private FMoveUp: Boolean; protected procedure DoAction(Target: TObject; Data: Integer); override; public procedure UpdateTarget(Target: TObject); override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property MoveUp: Boolean read FMoveUp write FMoveUp default False; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; TWebBrowserTableDeleteCell = class(TWebBrowserTableCellAction) public procedure DoAction(Target: TObject; Data: Integer); override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; TWebBrowserTableInsertCell = class(TWebBrowserTableCellAction) protected procedure DoAction(Target: TObject; Data: Integer); override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property UpdateChecked default False; property Visible; end; TWebBrowserTableColumnAction = class(TWebBrowserTableCellAction) private FActiveRow: IHTMLTableRow; protected property ActiveRow: IHTMLTableRow read FActiveRow; public procedure ExecuteTarget(Target: TObject); override; end; TWebBrowserTableInsertColumn = class(TWebBrowserTableColumnAction) private FInsertToLeft: boolean; protected procedure DoAction(Target: TObject; Data: Integer); override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property InsertToLeft: boolean read FInsertToLeft write FInsertToLeft; property Visible; end; TWebBrowserTableDeleteColumn = class(TWebBrowserTableColumnAction) protected procedure DoAction(Target: TObject; Data: Integer); override; published property AllowBatchUndo; property AutoCheck; property CommandUpdater; property Caption; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property Visible; end; { Control Selection Actions } TWebBrowserControlSelection = class(TCustomWebBrowserAction) private FControlRange: IHTMLControlRange; FAllowBatchUndo: Boolean; FMaxSelCount: Integer; FMinSelCount: Integer; FRange: IHTMLControlRange; FIgnoreLockedControls: Boolean; protected procedure BeforeAction; virtual; procedure DoAction(Index: Integer; Element: IHTMLElement); virtual; abstract; procedure AfterAction; virtual; function GetEnabled: Boolean; virtual; property ControlRange: IHTMLControlRange read FControlRange; public constructor Create(AOwner: TComponent); override; procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; property AllowBatchUndo: Boolean read FAllowBatchUndo write FAllowBatchUndo default True; property MinSelCount: Integer read FMinSelCount write FMinSelCount; property MaxSelCount: Integer read FMaxSelCount write FMaxSelCount; property IgnoreLockedControls: Boolean read FIgnoreLockedControls write FIgnoreLockedControls; end; { Z-Order Actions } TGetNextZIndexEvent = procedure(Sender: TObject; var NextZIndex: Integer) of object; TGetPrevZIndexEvent = procedure(Sender: TObject; var PrevZIndex: Integer) of object; TWebBrowserAbsolutionPositionAction = class(TWebBrowserControlSelection) protected function GetEnabled: Boolean; override; end; TWebBrowserBringToFront = class(TWebBrowserAbsolutionPositionAction) private FOnGetNextZIndex: TGetNextZIndexEvent; protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; published property CommandUpdater; property Caption; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property OnGetNextZIndex: TGetNextZIndexEvent read FOnGetNextZIndex write FOnGetNextZIndex; property SecondaryShortCuts; property ShortCut; property Visible; end; TWebBrowserSendToBack = class(TWebBrowserAbsolutionPositionAction) private FOnGetPrevZIndex: TGetPrevZIndexEvent; protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; published property CommandUpdater; property Caption; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property Visible; property OnGetPrevZIndex: TGetPrevZIndexEvent read FOnGetPrevZIndex write FOnGetPrevZIndex; end; { Control Alignment Actions } TWebBrowserAlignControls = class(TWebBrowserControlSelection) private FPrimaryElement: IHTMLElement; protected procedure BeforeAction; override; property PrimaryElement: IHTMLElement read FPrimaryElement; public constructor Create(AOwner: TComponent); override; published property CommandUpdater; property Caption; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property Visible; end; TWebBrowserAlignControlsLeft = class(TWebBrowserAlignControls) protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; end; TWebBrowserAlignControlsRight = class(TWebBrowserAlignControls) protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; end; TWebBrowserAlignControlsTop = class(TWebBrowserAlignControls) protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; end; TWebBrowserAlignControlsBottom = class(TWebBrowserAlignControls) protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; end; TWebBrowserAlignVerticalCenters = class(TWebBrowserAlignControls) protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; end; TWebBrowserAlignHorizontalCenters = class(TWebBrowserAlignControls) protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; end; { Control Size Actions } TWebBrowserControlSize = class(TWebBrowserAlignControls) published property CommandUpdater; property Caption; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property Visible; end; TWebBrowserMakeSameWidth = class(TWebBrowserControlSize) protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; end; TWebBrowserMakeSameHeight = class(TWebBrowserControlSize) protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; end; TWebBrowserMakeSameSize = class(TWebBrowserControlSize) protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; end; { TWebBrowserDesignTimeLock } TWebBrowserDesignTimeLock = class(TWebBrowserControlSelection) protected procedure DoAction(Index: Integer; Element: IHTMLElement); override; public procedure UpdateTarget(Target: TObject); override; published property CommandUpdater; property Caption; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ImageIndex; property OnChange; property OnExecute; property OnHint; property OnUpdate; property SecondaryShortCuts; property ShortCut; property Visible; end; { TWebBrowserInsertTag } TWebBrowserInsertTag = class; TElementCreatedEvent = procedure(Sender: TWebBrowserInsertTag; Element: IHTMLElement) of object; TWebBrowserInsertTag = class(TWebBrowserAction) private FHTMLTag: string; FOnElementCreated: TElementCreatedEvent; procedure SetHTMLTag(const Value: string); protected function CanInsert: Boolean; virtual; //function GetElement: IHTMLElement; function GetTagID: _ELEMENT_TAG_ID; public procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; published property HTMLTag: string read FHTMLTag write SetHTMLTag; property OnElementCreated: TElementCreatedEvent read FOnElementCreated write FOnElementCreated; end; TWebBrowserInsertFormTag = class(TWebBrowserInsertTag) protected function CanInsert: Boolean; override; end; { TWebBrowserOverwrite } TWebBrowserOverwrite = class(TWebBrowserAction) public constructor Create(AOwner: TComponent); override; end; procedure ValidateInsertablePosition(WebBrowser: TWebBrowserEx; StartPos: IMarkupPointer); procedure ShowElementCreateError(const ATagName, AMessage: string); function CanInsertControlAtCurrentPosition(WebBrowser: TWebBrowserEx): Boolean; const sDesignTimeLock = 'Design_Time_Lock'; { do not localize } implementation uses System.Win.ComObj, System.Variants, Vcl.Clipbrd, mshtmcid, Vcl.Menus, SHDocVw, Vcl.OleCtrls, IEConst; const CmdExecOption: array[TWebActionOption] of Integer = (OLECMDEXECOPT_DODEFAULT, OLECMDEXECOPT_PROMPTUSER, OLECMDEXECOPT_DONTPROMPTUSER, OLECMDEXECOPT_SHOWHELP); { TCustomWebBrowserAction } constructor TCustomWebBrowserAction.Create(AOwner: TComponent); begin inherited; Assert(ApplyOption = applyRootDocument); // Verify that this is the default FUpdateChecked := False; FInParam := Null; FOutParam := Null; FOption := woDontPrompt; FCmdID := 0; FCmdGroup := CGID_MSHTML; end; destructor TCustomWebBrowserAction.Destroy; begin if Assigned(FControl) then FControl.RemoveFreeNotification(Self); inherited; end; procedure TCustomWebBrowserAction.ExecuteTarget(Target: TObject); var Executed: Boolean; LViewLinkDocuments: IInterfaceList; I: Integer; LCommandTarget: IOleCommandTarget; begin inherited; if Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) and Assigned(CommandUpdater.WebBrowser.Document2) then begin CommandUpdater.DoBeforeCommand(FCmdID, Executed); if not Executed then begin if UseexecCommand then begin (CommandUpdater.WebBrowser.ActiveDocument as IHTMLDocument2).execCommand(FCmdStr, FOption = woPromptUser, FInParam); Assert(ApplyOption = applyActiveDocument); // Make sure we don't need to handle other cases end else begin case ApplyOption of applyAllDocuments, applyRootDocument: LCommandTarget := CommandUpdater.WebBrowser.Document2 as IOleCommandTarget; applyActiveDocument: LCommandTarget := CommandUpdater.WebBrowser.ActiveDocument as IOleCommandTarget; else Assert(false); end; if LCommandTarget <> nil then LCommandTarget.Exec(@FCmdGroup, FCmdID, CmdExecOption[FOption], FInParam, FOutParam); if ApplyOption = applyAllDocuments then begin LViewLinkDocuments := CommandUpdater.WebBrowser.GetViewLinkDocuments(FCmdID); if LViewLinkDocuments <> nil then begin for I := 0 to LViewLinkDocuments.Count - 1 do begin LCommandTarget := LViewLinkDocuments[I] as IOleCommandTarget; if LCommandTarget <> nil then LCommandTarget.Exec(@FCmdGroup, FCmdID, CmdExecOption[FOption], FInParam, FOutParam); end; end; end end; end; CommandUpdater.UpdateCommands(FCmdID); // Update the checked state here so that tool buttons won't bounce FCommandState := CommandUpdater.CommandState(FCmdID); UpdateCheckedState; CommandUpdater.DoAfterCommand(FCmdID); end; end; function TCustomWebBrowserAction.HandlesTarget(Target: TObject): Boolean; begin Result := Assigned(CommandUpdater); {and (Assigned(CommandUpdater.WebBrowser) or (((CommandUpdater.WebBrowser <> nil) and (Target = CommandUpdater.WebBrowser) or (CommandUpdater.WebBrowser = nil) and (Target is TWebBrowserEx)) and IsChild(TWebBrowserEx(Target).Handle, GetFocus)));} { if FBrowserControl = nil then if Result then begin if Assigned(FRegisteredBrowser) then begin if FRegisteredBrowser <> Target then FRegisteredBrowser.CommandUpdater.UnRegisterCommand(FCmdID); end else begin FRegisteredBrowser := Target as TWebBrowserEx; FRegisteredBrowser.CommandUpdater.RegisterCommand(FCmdID); end; end else if Assigned(FRegisteredBrowser) then begin FRegisteredBrowser.CommandUpdater.UnRegisterCommand(FCmdID); FRegisteredBrowser := nil; end;} end; procedure TCustomWebBrowserAction.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = CommandUpdater) then FCommandUpdater := nil; end; procedure TCustomWebBrowserAction.SetCmdID(const Value: TOleEnum); begin if FCmdID <> Value then begin if Assigned(CommandUpdater) and (Value <> 0) then CommandUpdater.UnRegisterCommand(CmdID); FCmdID := Value; if Assigned(CommandUpdater) and (FCmdID <> 0) then CommandUpdater.RegisterCommand(CmdID); end; end; procedure TCustomWebBrowserAction.SetCommandUpdater( const Value: TWebBrowserCommandUpdater); begin if FCommandUpdater <> Value then begin FCommandUpdater := Value; if Value <> nil then Value.FreeNotification(Self); if Assigned(FCommandUpdater) and (CmdID <> 0) then FCommandUpdater.RegisterCommand(CmdID); end; end; procedure TCustomWebBrowserAction.UpdateCheckedState; begin if csChecked in FCommandState then Checked := True else if UpdateChecked and Checked then Checked := False; end; procedure TCustomWebBrowserAction.UpdateTarget(Target: TObject); begin if not Assigned(CommandUpdater) or not Assigned(CommandUpdater.WebBrowser) then begin Enabled := False; exit; end; FCommandState := CommandUpdater.CommandState(FCmdID); Enabled := csEnabled in FCommandState; UpdateCheckedState; end; { TWebBrowserOverrideCursor } constructor TWebBrowserOverrideCursor.Create(AOwner: TComponent); begin inherited; CmdID := IDM_OVERRIDE_CURSOR; end; { TWebBrowserCut } constructor TWebBrowserCut.Create(AOwner: TComponent); begin inherited; CmdID := IDM_CUT; end; procedure TWebBrowserCut.ExecuteTarget(Target: TObject); begin CommandUpdater.WebBrowser.CutToClipboard end; { TWebBrowserCopy } constructor TWebBrowserCopy.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Copy'; { do not localize } CmdID := IDM_COPY; end; procedure TWebBrowserCopy.ExecuteTarget(Target: TObject); begin CommandUpdater.WebBrowser.CopyToClipboard end; { TWebBrowserPaste } constructor TWebBrowserPaste.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Paste'; { do not localize } CmdID := IDM_PASTE; end; { TWebBrowserSelectAll } constructor TWebBrowserSelectAll.Create(AOwner: TComponent); begin inherited; FCmdStr := 'SelectAll'; { do not localize } CmdID := IDM_SELECTALL; end; { TWebBrowserUndo } constructor TWebBrowserUndo.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Undo'; { do not localize } CmdID := IDM_UNDO; end; { TWebBrowserRedo } constructor TWebBrowserRedo.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Redo'; { do not localize } CmdID := IDM_REDO; end; { TWebBrowserDelete } constructor TWebBrowserDelete.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Delete'; { do not localize } CmdID := IDM_DELETE; end; { TWebBrowserBold } constructor TWebBrowserBold.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Bold'; { do not localize } CmdID := IDM_BOLD; FHTMLTag := 'strong'; { do not localize } UpdateChecked := True; end; { TWebBrowserItalic } constructor TWebBrowserItalic.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Italic'; { do not localize } CmdID := IDM_ITALIC; FHTMLTag := 'i'; { do not localize } UpdateChecked := True; end; { TWebBrowserUnderLine } constructor TWebBrowserUnderLine.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Underline'; { do not localize } CmdID := IDM_UNDERLINE; FHTMLTag := 'u'; { do not localize } UpdateChecked := True; end; { TWebBrowserClearSelection } constructor TWebBrowserClearSelection.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Unselect'; { do not localize } CmdID := IDM_CLEARSELECTION; end; { TWebBrowserMultiSelect } constructor TWebBrowserMultiSelect.Create(AOwner: TComponent); begin inherited; AutoCheck := True; CmdID := IDM_MULTIPLESELECTION; UpdateChecked := True; end; { TWebBrowserAtomicSelect } constructor TWebBrowserAtomicSelect.Create(AOwner: TComponent); begin inherited; CmdID := IDM_ATOMICSELECTION; UpdateChecked := True; end; { TWebBrowserOrderedList } constructor TWebBrowserOrderedList.Create(AOwner: TComponent); begin inherited; FCmdStr := 'InsertOrderedList'; { do not localize } CmdID := IDM_ORDERLIST; FHTMLTag := 'ol'; { do not localize } UpdateChecked := True; end; { TWebBrowserUnorderedList } constructor TWebBrowserUnorderedList.Create(AOwner: TComponent); begin inherited; FCmdStr := 'InsertUnorderedList'; { do not localize } CmdID := IDM_UNORDERLIST; FHTMLTag := 'ul'; { do not localize } UpdateChecked := True; end; { TWebBrowserAlignLeft } constructor TWebBrowserAlignLeft.Create(AOwner: TComponent); begin inherited; FCmdStr := 'JustifyLeft'; { do not localize } CmdID := IDM_JUSTIFYLEFT; FHTMLTag := 'div align=left'; { do not localize } UpdateChecked := True; end; { TWebBrowserAlignRight } constructor TWebBrowserAlignRight.Create(AOwner: TComponent); begin inherited; FCmdStr := 'JustifyRight'; { do not localize } CmdID := IDM_JUSTIFYRIGHT; FHTMLTag := 'div align=right'; { do not localize } UpdateChecked := True; end; { TWebBrowserAlignCenter } constructor TWebBrowserAlignCenter.Create(AOwner: TComponent); begin inherited; FCmdStr := 'JustifyCenter'; { do not localize } CmdID := IDM_JUSTIFYCENTER; FHTMLTag := 'div align=center'; { do not localize } UpdateChecked := True; end; { TWebBrowserAlignFull } constructor TWebBrowserAlignFull.Create(AOwner: TComponent); begin inherited; FCmdStr := 'JustifyFull'; { do not localize } CmdID := IDM_JUSTIFYFULL; UpdateChecked := True; //!! FHTMLTag := '???'; { do not localize } end; { TWebBrowserIndent } constructor TWebBrowserIndent.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Indent'; { do not localize } CmdID := IDM_INDENT; FHTMLTag := 'blockquote dir=ltr style="MARGIN-RIGHT: 0px"' { do not localize } end; { TWebBrowserUnindent } constructor TWebBrowserUnindent.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Outdent'; { do not localize } CmdID := IDM_OUTDENT; end; { TWebBrowserCreateURL } constructor TWebBrowserCreateURL.Create(AOwner: TComponent); begin inherited; FShowUI := True; FCmdStr := 'CreateLink'; { do not localize } CmdID := IDM_HYPERLINK; FOption := woDoDefault; end; procedure TWebBrowserCreateURL.UpdateTarget(Target: TObject); var D2: IHTMLDocument2; begin if not Assigned(CommandUpdater) or not Assigned(CommandUpdater.WebBrowser) then begin Enabled := False; exit; end; if CommandUpdater.WebBrowser.ActiveDocument <> nil then if Supports(CommandUpdater.WebBrowser.ActiveDocument, IHTMLDocument2, D2) then Enabled := D2.queryCommandEnabled(FCmdStr) else Enabled := False; end; { TWebBrowserRemoveURL } constructor TWebBrowserRemoveURL.Create(AOwner: TComponent); begin inherited; FCmdStr := 'Unlink'; CmdID := IDM_UNLINK; end; { TWebBrowser2DPosition } constructor TWebBrowser2DPosition.Create(AOwner: TComponent); begin inherited; FCmdStr := '2D-Position'; { do not localize } CmdID := IDM_2D_POSITION; UpdateChecked := True; end; { TWebBrowserAbsolutePosition } constructor TWebBrowserAbsolutePosition.Create(AOwner: TComponent); begin inherited; FCmdStr := 'AbsolutePosition'; { do not localize } CmdID := IDM_ABSOLUTE_POSITION; // Jmt. Not sure why this is needed. Seems like ApplyAllDocuments should work but doesn't ApplyOption := applyActiveDocument; UpdateChecked := True; end; { TWebBrowserDesignMode } constructor TWebBrowserDesignMode.Create(AOwner: TComponent); begin inherited; AutoCheck := True; end; procedure TWebBrowserDesignMode.ExecuteTarget(Target: TObject); const DesignMode: array[Boolean] of string = ('Off', 'On'); begin if Checked then CommandUpdater.WebBrowser.Document2.designMode := 'On' else CommandUpdater.WebBrowser.Document2.designMode := 'Off'; end; procedure TWebBrowserDesignMode.UpdateTarget(Target: TObject); begin Enabled := Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) and (CommandUpdater.WebBrowser.Document2 <> nil); end; { TWebBrowserPrint } constructor TWebBrowserPrint.Create(AOwner: TComponent); begin inherited; FShowUI := True; FCmdStr := 'Print'; CmdID := IDM_PRINT; FOption := woDoDefault; end; { TWebBrowserRefresh } constructor TWebBrowserRefresh.Create(AOwner: TComponent); begin inherited; CmdID := IDM_REFRESH; end; { TWebBrowserSaveAs } constructor TWebBrowserSaveAs.Create(AOwner: TComponent); begin inherited; FShowUI := True; FCmdStr := 'SaveAs'; CmdID := IDM_SAVEAS; FOption := woDoDefault; end; { TWebBrowserBack } procedure TWebBrowserBack.ExecuteTarget(Target: TObject); begin CommandUpdater.WebBrowser.GoBack; end; procedure TWebBrowserBack.UpdateTarget(Target: TObject); begin Enabled := Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) and CommandUpdater.WebBrowser.BackEnabled; end; { TWebBrowserForward } procedure TWebBrowserForward.ExecuteTarget(Target: TObject); begin CommandUpdater.WebBrowser.GoForward; end; procedure TWebBrowserForward.UpdateTarget(Target: TObject); begin Enabled := Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) and CommandUpdater.WebBrowser.ForwardEnabled; end; { TWebBrowserHome } procedure TWebBrowserHome.ExecuteTarget(Target: TObject); begin CommandUpdater.WebBrowser.GoHome; end; procedure TWebBrowserHome.UpdateTarget(Target: TObject); begin Enabled := Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser); end; { TWebBrowserSearch } procedure TWebBrowserSearch.ExecuteTarget(Target: TObject); begin CommandUpdater.WebBrowser.GoSearch; end; procedure TWebBrowserSearch.UpdateTarget(Target: TObject); begin Enabled := Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser); end; procedure TWebBrowserSearchAction.ExecuteTarget(Target: TObject); begin FControl := TWebBrowserEx(Target); if Assigned(FControl) then FControl.FreeNotification(Self); inherited ExecuteTarget(Target); end; function TWebBrowserSearchAction.HandlesTarget(Target: TObject): Boolean; begin Result := Screen.ActiveControl is TWebBrowser; if not Result then Enabled := False; end; procedure TWebBrowserSearchAction.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FControl) then FControl := nil; end; procedure TWebBrowserSearchAction.Search(Sender: TObject); {var EndPtr: IMarkupPointer; SearchPos: IMarkupPointer; E: IHTMLElement; Result: HRESULT;} begin if not Assigned(FControl) then exit; (* WebBrowserEx1.MarkupServices.CreateMarkupPointer(EndPtr); Result := WebBrowserEx1.MarkupServices.CreateMarkupPointer(SearchPos); Result := EndPtr.MoveAdjacentToElement(WebBrowserEx1.Document2.body, ELEM_ADJ_BeforeEnd); Result := SearchPos.MoveAdjacentToElement(WebBrowserEx1.Document2.body, ELEM_ADJ_AfterBegin); OleCheck(SearchPos.findText('test', 0, EndPtr, EndPtr)); // OleCheck(SearchPos.findText('test', 0, EndPtr, EndPtr)); // WebBrowserEx1.MarkupServices.Remove(SearchPos, EndPtr); WebBrowserEx1.MarkupServices.InsertText('STEVE', Length('STEVE'), SearchPos); // Result := SearchPos.findText('test', 0, EndPtr, EndPtr); // if not SearchEdit(FControl, TFindDialog(FDialog).FindText, // TFindDialog(FDialog).Options, FFindFirst) then // ShowMessage(Format(STextNotFound, [TFindDialog(FDialog).FindText])); *) end; procedure TWebBrowserSearchAction.UpdateTarget(Target: TObject); begin Enabled := (Target is TWebBrowser) and (TWebBrowser(Target).Document <> nil); end; { TWebBrowserZeroBorder } constructor TWebBrowserZeroBorder.Create(AOwner: TComponent); begin inherited; // !! This action is very expensive to execute on idle CmdID := IDM_SHOWZEROBORDERATDESIGNTIME; Option := woDontPrompt; ApplyOption := applyAllDocuments; end; procedure TWebBrowserZeroBorder.UpdateTarget(Target: TObject); begin Enabled := Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) and not CommandUpdater.WebBrowser.UserMode;// CompareText(GetBrowserControl(Target).Document2.designMode, 'On') = 0; Checked := csSupported in CommandUpdater.CommandState(CmdID); end; { TWebBrowserShowTags } const HTMLTags: array[TShowTags] of Integer = (IDM_SHOWALLTAGS, IDM_SHOWALIGNEDSITETAGS, IDM_SHOWSCRIPTTAGS, IDM_SHOWSTYLETAGS, IDM_SHOWCOMMENTTAGS, IDM_SHOWAREATAGS, IDM_SHOWUNKNOWNTAGS, IDM_SHOWMISCTAGS); constructor TWebBrowserShowTags.Create(AOwner: TComponent); begin inherited; ShowTags := stAll; CmdID := HTMLTags[FShowTags]; Option := woDontPrompt; FOutParam := NULL; UpdateChecked := True; ApplyOption := applyAllDocuments; end; procedure TWebBrowserShowTags.SetShowTags(const Value: TShowTags); begin // favor of the new style if ShowTags <> Value then begin FShowTags := Value; CmdID := HTMLTags[Value]; end; end; { TWebBrowserLiveResize } constructor TWebBrowserLiveResize.Create(AOwner: TComponent); begin inherited; FCmdStr := 'LiveResize'; CmdID := IDM_LIVERESIZE; FOption := woDoDefault; UpdateChecked := True; end; { TWebBrowserRespectVisiblity } constructor TWebBrowserRespectVisiblity.Create(AOwner: TComponent); begin inherited; CmdID := IDM_RESPECTVISIBILITY_INDESIGN; AutoCheck := True; UpdateChecked := True; end; { TWebBrowserUndoAction } procedure TWebBrowserUndoAction.AfterAction; begin // Now that we are done with the Action end the undo unit if AllowBatchUndo then CommandUpdater.WebBrowser.MarkupServices.EndUndoUnit; end; procedure TWebBrowserUndoAction.BeforeAction; begin // Start an undo unit so that the action can be undone if AllowBatchUndo then CommandUpdater.WebBrowser.MarkupServices.BeginUndoUnit(Name); end; constructor TWebBrowserUndoAction.Create(AOwner: TComponent); begin inherited; FAllowBatchUndo := True; end; procedure TWebBrowserUndoAction.DoAction(Target: TObject; Data: Integer); begin end; procedure TWebBrowserUndoAction.ExecuteTarget(Target: TObject); begin BeforeAction(Target); DoAction(Target, 0); AfterAction(Target); end; { TWebBrowserToggleAction } constructor TWebBrowserToggleAction.Create(AOwner: TComponent); begin inherited; AutoCheck := True; FOutParam := Null; TVarData(FInParam).VType := varBoolean; Option := woDontPrompt; end; procedure TWebBrowserToggleAction.ExecuteTarget(Target: TObject); begin // NotInParam allows this descendants to control the FInParam value if NotInParam then FInParam := not Checked else FInParam := Checked; inherited; end; procedure TWebBrowserToggleAction.UpdateTarget(Target: TObject); begin inherited; end; { TWebBrowserAddFavorites } constructor TWebBrowserAddFavorites.Create(AOwner: TComponent); begin inherited; CmdID := IDM_ADDFAVORITES; FOption := woPromptUser; end; { TWebBrowserFont } constructor TWebBrowserFont.Create(AOwner: TComponent); begin inherited; CmdID := IDM_FONT; FOption := woPromptUser; end; { TWebBrowserColor } constructor TWebBrowserColor.Create(AOwner: TComponent); begin inherited; SetupDialog; DisableIfNoHandler := False; end; destructor TWebBrowserColor.Destroy; begin if Assigned(FDialog) then FDialog.RemoveFreeNotification(Self); inherited; end; procedure TWebBrowserColor.DoAccept; begin if Assigned(FOnAccept) then FOnAccept(Self) else Color := FDialog.Color; end; procedure TWebBrowserColor.DoCancel; begin if Assigned(FOnCancel) then FOnCancel(Self); end; procedure TWebBrowserColor.ExecuteTarget(Target: TObject); begin FExecuteResult := False; if Assigned(FDialog) then begin if Assigned(FBeforeExecute) then FBeforeExecute(Self); FControl := CommandUpdater.WebBrowser; try FDialog.Color := Color; FExecuteResult := FDialog.Execute; if FExecuteResult then DoAccept else DoCancel; finally FControl := nil; end; end; end; function TWebBrowserColor.GetColor: TColor; var Clr: OleVariant; begin if csDesigning in ComponentState then begin Result := clDefault; exit; end; Control.CommandTarget.Exec(@FCmdGroup, CmdID, OLECMDEXECOPT_DONTPROMPTUSER, POleVariant(nil)^, Clr); Result := Clr; end; procedure TWebBrowserColor.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if not (csDestroying in ComponentState) and (Operation = opRemove) and (AComponent = FDialog) then SetupDialog; end; procedure TWebBrowserColor.SetColor(const Value: TColor); var Clr: OleVariant; begin if csDesigning in ComponentState then exit; Clr := Value; OleCheck(Control.CommandTarget.Exec(@FCmdGroup, CmdID, OLECMDEXECOPT_DONTPROMPTUSER, Clr, POleVariant(nil)^)); end; procedure TWebBrowserColor.SetupDialog; begin FDialog := TColorDialog.Create(Self); FDialog.Name := Copy(TColorDialog.ClassName, 2, Length(TColorDialog.ClassName)); FDialog.SetSubComponent(True); FDialog.FreeNotification(Self); end; { TWebBrowserBackColor } constructor TWebBrowserBackColor.Create(AOwner: TComponent); begin inherited; CmdID := IDM_BACKCOLOR; FOption := woDontPrompt; end; { TWebBrowserForeColor } constructor TWebBrowserForeColor.Create(AOwner: TComponent); begin inherited; CmdID := IDM_FORECOLOR; FOption := woDontPrompt; end; { TWebBrowserPrintPreview } constructor TWebBrowserPrintPreview.Create(AOwner: TComponent); begin inherited; CmdID := IDM_PRINTPREVIEW; FOption := woPromptUser; end; { TWebBrowserAutoURLDetect } constructor TWebBrowserAutoURLDetect.Create(AOwner: TComponent); begin inherited; CmdID := IDM_AUTOURLDETECT_MODE; UpdateChecked := True; end; { TWebBrowserSearchFind } constructor TWebBrowserSearchFind.Create(AOwner: TComponent); begin inherited; CmdID := IDM_FIND; end; {function TWebBrowserSearchFind.GetDialogClass: TCommonDialogClass; begin Result := TFindDialog; end; function TWebBrowserSearchFind.GetFindDialog: TFindDialog; begin Result := TFindDialog(FDialog); end;} { TWebBrowserSearchReplace } procedure TWebBrowserSearchReplace.ExecuteTarget(Target: TObject); begin inherited ExecuteTarget(Target); TReplaceDialog(FDialog).OnReplace := Replace; end; function TWebBrowserSearchReplace.GetDialogClass: TCommonDialogClass; begin Result := TReplaceDialog; end; function TWebBrowserSearchReplace.GetReplaceDialog: TReplaceDialog; begin Result := TReplaceDialog(FDialog); end; procedure TWebBrowserSearchReplace.Replace(Sender: TObject); {var Found: Boolean; FoundCount: Integer;} begin // FBrowserControl gets set in ExecuteTarget // Found := False; // FoundCount := 0; { if Assigned(FControl) then with Sender as TReplaceDialog do begin if (Length(FControl.SelText) > 0) and (not (frReplaceAll in Dialog.Options) and (AnsiCompareText(FControl.SelText, FindText) = 0) or (frReplaceAll in Dialog.Options) and (FControl.SelText = FindText)) then begin FControl.SelText := ReplaceText; SearchEdit(FControl, Dialog.FindText, Dialog.Options, FFindFirst); if not (frReplaceAll in Dialog.Options) then exit; end; repeat Found := SearchEdit(FControl, Dialog.FindText, Dialog.Options, FFindFirst); if Found then begin FControl.SelText := ReplaceText; Inc(FoundCount); end; until not Found or not (frReplaceAll in Dialog.Options); end; if not Found and (FoundCount = 0) then ShowMessage(Format(STextNotFound, [Dialog.FindText]));} end; { TWebBrowserSearchFindFirst } constructor TWebBrowserSearchFindFirst.Create(AOwner: TComponent); begin inherited; // FFindFirst := True; end; { TWebBrowserSearchFindNext } constructor TWebBrowserSearchFindNext.Create(AOwner: TComponent); begin inherited; DisableIfNoHandler := False; end; procedure TWebBrowserSearchFindNext.ExecuteTarget(Target: TObject); begin FSearchFind.FControl := TWebBrowserEx(Target); if not Assigned(FSearchFind) then exit; // FSearchFind.Search(Target); end; function TWebBrowserSearchFindNext.HandlesTarget(Target: TObject): Boolean; begin Result := inherited HandlesTarget(Target); // Result := Assigned(FSearchFind) and FSearchFind.Enabled and // (Length(TFindDialog(FSearchFind.Dialog).FindText) <> 0); // Enabled := Result; end; procedure TWebBrowserSearchFindNext.UpdateTarget(Target: TObject); begin if Assigned(FSearchFind) then // Enabled := FSearchFind.Enabled and (Length(TFindDialog(FSearchFind.Dialog).FindText) <> 0) else Enabled := False; end; { TWebBrowserSuperscript } constructor TWebBrowserSuperscript.Create(AOwner: TComponent); begin inherited; FCmdID := IDM_SUPERSCRIPT; UpdateChecked := True; end; { TWebBrowserSubscript } constructor TWebBrowserSubscript.Create(AOwner: TComponent); begin inherited; FCmdID := IDM_SUBSCRIPT; UpdateChecked := True; end; { TWebBrowserFrameAction } procedure TWebBrowserFrameAction.UpdateTarget(Target: TObject); begin if Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) and Assigned(CommandUpdater.WebBrowser.Document2) then Enabled := CommandUpdater.WebBrowser.Document2.frames.length <> 0 else Enabled := False; end; { TWebBrowserSeamlessJoin } constructor TWebBrowserSeamlessJoin.Create(AOwner: TComponent); begin inherited; AutoCheck := True; end; procedure TWebBrowserSeamlessJoin.DoAction(Target: TObject; Data: Integer); var FrameSet: IHTMLFrameSetElement; begin inherited; CommandUpdater.WebBrowser.MarkupServices.BeginUndoUnit(Name); try if Checked then begin if Supports(CommandUpdater.WebBrowser.Document2.body, IHTMLFrameSetElement, FrameSet) then begin FrameSet.frameBorder := '0'; { do not localize } FrameSet.frameSpacing := 0; FrameSet.border := 0; end; end else with CommandUpdater.WebBrowser.Document2.body do begin removeAttribute('frameBorder', 0); { do not localize } removeAttribute('border', 0); { do not localize } removeAttribute('frameSpacing', 0); { do not localize } end; finally CommandUpdater.WebBrowser.MarkupServices.EndUndoUnit; end; end; procedure TWebBrowserSeamlessJoin.UpdateTarget(Target: TObject); begin inherited; end; { TWebBrowserDeleteFrame } procedure TWebBrowserDeleteFrame.DoAction(Target: TObject; Data: Integer); begin inherited; // and the frame just moved to it's parent. with CommandUpdater.WebBrowser do MarkupServices.RemoveElement(Document2.activeElement); end; function TWebBrowserDeleteFrame.HandlesTarget(Target: TObject): Boolean; begin Result := Assigned(CommandUpdater) and (CommandUpdater.WebBrowser <> nil); end; procedure TWebBrowserDeleteFrame.UpdateTarget(Target: TObject); begin if Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) and Assigned(CommandUpdater.WebBrowser.Document2) then if CommandUpdater.WebBrowser.Document2.frames.length <> 0 then Enabled := Supports(CommandUpdater.WebBrowser.Document2.activeElement, IHTMLFrameElement) else Enabled := False else Enabled := False; end; { TWebBrowserElementAction } function TWebBrowserElementAction.GetElement: IHTMLElement; begin Result := nil; if (CommandUpdater = nil) or (CommandUpdater.WebBrowser = nil) or (CommandUpdater.WebBrowser.DisplayServices = nil) or (csDesigning in ComponentState) then exit; // Used cached current element Result := CommandUpdater.WebBrowser.CurrentElement; end; (* Slow version function TWebBrowserElementAction.GetElement: IHTMLElement; function CreateRange: IDispatch; var Selection: IHTMLSelectionObject; begin Result := nil; try Selection := CommandUpdater.WebBrowser.Selection; if (Selection <> nil) then Result := Selection.createRange else Result := nil; except // Silent exceptions that occur when document is // <body><frameset rows="*,5*"/><html></html></body> Result := nil; end; end; var Range: IDispatch; TxtRange: IHTMLTxtRange; CtrlRange: IHTMLControlRange; DisplayServices: TDisplayServices; MarkupPointer: IMarkupPointer; begin Result := nil; if (CommandUpdater = nil) or (CommandUpdater.WebBrowser = nil) or (CommandUpdater.WebBrowser.DisplayServices = nil) or (csDesigning in ComponentState) then exit; //Range := SafeCreateRange(CommandUpdater.WebBrowser); Range := CreateRange; if Supports(Range, IHTMLControlRange, CtrlRange) then Result := CtrlRange.item(0) else if Supports(Range, IHTMLTxtRange, TxtRange) then Result := TxtRange.parentElement else begin // Very slow OleCheck(CommandUpdater.WebBrowser.MarkupServices.CreateMarkupPointer(MarkupPointer)); CommandUpdater.WebBrowser.Caret.MoveMarkupPointerToCaret(MarkupPointer); MarkupPointer.CurrentScope(Result); end; end; *) function TWebBrowserElementAction.IsTargetElement: Boolean; begin Result := Supports(GetElement, IHTMLElement); end; procedure TWebBrowserElementAction.UpdateTarget(Target: TObject); begin if not (csDesigning in ComponentState) then Enabled := IsTargetElement; end; { TWebBrowserTableAction } function TWebBrowserTableAction.IsTargetElement: Boolean; begin Result := Supports(GetElement, IHTMLTable); end; { TWebBrowserTableCellAction } function TWebBrowserTableCellAction.GetElement: IHTMLElement; begin Result := inherited GetElement; while Assigned(Result) do if Supports(Result, IHTMLTableCell) then break else Result := Result.parentElement; if Result <> nil then if not CommandUpdater.WebBrowser.GetIsEditableElement(Result.ParentElement, [efInnerRequired]) then Result := nil; end; function TWebBrowserTableCellAction.IsTargetElement: Boolean; var E: IHTMLElement; begin E := GetElement; Result := Assigned(E); end; { TWebBrowserTableInsertRow } procedure TWebBrowserTableInsertRow.DoAction(Target: TObject; Data: Integer); const RowPosition: array[Boolean] of Integer = (ELEM_ADJ_AfterEnd, ELEM_ADJ_BeforeBegin); var E: IHTMLElement; NewRow: IHTMLElement; NewCell: IHTMLElement; Row: IHTMLTableRow; Cells: IHTMLElementCollection; I: Integer; Table: IHTMLTable; MS: TMarkupServices; begin inherited; E := GetElement; while Assigned(E) and not Supports(E, IHTMLTable) do begin E := E.parentElement; if Supports(E, IHTMLTableRow) then Row := E as IHTMLTableRow; end; if Assigned(E) then if Assigned(Row) and Supports(E, IHTMLTable, Table) then begin MS := TMarkupServices.Create(nil); try MS.WebBrowser := CommandUpdater.WebBrowser; MS.StartPos.MoveAdjacentToElement(Row as IHTMLElement, RowPosition[FInsertAbove]); MS.FinishPos.MoveAdjacentToElement(Row as IHTMLElement, RowPosition[FInsertAbove]); MS.InsertPos.MoveAdjacentToElement(Row as IHTMLElement, RowPosition[FInsertAbove]); MS.MarkupServices.CloneElement(Row as IHTMLElement, NewRow); MS.InsertElement(NewRow); Cells := Row.cells; MS.StartPos.MoveAdjacentToElement(NewRow, ELEM_ADJ_AfterBegin); MS.FinishPos.MoveAdjacentToElement(NewRow, ELEM_ADJ_AfterBegin); MS.InsertPos.MoveAdjacentToElement(NewRow, ELEM_ADJ_AfterBegin); for I := 0 to Row.cells.length - 1 do begin MS.MarkupServices.CloneElement(Cells.item(i, i) as IHTMLElement, NewCell); MS.InsertElement(NewCell); MS.StartPos.MoveAdjacentToElement(NewCell, ELEM_ADJ_AfterEnd); MS.FinishPos.MoveAdjacentToElement(NewCell, ELEM_ADJ_AfterEnd); MS.InsertPos.MoveAdjacentToElement(NewCell, ELEM_ADJ_AfterEnd); end; finally MS.Free; end; end; end; { TWebBrowserTableDeleteCell } procedure TWebBrowserTableDeleteCell.DoAction(Target: TObject; Data: Integer); var Cell: IHTMLTableCell; CellIdx: Integer; E: IHTMLElement; Row: IHTMLTableRow; Table: IHTMLTableSection; begin inherited; E := GetElement; if Supports(E, IHTMLTableCell, Cell) then begin CellIdx := Cell.cellIndex; if Supports(E.parentElement, IHTMLTableRow, Row) then Row.deleteCell(CellIdx); if Row.cells.length = 0 then with (Row as IHTMLElement) do if Supports(parentElement, IHTMLTableSection, Table) then Table.deleteRow(Row.rowIndex); end; end; { TWebBrowserTableInsertCell } procedure TWebBrowserTableInsertCell.DoAction(Target: TObject; Data: Integer); var Cell: IHTMLTableCell; CellIdx: Integer; E: IHTMLElement; Row: IHTMLTableRow; begin inherited; E := GetElement; if Supports(E, IHTMLTableCell, Cell) then begin CellIdx := Cell.cellIndex; if Supports(E.parentElement, IHTMLTableRow, Row) then Row.insertCell(CellIdx); end; end; { TWebBrowserTableColumnAction } procedure TWebBrowserTableColumnAction.ExecuteTarget(Target: TObject); var Cell: IHTMLTableCell; CellIdx: Integer; E: IHTMLElement; Row: IHTMLTableRow; I: Integer; Table: IHTMLTable; begin BeforeAction(Target); E := GetElement; CellIdx := -1; if Supports(E, IHTMLTableCell, Cell) then CellIdx := Cell.cellIndex; while Assigned(E) and not Supports(E, IHTMLTable) do begin E := E.parentElement; Supports(E, IHTMLTableRow, Row); end; if Assigned(E) and (CellIdx <> -1) then if Supports(E, IHTMLTable, Table) then for I := 0 to Table.rows.length - 1 do begin FActiveRow := Table.rows.item(I,I) as IHTMLTableRow; if FActiveRow.cells.length < CellIdx then DoAction(Target, FActiveRow.cells.length - 1) else DoAction(Target, CellIdx); end; AfterAction(Target); end; { TWebBrowserTableInsertColumn } procedure TWebBrowserTableInsertColumn.DoAction(Target: TObject; Data: Integer); begin if not FInsertToLeft then Inc(Data); if Data = ActiveRow.cells.length then Data := -1; ActiveRow.insertCell(Data); end; { TWebBrowserTableDeleteColumn } procedure TWebBrowserTableDeleteColumn.DoAction(Target: TObject; Data: Integer); begin ActiveRow.deleteCell(Data); end; { TWebBrowserTableMoveRow } procedure TWebBrowserTableMoveRow.DoAction(Target: TObject; Data: Integer); const MoveDirection: array[Boolean] of Integer = (1,-1); var E: IHTMLElement; Row: IHTMLTableRow; Body: IHTMLTableSection2; begin inherited; E := GetElement; if Supports(E, IHTMLTableCell) then begin E := E.parentElement; if Supports(E, IHTMLTableRow, Row) then if Supports((Row as IHTMLElement).parentElement, IHTMLTableSection2, Body) then Body.moveRow(Row.rowIndex, Row.rowIndex + MoveDirection[MoveUp]); end; end; procedure TWebBrowserTableMoveRow.UpdateTarget(Target: TObject); const MoveDirection: array[Boolean] of Integer = (1,-1); var E: IHTMLElement; Table: IHTMLTable; Row: IHTMLTableRow; begin if not (csDesigning in ComponentState) then if IsTargetElement then begin if Supports(Element, IHTMLTableCell) then begin E := Element.parentElement; if Supports(E, IHTMLTableRow, Row) then if MoveUp then Enabled := Row.rowIndex > 0 else begin Table := nil; while Assigned(E) and not Supports(E, IHTMLTable, Table) do E := E.parentElement; if Assigned(Table) then Enabled := Row.rowIndex < Table.rows.length - 1; end; end; end else Enabled := False; end; { TWebBrowserTableDeleteRow } procedure TWebBrowserTableDeleteRow.DoAction(Target: TObject; Data: Integer); var E: IHTMLElement; Row: IHTMLTableRow; TBody: IHTMLTableSection; Table: IHTMLTable; DOMNode: IHTMLDOMNode; begin inherited; E := GetElement; if Supports(E.parentElement, IHTMLTableRow, Row) then if Supports((Row as IHTMLElement).parentElement, IHTMLTableSection, TBody) then begin TBody.deleteRow(Row.rowIndex); if TBody.rows.length = 0 then with TBody as IHTMLElement do if Supports(parentElement, IHTMLTable, Table) then if Supports(Table, IHTMLDOMNode, DOMNode) then DOMNode.removeNode(True); end; end; { TWebBrowserKeepSelection } constructor TWebBrowserKeepSelection.Create(AOwner: TComponent); begin inherited; FOption := woDontPrompt; CmdID := IDM_KEEPSELECTION; end; { TWebBrowserTableDelete } procedure TWebBrowserTableDelete.DoAction(Target: TObject; Data: Integer); var E: IHTMLElement; DOMNode: IHTMLDOMNode; begin inherited; E := GetElement; if Supports(E, IHTMLDOMNode, DOMNode) then DOMNode.removeNode(True); end; function TWebBrowserTableDelete.GetElement: IHTMLElement; begin Result := inherited GetElement; while Assigned(Result) and not Supports(Result, IHTMLTable) do Result := Result.parentElement; end; { TWebBrowserControlSelection } procedure TWebBrowserControlSelection.AfterAction; begin // Now that we are done with the Action end the undo unit if AllowBatchUndo then CommandUpdater.WebBrowser.MarkupServices.EndUndoUnit; end; procedure TWebBrowserControlSelection.BeforeAction; begin // Start an undo unit so that the action can be undone if AllowBatchUndo then CommandUpdater.WebBrowser.MarkupServices.BeginUndoUnit(Name); end; constructor TWebBrowserControlSelection.Create(AOwner: TComponent); begin inherited; FAllowBatchUndo := True; FMaxSelCount := MaxInt; FMinSelCount := 1; end; procedure TWebBrowserControlSelection.ExecuteTarget(Target: TObject); var I: Integer; var IsLocked: OleVariant; begin if Supports(SafeCreateControlRange(CommandUpdater.WebBrowser), IHTMLControlRange, FControlRange) then try BeforeAction; if Assigned(FControlRange) then for I := 0 to FControlRange.length - 1 do begin IsLocked := FControlRange.item(I).getAttribute('Design_Time_Lock', 0); if FIgnoreLockedControls and (not VarIsNull(IsLocked) and IsLocked) then continue; DoAction(I, FControlRange.item(I)); end; AfterAction; finally FControlRange := nil; end; end; function TWebBrowserControlSelection.GetEnabled: Boolean; begin Result := False; if Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) then begin if Supports(SafeCreateControlRange(CommandUpdater.WebBrowser), IHTMLControlRange, FRange) then begin Result := (FRange.length >= FMinSelCount) and (FRange.length <= FMaxSelCount); if Result then if CommandUpdater.WebBrowser.GetIsContentPage then if not CommandUpdater.WebBrowser.GetIsEditableElement( CommandUpdater.WebBrowser.CurrentElement, [efOuterRequired]) then Result := False; end; end end; procedure TWebBrowserControlSelection.UpdateTarget(Target: TObject); begin try Enabled := GetEnabled; finally FRange := nil; end; end; { TWebBrowserAlignControls } procedure TWebBrowserAlignControls.BeforeAction; begin inherited; FPrimaryElement := ControlRange.item(0); end; constructor TWebBrowserAlignControls.Create(AOwner: TComponent); begin inherited; IgnoreLockedControls := True; MinSelCount := 2; end; { TWebBrowserAlignControlsLeft } procedure TWebBrowserAlignControlsLeft.DoAction(Index: Integer; Element: IHTMLElement); begin if (Index = 0) then exit; Element.style.left := PrimaryElement.offsetLeft; end; { TWebBrowserAlignControlsRight } procedure TWebBrowserAlignControlsRight.DoAction(Index: Integer; Element: IHTMLElement); begin if (Index = 0) then exit; Element.style.left := PrimaryElement.offsetLeft + PrimaryElement.offsetWidth - Element.offsetWidth; end; { TWebBrowserAlignControlsTop } procedure TWebBrowserAlignControlsTop.DoAction(Index: Integer; Element: IHTMLElement); begin if (Index = 0) then exit; Element.style.top := PrimaryElement.offsetTop; end; { TWebBrowserAlignControlsBottom } procedure TWebBrowserAlignControlsBottom.DoAction(Index: Integer; Element: IHTMLElement); begin if (Index = 0) then exit; Element.style.top := (PrimaryElement.style.pixelTop + PrimaryElement.offsetHeight) - Element.offsetHeight; end; { TWebBrowserAlignVerticalCenters } procedure TWebBrowserAlignVerticalCenters.DoAction(Index: Integer; Element: IHTMLElement); begin if (Index = 0) then exit; Element.style.top := (PrimaryElement.style.pixelTop + PrimaryElement.offsetHeight div 2) - Element.offsetHeight div 2; end; { TWebBrowserAlignHorizontalCenters } procedure TWebBrowserAlignHorizontalCenters.DoAction(Index: Integer; Element: IHTMLElement); begin if (Index = 0) then exit; Element.style.left := (PrimaryElement.style.pixelLeft + PrimaryElement.offsetWidth div 2) - Element.offsetWidth div 2; end; { TWebBrowserMakeSameWidth } procedure TWebBrowserMakeSameWidth.DoAction(Index: Integer; Element: IHTMLElement); begin if (Index = 0) then exit; Element.style.width := GetPixelWidthPropertyValue(PrimaryElement); CommandUpdater.DoElementPropertiesChanged(Element, [epWidth]); end; { TWebBrowserMakeSameHeight } procedure TWebBrowserMakeSameHeight.DoAction(Index: Integer; Element: IHTMLElement); begin if (Index = 0) then exit; Element.style.height := GetPixelHeightPropertyValue(PrimaryElement); CommandUpdater.DoElementPropertiesChanged(Element, [epHeight]); end; { TWebBrowserMakeSameSize } procedure TWebBrowserMakeSameSize.DoAction(Index: Integer; Element: IHTMLElement); begin if (Index = 0) then exit; Element.style.Width := GetPixelWidthPropertyValue(PrimaryElement); Element.style.Height := GetPixelHeightPropertyValue(PrimaryElement); CommandUpdater.DoElementPropertiesChanged(Element, [epHeight, epHeight]); end; { TWebBrowserDesignTimeLock } procedure TWebBrowserDesignTimeLock.DoAction(Index: Integer; Element: IHTMLElement); var Value: OleVariant; I: Integer; Range: IHTMLControlRange; begin if Supports(SafeCreateControlRange(CommandUpdater.WebBrowser), IHTMLControlRange, Range) then begin for I := 0 to Range.length - 1 do begin Value := Range.Item(I).getAttribute('Design_Time_Lock', 0); if VarIsNull(Value) then Value := False; if Value then begin Element.removeAttribute(WideString(sDesignTimeLock), 0); Element.style.removeAttribute(sDesignTimeLock, 0); end else begin Element.setAttribute(sDesignTimeLock, 'true', 1); Element.style.setAttribute(sDesignTimeLock, 'true', 0); end; end; Range.select; // Reselect range so the border around controls is redrawn end; end; procedure TWebBrowserDesignTimeLock.UpdateTarget(Target: TObject); var I: Integer; IsLocked: OleVariant; Range: IHTMLControlRange; begin inherited; if Enabled then begin if Supports(SafeCreateControlRange(CommandUpdater.WebBrowser), IHTMLControlRange, Range) then for I := 0 to Range.length - 1 do begin IsLocked := Range.Item(I).getAttribute('Design_Time_Lock', 0); if VarIsNull(IsLocked) or not IsLocked then break end; if VarIsNull(IsLocked) then Checked := False else Checked := IsLocked; end else Checked := False; end; { TWebBrowserInsertTag } function TWebBrowserInsertTag.CanInsert: Boolean; begin if Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) and (Supports(SafeCreateControlRange(CommandUpdater.WebBrowser), IHTMLControlRange) or (CommandUpdater.WebBrowser.Document2.frames.length <> 0)) then Result := False else Result := IEActions.CanInsertControlAtCurrentPosition(CommandUpdater.WebBrowser); end; procedure ValidateInsertablePosition(WebBrowser: TWebBrowserEx; StartPos: IMarkupPointer); var LElement: IHTMLElement; begin if WebBrowser.GetIsContentPage then begin OleCheck(StartPos.CurrentScope(LElement)); if not WebBrowser.GetIsEditableElement(LElement, [efInnerRequired]) then raise Exception.Create(sCannotInsertAtCurrentPosition); end; end; function CanInsertControlAtCurrentPosition(WebBrowser: TWebBrowserEx): Boolean; begin Result := True; if WebBrowser.GetIsContentPage then begin case WebBrowser.CurrentElementType of cetAtCursor, cetTextRange: Result := WebBrowser.GetIsEditableElement( WebBrowser.CurrentElement, [efInnerRequired]); cetControlRange: Result := WebBrowser.GetIsEditableElement( WebBrowser.CurrentElement.parentElement, [efInnerRequired]); end; end; end; procedure ShowElementCreateError(const ATagName, AMessage: string); begin MessageDlg(Format(sElementCreateError, [ATagName, AMessage]), mtError, [mbOk], 0); end; procedure TWebBrowserInsertTag.ExecuteTarget(Target: TObject); var E: IHTMLElement; StartMP, FinishMP: IMarkupPointer; DP: IDisplayPointer; begin with CommandUpdater.WebBrowser, CommandUpdater.WebBrowser.MarkupServices do begin BeginUndoUnit('Insert_Tag'); { do not localize } try OleCheck(createElement(GetTagID, #0, E)); OleCheck(CreateMarkupPointer(StartMP)); OleCheck(Caret.MoveMarkupPointerToCaret(StartMP)); OleCheck(StartMP.SetGravity(POINTER_GRAVITY_Left)); OleCheck(CreateMarkupPointer(FinishMP)); OleCheck(Caret.MoveMarkupPointerToCaret(FinishMP)); OleCheck(FinishMP.SetGravity(POINTER_GRAVITY_Right)); try ValidateInsertablePosition(CommandUpdater.WebBrowser, StartMP); // raises exception except on E:Exception do begin ShowElementCreateError(HTMLTag, E.Message); Abort; end; end; OleCheck(InsertElement(E, StartMP, FinishMP)); OleCheck(StartMP.MoveAdjacentToElement(E, ELEM_ADJ_AfterBegin)); OleCheck(DisplayServices.CreateDisplayPointer(DP)); OleCheck(DP.MoveToMarkupPointer(StartMP, nil)); OleCheck(Caret.MoveCaretToPointer(DP, 0, CARET_DIRECTION_SAME)); finally EndUndoUnit; { do not localize } end; end; if Assigned(FOnElementCreated) then FOnElementCreated(Self, E); end; //function TWebBrowserInsertTag.GetElement: IHTMLElement; //var // Pointer: IMarkupPointer; // DispPtr: IDisplayPointer; //begin // Result := nil; // if (CommandUpdater = nil) or (CommandUpdater.WebBrowser = nil) or // (CommandUpdater.WebBrowser.DisplayServices = nil) or // (csDesigning in ComponentState) then exit; // Result := CommandUpdater.WebBrowser.CurrentInsertionPoint; //// CommandUpdater.WebBrowser.DisplayServices.CreateDisplayPointer(DispPtr); //// if Assigned(DispPtr) then //// begin //// OleCheck(CommandUpdater.WebBrowser.MarkupServices.CreateMarkupPointer(Pointer)); //// OleCheck(CommandUpdater.WebBrowser.Caret.MoveDisplayPointerToCaret(DispPtr)); //// OleCheck(DispPtr.PositionMarkupPointer(Pointer)); //// OleCheck(Pointer.CurrentScope(Result)); //// end; //end; function TWebBrowserInsertTag.GetTagID: _ELEMENT_TAG_ID; var WS: WideString; begin Result := TAGID_NULL; if Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) then begin WS := FHTMLTag; OleCheck(CommandUpdater.WebBrowser.MarkupServices.GetTagIDForName(WS, Result)); end end; procedure TWebBrowserInsertTag.SetHTMLTag(const Value: string); var WS: WideString; TagID: _ELEMENT_TAG_ID; begin if AnsiCompareText(Value, FHTMLTag) <> 0 then begin if Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) then begin WS := Value; OleCheck(CommandUpdater.WebBrowser.MarkupServices.GetTagIDForName(WS, TagID)); FHTMLTag := Value; end else FHTMLTag := Value; end; end; procedure TWebBrowserInsertTag.UpdateTarget(Target: TObject); begin Enabled := Assigned(CommandUpdater) and Assigned(CommandUpdater.WebBrowser) and Assigned(CommandUpdater.WebBrowser.Document) and CanInsert; end; { TWebBrowserOverwrite } constructor TWebBrowserOverwrite.Create(AOwner: TComponent); begin inherited; CmdID := IDM_OVERWRITE; end; { TWebBrowserInputAction } function TWebBrowserInputAction.IsTargetElement: Boolean; begin Result := Supports(GetElement, IHTMLInputElement); end; { TWebBrowserControlAction } function TWebBrowserControlAction.GetElement: IHTMLElement; var Selection: IHTMLControlRange; CtrlRange: IHTMLControlRange; begin Result := nil; if not Assigned(CommandUpdater) or (CommandUpdater.WebBrowser = nil) or (csDesigning in ComponentState) then exit; if CommandUpdater.WebBrowser.Selection <> nil then begin Selection := SafeCreateControlRange(CommandUpdater.WebBrowser); if Supports(Selection, IHTMLControlRange, CtrlRange) then if (CtrlRange.length = 1) then Result := CtrlRange.item(0); end; end; { TWebBrowserImageAction } function TWebBrowserImageAction.IsTargetElement: Boolean; begin Result := Supports(GetElement, IHTMLImgElement); end; { TWebBrowserAbsolutionPositionAction } function TWebBrowserAbsolutionPositionAction.GetEnabled: Boolean; var Style: IHTMLStyle; I: Integer; begin Result := inherited GetEnabled; if Result then begin if CommandUpdater.GetActionState(Self, csEnabled, Result) then Exit; for I := 0 to FRange.length - 1 do begin Style := FRange.item(I).style; if WideCompareText(Style.position, 'absolute') <> 0 then begin Result := False; break; end; end; CommandUpdater.SaveActionState(Self, csEnabled, Result); end; end; { TWebBrowserBringToFront } procedure TWebBrowserBringToFront.DoAction(Index: Integer; Element: IHTMLElement); var ZIndex: Integer; Style: IHTMLStyle; I: Integer; begin if Assigned(FOnGetNextZIndex) then for I := 0 to FControlRange.length - 1 do begin FOnGetNextZIndex(Self, ZIndex); Style := FControlRange.item(I).style; Style.zIndex := ZIndex; end; end; { TWebBrowserSendToBack } procedure TWebBrowserSendToBack.DoAction(Index: Integer; Element: IHTMLElement); var ZIndex: Integer; Style: IHTMLStyle; I: Integer; begin if Assigned(FOnGetPrevZIndex) then for I := 0 to FControlRange.length - 1 do begin FOnGetPrevZIndex(Self, ZIndex); Style := FControlRange.item(I).style; Style.zIndex := ZIndex; end; end; { TWebBrowserInsertFormTag } function TWebBrowserInsertFormTag.CanInsert: Boolean; var E: IHTMLElement; begin Result := inherited CanInsert; if not Result then exit; //E := GetElement; E := CommandUpdater.WebBrowser.CurrentElement; Result := True; while Assigned(E) do if Supports(E, IHTMLFormElement) then begin Result := False; Break; end else E := E.parentElement; end; { TWebBrowserSelectAllControls } procedure TWebBrowserSelectAllControls.ExecuteTarget(Target: TObject); var FContentPage: Boolean; function CanSelect(AElement: IHTMLElement): Boolean; begin Result := (not FContentPage) or CommandUpdater.WebBrowser.GetIsEditableElement(AElement, [efOuterRequired, efSelectableControlRequired]); end; var I: Integer; ControlRange: IHTMLControlRange; E2: IHTMLElement2; D2: IHTMLDocument2; CtrlElement: IHTMLControlElement; ElementCol: IHTMLElementCollection; begin if Supports(CommandUpdater.WebBrowser.ActiveDocument, IHTMLDocument2, D2) and Supports(D2.body, IHTMLElement2, E2) and Supports(E2.createControlRange, IHTMLControlRange, ControlRange) and Supports(D2.body.all, IHTMLElementCollection, ElementCol) then begin FContentPage := CommandUpdater.WebBrowser.GetIsContentPage; for I := 0 to ElementCol.length - 1 do begin if Supports(ElementCol.item(I, I), IHTMLControlElement, CtrlElement) then try // Wrap in a try...except since certain table tags cause "Invalid argument" errors if CanSelect(CtrlElement as IHTMLElement) then ControlRange.add(CtrlElement) except end else if Supports(ElementCol.item(I, I), IHTMLElement2, E2) then if (E2.currentStyle as IHTMLCurrentStyle2).hasLayout then if CanSelect(E2 as IHTMLElement) then (ControlRange as IHTMLControlRange2).addElement(E2 as IHTMLElement); end; if ControlRange.Length > 0 then ControlRange.select; end; end; procedure TWebBrowserSelectAllControls.UpdateTarget(Target: TObject); begin Enabled := (CommandUpdater <> nil) and (CommandUpdater.WebBrowser <> nil); end; { TWebBrowserFormatAction } procedure TWebBrowserFormatAction.UpdateTarget(Target: TObject); begin inherited; if Enabled and CommandUpdater.WebBrowser.GetIsContentPage then begin if not CommandUpdater.WebBrowser.GetIsEditableElement( CommandUpdater.WebBrowser.CurrentElement, [efOuterRequired]) then begin Enabled := False; Checked := False; end; end; end; end.
{**********************************************************} { } { Zlib Compression Algorithm for TinyDB } { } {**********************************************************} unit Compress_Zlib; {$I TinyDB.INC} interface uses Windows, Messages, SysUtils, Classes, Forms, Dialogs, Db, TinyDB, ZLibUnit; type TCompAlgo_Zlib = class(TCompressAlgo) private FLevel: TCompressLevel; FSourceSize: Integer; function ConvertCompLevel(Value: TCompressLevel): TCompressionLevel; procedure Compress(SourceStream, DestStream: TMemoryStream; const CompressionLevel: TCompressionLevel); procedure Decompress(SourceStream, DestStream: TMemoryStream); procedure DoCompressProgress(Sender: TObject); procedure DoDecompressProgress(Sender: TObject); procedure InternalDoEncodeProgress(Size, Pos: Integer); procedure InternalDoDecodeProgress(Size, Pos: Integer); protected procedure SetLevel(Value: TCompressLevel); override; function GetLevel: TCompressLevel; override; public constructor Create(AOwner: TObject); override; procedure EncodeStream(Source, Dest: TMemoryStream; DataSize: Integer); override; procedure DecodeStream(Source, Dest: TMemoryStream; DataSize: Integer); override; end; implementation { TCompAlgo_Zlib } constructor TCompAlgo_Zlib.Create(AOwner: TObject); begin inherited; FLevel := clNormal; end; function TCompAlgo_Zlib.ConvertCompLevel(Value: TCompressLevel): TCompressionLevel; begin case Value of clMaximum: Result := clMax; clNormal: Result := clDefault; clFast, clSuperFast: Result := clFastest; else Result := clNone; end; end; //----------------------------------------------------------------------------- // Compress data //----------------------------------------------------------------------------- procedure TCompAlgo_Zlib.Compress(SourceStream, DestStream: TMemoryStream; const CompressionLevel: TCompressionLevel); var CompStream: TCompressionStream; Count: Integer; begin // 如果源数据长度为0 FSourceSize := SourceStream.Size; if SourceStream.Size = 0 then begin DestStream.Clear; Exit; end; // 在DestStream的头部写入数据压缩前的大小 Count := SourceStream.Size; DestStream.Clear; DestStream.WriteBuffer(Count, SizeOf(Integer)); // 写入经过压缩的数据流(SourceStream中保存着原始的数据流) CompStream := TCompressionStream.Create(CompressionLevel, DestStream); try CompStream.OnProgress := DoCompressProgress; SourceStream.SaveToStream(CompStream); finally CompStream.Free; end; DestStream.Position := 0; // 如果压缩后的长度反而增长 if DestStream.Size - SizeOf(Integer) >= SourceStream.Size then begin Count := -Count; // 用负数表示数据未被压缩 DestStream.Clear; DestStream.WriteBuffer(Count, SizeOf(Integer)); DestStream.CopyFrom(SourceStream, 0); end; end; //----------------------------------------------------------------------------- // Decompress data //----------------------------------------------------------------------------- procedure TCompAlgo_Zlib.Decompress(SourceStream, DestStream: TMemoryStream); var DecompStream: TDecompressionStream; TempStream: TMemoryStream; Count: Integer; begin // 如果源数据长度为0 FSourceSize := SourceStream.Size; if SourceStream.Size = 0 then begin DestStream.Clear; Exit; end; // 从未压缩的数据头部读出字节数 SourceStream.Position := 0; SourceStream.ReadBuffer(Count, SizeOf(Integer)); // 如果数据被压缩 if Count >= 0 then begin // 数据解压 DecompStream := TDecompressionStream.Create(SourceStream); try DecompStream.OnProgress := DoDecompressProgress; TempStream := TMemoryStream.Create; try TempStream.SetSize(Count); DecompStream.ReadBuffer(TempStream.Memory^, Count); DestStream.LoadFromStream(TempStream); DestStream.Position := 0; finally TempStream.Free; end; finally DecompStream.Free; end; end else // 如果数据未被压缩 begin DestStream.Clear; DestStream.CopyFrom(SourceStream, SourceStream.Size - SizeOf(Integer)); end; end; procedure TCompAlgo_Zlib.DoCompressProgress(Sender: TObject); begin InternalDoEncodeProgress(FSourceSize, (Sender as TCompressionStream).BytesProcessed); end; procedure TCompAlgo_Zlib.DoDecompressProgress(Sender: TObject); begin InternalDoDecodeProgress(FSourceSize, (Sender as TDecompressionStream).BytesProcessed); end; procedure TCompAlgo_Zlib.InternalDoEncodeProgress(Size, Pos: Integer); begin if Size = 0 then DoEncodeProgress(0) else DoEncodeProgress(Round(Pos / Size * 100)); end; procedure TCompAlgo_Zlib.InternalDoDecodeProgress(Size, Pos: Integer); begin if Size = 0 then DoDecodeProgress(0) else DoDecodeProgress(Round(Pos / Size * 100)); end; procedure TCompAlgo_Zlib.EncodeStream(Source, Dest: TMemoryStream; DataSize: Integer); begin Compress(Source, Dest, ConvertCompLevel(FLevel)); end; procedure TCompAlgo_Zlib.DecodeStream(Source, Dest: TMemoryStream; DataSize: Integer); begin Decompress(Source, Dest); end; procedure TCompAlgo_Zlib.SetLevel(Value: TCompressLevel); begin FLevel := Value; end; function TCompAlgo_Zlib.GetLevel: TCompressLevel; begin Result := FLevel; end; initialization RegisterCompressClass(TCompAlgo_Zlib, 'ZLIB'); end.
(* MPC: SWa, MM, 2020-05-20 *) (* ---- *) (* MidiPascal compiler. *) (* ========================================================================= *) PROGRAM MPC; USES MPL, MPPC, CodeDef, CodeGen, CodeInt, CodeDis; VAR inputFilePath: STRING; ca: CodeArray; ok: BOOLEAN; BEGIN (* MPC *) IF (ParamCount = 1) THEN BEGIN inputFilePath := ParamStr(1); END ELSE BEGIN Write('MidiPascal source file > '); ReadLn(inputFilePath); END; (* IF *) InitLex(inputFilePath); S; IF (success) THEN BEGIN WriteLn('parsing completed: success'); GetCode(ca); StoreCode(inputFilePath + 'c', ca); // MidiPascal virtual Machine: LoadCode(inputFilePath + 'c', ca, ok); IF (NOT ok) THEN BEGIN WriteLn('ERROR: cannot open mpc file'); HALT; END; (* IF *) InterpretCode(ca); END ELSE BEGIN WriteLn('parsing failed. ERROR at position (', syLineNr, ',', syColNr, ', ', sy, ')'); END; (* IF *) END. (* MPC *)
(******************************************************************************) (* This file conteins definitions, data sructures and the implementations of *) (* a two channels 2681 serial device. *) (* Designed to be interfaced with MC68k Class. *) (* *) (******************************************************************************) unit timer; (***********************************************************) (**) interface (**) (***********************************************************) uses ictrl,sysutils; const SaveFileName='.\sav\timer.sav'; type ETimerEx=class(exception); type c2500timer=class (***********************************************************) (**) private (**) (***********************************************************) TimerControl : byte; //0x02120040 TimerRegister0 : word; //0x02120050 TimerRegister1 : word; //0x02120060 TimerRegister2 : word; //0x02120070 TimerCount0 : word; //0x02120050 TimerCount1 : word; //0x02120060 TimerCount2 : word; //0x02120070 fakeCpuCycles : int64; precCpuCycles : int64; NoUseButItsAddress:byte; intc : ^IntrCtrl; Cpucycles : ^int64; // function lbendian(a:word):word; (***********************************************************) (**) protected (**) (***********************************************************) (***********************************************************) (**) public (**) (***********************************************************) function InterfaceRead8 (address:word): byte; //By this function cpu access in reading mode to 8 bit memory mapped registers. procedure InterfaceWrite8 (address:word;data:byte); //By this function cpu access in writing mode to 8 bit memory mapped registers. function InterfaceRead16 (address:word): word; //By this function cpu access in reading mode to 16 bit memory mapped registers. procedure InterfaceWrite16 (address:word;data:word); //By this function cpu access in writing mode to 16 bit memory mapped registers. procedure SetCPUCyclescCounter(CPUCycl:pointer); //Links timer counters to cpu cyles couter. procedure SetInterruptController(ic:pointer); //Assigns an interrupt controller to the device. procedure StatusSave; procedure StatusRestore; procedure reset; procedure tick; //Updates status of the device. constructor create; end; (******************************************************************************) (**) (**) (**) implementation (**) (**) (**) (******************************************************************************) procedure c2500timer.InterfaceWrite8 (address:word;data:byte); begin case address of $00:begin //Timer Control timercontrol:=data; end; $10:begin //Timer Register 0 end; $20:begin //Timer Register 1 end; $30:begin //Timer Register 2 end; end; end; (******************************************************************************) function c2500timer.InterfaceRead8 (address:word): byte; begin case address of $00:begin //Timer Control result:=timercontrol; end; $10:begin //Timer Register 0 end; $20:begin //Timer Register 1 end; $30:begin //Timer Register 2 end; end; end; (******************************************************************************) procedure c2500timer.InterfaceWrite16 (address:word;data:word); begin case address of $00:begin //Timer Control end; $10:begin //Timer Register 0 TimerRegister0:=data; timercount0:=0; end; $20:begin //Timer Register 1 TimerRegister1:=data; timercount1:=0; end; $30:begin //Timer Register 2 TimerRegister2:=data; timercount2:=0; end; end; end; (******************************************************************************) function c2500timer.InterfaceRead16 (address:word):word; begin case address of $00:begin //Timer Control end; $10:begin //Timer Register 0 result:=timercount0; end; $20:begin //Timer Register 1 result:=timercount1; end; $30:begin //Timer Register 2 result:=timercount2; end; end; end; (******************************************************************************) constructor c2500timer.create; begin cpucycles:=@fakecpucycles; end; (******************************************************************************) procedure c2500timer.SetCPUCyclescCounter(CPUCycl:pointer); begin cpucycles:=CPUCycl; end; (******************************************************************************) procedure c2500timer.SetInterruptController(ic:pointer); begin intc:=ic; end; (******************************************************************************) procedure c2500timer.tick; var app:int64; begin app:=Cpucycles^-preccpucycles; if timerregister0<>0 then TimerCount0:=TimerCount0+app; if timerregister1<>0 then TimerCount1:=TimerCount1+app; if timerregister2<>0 then TimerCount2:=TimerCount2+app; preccpucycles:=Cpucycles^; if TimerCount0>timerregister0 then begin TimerCount0:=0; timerregister0:=0; if timercontrol and $40<>0 then raise ETimerEx.Create('Watchdog is barking: Bau bau.'); end; if TimerCount1>timerregister1 then begin if timerregister1<>1 then intc^.irq($1f); //autovectored 7 TimerCount1:=0; timerregister1:=0; end; if TimerCount2>timerregister2 then begin if timerregister2<>1 then begin //timerregister2:=0; intc^.irq($1f); //autovectored 7 end else asm nop end; TimerCount2:=0; end; end; (******************************************************************************) procedure c2500timer.reset; begin TimerControl := 0; TimerRegister0 := 0; TimerRegister1 := 0; TimerRegister2 := 0; TimerCount0 := 0; TimerCount1 := 0; TimerCount2 := 0; end; (******************************************************************************) procedure c2500timer.StatusSave; var f:file; function addrcalc(addr1,addr2:pointer):longword; assembler; asm push ebx mov eax,addr1 mov ebx,addr2 sub eax,ebx pop ebx end; begin assignfile(f,SaveFileName); rewrite(f,1); blockwrite(f,TimerControl,addrcalc(@NoUseButItsAddress,@TimerControl));//29); closefile(f); end; (******************************************************************************) procedure c2500timer.StatusRestore; var f:file; function addrcalc(addr1,addr2:pointer):longword; assembler; asm push ebx mov eax,addr1 mov ebx,addr2 sub eax,ebx pop ebx end; begin assignfile(f,SaveFileName); system.Reset(f,1); blockread(f,TimerControl,addrcalc(@NoUseButItsAddress,@TimerControl));//29); closefile(f); end; end.
{----------------------------------------------------------------------------- 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/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvPageListEditorForm.PAS, released on 2004-03-28. The Initial Developer of the Original Code is Peter Thornqvist <peter3 at sourceforge dot net> Portions created by Peter Thornqvist are Copyright (C) 2004 Peter Thornqvist. All Rights Reserved. Contributor(s): You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Known Issues: -----------------------------------------------------------------------------} // $Id$ unit JvPageListEditorForm; {$mode objfpc}{$H+} interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ActnList, ImgList, ComCtrls, StdCtrls, {ToolWin, }Menus, PropEdits, PropEditUtils, ComponentEditors, JvPageList, JvPageListEditors, IDEWindowIntf; type { TfrmPageListEditor } TfrmPageListEditor = class(TForm) ToolBar1: TToolBar; btnAdd: TToolButton; btnDelete: TToolButton; ToolButton1: TToolButton; tbMoveUp: TToolButton; tbMoveDown: TToolButton; lbPages: TListBox; alEditor: TActionList; acAdd: TAction; acDelete: TAction; acMoveUp: TAction; acMoveDown: TAction; ilButtons: TImageList; StatusBar1: TStatusBar; popEditor: TPopupMenu; Add1: TMenuItem; Delete1: TMenuItem; N1: TMenuItem; MoveUp1: TMenuItem; MoveDown1: TMenuItem; procedure FormCreate(Sender: TObject); procedure acAddExecute(Sender: TObject); procedure acDeleteExecute(Sender: TObject); procedure acMoveUpExecute(Sender: TObject); procedure acMoveDownExecute(Sender: TObject); procedure FormClose(Sender: TObject; var AAction: TCloseAction); procedure acDeleteUpdate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lbPagesClick(Sender: TObject); procedure alEditorUpdate(AAction: TBasicAction; var Handled: Boolean); procedure lbPagesKeyPress(Sender: TObject; var Key: Char); private FPageList: TJvCustomPageList; FIgnoreEvents: Boolean; FEditor: TJvCustomPageEditor; procedure SetPageList(const Value: TJvCustomPageList); procedure UpdateList(ItemIndex: Integer); procedure SelectPage(const Index: Integer); //procedure Add(Page: TJvCustomPage); function FindPage(APage: TJvCustomPage; out AIndex: Integer): Boolean; procedure OnComponentRenamed(AComponent: TComponent); procedure OnPersistentDeleting(APersistent: TPersistent); procedure OnPersistentAdded(APersistent: TPersistent; Select: boolean); public property PageList:TJvCustomPageList read FPageList write SetPageList; end; procedure ShowPageListEditor(Editor: TJvCustomPageEditor; APageList: TJvCustomPageList); implementation uses JvDsgnConsts; {$R *.lfm} procedure ShowPageListEditor(Editor: TJvCustomPageEditor; APageList: TJvCustomPageList); var frmPageListEditor: TfrmPageListEditor = nil; begin // Show the editor frmPageListEditor := FindEditorForm(Editor.GetComponent) as TfrmPageListEditor; if not Assigned(frmPageListEditor) then frmPageListEditor := TfrmPageListEditor.Create(Application); try frmPageListEditor.FEditor := Editor; frmPageListEditor.PageList := APageList; frmPageListEditor.Caption := Format(RsFmtCaption,[APageList.Name]); RegisterEditorForm(frmPageListEditor, Editor.GetComponent); except frmPageListEditor.Free; raise; end; frmPageListEditor.EnsureVisible; end; type TJvCustomPageAccess = class(TJvCustomPage); procedure TfrmPageListEditor.acAddExecute(Sender: TObject); //var //APage: TJvCustomPage; //Hook: TPropertyEditorHook; begin //if not FEditor.GetHook(Hook) then // Exit; //APage := PageList.GetPageClass.Create(PageList.Owner); //try // APage.Name := FEditor.GetDesigner.CreateUniqueComponentName(APage.ClassName); // Add(APage); // Hook.PersistentAdded(APage, True); // FEditor.Modified; //except // APage.Free; // raise; //end; if FEditor.GetPageControl <> nil then FEditor.InsertPage; end; procedure TfrmPageListEditor.acDeleteExecute(Sender: TObject); //var // I: Integer; // Hook: TPropertyEditorHook; begin //if Assigned(PageList.ActivePage) and FEditor.GetHook(Hook) then //begin // I := lbPages.ItemIndex; // if lbPages.ItemIndex >= 0 then // lbPages.Items.Delete(TJvCustomPageAccess(PageList.ActivePage).PageIndex); // if GlobalDesignHook <> nil then // GlobalDesignHook.SelectOnlyThis(PageList); // PageList.ActivePage.Free; // Hook.PersistentDeleted; // if I >= lbPages.Items.Count then // Dec(I); // if (I >= 0) and (I < lbPages.Items.Count) then // begin // lbPages.ItemIndex := I; // SelectPage(I); // end // else // FEditor.Modified; //end; if (FEditor.GetPageControl <> nil) then FEditor.RemovePage; end; procedure TfrmPageListEditor.acMoveUpExecute(Sender: TObject); var I: Integer; begin I := lbPages.ItemIndex; lbPages.Items.Move(I, I-1); if Assigned(PageList) then begin TJvCustomPageAccess(PageList.Pages[I]).PageIndex := I - 1; lbPages.ItemIndex := I - 1; end; end; procedure TfrmPageListEditor.acMoveDownExecute(Sender: TObject); var I: Integer; begin I := lbPages.ItemIndex; lbPages.Items.Move(I, I+1); if Assigned(PageList) then begin TJvCustomPageAccess(PageList.Pages[I]).PageIndex := I + 1; lbPages.ItemIndex := I + 1; end; end; procedure TfrmPageListEditor.SetPageList(const Value: TJvCustomPageList); begin if FPageList <> Value then begin FPageList := Value; UpdateList(0); end; end; //procedure TfrmPageListEditor.Add(Page: TJvCustomPage); //var // Hook: TPropertyEditorHook; //begin // if not FEditor.GetHook(Hook) then // Exit; // Page.Parent := PageList; // Page.PageList := PageList; // PageList.ActivePage := Page; // Hook.PersistentAdded(Page, True); // GlobalDesignHook.SelectOnlyThis(Page); // FEditor.Modified; // lbPages.ItemIndex := lbPages.Items.Add(Page.Name); //end; function TfrmPageListEditor.FindPage(APage: TJvCustomPage; out AIndex: Integer ): Boolean; var I: Integer; begin if Assigned(PageList) and (PageList.PageCount > 0) then for I := 0 to PageList.PageCount - 1 do if PageList.Pages[I] = APage then begin AIndex := I; Exit(True); end; AIndex := -1; Result := False; end; procedure TfrmPageListEditor.OnComponentRenamed(AComponent: TComponent); var I: Integer; begin if FIgnoreEvents then Exit; if (AComponent is TJvCustomPage) and FindPage(TJvCustomPage(AComponent), I) then UpdateList(I); end; procedure TfrmPageListEditor.OnPersistentDeleting(APersistent: TPersistent); begin if FIgnoreEvents then Exit; if (APersistent is TJvCustomPage) then UpdateList(-1) else if (APersistent is TJvCustomPageList) and (FEditor.GetPageControl = APersistent) then Close; end; procedure TfrmPageListEditor.OnPersistentAdded(APersistent: TPersistent; Select: boolean); var I: Integer; begin if FIgnoreEvents then Exit; if (APersistent is TJvCustomPage) and FindPage(TJvCustomPage(APersistent), I) then begin UpdateList(I); lbPages.Selected[I] := Select; end; end; procedure TfrmPageListEditor.SelectPage(const Index: Integer); var Page: TJvCustomPageAccess; begin if Assigned(FPageList) and Active then begin FIgnoreEvents := True; try Page := nil; if (Index >= 0) and (Index < FPageList.PageCount) then Page := TJvCustomPageAccess(FPageList.Pages[Index]); PageList.ActivePage := Page; if GlobalDesignHook <> nil then begin GlobalDesignHook.SelectOnlyThis(Page); GlobalDesignHook.Modified(PageList); end; finally FIgnoreEvents := False; end; end; end; procedure TfrmPageListEditor.UpdateList(ItemIndex: Integer); var I: Integer; begin if Assigned(FPageList) then begin FIgnoreEvents := True; lbPages.Items.BeginUpdate; try lbPages.Items.Clear; for I := 0 to FPageList.PageCount - 1 do lbPages.Items.Add(TJvCustomPageAccess(FPageList.Pages[I]).Name); if (ItemIndex >= 0) and (ItemIndex < lbPages.Items.Count) then lbPages.ItemIndex := ItemIndex else lbPages.ItemIndex := -1; finally lbPages.Items.EndUpdate; FIgnoreEvents := False; end; end else lbPages.Items.Clear; end; procedure TfrmPageListEditor.FormClose(Sender: TObject; var AAction: TCloseAction); begin IDEDialogLayoutList.SaveLayout(Self); AAction := caFree; end; procedure TfrmPageListEditor.acDeleteUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (lbPages.Items.Count > 0) and (lbPages.ItemIndex >= 0); end; procedure TfrmPageListEditor.FormDestroy(Sender: TObject); begin if Assigned(GlobalDesignHook) then GlobalDesignHook.RemoveAllHandlersForObject(Self); UnregisterEditorForm(Self); end; procedure TfrmPageListEditor.lbPagesClick(Sender: TObject); begin SelectPage(lbPages.ItemIndex); end; procedure TfrmPageListEditor.alEditorUpdate(AAction: TBasicAction; var Handled: Boolean); begin acMoveUp.Enabled := lbPages.ItemIndex > 0; acMoveDown.Enabled := (lbPages.ItemIndex <> -1) and (lbPages.ItemIndex < lbPages.Items.Count - 1); end; procedure TfrmPageListEditor.lbPagesKeyPress(Sender: TObject; var Key: Char); begin if lbPages.ItemIndex <> -1 then begin SelectPage(lbPages.ItemIndex); //ActivateInspector(Key); Key := #0; end; end; procedure TfrmPageListEditor.FormCreate(Sender: TObject); begin IDEDialogLayoutList.ApplyLayout(Self); if Assigned(GlobalDesignHook) then begin GlobalDesignHook.AddHandlerComponentRenamed(@OnComponentRenamed); GlobalDesignHook.AddHandlerPersistentDeleting(@OnPersistentDeleting); GlobalDesignHook.AddHandlerPersistentAdded(@OnPersistentAdded); end; end; end.
PROGRAM MirrorText; FUNCTION ShortenString(s: string): string; BEGIN (* ShortenString *) Delete(s, Length(s), 1); ShortenString := s; END; (* ShortenString *) FUNCTION Mirror(s: string): string; BEGIN (* Mirror *) if Length(s) > 1 then Mirror := s[Length(s)] + Mirror(ShortenString(s)) else Mirror := s; END; (* Mirror *) PROCEDURE ReadString; var ch: char; BEGIN (* ReadString *) Read(ch); if ch <> Chr(13) then ReadString(); Write(ch); END; (* ReadString *) BEGIN (* Mirror *) { WriteLn(Mirror('test')); WriteLn(Mirror('this is a test sentence')); WriteLn(Mirror('Maximilian')); } Write('Please enter a word to Mirror: '); ReadString(); END. (* Mirror *)
unit mDrawers; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ORCtrls, ComCtrls, Buttons, ExtCtrls, Menus, ActnList, uTemplates, ORClasses, System.Actions, U_CPTPasteDetails; type // Indicates what a drawer is doing at the moment TDrawerState = (dsEnabled, dsDisabled, dsHidden, dsOpen); // Drawer listing TDrawer = (odNone, odTemplates, odEncounter, odReminders, odOrders); TDrawers = set of TDrawer; (* {TTabOrder - class used to handle tabbing on an irrregular form, may need to be moved to it's own unit someday.} TTabOrder = class(TWinControl) // only reason it's a win control is so FindNextControl will work. private fData: array of TWinControl; function GetData(AnIdx: integer): TWinControl; procedure SetData(AnIdx: integer; const Value: TWinControl); public Count: integer; // holds the number of controls in the list Above: TWinControl; Below: TWinControl; constructor CreateTabOrder(AboveCtrl, BelowCtrl: TWinControl); // creates and assigns the boundaries for the control list property Data[AnIdx: integer]: TWinControl read GetData write SetData; // holds the controls in the list procedure Add(AControl: TWinControl); // add a control to the bottom of the list procedure Clear; // clear out the list; does not affect the controls referenced in the list function Next(AControl: TWinControl): TWinControl; // finds the next control in the tab order function Previous(AControl: TWinControl): TWinControl; // finds the previous control in the tab order function IndexOf(AControl: TWinControl): integer; // locates the position of a control in the list procedure Swap(IndexA, IndexB: integer); procedure PromoteAboveOther(ControlA, ControlB: TWinControl); end;*) TDrawerEvent = procedure(ADrawer: TDrawer; ADrawerState: TDrawerState) of object; TTemplateEditEvent = procedure of object; TDrawerConfiguration = record TemplateState: TDrawerState; // state of the template drawer EncounterState: TDrawerState; // state of the encounter drawer ReminderState: TDrawerState; // state of the reminder drawer OrderState: TDrawerState; // state of the order drawer ActiveDrawer: TDrawer; // currently active drawer, if any ButtonMargin: integer; BaseHeight: integer; LastOpenSize: integer; end; TfraDrawers = class(TFrame) pnlTemplate: TPanel; pnlEncounter: TPanel; pnlReminder: TPanel; pnlOrder: TPanel; pnlTemplates: TPanel; btnTemplate: TBitBtn; btnEncounter: TBitBtn; pnlEncounters: TPanel; btnReminder: TBitBtn; pnlReminders: TPanel; btnOrder: TBitBtn; pnlOrders: TPanel; popTemplates: TPopupMenu; mnuCopyTemplate: TMenuItem; mnuInsertTemplate: TMenuItem; mnuPreviewTemplate: TMenuItem; N1: TMenuItem; mnuGotoDefault: TMenuItem; mnuDefault: TMenuItem; N3: TMenuItem; mnuViewNotes: TMenuItem; N4: TMenuItem; mnuFindTemplates: TMenuItem; mnuCollapseTree: TMenuItem; N2: TMenuItem; mnuEditTemplates: TMenuItem; mnuNewTemplate: TMenuItem; N5: TMenuItem; mnuViewTemplateIconLegend: TMenuItem; tvTemplates: TORTreeView; lbEncounter: TORListBox; tvReminders: TORTreeView; lbOrders: TORListBox; al: TActionList; acTemplates: TAction; acEncounter: TAction; acReminders: TAction; acOrders: TAction; pnlTemplateSearch: TPanel; edtSearch: TCaptionEdit; btnFind: TORAlignButton; cbWholeWords: TCheckBox; cbMatchCase: TCheckBox; acFind: TAction; acCopyTemplateText: TAction; acInsertTemplate: TAction; acPreviewTemplate: TAction; acGotoDefault: TAction; acMarkDefault: TAction; acViewTemplateNotes: TAction; acCollapseTree: TAction; acFindTemplate: TAction; acEditTemplates: TAction; acNewTemplate: TAction; acIconLegend: TAction; procedure tvRemindersMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure acTemplatesExecute(Sender: TObject); procedure acEncounterExecute(Sender: TObject); procedure acOrdersExecute(Sender: TObject); procedure acRemindersExecute(Sender: TObject); procedure acFindExecute(Sender: TObject); procedure popTemplatesPopup(Sender: TObject); procedure acInsertTemplateExecute(Sender: TObject); procedure acPreviewTemplateExecute(Sender: TObject); procedure acCopyTemplateTextExecute(Sender: TObject); procedure acGotoDefaultExecute(Sender: TObject); procedure acMarkDefaultExecute(Sender: TObject); procedure acViewTemplateNotesExecute(Sender: TObject); procedure acFindTemplateExecute(Sender: TObject); procedure acFindTemplateUpdate(Sender: TObject); procedure acCollapseTreeExecute(Sender: TObject); procedure acEditTemplatesExecute(Sender: TObject); procedure acNewTemplateExecute(Sender: TObject); procedure acIconLegendExecute(Sender: TObject); procedure acTemplatesUpdate(Sender: TObject); procedure acFindUpdate(Sender: TObject); procedure acRemindersUpdate(Sender: TObject); procedure acEncounterUpdate(Sender: TObject); procedure acOrdersUpdate(Sender: TObject); procedure tvTemplatesGetSelectedIndex(Sender: TObject; Node: TTreeNode); procedure tvTemplatesGetImageIndex(Sender: TObject; Node: TTreeNode); procedure tvTemplatesExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); procedure tvTemplatesClick(Sender: TObject); procedure tvTemplatesDblClick(Sender: TObject); procedure tvTemplatesCollapsing(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean); procedure tvTemplatesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tvTemplatesKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtSearchEnter(Sender: TObject); procedure edtSearchExit(Sender: TObject); procedure tvTemplatesDragging(Sender: TObject; Node: TTreeNode; var CanDrag: Boolean); procedure tvRemindersNodeCaptioning(Sender: TObject; var Caption: string); procedure tvRemindersKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tvRemindersCurListChanged(Sender: TObject; Node: TTreeNode); procedure edtSearchChange(Sender: TObject); procedure cbFindOptionClick(Sender: TObject); private FOldMouseUp: TMouseEvent; FOnDrawerStateChange: TDrawerEvent; FEmptyNodeCount: integer; FInternalExpand :boolean; FInternalHiddenExpand :boolean; FLastFoundNode: TTreeNode; FOpenToNode: string; FDefTempPiece: integer; FAsk :boolean; FAskExp :boolean; FAskNode :TTreeNode; FDragNode :TTreeNode; FClickOccurred: boolean; fActiveDrawer: TDrawer; UpdatingVisual: boolean; fEncounterState: TDrawerState; fReminderState: TDrawerState; fTemplateState: TDrawerState; fOrderState: TDrawerState; fButtonMargin: integer; fBaseHeight: integer; FLastOpenSize: integer; FRichEditControl: TRichEdit; FOldDragDrop: TDragDropEvent; FOldDragOver: TDragOverEvent; FNewNoteButton: TButton; FFindNext: boolean; FHasPersonalTemplates: boolean; FOnDrawerButtonClick: TNotifyEvent; FOnUpdateVisualsEvent: TNotifyEvent; fTemplateEditEvent: TTemplateEditEvent; FCopyMonitor: TCopyPasteDetails; procedure SetEncounterState(const Value: TDrawerState); procedure SetOrderState(const Value: TDrawerState); procedure SetReminderState(const Value: TDrawerState); procedure SetTemplateState(const Value: TDrawerState); procedure SetActiveDrawer(const Value: TDrawer); procedure SetBaseHeight(const Value: integer); function GetTotalButtonHeight: integer; function GetDrawerIsOpen: boolean; function GetDrawerButtonsVisible: boolean; protected procedure CheckAsk; procedure PositionToReminder(Sender: TObject); procedure RemindersChanged(Sender: TObject); procedure InsertText; function InsertOK(Ask: boolean): boolean; procedure SetRichEditControl(const Value: TRichEdit); procedure NewRECDragDrop(Sender, Source: TObject; X, Y: Integer); procedure NewRECDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure MoveCaret(X, Y: integer); procedure ReloadTemplates; procedure SetFindNext(const Value: boolean); procedure AddTemplateNode(const tmpl: TTemplate; const Owner: TTreeNode = nil); procedure OpenToNode(Path: string = ''); public RemNotifyList: TORNotifyList; FTotalButtonHeight: integer; // height of all the non-hidden buttons constructor Create(AOwner: TComponent); Override; destructor Destroy; Override; property TemplateState: TDrawerState read fTemplateState write SetTemplateState; // state of the template drawer property EncounterState: TDrawerState read fEncounterState write SetEncounterState; // state of the encounter drawer property ReminderState: TDrawerState read fReminderState write SetReminderState; // state of the reminder drawer property OrderState: TDrawerState read fOrderState write SetOrderState; // state of the order drawer property ActiveDrawer: TDrawer read fActiveDrawer write SetActiveDrawer; // currently active drawer, if any property OnDrawerButtonClick: TNotifyEvent read FOnDrawerButtonClick write FOnDrawerButtonClick; property OnUpdateVisualsEvent: TNotifyEvent read FOnUpdateVisualsEvent write FOnUpdateVisualsEvent; property TotalButtonHeight: integer read GetTotalButtonHeight; property OnDrawerStateChange: TDrawerEvent read FOnDrawerStateChange write fOnDrawerStateChange; property OnTemplateEditEvent: TTemplateEditEvent read fTemplateEditEvent write fTemplateEditEvent; property ButtonMargin: integer read fButtonMargin write fButtonMargin; property BaseHeight: integer read fBaseHeight write SetBaseHeight; property LastOpenSize: integer read FLastOpenSize write FLastOpenSize; property RichEditControl: TRichEdit read FRichEditControl write SetRichEditControl; property NewNoteButton: TButton read FNewNoteButton write FNewNoteButton; property FindNext: boolean read FFindNext write SetFindNext; property HasPersonalTemplates: boolean read FHasPersonalTemplates; property DrawerIsOpen: boolean read GetDrawerIsOpen; property DrawerButtonsVisible: Boolean read GetDrawerButtonsVisible; procedure ResetTemplates; procedure UpdateVisual; procedure Init; procedure DisplayDrawers(Show: Boolean; OpenDrawer: TDrawer = odNone; AEnable: TDrawers = []; ADisplay: TDrawers = []); function CanEditTemplates: boolean; function CanEditShared: boolean; procedure NotifyWhenRemTreeChanges(Proc: TNotifyEvent); procedure RemoveNotifyWhenRemTreeChanges(Proc: TNotifyEvent); procedure ExternalReloadTemplates; procedure UpdatePersonalTemplates; function ButtonByDrawer(Value: TDrawer): TBitBtn; procedure SaveDrawerConfiguration(var Configuration: TDrawerConfiguration); procedure LoadDrawerConfiguration(Configuration: TDrawerConfiguration); Property CopyMonitor: TCopyPasteDetails read fCopyMonitor write fCopyMonitor; end; var FocusMonitorOn: boolean; implementation {$R *.dfm} uses VAUtils, rTemplates, dShared, fTemplateDialog, RichEdit, fFindingTemplates, Clipbrd, VA508AccessibilityRouter, ORFn, fRptBox, fTemplateEditor, fIconLegend, fTemplateView, fReminderDialog, uReminders, uVA508CPRSCompatibility, System.Types, uConst; const FindNextText = 'Find Next'; { TfraDrawers } constructor TfraDrawers.Create(AOwner: TComponent); begin inherited; dmodShared.AddDrawerTree(Self); FHasPersonalTemplates := FALSE; end; destructor TfraDrawers.Destroy; begin dmodShared.RemoveDrawerTree(Self); KillObj(@RemNotifyList); inherited; end; {------------------------------------} { MoveCaret - Copied from fDrawers } {------------------------------------} procedure TfraDrawers.MoveCaret(X, Y: integer); var pt: TPoint; begin FRichEditControl.SetFocus; pt := Point(x, y); FRichEditControl.SelStart := FRichEditControl.Perform(EM_CHARFROMPOS,0,LParam(@pt)); end; {-----------------------------------------} { NewRECDragDrop - Copied from fDrawers } {-----------------------------------------} procedure TfraDrawers.NewRECDragDrop(Sender, Source: TObject; X, Y: Integer); begin if(Source = tvTemplates) then begin MoveCaret(X, Y); InsertText; end else if(assigned(FOldDragDrop)) then FOldDragDrop(Sender, Source, X, Y); end; {-----------------------------------------} { NewRECDragOver - Copied from fDrawers } {-----------------------------------------} procedure TfraDrawers.NewRECDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := FALSE; if(Source = tvTemplates) then begin if(assigned(FDragNode)) and (TTemplate(FDragNode.Data).RealType in [ttDoc, ttGroup]) then begin Accept := TRUE; MoveCaret(X, Y); end; end else if(assigned(FOldDragOver)) then FOldDragOver(Sender, Source, X, Y, State, Accept); end; {-------------------------------------------------------------------------------------} { acCollapseTreeExecute - Converted to an action from fDrawers.mnuCollapseTreeClick } {-------------------------------------------------------------------------------------} procedure TfraDrawers.acCollapseTreeExecute(Sender: TObject); begin tvTemplates.Selected := nil; tvTemplates.FullCollapse; end; {-----------------------------------------------------------------------------------------} { acCopyTemplateTextExecute - Converted to an action from fDrawers.mnuCopyTemplateClick } {-----------------------------------------------------------------------------------------} procedure TfraDrawers.acCopyTemplateTextExecute(Sender: TObject); var txt: string; Template: TTemplate; begin txt := ''; if((assigned(tvTemplates.Selected)) and (TTemplate(tvTemplates.Selected.Data).RealType in [ttDoc, ttGroup])) and (dmodShared.TemplateOK(tvTemplates.Selected.Data)) then begin Template := TTemplate(tvTemplates.Selected.Data); txt := Template.Text; CheckBoilerplate4Fields(txt, 'Template: ' + Template.PrintName, false, FCopyMonitor); if txt <> '' then begin Clipboard.SetTextBuf(PChar(txt)); GetScreenReader.Speak('Text copied to clip board'); end; end; if txt <> '' then StatusText('Templated Text copied to clipboard.'); end; {---------------------------------------------------------------------------------------} { acEditTemplatesExecute - Converted to an action from fDrawers.mnuEditTemplatesClick } { Also altered to interface with fTemplatesEditor } {---------------------------------------------------------------------------------------} procedure TfraDrawers.acEditTemplatesExecute(Sender: TObject); begin EditTemplates(TForm(Owner)); end; {-------------------------------------------------------} { acEncounterExecute - Activates the encounter drawer } {-------------------------------------------------------} procedure TfraDrawers.acEncounterExecute(Sender: TObject); begin if (ActiveDrawer <> odEncounter) then ActiveDrawer := odEncounter else ActiveDrawer := odNone; end; {------------------------------------------------------------} { acEncounterUpdate - Updates the encounter control states } {------------------------------------------------------------} procedure TfraDrawers.acEncounterUpdate(Sender: TObject); begin acEncounter.Enabled := (EncounterState in [dsOpen, dsEnabled]); acEncounter.Visible := not (EncounterState = dsHidden); pnlEncounter.Visible := (EncounterState = dsOpen); pnlEncounter.Enabled := (EncounterState in [dsOpen, dsEnabled]); end; {---------------------------------------------------------------------} { acFindExecute - Converted to an action from fDrawers.btnFindClick } {---------------------------------------------------------------------} procedure TfraDrawers.acFindExecute(Sender: TObject); var Found, TmpNode: TTreeNode; IsNext: boolean; begin if(edtSearch.text <> '') then begin IsNext := ((FFindNext) and assigned (FLastFoundNode)); if IsNext then TmpNode := FLastFoundNode else TmpNode := tvTemplates.Items.GetFirstNode; FInternalExpand := TRUE; FInternalHiddenExpand := TRUE; try Found := FindTemplate(edtSearch.Text, tvTemplates, Application.MainForm, TmpNode, IsNext, not cbMatchCase.Checked, cbWholeWords.Checked); finally FInternalExpand := FALSE; FInternalHiddenExpand := FALSE; end; if assigned(Found) then begin FLastFoundNode := Found; FindNext := True; FInternalExpand := TRUE; try tvTemplates.Selected := Found; finally FInternalExpand := FALSE; end; end; end; edtSearch.SetFocus; end; {--------------------------------------------------------------------------------------} { acFindTemplateExecute - Converted to an action from fDrawers.mnuFindTemplatesClick } {--------------------------------------------------------------------------------------} procedure TfraDrawers.acFindTemplateExecute(Sender: TObject); begin acFindTemplate.Checked := not acFindTemplate.Checked; acFindTemplateUpdate(nil); // just making sure state is checked if acFindTemplate.Checked and (ActiveDrawer = odTemplates) and edtSearch.CanFocus then edtSearch.SetFocus; end; {--------------------------------------------------------------------------------------} { acFindTemplateUpdate - Sets Find Template status based on menu item checked or not } {--------------------------------------------------------------------------------------} procedure TfraDrawers.acFindTemplateUpdate(Sender: TObject); begin pnlTemplateSearch.Visible := acFindTemplate.Checked; end; {--------------------------------------------------------} { acFindUpdate - Sets Find status based on search text } {--------------------------------------------------------} procedure TfraDrawers.acFindUpdate(Sender: TObject); begin acFind.Enabled := (edtSearch.Text <> ''); end; {-----------------------------------------------------------------------------------} { acGotoDefaultExecute - Converted to an action from fDrawers.mnuGotoDefaultClick } {-----------------------------------------------------------------------------------} procedure TfraDrawers.acGotoDefaultExecute(Sender: TObject); begin OpenToNode(Piece(GetUserTemplateDefaults, '/', FDefTempPiece)); end; {---------------------------------------------------------------------------------------------} { acIconLegendExecute - Converted to an action from fDrawers.mnuViewTemplateIconLegendClick } {---------------------------------------------------------------------------------------------} procedure TfraDrawers.acIconLegendExecute(Sender: TObject); begin ShowIconLegend(ilTemplates); end; {-----------------------------------------------------------------------------------------} { acInsertTemplateExecute - Converted to an action from fDrawers.mnuInsertTemplateClick } {-----------------------------------------------------------------------------------------} procedure TfraDrawers.acInsertTemplateExecute(Sender: TObject); begin if((assigned(tvTemplates.Selected)) and (TTemplate(tvTemplates.Selected.Data).RealType in [ttDoc, ttGroup])) then InsertText; end; {-------------------------------------------------------------------------------} { acMarkDefaultExecute - Converted to an action from fDrawers.mnuDefaultClick } {-------------------------------------------------------------------------------} procedure TfraDrawers.acMarkDefaultExecute(Sender: TObject); var NodeID: string; UserTempDefNode: string; begin NodeID := tvTemplates.GetNodeID(TORTreeNode(tvTemplates.Selected), 1, ';'); UserTempDefNode := Piece(GetUserTemplateDefaults, '/', FDefTempPiece); if NodeID <> UserTempDefNode then SetUserTemplateDefaults(tvTemplates.GetNodeID(TORTreeNode(tvTemplates.Selected), 1, ';'), FDefTempPiece) else SetUserTemplateDefaults('', FDefTempPiece); end; {-----------------------------------------------------------------------------------} { acNewTemplateExecute - Converted to an action from fDrawers.mnuNewTemplateClick } {-----------------------------------------------------------------------------------} procedure TfraDrawers.acNewTemplateExecute(Sender: TObject); begin EditTemplates(TForm(Owner), TRUE); end; {-------------------------------------------------} { acOrdersExecute - Activates the orders drawer } {-------------------------------------------------} procedure TfraDrawers.acOrdersExecute(Sender: TObject); begin if (ActiveDrawer <> odOrders) then ActiveDrawer := odOrders else ActiveDrawer := odNone; end; {------------------------------------------------------} { acOrdersUpdate - Updates the orders control states } {------------------------------------------------------} procedure TfraDrawers.acOrdersUpdate(Sender: TObject); begin acOrders.Enabled := (OrderState in [dsOpen, dsEnabled]); acOrders.Visible := not (OrderState = dsHidden); pnlOrders.Visible := (OrderState = dsOpen); pnlOrders.Enabled := (OrderState in [dsOpen, dsEnabled]); end; {-------------------------------------------------------------------------------------------} { acPreviewTemplateExecute - Converted to an action from fDrawers.mnuPreviewTemplateClick } {-------------------------------------------------------------------------------------------} procedure TfraDrawers.acPreviewTemplateExecute(Sender: TObject); var tmpl: TTemplate; txt: String; begin if(assigned(tvTemplates.Selected)) then begin if(dmodShared.TemplateOK(tvTemplates.Selected.Data,'template preview')) then begin tmpl := TTemplate(tvTemplates.Selected.Data); tmpl.TemplatePreviewMode := TRUE; // Prevents "Are you sure?" dialog when canceling txt := tmpl.Text; if(not tmpl.DialogAborted) then ShowTemplateData(nil, tmpl.PrintName, txt); end; end; end; {-------------------------------------------------------} { acRemindersExecute - Activates the reminders drawer } {-------------------------------------------------------} procedure TfraDrawers.acRemindersExecute(Sender: TObject); begin if(ActiveDrawer <> odReminders) then begin if(InitialRemindersLoaded) then begin ActiveDrawer := odReminders; end else begin StartupReminders; if(GetReminderStatus = rsNone) then begin ReminderState := dsDisabled; ActiveDrawer := odNone; end else begin ActiveDrawer := odReminders; end; end; end else begin ActiveDrawer := odNone; end; if (ActiveDrawer = odReminders) then BuildReminderTree(tvReminders); end; {------------------------------------------------------------} { acRemindersUpdate - Updates the reminders control states } {------------------------------------------------------------} procedure TfraDrawers.acRemindersUpdate(Sender: TObject); begin acReminders.Enabled := (ReminderState in [dsOpen, dsEnabled]); acReminders.Visible := not (ReminderState = dsHidden); pnlReminders.Enabled := (ReminderState in [dsOpen, dsEnabled]); pnlReminders.Visible := (ReminderState = dsOpen); end; {---------------------------------------------------------------------------------------} { acTemplatesExecute - Activates the templates drawer, some code copied from fDrawers } {---------------------------------------------------------------------------------------} procedure TfraDrawers.acTemplatesExecute(Sender: TObject); begin if(ActiveDrawer <> odTemplates) then begin ReloadTemplates; btnFind.Enabled := (edtSearch.Text <> ''); pnlTemplateSearch.Visible := mnuFindTemplates.Checked; ActiveDrawer := odTemplates; if ScreenReaderActive then pnlTemplates.SetFocus; end else begin ActiveDrawer := odNone; end; end; {------------------------------------------------------------} { acTemplatesUpdate - Updates the templates control states } {------------------------------------------------------------} procedure TfraDrawers.acTemplatesUpdate(Sender: TObject); begin acTemplates.Enabled := (TemplateState in [dsOpen, dsEnabled]); acTemplates.Visible := (not (TemplateState = dsHidden)); pnlTemplates.Enabled := (TemplateState in [dsOpen, dsEnabled]); pnlTemplates.Visible := (TemplateState = dsOpen); pnlTemplateSearch.Visible := pnlTemplates.Visible and acFindTemplate.Checked; end; {---------------------------------------------------------------------------------------} { acViewTemplateNotesExecute - Converted to an action from fDrawers.mnuViewNotesClick } {---------------------------------------------------------------------------------------} procedure TfraDrawers.acViewTemplateNotesExecute(Sender: TObject); var tmpl: TTemplate; tmpSL: TStringList; begin if(assigned(tvTemplates.Selected)) then begin tmpl := TTemplate(tvTemplates.Selected.Data); if(tmpl.Description = '') then ShowMsg('No notes found for ' + tmpl.PrintName) else begin tmpSL := TStringList.Create; try tmpSL.Text := tmpl.Description; ReportBox(tmpSL, tmpl.PrintName + ' Notes:', TRUE); finally tmpSL.Free; end; end; end; end; {----------------------------------------} { CanEditShared - Copied from fDrawers } {----------------------------------------} function TfraDrawers.CanEditShared: boolean; begin Result := (UserTemplateAccessLevel = taEditor); end; {-------------------------------------------} { CanEditTemplates - Copied from fDrawers } {-------------------------------------------} function TfraDrawers.CanEditTemplates: boolean; begin Result := (UserTemplateAccessLevel in [taAll, taEditor]); end; {--------------------------------------------} { cbFindOptionClick - Copied from fDrawers } {--------------------------------------------} procedure TfraDrawers.cbFindOptionClick(Sender: TObject); begin FindNext := False; if(pnlTemplateSearch.Visible) then edtSearch.SetFocus; end; {-----------------------------------------} { DisplayDrawers - Copied from fDrawers } {-----------------------------------------} procedure TfraDrawers.DisplayDrawers(Show: Boolean; OpenDrawer: TDrawer; AEnable, ADisplay: TDrawers); begin if not show then ADisplay := []; if odTemplates in ADisplay then begin if odTemplates in AEnable then begin if odTemplates = OpenDrawer then TemplateState := dsOpen else TemplateState := dsEnabled; end else begin TemplateState := dsDisabled; end; end else begin TemplateState := dsHidden; end; if odEncounter in ADisplay then begin if odEncounter in AEnable then begin if odEncounter = OpenDrawer then EncounterState := dsOpen else EncounterState := dsEnabled; end else begin EncounterState := dsDisabled; end; end else begin EncounterState := dsHidden; end; if odReminders in ADisplay then begin if odReminders in AEnable then begin if odReminders = OpenDrawer then ReminderState := dsOpen else ReminderState := dsEnabled; end else begin ReminderState := dsDisabled; end; end else begin ReminderState := dsHidden; end; if odOrders in ADisplay then begin if odOrders in AEnable then begin if odOrders = OpenDrawer then OrderState := dsOpen else OrderState := dsEnabled; end else begin OrderState := dsDisabled; end; end else begin OrderState := dsHidden; end; UpdateVisual; end; {------------------------------------------} { edtSearchChange - Copied from fDrawers } {------------------------------------------} procedure TfraDrawers.edtSearchChange(Sender: TObject); begin FindNext := False; end; {-----------------------------------------} { edtSearchEnter - Copied from fDrawers } {-----------------------------------------} procedure TfraDrawers.edtSearchEnter(Sender: TObject); begin btnFind.Default := True; end; {----------------------------------------} { edtSearchExit - Copied from fDrawers } {----------------------------------------} procedure TfraDrawers.edtSearchExit(Sender: TObject); begin btnFind.Default := False; end; {---------------------------------------------------------} { Init - Called from the parent to initialize the frame } {---------------------------------------------------------} procedure TfraDrawers.Init; begin fActiveDrawer := odNone; // indicates all toggled off. fBaseHeight := Height; UpdatingVisual := False; fEncounterState := dsEnabled; fReminderState := dsEnabled; fTemplateState := dsEnabled; fOrderState := dsEnabled; fButtonMargin := 2; fTemplateEditEvent := nil; UpdateVisual; end; {-----------------------------------} { InsertOK - Copied from fDrawers } {-----------------------------------} function TfraDrawers.InsertOK(Ask: boolean): boolean; function REOK: boolean; begin Result := assigned(FRichEditControl) and FRichEditControl.Visible and FRichEditControl.Parent.Visible; end; begin Result := REOK; if (not ask) and (not Result) and (assigned(FNewNoteButton)) then Result := TRUE else if ask and (not Result) and assigned(FNewNoteButton) and FNewNoteButton.Visible and FNewNoteButton.Enabled then begin FNewNoteButton.Click; Result := REOK; end; end; {-------------------------------------} { InsertText - Copied from fDrawers } {-------------------------------------} procedure TfraDrawers.InsertText; var BeforeLine, AfterTop: integer; txt, DocInfo: string; Template: TTemplate; begin DocInfo := ''; if InsertOK(TRUE) and (dmodShared.TemplateOK(tvTemplates.Selected.Data)) then begin Template := TTemplate(tvTemplates.Selected.Data); Template.TemplatePreviewMode := FALSE; Template.ExtCPMon := FCopyMonitor; if Template.IsReminderDialog then begin FocusMonitorOn := False; Template.ExecuteReminderDialog(TForm(Owner)); FocusMonitorOn := True; end else begin if Template.IsCOMObject then txt := Template.COMObjectText('', DocInfo) else txt := Template.Text; if(txt <> '') then begin CheckBoilerplate4Fields(txt, 'Template: ' + Template.PrintName); if (txt <> '') and (FRichEditControl.CanFocus) then begin BeforeLine := SendMessage(FRichEditControl.Handle, EM_EXLINEFROMCHAR, 0, FRichEditControl.SelStart); //Limit the editable recatnge SendMessage(Application.MainForm.Handle, UM_NOTELIMIT, 1, 1); FRichEditControl.SelText := txt; FRichEditControl.SetFocus; SendMessage(FRichEditControl.Handle, EM_SCROLLCARET, 0, 0); AfterTop := SendMessage(FRichEditControl.Handle, EM_GETFIRSTVISIBLELINE, 0, 0); SendMessage(FRichEditControl.Handle, EM_LINESCROLL, 0, -1 * (AfterTop - BeforeLine)); SpeakTextInserted; //show copy/paste entries CopyMonitor.ManuallyShowNewHighlights; end; end; end; end; end; procedure TfraDrawers.LoadDrawerConfiguration(Configuration: TDrawerConfiguration); begin fTemplateState := Configuration.TemplateState; fEncounterState := Configuration.EncounterState; fReminderState := Configuration.ReminderState; fOrderState := Configuration.OrderState; fActiveDrawer := Configuration.ActiveDrawer; fButtonMargin := Configuration.ButtonMargin; fBaseHeight := Configuration.BaseHeight; fLastOpenSize := Configuration.LastOpenSize; end; procedure TfraDrawers.SaveDrawerConfiguration(var Configuration: TDrawerConfiguration); begin Configuration.TemplateState := fTemplateState; Configuration.EncounterState := fEncounterState; Configuration.ReminderState := fReminderState; Configuration.OrderState := fOrderState; Configuration.ActiveDrawer := fActiveDrawer; Configuration.ButtonMargin := fButtonMargin; Configuration.BaseHeight := fBaseHeight; Configuration.LastOpenSize := fLastOpenSize; end; {-----------------------------------------------------} { SetActiveDrawer - Write accessor for ActiveDrawer } {-----------------------------------------------------} procedure TfraDrawers.SetActiveDrawer(const Value: TDrawer); begin case fActiveDrawer of // enabled the passed drawer odTemplates: TemplateState := dsEnabled; odEncounter: EncounterState := dsEnabled; odReminders: ReminderState := dsEnabled; odOrders: OrderState := dsEnabled; end; if fActiveDrawer <> Value then begin // opens or closes the drawer case Value of odTemplates: if TemplateState = dsEnabled then begin TemplateState := dsOpen; fActiveDrawer := Value; end else fActiveDrawer := odNone; odEncounter: if EncounterState = dsEnabled then begin EncounterState := dsOpen; fActiveDrawer := Value; end else fActiveDrawer := odNone; odReminders: if ReminderState = dsEnabled then begin ReminderState := dsOpen; fActiveDrawer := Value; end else fActiveDrawer := odNone; odOrders: if OrderState = dsEnabled then begin OrderState := dsOpen; fActiveDrawer := Value; end else fActiveDrawer := odNone; odNone: fActiveDrawer := odNone; end; end; if assigned(FOnDrawerButtonClick) then FOnDrawerButtonClick(ButtonByDrawer(Value)); UpdateVisual; end; {--------------------------------------------------------------} { SetBaseHeight - Write accessor for the BaseHeight property } {--------------------------------------------------------------} procedure TfraDrawers.SetBaseHeight(const Value: integer); begin if not UpdatingVisual then begin fBaseHeight := Value; UpdateVisual; end; end; {----------------------------------------------------------------------} { SetEncounterState - Write accessor for the EncounterState property } {----------------------------------------------------------------------} procedure TfraDrawers.SetEncounterState(const Value: TDrawerState); begin fEncounterState := Value; UpdateVisual; if assigned(fOnDrawerStateChange) then fOnDrawerStateChange(odEncounter, fEncounterState); end; {----------------------------------------------------------} { SetFindNext - Write accessor for the FindNext property } {----------------------------------------------------------} procedure TfraDrawers.SetFindNext(const Value: boolean); begin if(FFindNext <> Value) then begin FFindNext := Value; if(FFindNext) then btnFind.Caption := FindNextText else btnFind.Caption := 'Find'; end; end; {--------------------------------------------------------------} { SetOrderState - Write accessor for the OrderState property } {--------------------------------------------------------------} procedure TfraDrawers.SetOrderState(const Value: TDrawerState); begin fOrderState := Value; UpdateVisual; if assigned(fOnDrawerStateChange) then fOnDrawerStateChange(odOrders, fOrderState); end; {-------------------------------------------} { RemindersChanged - Copied from fDrawers } {-------------------------------------------} procedure TfraDrawers.RemindersChanged(Sender: TObject); begin if(ActiveDrawer = odReminders) then begin BuildReminderTree(tvReminders); FOldMouseUp := tvReminders.OnMouseUp; end else begin FOldMouseUp := nil; tvReminders.PopupMenu := nil; end; tvReminders.OnMouseUp := tvRemindersMouseUp; end; {---------------------------------------------} { PositionToReminder - Copied from fDrawers } {---------------------------------------------} procedure TfraDrawers.PositionToReminder(Sender: TObject); var Rem: TReminder; begin if(assigned(Sender)) then begin if(Sender is TReminder) then begin Rem := TReminder(Sender); if(Rem.CurrentNodeID <> '') then tvReminders.Selected := tvReminders.FindPieceNode(Rem.CurrentNodeID, 1, IncludeParentID) else begin tvReminders.Selected := tvReminders.FindPieceNode(RemCode + (Sender as TReminder).IEN, 1); if(assigned(tvReminders.Selected)) then TORTreeNode(tvReminders.Selected).EnsureVisible; end; Rem.CurrentNodeID := ''; end; end else tvReminders.Selected := nil; end; {-------------------------------------------------------------} { SetReminderState - Write accessor for ReminderState } { Code borowed from fDrawers.ShowDrawers } {-------------------------------------------------------------} procedure TfraDrawers.SetReminderState(const Value: TDrawerState); begin if (Value <> fReminderState) then begin fReminderState := Value; if Value <> dsHidden then begin NotifyWhenRemindersChange(RemindersChanged); NotifyWhenProcessingReminderChanges(PositionToReminder); end else begin RemoveNotifyRemindersChange(RemindersChanged); RemoveNotifyWhenProcessingReminderChanges(PositionToReminder); end; UpdateVisual; if assigned(fOnDrawerStateChange) then fOnDrawerStateChange(odReminders, fReminderState); end; end; {---------------------------------------------} { SetRichEditControl - Copied from fDrawers } {---------------------------------------------} procedure TfraDrawers.SetRichEditControl(const Value: TRichEdit); begin if(FRichEditControl <> Value) then begin if(assigned(FRichEditControl)) then begin FRichEditControl.OnDragDrop := FOldDragDrop; FRichEditControl.OnDragOver := FOldDragOver; end; FRichEditControl := Value; if(assigned(FRichEditControl)) then begin FOldDragDrop := FRichEditControl.OnDragDrop; FOldDragOver := FRichEditControl.OnDragOver; FRichEditControl.OnDragDrop := NewRECDragDrop; FRichEditControl.OnDragOver := NewRECDragOver; end; end; end; {-------------------------------------------------------------} { SetTemplateState - Write accessor for TemplateState } {-------------------------------------------------------------} procedure TfraDrawers.SetTemplateState(const Value: TDrawerState); begin fTemplateState := Value; UpdateVisual; if assigned(fOnDrawerStateChange) then fOnDrawerStateChange(odTemplates, fTemplateState); end; {----------------------------------------------------} { tvRemindersCurListChanged - Copied from fDrawers } {----------------------------------------------------} procedure TfraDrawers.tvRemindersCurListChanged(Sender: TObject; Node: TTreeNode); begin if(assigned(RemNotifyList)) then RemNotifyList.Notify(Node); end; {---------------------------------------------------} { NotifyWhenRemTreeChanges - Copied from fDrawers } {---------------------------------------------------} procedure TfraDrawers.NotifyWhenRemTreeChanges(Proc: TNotifyEvent); begin if(not assigned(RemNotifyList)) then RemNotifyList := TORNotifyList.Create; RemNotifyList.Add(Proc); end; {---------------------------------------------------------} { RemoveNotifyWhenRemTreeChanges - Copied from fDrawers } {---------------------------------------------------------} procedure TfraDrawers.RemoveNotifyWhenRemTreeChanges(Proc: TNotifyEvent); begin if(assigned(RemNotifyList)) then RemNotifyList.Remove(Proc); end; {---------------------------------------------} { tvRemindersKeyDown - Copied from fDrawers } {---------------------------------------------} procedure TfraDrawers.tvRemindersKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN, VK_SPACE: begin FocusMonitorOn := False; ViewReminderDialog(ReminderNode(tvReminders.Selected)); FocusMonitorOn := True; Key := 0; end; end; end; {---------------------------------------------} { tvRemindersMouseUp - Copied from fDrawers } {---------------------------------------------} procedure TfraDrawers.tvRemindersMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button = mbLeft) and (assigned(tvReminders.Selected)) and (htOnItem in tvReminders.GetHitTestInfoAt(X, Y)) then begin FocusMonitorOn := False; ViewReminderDialog(ReminderNode(tvReminders.Selected)); FocusMonitorOn := True; end; end; {----------------------------------------------------} { tvRemindersNodeCaptioning - Copied from fDrawers } {----------------------------------------------------} procedure TfraDrawers.tvRemindersNodeCaptioning(Sender: TObject; var Caption: string); var StringData: string; begin StringData := (Sender as TORTreeNode).StringData; if (Length(StringData) > 0) and (StringData[1] = 'R') then begin //Only tag reminder statuses case StrToIntDef(Piece(StringData,'^',6 {Due}),-1) of 0: Caption := Caption + ' -- Applicable'; 1: Caption := Caption + ' -- DUE'; 2: Caption := Caption + ' -- Not Applicable'; else Caption := Caption + ' -- Not Evaluated'; end; end; end; {-----------------------------------} { CheckAsk - Copied from fDrawers } {-----------------------------------} procedure TfraDrawers.CheckAsk; begin if(FAsk) then begin FAsk := FALSE; FInternalExpand := TRUE; try if(FAskExp) then FAskNode.Expand(FALSE) else FAskNode.Collapse(FALSE); finally FInternalExpand := FALSE; end; end; end; {-------------------------------------------} { tvTemplatesClick - Copied from fDrawers } {-------------------------------------------} procedure TfraDrawers.tvTemplatesClick(Sender: TObject); begin FClickOccurred := TRUE; CheckAsk; end; {------------------------------------------------} { tvTemplatesCollapsing - Copied from fDrawers } {------------------------------------------------} procedure TfraDrawers.tvTemplatesCollapsing(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean); begin if(assigned(Node)) then begin if(Dragging) then EndDrag(FALSE); if(not FInternalExpand) then begin if(TTemplate(Node.Data).RealType = ttGroup) then begin FAsk := TRUE; FAskExp := FALSE; AllowCollapse := FALSE; FAskNode := Node; end; end; if(AllowCollapse) then FClickOccurred := FALSE; end; end; {----------------------------------------------} { tvTemplatesDblClick - Copied from fDrawers } {----------------------------------------------} procedure TfraDrawers.tvTemplatesDblClick(Sender: TObject); begin if(not FClickOccurred) then CheckAsk else begin FAsk := FALSE; if((assigned(tvTemplates.Selected)) and (TTemplate(tvTemplates.Selected.Data).RealType in [ttDoc, ttGroup])) then InsertText; end; end; {----------------------------------------------} { tvTemplatesDragging - Copied from fDrawers } {----------------------------------------------} procedure TfraDrawers.tvTemplatesDragging(Sender: TObject; Node: TTreeNode; var CanDrag: Boolean); begin if(TTemplate(Node.Data).RealType in [ttDoc, ttGroup]) then begin FDragNode := Node; CanDrag := TRUE; end else begin FDragNode := nil; CanDrag := FALSE; end; end; {-----------------------------------------------} { tvTemplatesExpanding - Copied from fDrawers } {-----------------------------------------------} procedure TfraDrawers.tvTemplatesExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); begin if(assigned(Node)) then begin if(Dragging) then EndDrag(FALSE); if(not FInternalExpand) then begin if(TTemplate(Node.Data).RealType = ttGroup) then begin FAsk := TRUE; FAskExp := TRUE; AllowExpansion := FALSE; FAskNode := Node; end; end; if(AllowExpansion) then begin FClickOccurred := FALSE; AllowExpansion := dmodShared.ExpandNode(tvTemplates, Node, FEmptyNodeCount); if(FInternalHiddenExpand) then AllowExpansion := FALSE; end; end; end; {---------------------------------------------------} { tvTemplatesGetImageIndex - Copied from fDrawers } {---------------------------------------------------} procedure TfraDrawers.tvTemplatesGetImageIndex(Sender: TObject; Node: TTreeNode); begin Node.ImageIndex := dmodShared.ImgIdx(Node); end; {------------------------------------------------------} { tvTemplatesGetSelectedIndex - Copied from fDrawers } {------------------------------------------------------} procedure TfraDrawers.tvTemplatesGetSelectedIndex(Sender: TObject; Node: TTreeNode); begin Node.SelectedIndex := dmodShared.ImgIdx(Node); end; {---------------------------------------------} { tvTemplatesKeyDown - Copied from fDrawers } {---------------------------------------------} procedure TfraDrawers.tvTemplatesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin CheckAsk; case Key of VK_SPACE, VK_RETURN: begin InsertText; Key := 0; end; end; end; {-------------------------------------------} { tvTemplatesKeyUp - Copied from fDrawers } {-------------------------------------------} procedure TfraDrawers.tvTemplatesKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin CheckAsk; end; {--------------------------------------------------} { UpdatePersonalTemplates - Copied from fDrawers } {--------------------------------------------------} procedure TfraDrawers.UpdatePersonalTemplates; var NeedPersonal: boolean; Node: TTreeNode; function FindNode: TTreeNode; begin Result := tvTemplates.Items.GetFirstNode; while assigned(Result) do begin if(Result.Data = MyTemplate) then exit; Result := Result.getNextSibling; end; end; begin NeedPersonal := (UserTemplateAccessLevel <> taNone); if(NeedPersonal <> FHasPersonalTemplates) then begin if(NeedPersonal) then begin if(assigned(MyTemplate)) and (MyTemplate.Children in [tcActive, tcBoth]) then begin AddTemplateNode(MyTemplate); FHasPersonalTemplates := TRUE; if(assigned(MyTemplate)) then begin Node := FindNode; if(assigned(Node)) then Node.MoveTo(nil, naAddFirst); end; end; end else begin if(assigned(MyTemplate)) then begin Node := FindNode; if(assigned(Node)) then Node.Delete; end; FHasPersonalTemplates := FALSE; end; end; end; {------------------------------------------------------------------------------} { UpdateVisual - Updates the appearance of the drawers based on their states } {------------------------------------------------------------------------------} procedure TfraDrawers.UpdateVisual; var DrawerSpace: integer; // space allowed for the open drawer begin if not UpdatingVisual then begin // skip if already updating UpdatingVisual := True; try acTemplatesUpdate(nil); acRemindersUpdate(nil); acOrdersUpdate(nil); acEncounterUpdate(nil); (* // calculate total button height TotalButtonHeight := 0; if TemplateState <> dsHidden then inc(TotalButtonHeight, btnTemplate.Height+ButtonMargin); if EncounterState <> dsHidden then inc(TotalButtonHeight, btnEncounter.Height+ButtonMargin); if ReminderState <> dsHidden then inc(TotalButtonHeight, btnReminder.Height+ButtonMargin); if OrderState <> dsHidden then inc(TotalButtonHeight, btnOrder.Height+ButtonMargin); *) // calculate Drawer Space DrawerSpace := BaseHeight - TotalButtonHeight; // Set component height based on if a drawer is open if DrawerIsOpen then begin Height := BaseHeight; end else begin Height := TotalButtonHeight; end; // set order controls btnOrder.Width := pnlOrder.Width; case OrderState of dsEnabled: begin pnlOrder.Height := btnOrder.Height + ButtonMargin; btnOrder.Enabled := True; pnlOrders.Height := 1; end; dsDisabled: begin; pnlOrder.Height := btnOrder.Height + ButtonMargin; btnOrder.Enabled := False; pnlOrders.Height := 1; end; dsHidden: begin pnlOrder.Height := 1; btnOrder.Enabled := False; pnlOrders.Height := 1; end; dsOpen: begin pnlOrder.Height := btnOrder.Height + ButtonMargin + DrawerSpace; btnOrder.Enabled := True; pnlOrders.Height := DrawerSpace; end; end; // set reminder controls btnReminder.Width := pnlReminder.Width; case ReminderState of dsEnabled: begin pnlReminder.Height := btnReminder.Height + ButtonMargin; btnReminder.Enabled := True; pnlReminders.Height := 1; end; dsDisabled: begin; pnlReminder.Height := btnReminder.Height + ButtonMargin; btnReminder.Enabled := False; pnlReminders.Height := 1; end; dsHidden: begin pnlReminder.Height := 1; btnReminder.Enabled := False; pnlReminders.Height := 1; end; dsOpen: begin pnlReminder.Height := btnReminder.Height + ButtonMargin + DrawerSpace; btnReminder.Enabled := True; pnlReminders.Height := DrawerSpace; end; end; // set encounter controls btnEncounter.Width := pnlEncounter.Width; case EncounterState of dsEnabled: begin pnlEncounter.Height := btnEncounter.Height + ButtonMargin; btnEncounter.Enabled := True; pnlEncounters.Height := 1; end; dsDisabled: begin; pnlEncounter.Height := btnEncounter.Height + ButtonMargin; btnEncounter.Enabled := False; pnlEncounters.Height := 1; end; dsHidden: begin pnlEncounter.Height := 1; btnEncounter.Enabled := False; pnlEncounters.Height := 1; end; dsOpen: begin pnlEncounter.Height := btnEncounter.Height + ButtonMargin + DrawerSpace; btnEncounter.Enabled := True; pnlEncounters.Height := DrawerSpace; end; end; // set template controls btnTemplate.Width := pnlTemplate.Width; case TemplateState of dsEnabled: begin pnlTemplate.Height := btnTemplate.Height + ButtonMargin; btnTemplate.Enabled := True; pnlTemplates.Height := 1; end; dsDisabled: begin; pnlTemplate.Height := btnTemplate.Height + ButtonMargin; btnTemplate.Enabled := False; pnlTemplates.Height := 1; end; dsHidden: begin pnlTemplate.Height := 1; btnTemplate.Enabled := False; pnlTemplates.Height := 1; end; dsOpen: begin pnlTemplate.Height := btnTemplate.Height + ButtonMargin + DrawerSpace; btnTemplate.Enabled := True; pnlTemplates.Height := DrawerSpace; end; end; if assigned(FOnUpdateVisualsEvent) then FOnUpdateVisualsEvent(self); finally UpdatingVisual := False; end; end; end; {-----------------------------------------} { ResetTemplates - Copied from fDrawers } {-----------------------------------------} procedure TfraDrawers.ResetTemplates; begin FOpenToNode := Piece(GetUserTemplateDefaults, '/', FDefTempPiece); end; {------------------------------------------} { ReloadTemplates - Copied from fDrawers } {------------------------------------------} procedure TfraDrawers.ReloadTemplates; begin FindNext := False; LoadTemplateData; if(UserTemplateAccessLevel <> taNone) and (assigned(MyTemplate)) and (MyTemplate.Children in [tcActive, tcBoth]) then begin AddTemplateNode(MyTemplate); FHasPersonalTemplates := TRUE; end; AddTemplateNode(RootTemplate); OpenToNode; end; {--------------------------------------------------} { ExternalReloadTemplates - Copied from fDrawers } {--------------------------------------------------} procedure TfraDrawers.ExternalReloadTemplates; begin if(FOpenToNode = '') and (assigned(tvTemplates.Selected)) then FOpenToNode := tvTemplates.GetNodeID(TORTreeNode(tvTemplates.Selected),1,';'); tvTemplates.Items.Clear; FHasPersonalTemplates := FALSE; FEmptyNodeCount := 0; ReloadTemplates; end; function TfraDrawers.GetDrawerIsOpen: boolean; begin case fActiveDrawer of odTemplates: Result := (TemplateState = dsOpen); odEncounter: Result := (EncounterState = dsOpen); odReminders: Result := (ReminderState = dsOpen); odOrders: Result := (OrderState = dsOpen); else Result := False; end; end; function TfraDrawers.GetDrawerButtonsVisible: boolean; begin Result := false; if (TemplateState <> dshidden) or (EncounterState <> dshidden) or (ReminderState <> dshidden) or (OrderState <> dshidden) then Result := True; end; function TfraDrawers.GetTotalButtonHeight: integer; begin FTotalButtonHeight := 0; if TemplateState <> dsHidden then inc(FTotalButtonHeight, btnTemplate.Height+ButtonMargin); if EncounterState <> dsHidden then inc(FTotalButtonHeight, btnEncounter.Height+ButtonMargin); if ReminderState <> dsHidden then inc(FTotalButtonHeight, btnReminder.Height+ButtonMargin); if OrderState <> dsHidden then inc(FTotalButtonHeight, btnOrder.Height+ButtonMargin); Result := FTotalButtonHeight; end; {------------------------------------------} { AddTemplateNode - Copied from fDrawers } {------------------------------------------} procedure TfraDrawers.AddTemplateNode(const tmpl: TTemplate; const Owner: TTreeNode = nil); begin dmodShared.AddTemplateNode(tvTemplates, FEmptyNodeCount, tmpl, FALSE, Owner); end; function TfraDrawers.ButtonByDrawer(Value: TDrawer): TBitBtn; begin case Value of odTemplates: Result := btnTemplate; odEncounter: Result := btnEncounter; odReminders: Result := btnReminder; odOrders: Result := btnOrder; else Result := nil; end; end; {-------------------------------------} { OpenToNode - Copied from fDrawers } {-------------------------------------} procedure TfraDrawers.OpenToNode(Path: string = ''); var OldInternalHE, OldInternalEX: boolean; begin if(Path <> '') then FOpenToNode := PATH; if(FOpenToNode <> '') then begin OldInternalHE := FInternalHiddenExpand; OldInternalEX := FInternalExpand; try FInternalExpand := TRUE; FInternalHiddenExpand := FALSE; dmodShared.SelectNode(tvTemplates, FOpenToNode, FEmptyNodeCount); finally FInternalHiddenExpand := OldInternalHE; FInternalExpand := OldInternalEX; end; FOpenToNode := ''; end; end; {--------------------------------------------} { popTemplatesPopup - Copied from fDrawers } {--------------------------------------------} procedure TfraDrawers.popTemplatesPopup(Sender: TObject); var Node: TTreeNode; ok, ok2, NodeFound: boolean; Def: string; begin ok := FALSE; ok2 := FALSE; if(ActiveDrawer = odTemplates) then begin Node := tvTemplates.Selected; tvTemplates.Selected := Node; // This line prevents selected from changing after menu closes NodeFound := (assigned(Node)); if(NodeFound) then begin with TTemplate(Node.Data) do begin ok := (RealType in [ttDoc, ttGroup]); ok2 := ok and (not IsReminderDialog) and (not IsCOMObject); end; end; Def := Piece(GetUserTemplateDefaults, '/', FDefTempPiece); mnuGotoDefault.Enabled := (Def <> ''); mnuViewNotes.Enabled := NodeFound and (TTemplate(Node.Data).Description <> ''); mnuDefault.Enabled := NodeFound; mnuDefault.Checked := NodeFound and (tvTemplates.GetNodeID(TORTreeNode(Node), 1, ';') = Def); end else begin mnuDefault.Enabled := FALSE; mnuGotoDefault.Enabled := FALSE; mnuViewNotes.Enabled := FALSE; end; mnuPreviewTemplate.Enabled := ok2; mnuCopyTemplate.Enabled := ok2; mnuInsertTemplate.Enabled := ok and InsertOK(FALSE); mnuFindTemplates.Enabled := (ActiveDrawer = odTemplates); mnuCollapseTree.Enabled := ((ActiveDrawer = odTemplates) and (dmodShared.NeedsCollapsing(tvTemplates))); mnuEditTemplates.Enabled := (UserTemplateAccessLevel in [taAll, taEditor]); mnuNewTemplate.Enabled := (UserTemplateAccessLevel in [taAll, taEditor]); end; (*{ TTabOrder } {-------------------------------------------------} { Add - Add a control to the bottom of the list } { AControl: windows control to be added } {-------------------------------------------------} procedure TTabOrder.Add(AControl: TWinControl); begin if assigned(AControl) then begin SetLength(fData, Count + 1); fData[Count] := AControl; Count := Length(fData); end; end; {---------------------------------------------------------------} { Clear - Clear out the list } { Does not affect the controls referenced in the list } {---------------------------------------------------------------} procedure TTabOrder.Clear; begin SetLength(fData, 0); Count := 0; end; {--------------------------------------------------------------------------------------------} { Create - Creates and assigns the boundaries for the control list } { Above: Control who receives focus on a shift-tab from the beginning of the list } { Below: Control who receives focus on a tab from the end of the list } {--------------------------------------------------------------------------------------------} constructor TTabOrder.CreateTabOrder(AboveCtrl, BelowCtrl: TWinControl); begin inherited Create(nil); Above := AboveCtrl; Below := BelowCtrl; Count := 0; end; {-------------------------------------------------------------} { GetData - Read accessor for the Data property } { AnIdx: Index of the desired control in the list } {-------------------------------------------------------------} function TTabOrder.GetData(AnIdx: integer): TWinControl; begin if (AnIdx >= 0) and (AnIdx < Count) then begin Result := fData[AnIdx]; end else begin Result := nil; end; end; {-----------------------------------------------------------} { IndexOf - Locates the position of a control in the list } { AControl: Name of the control to find } {-----------------------------------------------------------} function TTabOrder.IndexOf(AControl: TWinControl): integer; begin Result := 0; while (Result < Count) and (AControl <> fData[Result]) do inc(Result); if Result >= Count then Result := -1; end; {------------------------------------------------------} { Next - Finds the next control in the tab order } { AControl: Beginning point for the search } {------------------------------------------------------} function TTabOrder.Next(AControl: TWinControl): TWinControl; var idx: integer; // loop controller c: TWinControl; // currently evaluating this control begin Result := nil; idx := IndexOf(AControl); // find starting position if (idx <> -1) then begin repeat if (idx + 1) >= Count then begin // going forward, use Below if the index goes out of range if (Below.CanFocus and Below.TabStop) then Result := Below else Result := FindNextControl(Below, True, True, False); end else begin c := fData[idx + 1]; if (assigned(c) and c.CanFocus and c.TabStop) then begin // valid control found, assign to result Result := fData[idx + 1]; end else begin inc(idx); // continue looping end; end; until (assigned(Result)); end; end; {----------------------------------------------------------} { Previous - Finds the previous control in the tab order } { AControl: Beginning point for the search } {----------------------------------------------------------} function TTabOrder.Previous(AControl: TWinControl): TWinControl; var idx: integer; // loop controller c: TWinControl; // currently evaluating this control begin Result := nil; idx := IndexOf(AControl); // find starting position if (idx <> -1) then begin repeat if (idx = 0) then begin // going backwards, use Above if the index reaches 0 if (Above.CanFocus and Above.TabStop) then Result := Above else Result := FindNextControl(Above, False, True, False); end else begin c := fData[idx - 1]; if (assigned(c) and c.CanFocus and c.TabStop) then begin // valid control found, assign to result Result := fData[idx - 1]; end else begin dec(idx); // continue looping end; end; until (assigned(Result)); end; end; procedure TTabOrder.PromoteAboveOther(ControlA, ControlB: TWinControl); var PositionA, PositionB: integer; begin PositionA := IndexOf(ControlA); PositionB := IndexOf(ControlB); if PositionA > PositionB then Swap(PositionA, PositionB); end; {-------------------------------------------------------------} { SetData - Write accessor for the Data property } { AnIdx: Index of the desired control in the list } { Value: Control to update in Data } {-------------------------------------------------------------} procedure TTabOrder.SetData(AnIdx: integer; const Value: TWinControl); begin if AnIdx >= 0 then begin if AnIdx >= Count then begin SetLength(fData, AnIdx + 1); Count := Length(fData); end; fData[AnIdx] := Value; end; end; procedure TTabOrder.Swap(IndexA, IndexB: integer); var AControl: TWinControl; begin if fData[IndexA] = Above then Above := fData[IndexB]; if fData[IndexB] = Below then Below := fData[IndexA]; AControl := fData[IndexA]; fData[IndexA] := fData[IndexB]; fData[IndexB] := AControl; end;*) initialization FocusMonitorOn := True; end.
unit WinShell; interface uses SysUtils, Windows, Registry, ActiveX, ShlObj; type EShellOleError = class(Exception); TShellLinkInfo = record PathName: string; Arguments: string; Description: string; WorkingDirectory: string; IconLocation: string; IconIndex: integer; ShowCmd: integer; HotKey: word; end; TSpecialFolderInfo = record Name: string; ID: Integer; end; const SpecialFolders: array[0..29] of TSpecialFolderInfo = ( (Name: 'Alt Startup'; ID: CSIDL_ALTSTARTUP), (Name: 'Application Data'; ID: CSIDL_APPDATA), (Name: 'Recycle Bin'; ID: CSIDL_BITBUCKET), (Name: 'Common Alt Startup'; ID: CSIDL_COMMON_ALTSTARTUP), (Name: 'Common Desktop'; ID: CSIDL_COMMON_DESKTOPDIRECTORY), (Name: 'Common Favorites'; ID: CSIDL_COMMON_FAVORITES), (Name: 'Common Programs'; ID: CSIDL_COMMON_PROGRAMS), (Name: 'Common Start Menu'; ID: CSIDL_COMMON_STARTMENU), (Name: 'Common Startup'; ID: CSIDL_COMMON_STARTUP), (Name: 'Controls'; ID: CSIDL_CONTROLS), (Name: 'Cookies'; ID: CSIDL_COOKIES), (Name: 'Desktop'; ID: CSIDL_DESKTOP), (Name: 'Desktop Directory'; ID: CSIDL_DESKTOPDIRECTORY), (Name: 'Drives'; ID: CSIDL_DRIVES), (Name: 'Favorites'; ID: CSIDL_FAVORITES), (Name: 'Fonts'; ID: CSIDL_FONTS), (Name: 'History'; ID: CSIDL_HISTORY), (Name: 'Internet'; ID: CSIDL_INTERNET), (Name: 'Internet Cache'; ID: CSIDL_INTERNET_CACHE), (Name: 'Network Neighborhood'; ID: CSIDL_NETHOOD), (Name: 'Network Top'; ID: CSIDL_NETWORK), (Name: 'Personal'; ID: CSIDL_PERSONAL), (Name: 'Printers'; ID: CSIDL_PRINTERS), (Name: 'Printer Links'; ID: CSIDL_PRINTHOOD), (Name: 'Programs'; ID: CSIDL_PROGRAMS), (Name: 'Recent Documents'; ID: CSIDL_RECENT), (Name: 'Send To'; ID: CSIDL_SENDTO), (Name: 'Start Menu'; ID: CSIDL_STARTMENU), (Name: 'Startup'; ID: CSIDL_STARTUP), (Name: 'Templates'; ID: CSIDL_TEMPLATES)); function CreateShellLink(const AppName, Desc: string; Dest: Integer): string; function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string; procedure GetShellLinkInfo(const LinkFile: WideString; var SLI: TShellLinkInfo); procedure SetShellLinkInfo(const LinkFile: WideString; const SLI: TShellLinkInfo); implementation uses ComObj; function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string; var FilePath: widestring; PFilePath: PWideChar; //array[0..MAX_PATH] of char; begin SetLength(FilePath, MAX_PATH); PFilePath := Addr(FilePath[1]); { Get path of selected location } SHGetSpecialFolderPathW(0, PFilePath, Folder, CanCreate); Result := FilePath; end; function CreateShellLink(const AppName, Desc: string; Dest: Integer): string; { Creates a shell link for application or document specified in } { AppName with description Desc. Link will be located in folder } { specified by Dest, which is one of the string constants shown } { at the top of this unit. Returns the full path name of the } { link file. } var SL: IShellLink; PF: IPersistFile; LnkName: WideString; begin OleCheck(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IShellLink, SL)); { The IShellLink implementer must also support the IPersistFile } { interface. Get an interface pointer to it. } PF := SL as IPersistFile; OleCheck(SL.SetPath(PChar(AppName))); // set link path to proper file if Desc <> '' then OleCheck(SL.SetDescription(PChar(Desc))); // set description { create a path location and filename for link file } LnkName := GetSpecialFolderPath(Dest, True) + '\' + ChangeFileExt(AppName, 'lnk'); PF.Save(PWideChar(LnkName), True); // save link file Result := LnkName; end; procedure GetShellLinkInfo(const LinkFile: WideString; var SLI: TShellLinkInfo); { Retrieves information on an existing shell link } var SL: IShellLink; PF: IPersistFile; FindData: TWin32FindData; AStr: array[0..MAX_PATH] of char; begin OleCheck(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IShellLink, SL)); { The IShellLink implementer must also support the IPersistFile } { interface. Get an interface pointer to it. } PF := SL as IPersistFile; { Load file into IPersistFile object } OleCheck(PF.Load(PWideChar(LinkFile), STGM_READ)); { Resolve the link by calling the Resolve interface function. } OleCheck(SL.Resolve(0, SLR_ANY_MATCH or SLR_NO_UI)); { Get all the info! } with SLI do begin OleCheck(SL.GetPath(AStr, MAX_PATH, FindData, SLGP_SHORTPATH)); PathName := AStr; OleCheck(SL.GetArguments(AStr, MAX_PATH)); Arguments := AStr; OleCheck(SL.GetDescription(AStr, MAX_PATH)); Description := AStr; OleCheck(SL.GetWorkingDirectory(AStr, MAX_PATH)); WorkingDirectory := AStr; OleCheck(SL.GetIconLocation(AStr, MAX_PATH, IconIndex)); IconLocation := AStr; OleCheck(SL.GetShowCmd(ShowCmd)); OleCheck(SL.GetHotKey(HotKey)); end; end; procedure SetShellLinkInfo(const LinkFile: WideString; const SLI: TShellLinkInfo); { Sets information for an existing shell link } var SL: IShellLink; PF: IPersistFile; begin OleCheck(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IShellLink, SL)); { The IShellLink implementer must also support the IPersistFile } { interface. Get an interface pointer to it. } PF := SL as IPersistFile; { Load file into IPersistFile object } OleCheck(PF.Load(PWideChar(LinkFile), STGM_SHARE_DENY_WRITE)); { Resolve the link by calling the Resolve interface function. } OleCheck(SL.Resolve(0, SLR_ANY_MATCH or SLR_UPDATE or SLR_NO_UI)); { Set all the info! } with SLI, SL do begin OleCheck(SetPath(PChar(PathName))); OleCheck(SetArguments(PChar(Arguments))); OleCheck(SetDescription(PChar(Description))); OleCheck(SetWorkingDirectory(PChar(WorkingDirectory))); OleCheck(SetIconLocation(PChar(IconLocation), IconIndex)); OleCheck(SetShowCmd(ShowCmd)); OleCheck(SetHotKey(HotKey)); end; PF.Save(PWideChar(LinkFile), True); // save file end; end.
unit Test_FIToolkit.Config.Defaults; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, FIToolkit.Config.Defaults; type // Test methods for class TDefaultValueAttribute TestTDefaultValueAttribute = class(TGenericTestCase) strict private FDefaultValueAttribute: TDefaultValueAttribute; public procedure SetUp; override; procedure TearDown; override; published procedure TestIsEmpty; end; // Test methods for class TDefaultValueAttribute<T> TestTDefaultValueAttributeT = class(TGenericTestCase) private type TTestAttribute = class (TDefaultValueAttribute<Integer>); const INT_ATTR_VALUE = 777; strict private FAttrWithNoValue, FAttrWithValue : TTestAttribute; public procedure SetUp; override; procedure TearDown; override; published procedure TestAttributeWithNoValue; procedure TestAttributeWithValue; end; // Test methods for class TDefaultsMap TestTDefaultsMap = class(TGenericTestCase) private type TTestAttributeBase = class abstract (TDefaultValueAttribute<Integer>); TTestAddAttr = class (TTestAttributeBase); TTestGetAttr = class (TTestAttributeBase); TTestHasAttr = class (TTestAttributeBase); TDummyAttr = class (TTestAttributeBase); const INT_ATTR_VALUE = 777; strict private FDefaultsMap1, FDefaultsMap2 : TDefaultsMap; public procedure SetUp; override; procedure TearDown; override; published procedure TestAddValue; procedure TestGetValue; procedure TestHasValue; procedure TestIsSingleton; end; implementation uses System.SysUtils, System.Rtti, TestUtils, FIToolkit.Config.Types; { TestTDefaultValueAttribute } procedure TestTDefaultValueAttribute.SetUp; begin FDefaultValueAttribute := TDefaultValueAttribute.Create; end; procedure TestTDefaultValueAttribute.TearDown; begin FreeAndNil(FDefaultValueAttribute); end; procedure TestTDefaultValueAttribute.TestIsEmpty; var ReturnValue : TValue; begin CheckEquals<TDefaultValueKind>(dvkUndefined, FDefaultValueAttribute.ValueKind, 'ValueKind = dvkUndefined'); CheckException( procedure begin ReturnValue := FDefaultValueAttribute.Value; end, EAssertionFailed, 'CheckException::EAssertionFailed(ValueKind <> dvkUndefined)' ); end; { TestTDefaultValueAttributeT } procedure TestTDefaultValueAttributeT.SetUp; begin FAttrWithNoValue := TTestAttribute.Create; FAttrWithValue := TTestAttribute.Create(INT_ATTR_VALUE); end; procedure TestTDefaultValueAttributeT.TearDown; begin FreeAndNil(FAttrWithNoValue); FreeAndNil(FAttrWithValue); end; procedure TestTDefaultValueAttributeT.TestAttributeWithNoValue; begin CheckEquals<TDefaultValueKind>(dvkCalculated, FAttrWithNoValue.ValueKind, 'ValueKind = dvkCalculated'); CheckTrue(FAttrWithNoValue.Value.IsEmpty, 'CheckTrue::IsEmpty'); RegisterDefaultValue(TTestAttribute, INT_ATTR_VALUE); CheckEquals(INT_ATTR_VALUE, FAttrWithNoValue.Value.AsInteger, 'Value = INT_ATTR_VALUE'); end; procedure TestTDefaultValueAttributeT.TestAttributeWithValue; begin CheckEquals<TDefaultValueKind>(dvkData, FAttrWithValue.ValueKind, 'ValueKind = dvkData'); CheckFalse(FAttrWithValue.Value.IsEmpty, 'CheckFalse::IsEmpty'); CheckEquals(INT_ATTR_VALUE, FAttrWithValue.Value.AsInteger, 'Value = INT_ATTR_VALUE'); end; { TestTDefaultsMap } procedure TestTDefaultsMap.SetUp; begin FDefaultsMap1 := TDefaultsMap.Create; FDefaultsMap2 := TDefaultsMap.Create; end; procedure TestTDefaultsMap.TearDown; begin FreeAndNil(FDefaultsMap1); FreeAndNil(FDefaultsMap2); end; procedure TestTDefaultsMap.TestAddValue; var Value: TValue; DefValAttribClass: TDefaultValueAttributeClass; begin Value := INT_ATTR_VALUE; DefValAttribClass := TTestAddAttr; TDefaultsMap.AddValue(DefValAttribClass, Value); CheckTrue(TDefaultsMap.HasValue(DefValAttribClass), 'CheckTrue::HasValue'); CheckEquals(INT_ATTR_VALUE, TDefaultsMap.GetValue(DefValAttribClass).AsInteger, 'TDefaultsMap.GetValue = INT_ATTR_VALUE'); CheckEquals(INT_ATTR_VALUE, FDefaultsMap1.GetValue(DefValAttribClass).AsInteger, 'FDefaultsMap1.GetValue = INT_ATTR_VALUE'); CheckEquals(FDefaultsMap1.GetValue(DefValAttribClass).AsInteger, FDefaultsMap2.GetValue(DefValAttribClass).AsInteger, 'FDefaultsMap2.GetValue = FDefaultsMap1.GetValue'); end; procedure TestTDefaultsMap.TestGetValue; var ReturnValue: TValue; DefValAttribClass: TDefaultValueAttributeClass; begin DefValAttribClass := TTestGetAttr; CheckException( procedure begin ReturnValue := TDefaultsMap.GetValue(DefValAttribClass); end, EListError, 'CheckException::EListError' ); TDefaultsMap.AddValue(DefValAttribClass, INT_ATTR_VALUE); ReturnValue := TDefaultsMap.GetValue(DefValAttribClass); CheckEquals(INT_ATTR_VALUE, ReturnValue.AsInteger, 'ReturnValue = INT_ATTR_VALUE'); end; procedure TestTDefaultsMap.TestHasValue; var ReturnValue: Boolean; DefValAttribClass: TDefaultValueAttributeClass; begin DefValAttribClass := TTestHasAttr; ReturnValue := TDefaultsMap.HasValue(DefValAttribClass); CheckFalse(ReturnValue, 'CheckFalse::ReturnValue'); TDefaultsMap.AddValue(DefValAttribClass, INT_ATTR_VALUE); ReturnValue := TDefaultsMap.HasValue(DefValAttribClass); CheckTrue(ReturnValue, 'CheckTrue::ReturnValue'); end; procedure TestTDefaultsMap.TestIsSingleton; var DefValAttribClass: TDefaultValueAttributeClass; begin DefValAttribClass := TDummyAttr; TDefaultsMap.AddValue(DefValAttribClass, INT_ATTR_VALUE); CheckNotEquals(FDefaultsMap1, FDefaultsMap2, 'FDefaultsMap1 <> FDefaultsMap2'); CheckTrue(FDefaultsMap1.HasValue(DefValAttribClass), 'CheckTrue::(FDefaultsMap1.StaticInstance = TDefaultsMap.StaticInstance)'); CheckTrue(FDefaultsMap2.HasValue(DefValAttribClass), 'CheckTrue::(FDefaultsMap2.StaticInstance = TDefaultsMap.StaticInstance)'); end; initialization // Register any test cases with the test runner RegisterTest(TestTDefaultValueAttribute.Suite); RegisterTest(TestTDefaultValueAttributeT.Suite); RegisterTest(TestTDefaultsMap.Suite); end.
{******************************************} { } { vtk GridReport library } { } { Copyright (c) 2003 by vtkTools } { } {******************************************} {Constants used in the GridReport library.} unit vgr_Consts; interface const {Millimeters per inch} MillimetersPerInch = 25.4; {Twips Per Inch} TwipsPerInch = 1440; {TwipsPerInch / MillimetersPerInch} TwipsPerMMs = TwipsPerInch / MillimetersPerInch; {Default row height in points} cXLSDefaultRowHeightPoints = $00FF; {Average char width of Arial, 10 font} cXLSAveCharWidthPixels = 8; {Default column width in chars} cXLSDefaultColumnWidthInChars = 8; {Default column width (TvgrCol.Width) in twips.} cDefaultColWidthTwips = (cXLSDefaultColumnWidthInChars * cXLSAveCharWidthPixels * TwipsPerInch) div 96; {Default row height (TvgrRow.Height) in twips.} cDefaultRowHeightTwips = (cXLSDefaultRowHeightPoints * TwipsPerInch) div (72 * 20); {Twips per centimeter.} cTwipsPerCm = 567; // 1440 / 25.4 * 10 {Width in 1/10 mm of A4 paper} A4_PaperWidth = 2100; {Height in 1/10 mm of A4 paper} A4_PaperHeight = 2970; implementation end.
unit ClassFile; interface uses ClassStack, Classes, SysUtils; type TFile = class private Stack : TStack; function ReadItem( F : TFileStream ) : TStackItem; procedure ReadFromFile( FileName : string ); procedure WriteItem( F : TFileStream; Item : TStackItem ); procedure WriteToFile( FileName : string ); public constructor Create; destructor Destroy; override; procedure CreateDictionary( FileNameIn, FileNameOut : string ); end; implementation constructor TFile.Create; begin inherited; Stack := TStack.Create; end; destructor TFile.Destroy; begin Stack.Free; inherited; end; //============================================================================== // P R I V A T E //============================================================================== // Read one item from file (both slovak and english words) function TFile.ReadItem( F : TFileStream ) : TStackItem; var Count : integer; English : string; Slovak : string; begin // Read slovak word F.Read( Count , SizeOf( Count ) ); SetLength( Slovak , Count ); F.Read( Slovak[1] , Count ); // Read english word F.Read( Count , SizeOf( Count ) ); SetLength( English , Count ); F.Read( English[1] , Count ); Result := TStackItem.Create( English , Slovak , nil ); end; // Read all items from file and push them into the stack procedure TFile.ReadFromFile( FileName : string ); var F : TFileStream; begin F := TFileStream.Create( FileName , fmOpenRead ); try while (F.Position < F.Size) do Stack.Push( ReadItem( F ) ); finally F.Free; end; end; // Write one item to file procedure TFile.WriteItem( F : TFileStream; Item : TStackItem ); var Count : integer; begin // Write slovak word Count := Length( Item.English ); F.Write( Count , SizeOf( Count ) ); F.Write( Item.English[1] , Count ); // Write english word Count := Length( Item.Slovak ); F.Write( Count , SizeOf( Count ) ); F.Write( Item.Slovak[1] , Count ); end; // Write all items to file and empty stack procedure TFile.WriteToFile( FileName : string ); var F : TFileStream; S : TStackItem; begin F := TFileStream.Create( FileName , fmCreate ); try S := Stack.Pop; while (S <> nil) do begin WriteItem( F , S ); S.Free; S := Stack.Pop; end; finally F.Free; end; end; //============================================================================== // P U B L I C //============================================================================== procedure TFile.CreateDictionary( FileNameIn, FileNameOut : string ); begin ReadFromFile( FileNameIn ); WriteToFile( FileNameOut ); end; end.
{Draw menu} Unit Menu; Interface {program Graphic;} uses graph, crt, SUPM, Bas, Buffer, Device, Boos, Statist, Writer, Source1, Source2, MenuMod, MenuRes; type p_MainMenu = ^MainMenuObj; MainMenuObj = object private {variable for Initgraph} gh, gm : integer; {instance of classes} boosIn : p_Boos; buff: p_Buffer; writerIn : p_Writer; firstSource : p_Source1; secondSource : p_Source2; dev : p_Device; basIn : p_Bas; stat : p_Statistic; SubMenuSup : p_SMSUP; SubMenuMod : p_MenuMod; SubMenuRes : p_MenuRes; public {initialization our the massive for menu} constructor Init; {write a tips} procedure drawHelp; {draw button of setting params} procedure drawButtonOfSettingParams(color, fraim : longint); {draw button of modeling} procedure drawButtonOfModeling(color, fraim : longint); {draw button of results} procedure drawButtonOfResults(color, fraim : longint); {launch main menu} procedure launchMainMenu; end; Implementation constructor MainMenuObj.Init; begin gm := 0; gh := 0; new (firstSource, Init); new (secondSource, Init); new (stat, Init(0.9)); new (buff, Init(2)); new (dev, Init(buff, 1)); new (basIn, Init(dev, buff)); new (writerIn, Init); new (boosIn, Init(firstSource, secondSource, dev, basIn, stat, writerIn, 2.71, 0.1)); new(SubMenuSup, Init(boosIn)); new(SubMenuMod, Init(boosIn, stat)); new(SubMenuRes, Init(stat, firstSource, boosIn)); end; procedure MainMenuObj.drawHelp; begin setcolor(blue); SetTextStyle(DefaultFont, HorizDir, 1); OutTextXY(20, 420, 'Press right, left, up or down arrow to switch between the button.'); OutTextXY(20, 440, 'Press ENTER if you want choose this button. Press END if you want exit.'); OutTextXY(20, 460, 'SMO done by Maschenko Bogdan, group 13534/4, 2019 year'); end; procedure MainMenuObj.drawButtonOfSettingParams; begin setcolor(color); setfillstyle(1, color); Bar(30, 40, 180, 90); setcolor(fraim); Rectangle(30, 40, 180, 90); setcolor(black); SetTextStyle(DefaultFont, HorizDir, 1); OutTextXY(38, 60, 'Set up parameters'); end; procedure MainMenuObj.drawButtonOfModeling; begin setcolor(color); setfillstyle(1, color); Bar(230, 40, 380, 90); setcolor(fraim); Rectangle(230, 40, 380, 90); setcolor(black); SetTextStyle(DefaultFont, HorizDir, 1); OutTextXY(275, 60, 'Modeling'); end; procedure MainMenuObj.drawButtonOfResults; begin setcolor(color); setfillstyle(1, color); Bar(430, 40, 580, 90); setcolor(fraim); Rectangle(430, 40, 580, 90); setcolor(black); SetTextStyle(DefaultFont, HorizDir, 1); OutTextXY(480, 60, 'Results'); end; procedure MainMenuObj.launchMainMenu; var button : char; ind : longint; begin Initgraph(gm, gh, ''); drawButtonOfSettingParams(7, 15); drawButtonOfModeling(4, 15); drawButtonOfResults(4, 15); drawHelp; ind := 1; button := readkey; repeat if ((button = #77) and (ind < 3)) then inc(ind) else if ((button = #75) and (ind > 1)) then dec(ind); case ind of 1: begin drawButtonOfSettingParams(7, 15); drawButtonOfModeling(4, 15); drawButtonOfResults(4, 15); drawHelp; button := readkey; if button = #13 then begin SubMenuSup^.launchSubmenuOfSUP; button := readkey; end; end; 2: begin drawButtonOfSettingParams(4, 15); drawButtonOfModeling(7,15); drawButtonOfResults(4, 15); drawHelp; button := readkey; if button = #13 then begin SubMenuMod^.launchSubmenuMod; button := readkey; end; end; 3: begin drawButtonOfSettingParams(4, 15); drawButtonOfModeling(4, 15); drawButtonOfResults(7, 15); drawHelp; button := readkey; if button = #13 then begin SubMenuRes^.launchSubmenuRes; button := readkey; end; end; end; until button = #79; writerIn^.averageQuantityOfRequestInBufferMSG(stat); writerIn^.Done; CloseGraph; end; BEGIN END.
unit fEffectDate; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, Grids, Calendar, ORDtTmCal, StdCtrls, ORDtTm, ORFn, VA508AccessibilityManager; type TfrmEffectDate = class(TfrmAutoSz) calEffective: TORDateBox; Label2: TLabel; Label3: TStaticText; Label4: TStaticText; cmdOK: TButton; cmdCancel: TButton; procedure FormCreate(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); private OKPressed: Boolean; end; function ObtainEffectiveDate(var ADate: TFMDateTime): Boolean; implementation {$R *.DFM} function ObtainEffectiveDate(var ADate: TFMDateTime): Boolean; var frmEffectDate: TfrmEffectDate; begin Result := False; frmEffectDate := TfrmEffectDate.Create(Application); try ResizeFormToFont(TForm(frmEffectDate)); if ADate <> 0 then frmEffectDate.calEffective.FMDateTime := ADate; frmEffectDate.ShowModal; if frmEffectDate.OKPressed then begin ADate := frmEffectDate.calEffective.FMDateTime; Result := True; end; finally frmEffectDate.Release; end; end; procedure TfrmEffectDate.FormCreate(Sender: TObject); begin inherited; OKPressed := False; end; procedure TfrmEffectDate.cmdOKClick(Sender: TObject); begin inherited; OKPressed := True; Close; end; procedure TfrmEffectDate.cmdCancelClick(Sender: TObject); begin inherited; Close; end; end.
unit Dados.Firebird; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.IB, FireDAC.Phys.IBDef, FireDAC.VCLUI.Wait, FireDAC.Phys.FBDef, FireDAC.Phys.IBBase, FireDAC.Phys.FB, FireDAC.Comp.Client, FireDAC.Comp.UI, Data.DB, FireDAC.Comp.DataSet; type TDadosFirebird = class(TDataModule) FDQuery: TFDQuery; FDTransServidor: TFDTransaction; FDGeral: TFDQuery; FDComandoSQL: TFDQuery; FDConsulta: TFDQuery; FDDados: TFDConnection; FDGUIxWaitCursor: TFDGUIxWaitCursor; FDCmd: TFDCommand; FDPhysFBDriverLink: TFDPhysFBDriverLink; FDAluno: TFDQuery; FDAlunoIDALUNO: TIntegerField; FDAlunoNOME: TStringField; private { Private declarations } public { Public declarations } function Conectar(aServidor, aBanco, aUsuario, aSenha : string):boolean; function Desconectar: boolean; function getDataSet(aSql:string): TFDQuery; function OpenDataSet(aSql:string): boolean; overload; function OpenDataSet(aSql:string; aQuery: TFDQuery): boolean; overload; function ExecuteSql(aSql: string):boolean; function getMax(aNomeTabela, aNomeCampo:string): integer; end; var DadosFirebird: TDadosFirebird; implementation {$R *.dfm} function TDadosFirebird.Conectar(aServidor, aBanco, aUsuario, aSenha : string): boolean; var StrConnection: string; begin Result := False; try FDDados.Connected := False; FDDados.Params.Clear; FDDados.LoginPrompt := False; FDDados.DriverName := 'IB'; FDDados.Params.Add('DriverID=' + 'IB'); FDDados.Params.Add('DataBase=' + aBanco); FDDados.Params.Add('User_Name=' + aUsuario); FDDados.Params.Add('Password=' + aSenha); FDDados.Params.Add('Protocol=' +'TCPIP'); FDDados.Params.Add('LoginTimeout=' + '30'); FDDados.Params.Add('Server=' + aServidor); FDDados.Connected := True; Result := True; except on E: Exception do begin raise Exception.Create('Problemas ao conectar ao banco! '+E.message); end; end; end; function TDadosFirebird.Desconectar: boolean; begin Result:= False; try FDDados.Connected := False; Result:= True; except on E: Exception do begin raise; end; end; end; function TDadosFirebird.ExecuteSql(aSql: string): boolean; Var msgErro:string; begin result := false; FDQuery.Close; FDQuery.Params.Clear; FDQuery.Sql.Text := aSql; try FDQuery.ExecSQL; result := true; except on e: Exception do begin raise Exception.Create('Não foi possível executar o comando sql! '+e.Message) end; end; end; function TDadosFirebird.getDataSet(aSql: string): TFDQuery; begin FDQuery.Close; FDQuery.Params.Clear; FDQuery.SQL.Text := aSql; FDQuery.Open; result := FDQuery; end; function TDadosFirebird.getMax(aNomeTabela, aNomeCampo: string): integer; begin Result := 0; FDQuery.Close; FDQuery.Params.Clear; FDQuery.SQL.Text := 'Select Max('+trim(aNomeCampo)+') as Ultimo from '+trim(aNomeTabela); FDQuery.Open; if not FDQuery.IsEmpty then result := FDQuery.FieldByName('Ultimo').asInteger; end; function TDadosFirebird.OpenDataSet(aSql: string; aQuery: TFDQuery): boolean; begin Result := False; aQuery.Close; aQuery.Params.Clear; aQuery.SQL.Text := aSql; aQuery.Open; result := not aQuery.IsEmpty; end; function TDadosFirebird.OpenDataSet(aSql: string): boolean; begin Result := False; FDQuery.Close; FDQuery.Params.Clear; FDQuery.SQL.Text := aSql; FDQuery.Open; result := not FDQuery.IsEmpty; end; end.
unit Account_impl; {This file was generated on 5 Apr 2001 12:47:25 GMT by version 03.03.03.C1.A1 } {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file } {C:\CO86DA~1\Account.idl. } {Delphi Pascal unit : Account_impl } {derived from IDL module : default } interface uses SysUtils, CORBA, Account_i, Account_c; type TAccount = class; TAccount = class(TInterfacedObject, Account_i.Account) protected _balance : Single; public constructor Create; function balance : Single; end; implementation uses ServerMain; constructor TAccount.Create; begin inherited; _balance := random(10000); Form1.Memo1.Lines.Add('Object is ready...'); Form1.Memo1.Lines.Add(FormatFloat('Balance = $##,##0.00', _balance)); end; function TAccount.balance : Single; begin result := _balance; Form1.Memo1.Lines.Add('Got a balance request'); end; initialization randomize; end.
unit ListBoxImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB; type TListBoxX = class(TActiveXControl, IListBoxX) private { Private declarations } FDelphiControl: TListBox; FEvents: IListBoxXEvents; procedure ClickEvent(Sender: TObject); procedure DblClickEvent(Sender: TObject); procedure KeyPressEvent(Sender: TObject; var Key: Char); procedure MeasureItemEvent(Control: TWinControl; Index: Integer; var Height: Integer); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_BorderStyle: TxBorderStyle; safecall; function Get_Color: OLE_COLOR; safecall; function Get_Columns: Integer; safecall; function Get_Ctl3D: WordBool; safecall; function Get_Cursor: Smallint; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_Enabled: WordBool; safecall; function Get_ExtendedSelect: WordBool; safecall; function Get_Font: IFontDisp; safecall; function Get_ImeMode: TxImeMode; safecall; function Get_ImeName: WideString; safecall; function Get_IntegralHeight: WordBool; safecall; function Get_ItemHeight: Integer; safecall; function Get_ItemIndex: Integer; safecall; function Get_Items: IStrings; safecall; function Get_MultiSelect: WordBool; safecall; function Get_ParentColor: WordBool; safecall; function Get_ParentCtl3D: WordBool; safecall; function Get_ParentFont: WordBool; safecall; function Get_SelCount: Integer; safecall; function Get_Sorted: WordBool; safecall; function Get_Style: TxListBoxStyle; safecall; function Get_TabWidth: Integer; safecall; function Get_TopIndex: Integer; safecall; function Get_Visible: WordBool; safecall; function GetControlsAlignment: TxAlignment; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure _Set_Font(const Value: IFontDisp); safecall; procedure AboutBox; safecall; procedure Clear; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_BorderStyle(Value: TxBorderStyle); safecall; procedure Set_Color(Value: OLE_COLOR); safecall; procedure Set_Columns(Value: Integer); safecall; procedure Set_Ctl3D(Value: WordBool); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_ExtendedSelect(Value: WordBool); safecall; procedure Set_Font(const Value: IFontDisp); safecall; procedure Set_ImeMode(Value: TxImeMode); safecall; procedure Set_ImeName(const Value: WideString); safecall; procedure Set_IntegralHeight(Value: WordBool); safecall; procedure Set_ItemHeight(Value: Integer); safecall; procedure Set_ItemIndex(Value: Integer); safecall; procedure Set_Items(const Value: IStrings); safecall; procedure Set_MultiSelect(Value: WordBool); safecall; procedure Set_ParentColor(Value: WordBool); safecall; procedure Set_ParentCtl3D(Value: WordBool); safecall; procedure Set_ParentFont(Value: WordBool); safecall; procedure Set_Sorted(Value: WordBool); safecall; procedure Set_Style(Value: TxListBoxStyle); safecall; procedure Set_TabWidth(Value: Integer); safecall; procedure Set_TopIndex(Value: Integer); safecall; procedure Set_Visible(Value: WordBool); safecall; end; implementation uses ComObj, About14; { TListBoxX } procedure TListBoxX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_ListBoxXPage); } end; procedure TListBoxX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as IListBoxXEvents; end; procedure TListBoxX.InitializeControl; begin FDelphiControl := Control as TListBox; FDelphiControl.OnClick := ClickEvent; FDelphiControl.OnDblClick := DblClickEvent; FDelphiControl.OnKeyPress := KeyPressEvent; FDelphiControl.OnMeasureItem := MeasureItemEvent; end; function TListBoxX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TListBoxX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TListBoxX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TListBoxX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TListBoxX.Get_BorderStyle: TxBorderStyle; begin Result := Ord(FDelphiControl.BorderStyle); end; function TListBoxX.Get_Color: OLE_COLOR; begin Result := OLE_COLOR(FDelphiControl.Color); end; function TListBoxX.Get_Columns: Integer; begin Result := FDelphiControl.Columns; end; function TListBoxX.Get_Ctl3D: WordBool; begin Result := FDelphiControl.Ctl3D; end; function TListBoxX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TListBoxX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TListBoxX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TListBoxX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TListBoxX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TListBoxX.Get_ExtendedSelect: WordBool; begin Result := FDelphiControl.ExtendedSelect; end; function TListBoxX.Get_Font: IFontDisp; begin GetOleFont(FDelphiControl.Font, Result); end; function TListBoxX.Get_ImeMode: TxImeMode; begin Result := Ord(FDelphiControl.ImeMode); end; function TListBoxX.Get_ImeName: WideString; begin Result := WideString(FDelphiControl.ImeName); end; function TListBoxX.Get_IntegralHeight: WordBool; begin Result := FDelphiControl.IntegralHeight; end; function TListBoxX.Get_ItemHeight: Integer; begin Result := FDelphiControl.ItemHeight; end; function TListBoxX.Get_ItemIndex: Integer; begin Result := FDelphiControl.ItemIndex; end; function TListBoxX.Get_Items: IStrings; begin GetOleStrings(FDelphiControl.Items, Result); end; function TListBoxX.Get_MultiSelect: WordBool; begin Result := FDelphiControl.MultiSelect; end; function TListBoxX.Get_ParentColor: WordBool; begin Result := FDelphiControl.ParentColor; end; function TListBoxX.Get_ParentCtl3D: WordBool; begin Result := FDelphiControl.ParentCtl3D; end; function TListBoxX.Get_ParentFont: WordBool; begin Result := FDelphiControl.ParentFont; end; function TListBoxX.Get_SelCount: Integer; begin Result := FDelphiControl.SelCount; end; function TListBoxX.Get_Sorted: WordBool; begin Result := FDelphiControl.Sorted; end; function TListBoxX.Get_Style: TxListBoxStyle; begin Result := Ord(FDelphiControl.Style); end; function TListBoxX.Get_TabWidth: Integer; begin Result := FDelphiControl.TabWidth; end; function TListBoxX.Get_TopIndex: Integer; begin Result := FDelphiControl.TopIndex; end; function TListBoxX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TListBoxX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TListBoxX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TListBoxX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TListBoxX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TListBoxX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TListBoxX._Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TListBoxX.AboutBox; begin ShowListBoxXAbout; end; procedure TListBoxX.Clear; begin FDelphiControl.Clear; end; procedure TListBoxX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TListBoxX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TListBoxX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TListBoxX.Set_BorderStyle(Value: TxBorderStyle); begin FDelphiControl.BorderStyle := TBorderStyle(Value); end; procedure TListBoxX.Set_Color(Value: OLE_COLOR); begin FDelphiControl.Color := TColor(Value); end; procedure TListBoxX.Set_Columns(Value: Integer); begin FDelphiControl.Columns := Value; end; procedure TListBoxX.Set_Ctl3D(Value: WordBool); begin FDelphiControl.Ctl3D := Value; end; procedure TListBoxX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TListBoxX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TListBoxX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TListBoxX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TListBoxX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TListBoxX.Set_ExtendedSelect(Value: WordBool); begin FDelphiControl.ExtendedSelect := Value; end; procedure TListBoxX.Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TListBoxX.Set_ImeMode(Value: TxImeMode); begin FDelphiControl.ImeMode := TImeMode(Value); end; procedure TListBoxX.Set_ImeName(const Value: WideString); begin FDelphiControl.ImeName := TImeName(Value); end; procedure TListBoxX.Set_IntegralHeight(Value: WordBool); begin FDelphiControl.IntegralHeight := Value; end; procedure TListBoxX.Set_ItemHeight(Value: Integer); begin FDelphiControl.ItemHeight := Value; end; procedure TListBoxX.Set_ItemIndex(Value: Integer); begin FDelphiControl.ItemIndex := Value; end; procedure TListBoxX.Set_Items(const Value: IStrings); begin SetOleStrings(FDelphiControl.Items, Value); end; procedure TListBoxX.Set_MultiSelect(Value: WordBool); begin FDelphiControl.MultiSelect := Value; end; procedure TListBoxX.Set_ParentColor(Value: WordBool); begin FDelphiControl.ParentColor := Value; end; procedure TListBoxX.Set_ParentCtl3D(Value: WordBool); begin FDelphiControl.ParentCtl3D := Value; end; procedure TListBoxX.Set_ParentFont(Value: WordBool); begin FDelphiControl.ParentFont := Value; end; procedure TListBoxX.Set_Sorted(Value: WordBool); begin FDelphiControl.Sorted := Value; end; procedure TListBoxX.Set_Style(Value: TxListBoxStyle); begin FDelphiControl.Style := TListBoxStyle(Value); end; procedure TListBoxX.Set_TabWidth(Value: Integer); begin FDelphiControl.TabWidth := Value; end; procedure TListBoxX.Set_TopIndex(Value: Integer); begin FDelphiControl.TopIndex := Value; end; procedure TListBoxX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TListBoxX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; procedure TListBoxX.DblClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnDblClick; end; procedure TListBoxX.KeyPressEvent(Sender: TObject; var Key: Char); var TempKey: Smallint; begin TempKey := Smallint(Key); if FEvents <> nil then FEvents.OnKeyPress(TempKey); Key := Char(TempKey); end; procedure TListBoxX.MeasureItemEvent(Control: TWinControl; Index: Integer; var Height: Integer); var TempHeight: Integer; begin TempHeight := Integer(Height); if FEvents <> nil then FEvents.OnMeasureItem(Index, TempHeight); Height := Integer(TempHeight); end; initialization TActiveXControlFactory.Create( ComServer, TListBoxX, TListBox, Class_ListBoxX, 14, '{695CDB3F-02E5-11D2-B20D-00C04FA368D4}', 0, tmApartment); end.
(* Exemplo de consumo de uma API que espera e retorna um json. A autenticação é via token que deve ser enviado no cabeçalho da requisição. *) unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, StdCtrls, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, ExtCtrls, uLkJSON, IdIntercept, IdLogBase, IdLogDebug; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL; IdHTTP1: TIdHTTP; LabeledEdit1: TLabeledEdit; LabeledEdit2: TLabeledEdit; LabeledEdit3: TLabeledEdit; LabeledEdit4: TLabeledEdit; LabeledEdit5: TLabeledEdit; IdLogDebug1: TIdLogDebug; CheckBox1: TCheckBox; procedure Button1Click(Sender: TObject); procedure IdLogDebug1Send(ASender: TIdConnectionIntercept; var ABuffer: TBytes); procedure IdLogDebug1Receive(ASender: TIdConnectionIntercept; var ABuffer: TBytes); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var sResponse,url, json:string; JsonToSend:TStringStream; js : TlkJSONobject; ws: TlkJSONstring; token, HeaderStr: string; begin Memo1.Lines.Clear; IdLogDebug1.Active := CheckBox1.Checked; token := 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'; HeaderStr := 'token '+token; json := ('{"placa": "'+LabeledEdit1.Text+'", '+ '"data_hora": "'+LabeledEdit2.Text+' '+LabeledEdit3.Text+'"}' ); JsonToSend := TStringStream.Create(Utf8Encode(Json)); IdHTTP1.Request.ContentType := 'application/json'; IdHTTP1.Request.CharSet := 'utf-8'; IdHTTP1.Request.CustomHeaders.Clear; IdHttp1.Request.CustomHeaders.AddValue('Authorization', HeaderStr); try url := 'https://glatesat.herokuapp.com/api_odometro/'; sResponse := IdHTTP1.Post(url, JsonToSend); Memo1.Lines.Add('=====CONTENT====='); Memo1.Lines.Add(sResponse); Memo1.Lines.Add('================='); js := TlkJSON.ParseText(sResponse) as TlkJSONobject; // ws := js.Field['placa'] as TlkJSONstring; LabeledEdit4.Text := js.getString('placa'); // ws := js.Field['odometro'] as TlkJSONstring; LabeledEdit5.Text := FloatToStr(js.getDouble('odometro')); except on E: Exception do begin ShowMessage('Error on request: '#13#10 + e.Message); Memo1.Lines.Add(e.Message); end; end; end; procedure TForm1.IdLogDebug1Receive(ASender: TIdConnectionIntercept; var ABuffer: TBytes); begin Memo1.Lines.Add('Receive <<<<<<<<'); Memo1.Lines.Add(TEncoding.UTF8.GetString(ABuffer)); Memo1.Lines.Add(''); end; procedure TForm1.IdLogDebug1Send(ASender: TIdConnectionIntercept; var ABuffer: TBytes); begin Memo1.Lines.Add('Send >>>>>>>'); Memo1.Lines.Add(TEncoding.UTF8.GetString(ABuffer)); Memo1.Lines.Add(''); end; end.
{----------------------- VGA Hardware Library ------------------------} {$A+,B-,E-,F-,G+,I-,N-,O-,P-,Q-,R-,S-,T-,V-,X-} unit vga_hard; interface const INPUT_STATUS1 = $3da; MISC_OUTPUT = $3c2; SC_INDEX = $3c4; CRTC_INDEX = $3d4; GRAPH_INDEX = $3ce; ATTR_INDEX = $3c0; {-- Don't forget clear flipflop & set bit 5 on index } PEL_WRITE = $3c8; PEL_READ = $3c7; PEL_DATE = $3c9; MASK_PLANE1 = $00102; {-- Map Register + Plane 1 } MASK_PLANE2 = $01102; {-- Map Register + Plane 1 } ALL_PLANES = $00F02; {-- Map Register + All Bit Planes } CHAIN4_OFF = $00604; {-- Chain 4 mode Off } ASYNC_RESET = $00100; {-- (A)synchronous Reset } SEQU_RESTART= $00300; {-- Sequencer Restart } LATCHES_ON =$00008; {-- Bit Mask + Data from Latches } LATCHES_OFF=$0FF08; {-- Bit Mask + Data from CPU } procedure VGA_POS(x:word); procedure VGA_PAN(pan:byte); procedure VGA_PAN_C; procedure VGA_WPLANE(plane:byte); procedure VGA_RPLANE(plane:byte); procedure VGA_WMODE(mode:byte); procedure VGA_RMODE(mode:byte); procedure VGA_SPLIT(scanline:word); procedure VGA_VBLANK(start,ending:word); procedure HSYNCH; procedure VWAIT; procedure VSYNCH(n:word); procedure VSKIP; procedure screen_off; procedure screen_on; procedure video_hirez; procedure video_lorez; procedure scan_height(value:byte); {---------------------------------------------------------} implementation {$L vga_hard.obj} procedure VGA_POS(x:word); external; procedure VGA_PAN(pan:byte); external; procedure VGA_PAN_C; external; procedure VGA_WPLANE(plane:byte); external; procedure VGA_RPLANE(plane:byte); external; procedure VGA_WMODE(mode:byte); external; procedure VGA_RMODE(mode:byte); external; procedure VGA_SPLIT(scanline:word); external; procedure VGA_VBLANK(start,ending:word); external; procedure HSYNCH; external; procedure VWAIT; external; procedure VSYNCH(n:word); external; procedure VSKIP; external; procedure screen_off; external; procedure screen_on; external; procedure video_hirez; external; procedure video_lorez; external; procedure scan_height(value:byte); external; begin end.
{ Copyright (C) 1998-2018, written by Mike Shkolnik, Scalabium Software E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com TSMBevel component is extension of the standart TBevel and have additional features: - except standart styles (mbsLowered, mbsRaised) I add a new style mbsNone - usual line or triangle - except standart Shapes (mbsBox, mbsFrame, mbsTopLine, mbsBottomLine, mbsLeftLine, mbsRightLine) I add the new shapes mbsBoxIn - beautiful frame mbsTopLeftLine - diagonal right-to-left line mbsTopRightLine - diagonal left-to-right line mbsTriangle - standard triangle figure mbsOctogon - standard octogon figure mbsStar - star figure mbsRoundRect mbsSquare mbsRoundSquare mbsEllipse - added feature of the arrow drawing property Arrow (if Style not in [mbsBox, mbsBoxIn, mbsFrame]): smaFinish - arrow on end line smaStart - arrow on start line smaNone - arrow not available property ArrowType: atOutline - drawing a arrow contour only atSolid - drawing a fill arrow property ArrowAngle - angle of the arrow deviation from main line (in degrees) property ArrowLength - length of oblique side Written by Tommy Dillard request (dillard@cyberramp.net): 1. added two properties TopColor/BottomColor - colors for Raised/Lowered lines 2. fixed error: - not correct draw the arrow with Arrow = smaFinish and Shape = mbsTopRightLine } unit SMBevel; interface {$I SMVersion.inc} uses Windows, Messages, Classes, Graphics, Controls; type TSMBevelStyle = (mbsLowered, mbsNone, mbsRaised); TSMBevelShape = (mbsBox, mbsBoxIn, mbsFrame, mbsTopLine, mbsBottomLine, mbsLeftLine, mbsRightLine, mbsTopLeftLine, mbsTopRightLine, mbsStar, mbsTriangle, mbsOctogon, mbsRoundRect, mbsSquare, mbsRoundSquare, mbsEllipse); TSMArrowType = (atOutline, atSolid); TSMArrow = (smaNone, smaStart, smaFinish); TTextLayout = (tlTop, tlCenter, tlBottom); {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TSMBevel = class(TGraphicControl) private { Private declarations } FFocusControl: TWinControl; {arrows for line} FArrow: TSMArrow; FArrowType: TSMArrowType; FArrowAngle: Integer; FArrowLength: Integer; {relation description} FAlignment: TAlignment; FLayout: TTextLayout; FBevelWidth: Integer; FStyle: TSMBevelStyle; FShape: TSMBevelShape; FPenStyle: TPenStyle; {Added by Tommy Dillard} FTopColor: TColor; FBottomColor: TColor; procedure SetTopColor(Value: TColor); procedure SetBottomColor(Value: TColor); {End Addition by Tommy Dillard} procedure SetFocusControl(Value: TWinControl); procedure SetArrow(Value: TSMArrow); procedure SetArrowType(Value: TSMArrowType); procedure SetArrowAngle(Value: Integer); procedure SetArrowLength(Value: Integer); procedure SetAlignment(Value: TAlignment); procedure SetLayout(Value: TTextLayout); procedure SetBevelWidth(Value: Integer); procedure SetStyle(Value: TSMBevelStyle); procedure SetShape(Value: TSMBevelShape); procedure SetPenStyle(Value: TPenStyle); procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure DoDrawText(var Rect: TRect; Flags: Word); protected { Protected declarations } procedure Paint; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } property Arrow: TSMArrow read FArrow write SetArrow; property ArrowType: TSMArrowType read FArrowType write SetArrowType; property ArrowAngle: Integer read FArrowAngle write SetArrowAngle; property ArrowLength: Integer read FArrowLength write SetArrowLength; property Alignment: TAlignment read FAlignment write SetAlignment default taCenter; property Layout: TTextLayout read FLayout write SetLayout default tlTop; property PenStyle: TPenStyle read FPenStyle write SetPenStyle; {Added by Tommy Dillard} property TopColor: TColor read FTopColor write SetTopColor; property BottomColor: TColor read FBottomColor write SetBottomColor; {End Addition by Tommy Dillard} property Align; property Caption; property Font; property Enabled; property FocusControl: TWinControl read FFocusControl write SetFocusControl; property ParentShowHint; property Shape: TSMBevelShape read FShape write SetShape default mbsBox; property ShowHint; property BevelWidth: Integer read FBevelWidth write SetBevelWidth; property Style: TSMBevelStyle read FStyle write SetStyle default mbsLowered; property Visible; end; procedure Register; implementation procedure Register; begin RegisterComponents('SMComponents', [TSMBevel]); end; procedure Frame3D(Canvas: TCanvas; var Rect: TRect; TopColor, BottomColor: TColor; Width: Integer); procedure DoRect; var TopRight, BottomLeft: TPoint; begin with Canvas, Rect do begin TopRight.X := Right; TopRight.Y := Top; BottomLeft.X := Left; BottomLeft.Y := Bottom; Pen.Color := TopColor; PolyLine([BottomLeft, TopLeft, TopRight]); Pen.Color := BottomColor; Dec(BottomLeft.X); PolyLine([TopRight, BottomRight, BottomLeft]); end; end; begin Canvas.Pen.Width := 1; Dec(Rect.Bottom); Dec(Rect.Right); while Width > 0 do begin Dec(Width); DoRect; InflateRect(Rect, -1, -1); end; Inc(Rect.Bottom); Inc(Rect.Right); end; { TSMBevel } constructor TSMBevel.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; FBevelWidth := 1; FStyle := mbsLowered; FShape := mbsBox; Width := 50; Height := 50; FPenStyle := psSolid; FArrow := smaFinish; FArrowAngle := 25; FArrowLength := 15; FAlignment := taCenter; FArrowType := atSolid; {Added by Tommy Dillard} FTopColor := clBtnHighlight; FBottomColor := clBtnShadow; end; procedure TSMBevel.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FFocusControl) then FFocusControl := nil; end; procedure TSMBevel.CMDialogChar(var Message: TCMDialogChar); begin if (FFocusControl <> nil) and Enabled then with FFocusControl do if CanFocus then begin SetFocus; Message.Result := 1; end; end; procedure TSMBevel.SetFocusControl(Value: TWinControl); begin FFocusControl := Value; if Value <> nil then Value.FreeNotification(Self); end; {Added by Tommy Dillard} procedure TSMBevel.SetTopColor(Value: TColor); begin if (Value <> FTopColor) then begin FTopColor := Value; Invalidate; end; end; procedure TSMBevel.SetBottomColor(Value: TColor); begin if (Value <> FBottomColor) then begin FBottomColor := Value; Invalidate; end; end; {End Additon by Tommy Dillard} procedure TSMBevel.SetArrow(Value: TSMArrow); begin if (Value <> FArrow) then begin FArrow := Value; Invalidate; end; end; procedure TSMBevel.SetArrowType(Value: TSMArrowType); begin if (Value <> FArrowType) then begin FArrowType := Value; Invalidate; end; end; procedure TSMBevel.SetArrowAngle(Value: Integer); begin if (Value <> FArrowAngle) then begin FArrowAngle := Value; Invalidate; end; end; procedure TSMBevel.SetArrowLength(Value: Integer); begin if (Value <> FArrowLength) then begin FArrowLength := Value; Invalidate; end; end; procedure TSMBevel.SetAlignment(Value: TAlignment); begin if (Value <> FAlignment) then begin FAlignment := Value; Invalidate; end; end; procedure TSMBevel.SetLayout(Value: TTextLayout); begin if (FLayout <> Value) then begin FLayout := Value; Invalidate; end; end; procedure TSMBevel.SetBevelWidth(Value: Integer); begin if (Value <> FBevelWidth) and (Value > 0) then begin FBevelWidth := Value; Invalidate; end; end; procedure TSMBevel.SetStyle(Value: TSMBevelStyle); begin if (Value <> FStyle) then begin FStyle := Value; Invalidate; end; end; procedure TSMBevel.SetShape(Value: TSMBevelShape); begin if (Value <> FShape) then begin FShape := Value; Invalidate; end; end; procedure TSMBevel.SetPenStyle(Value: TPenStyle); begin if (Value <> FPenStyle) then begin FPenStyle := Value; Invalidate; end; end; procedure TSMBevel.DoDrawText(var Rect: TRect; Flags: Word); var Text: string; begin Text := Caption; if (Flags and DT_CALCRECT <> 0) and (Text = '') then Text := Text + ' '; Flags := Flags or DT_NOPREFIX; Canvas.Font := Font; if not Enabled then begin OffsetRect(Rect, 1, 1); Canvas.Font.Color := clBtnHighlight; DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); OffsetRect(Rect, -1, -1); Canvas.Font.Color := clBtnShadow; DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); end else DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); end; procedure TSMBevel.Paint; var Color1, Color2: TColor; Temp: TColor; function DegToRad(Degrees: Extended): Extended; begin Result := Degrees*(PI/180); end; procedure BevelRect(const R: TRect); begin with Canvas do begin Pen.Color := Color1; PolyLine([Point(R.Left, R.Bottom), Point(R.Left, R.Top), Point(R.Right, R.Top)]); Pen.Color := Color2; PolyLine([Point(R.Right, R.Top), Point(R.Right, R.Bottom), Point(R.Left, R.Bottom)]); end; end; procedure BevelLine(C: TColor; X1, Y1, X2, Y2: Integer); begin with Canvas do begin Pen.Color := C; MoveTo(X1, Y1); LineTo(X2, Y2); end; end; procedure BevelArrow(C1, C2: TColor; ARect: TRect); var Alpha, Beta: Extended; begin with Canvas do begin Pen.Color := C1; Brush.Color := C2; Beta := DegToRad(FArrowAngle)/2; if FArrowType = atOutline then begin if (FArrow = smaStart) then begin Alpha := ArcTan((ARect.Right - ARect.Left)/(ARect.Bottom - ARect.Top)); MoveTo(Round(ARect.Left + FArrowLength*Sin(Alpha-Beta)), Round(ARect.Top + FArrowLength*Cos(Alpha-Beta))); LineTo(ARect.Left, ARect.Top); LineTo(Round(ARect.Left + FArrowLength*Sin(Alpha+Beta)), Round(ARect.Top + FArrowLength*Cos(Alpha+Beta))) end else // smaFinish begin Alpha := ArcTan((ARect.Bottom - ARect.Top)/(ARect.Right - ARect.Left)); if (ARect.Right > ARect.Left) then begin MoveTo(Round(ARect.Right - FArrowLength*Cos(Alpha-Beta)), Round(ARect.Bottom - FArrowLength*Sin(Alpha-Beta))); LineTo(ARect.Right, ARect.Bottom); LineTo(Round(ARect.Right - FArrowLength*Cos(Alpha+Beta)), Round(ARect.Bottom - FArrowLength*Sin(Alpha+Beta))) end else begin MoveTo(Round(ARect.Right + FArrowLength*Cos(Alpha-Beta)), Round(ARect.Bottom + FArrowLength*Sin(Alpha-Beta))); LineTo(ARect.Right, ARect.Bottom); LineTo(Round(ARect.Right + FArrowLength*Cos(Alpha+Beta)), Round(ARect.Bottom + FArrowLength*Sin(Alpha+Beta))) end end; end else begin //atSolid if (FArrow = smaStart) then begin Alpha := ArcTan((ARect.Right - ARect.Left)/(ARect.Bottom - ARect.Top)); Polygon([Point(ARect.Left, ARect.Top), Point(Round(ARect.Left + FArrowLength*Sin(Alpha+Beta)), Round(ARect.Top + FArrowLength*Cos(Alpha+Beta))), Point(Round(ARect.Left + FArrowLength*Sin(Alpha-Beta)), Round(ARect.Top + FArrowLength*Cos(Alpha-Beta)))]); end else // smaFinish begin Alpha := ArcTan((ARect.Bottom - ARect.Top)/(ARect.Right - ARect.Left)); if (ARect.Right > ARect.Left) then Polygon([Point(ARect.Right, ARect.Bottom), Point(Round(ARect.Right - FArrowLength*Cos(Alpha+Beta)), Round(ARect.Bottom - FArrowLength*Sin(Alpha+Beta))), Point(Round(ARect.Right - FArrowLength*Cos(Alpha-Beta)), Round(ARect.Bottom - FArrowLength*Sin(Alpha-Beta)))]) else Polygon([Point(ARect.Right, ARect.Bottom), Point(Round(ARect.Right + FArrowLength*Cos(Alpha+Beta)), Round(ARect.Bottom + FArrowLength*Sin(Alpha+Beta))), Point(Round(ARect.Right + FArrowLength*Cos(Alpha-Beta)), Round(ARect.Bottom + FArrowLength*Sin(Alpha-Beta)))]) end; end; end; end; const Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER); var ArrowHeight, S: Integer; ARect, CalcRect: TRect; DrawStyle: Integer; PtsS: array[0..5] of TPoint; PtsT: array[0..3] of TPoint; PtsO: array[0..8] of TPoint; GapX, GapY: Integer; begin ArrowHeight := Round(FArrowLength*Sin(DegToRad(FArrowAngle)/2)); with Canvas do begin Pen.Width := BevelWidth; Pen.Style := FPenStyle; case FStyle of mbsLowered: begin Color1 := FBottomColor; Color2 := FTopColor; end; mbsRaised: begin Color1 := FTopColor; Color2 := FBottomColor; end; else begin Color1 := clWindowFrame; Color2 := clWindowFrame; end end; case FShape of mbsBox: begin ARect := Rect(0, 0, Width, Height); // BevelRect(ARect); Frame3D(Canvas, ARect, Color1, Color2, BevelWidth); end; mbsFrame: begin ARect := Rect(BevelWidth, BevelWidth, Width, Height); Frame3D(Canvas, ARect, Color1, Color1, BevelWidth); ARect := Rect(0, 0, Width-BevelWidth, Height-BevelWidth); Frame3D(Canvas, ARect, Color2, Color2, BevelWidth); ARect := Rect(BevelWidth, BevelWidth, Width - 2*BevelWidth, Height - 2*BevelWidth); end; mbsBoxIn: begin ARect := Rect(0, 0, Width, Height); Frame3D(Canvas, ARect, Color1, Color2, BevelWidth); ARect := Rect(BevelWidth, BevelWidth, Width - BevelWidth, Height - BevelWidth); Frame3D(Canvas, ARect, Color2, Color1, BevelWidth); ARect := Rect(BevelWidth, BevelWidth, Width - 2*BevelWidth, Height - 2*BevelWidth); end; mbsTopLine: if (FArrow = smaNone) then begin BevelLine(Color1, 0, BevelWidth div 2, Width, BevelWidth div 2); BevelLine(Color2, 0, 3*BevelWidth div 2, Width, 3*BevelWidth div 2); ARect := Rect(0, 0, Width, BevelWidth); end else begin BevelLine(Color1, 0, ArrowHeight, Width, ArrowHeight); BevelLine(Color2, 0, ArrowHeight + BevelWidth, Width, ArrowHeight + BevelWidth); ARect := Rect(0, ArrowHeight, Width, ArrowHeight + BevelWidth); BevelArrow(Color1, Color2, ARect); end; mbsBottomLine: if (FArrow = smaNone) then begin BevelLine(Color1, 0, Height - 3*BevelWidth div 2, Width, Height - 3*BevelWidth div 2); BevelLine(Color2, 0, Height - BevelWidth div 2, Width, Height - BevelWidth div 2); ARect := Rect(0, Height - 2*BevelWidth, Width, Height - BevelWidth); end else begin BevelLine(Color1, 0, Height - ArrowHeight - 2*BevelWidth, Width, Height - ArrowHeight - 2*BevelWidth); BevelLine(Color2, 0, Height - ArrowHeight - BevelWidth, Width, Height - ArrowHeight - BevelWidth); ARect := Rect(0, Height - ArrowHeight - 2*BevelWidth, Width, Height - ArrowHeight - BevelWidth); BevelArrow(Color1, Color2, ARect); end; mbsLeftLine: if (FArrow = smaNone) then begin BevelLine(Color1, BevelWidth div 2, 0, BevelWidth div 2, Height); BevelLine(Color2, 3*BevelWidth div 2, 0, 3*BevelWidth div 2, Height); ARect := Rect(0, 0, BevelWidth, Height); end else begin BevelLine(Color1, ArrowHeight, 0, ArrowHeight, Height); BevelLine(Color2, ArrowHeight + BevelWidth, 0, ArrowHeight + BevelWidth, Height); ARect := Rect(ArrowHeight, 0, ArrowHeight + BevelWidth, Height); BevelArrow(Color1, Color2, ARect); end; mbsRightLine: if (FArrow = smaNone) then begin BevelLine(Color1, Width - 3*BevelWidth div 2, 0, Width - 3*BevelWidth div 2, Height); BevelLine(Color2, Width - BevelWidth div 2, 0, Width - BevelWidth div 2, Height); ARect := Rect(Width - 2*BevelWidth, 0, Width - BevelWidth, Height); end else begin BevelLine(Color1, Width - ArrowHeight - 2*BevelWidth, 0, Width - ArrowHeight - 2*BevelWidth, Height); BevelLine(Color2, Width - ArrowHeight - BevelWidth, 0, Width - ArrowHeight - BevelWidth, Height); ARect := Rect(Width - ArrowHeight - 2*BevelWidth, 0, Width - ArrowHeight - BevelWidth, Height); BevelArrow(Color1, Color2, ARect); end; mbsTopLeftLine: if (FArrow = smaNone) then begin BevelLine(Color1, 0, 0, Width, Height - 2*BevelWidth); BevelLine(Color2, 0, BevelWidth, Width, Height - BevelWidth); ARect := Rect(0, 0, Width, Height - BevelWidth); end else begin BevelLine(Color1, 0, 0, Width, Height - 2*BevelWidth); BevelLine(Color2, 0, BevelWidth, Width, Height - BevelWidth); ARect := Rect(0, 0, Width, Height - BevelWidth); BevelArrow(Color1, Color2, ARect); end; mbsTopRightLine: if (FArrow = smaNone) then begin BevelLine(Color1, Width, 0, 0, Height - 2*BevelWidth); BevelLine(Color2, Width, BevelWidth, BevelWidth, Height - BevelWidth); ARect := Rect(Width, 0, BevelWidth, Height - BevelWidth); end else begin BevelLine(Color1, Width, 0, 0, Height - 2*BevelWidth); BevelLine(Color2, Width, BevelWidth, BevelWidth, Height - BevelWidth); ARect := Rect(Width, 0, BevelWidth, Height - BevelWidth); BevelArrow(Color1, Color2, ARect); end; mbsStar: begin Pen.Color := Color1; ARect := Rect(BevelWidth, BevelWidth, Width, Height); GapX := (ARect.Right - ARect.Left) div 6; GapY := (ARect.Bottom - ARect.Top) div 6; PtsS[0].X := (ARect.Right - ARect.Left) div 2; PtsS[0].Y := ARect.Top; PtsS[1].X := ARect.Left + GapX; PtsS[1].Y := ARect.Bottom - GapY; PtsS[2].X := ARect.Right; PtsS[2].Y := ((ARect.Bottom - ARect.Top) div 2) - GapY; PtsS[3].X := ARect.Left; PtsS[3].Y := ((ARect.Bottom - ARect.Top) div 2) - GapY; PtsS[4].X := ARect.Right - GapX; PtsS[4].Y := ARect.Bottom - GapY; PtsS[5].X := (ARect.Right - ARect.Left) div 2; PtsS[5].Y := ARect.Top; Canvas.Polyline(PtsS); end; mbsTriangle: begin Pen.Color := Color1; ARect := Rect(BevelWidth, BevelWidth, Width, Height); PtsT[0].X := ARect.Left; PtsT[0].Y := ARect.Bottom-1; PtsT[1].X := (ARect.Right - ARect.Left) div 2; PtsT[1].Y := ARect.Top; PtsT[2].X := ARect.Right; PtsT[2].Y := ARect.Bottom-1; PtsT[3].X := ARect.Left; PtsT[3].Y := ARect.Bottom-1; Canvas.Polyline(PtsT); end; mbsOctogon: begin Pen.Color := Color1; ARect := Rect(BevelWidth, BevelWidth, Width, Height); GapX := (ARect.Right - ARect.Left) div 3; GapY := (ARect.Bottom - ARect.Top) div 3; PtsO[0].X := ARect.Left + GapX; PtsO[0].Y := ARect.Top; PtsO[1].X := ARect.Right - GapX; PtsO[1].Y := ARect.Top; PtsO[2].X := ARect.Right-1; PtsO[2].Y := ARect.Top + GapY; PtsO[3].X := ARect.Right-1; PtsO[3].Y := ARect.Bottom - GapY; PtsO[4].X := ARect.Right - GapX; PtsO[4].Y := ARect.Bottom-1; PtsO[5].X := ARect.Left + GapX; PtsO[5].Y := ARect.Bottom-1; PtsO[6].X := ARect.Left; PtsO[6].Y := ARect.Bottom - GapY; PtsO[7].X := ARect.Left; PtsO[7].Y := ARect.Top + GapY; PtsO[8].X := ARect.Left + GapX; PtsO[8].Y := ARect.Top; Canvas.Polyline(PtsO); end; mbsRoundRect: begin Pen.Color := Color1; Canvas.RoundRect(0, 0, Width, Height, 10, 10); end; mbsSquare: begin if Width < Height then S := Width else S := Height; ARect := Rect(BevelWidth + (Width-S) div 2, BevelWidth + (Height-S) div 2, (Width+S) div 2, (Height+S) div 2); Frame3D(Canvas, ARect, Color1, Color1, BevelWidth); ARect := Rect((Width-S) div 2, (Height-S) div 2, (Width+S) div 2 - BevelWidth, (Height+S) div 2 -BevelWidth); Frame3D(Canvas, ARect, Color2, Color2, BevelWidth); end; mbsRoundSquare: begin Pen.Color := Color1; if Width < Height then S := Width else S := Height; Canvas.RoundRect((Width-S) div 2, (Height-S) div 2, (Width+S) div 2, (Height+S) div 2, 10, 10); end; mbsEllipse: begin Pen.Color := Color1; Canvas.Ellipse(0, 0, Width, Height); end; end; {draw caption} Brush.Style := bsClear; DrawStyle := DT_EXPANDTABS or DT_WORDBREAK or Alignments[FAlignment]; { Calculate vertical layout } ARect := ClientRect; if (FLayout <> tlTop) then begin CalcRect := ARect; DoDrawText(CalcRect, DrawStyle or DT_CALCRECT); if (FLayout = tlBottom) then OffsetRect(ARect, 0, Height - CalcRect.Bottom) else OffsetRect(ARect, 0, (Height - CalcRect.Bottom) div 2); end; DoDrawText(ARect, DrawStyle); end; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} /// <summary> dunit database related extensions. /// Supports the properties to be specified on the command line. /// The "connection" command line property directs TDBXTestCase to /// use the connection in your dbxconnections.ini as the default connection /// returned by TDBXTestCase.DbxConnection. This can also be used to /// specify ado.net connection strings that have been persisted in the dbxconnections.ini /// file. ado.net connection strings require an additional section and two /// property settings as follows: /// /// [AdoIbLocal] /// providerName=Borland.Data.AdoDbxClient /// ConnectionString=ConnectionName=IBLOCAL; /// /// The IBLOCAL refers to a regular dbexpress connection property section that looks /// something like this: /// /// [IBLOCAL] /// //DelegateConnection=DBXTraceConnection /// ServerCharSet=UNICODE_FSS /// drivername=INTERBASE /// Database=C:\Program Files\Borland\InterBase\examples\database\employee.gdb /// rolename=RoleName /// user_name=sysdba /// Password=masterkey /// sqldialect=3 /// blobsize=-1 /// commitretain=False /// waitonlocks=True /// localecode=0000 /// interbase transisolation=ReadCommitted /// trim char=False /// /// There is also a test selection command line option than can be used to only /// execute tests that start with a specific prefix. So to run all tests that /// begin with "Test", a command line option of "-s:Test" should be specified. /// If you are reporting a bug, the name of your test method should start with the /// letter "o" to indicate that the test is open. When the bug is fixed, we will /// remove the "o" from the name of the test method so that the test will be run /// automatically with our automated regression test system. /// /// </summary> unit DbxTest; interface uses {$IFDEF CLR} System.Data, System.Data.Common, System.Configuration, AdoMetaDataProvider, AdoDbxClientProvider, {$ENDIF} TestFrameworkExtension, Classes, DBXCommon, DbxMetaDataProvider; const //command line property to specify dbxConnection name sConnectionName = 'connection'; sAdoDbxClientProvider ='Borland.Data.AdoDbxClient'; type //custom test case to looks for a //command line property to setup SQLConnection or ALL TDBXTestCase = class(TTestCaseExtension) private FConnection: TDBXConnection; FDBXName: String; FMetaDataProvider: TDbxMetaDataProvider; {$IFDEF CLR} FAdoConnection: DbConnection; {$ENDIF} FTearDownList: TList; procedure FreeTearDownList; protected function IsExtendedMetaDataBeingUsed(ConnectionName: WideString): Boolean; function GetDbxConnection: TDbxConnection; virtual; procedure ExecuteStatement(const CommandText: WideString); procedure ExecuteStatementIgnoreError(const CommandText: WideString); function GetMetaDataProvider: TDbxMetaDataProvider; function IsTypeSupported(DataType, SubType: Integer): Boolean; function GetIsCreateTableInMultiStatementTransactionSupported: Boolean; {$IFDEF CLR} function GetAdoConnectionFromMachineConfig: DbConnection; function GetAdoConnection: DbConnection; {$ENDIF} function StartMetaDataTransaction: TObject; procedure CommitFreeAndNilMetaDataTransaction(var Transaction: TObject); procedure RollbackMetaDataTransaction(var Transaction: TObject); /// <summary> /// Important note on this version of setup. It uses information passed in /// from the command line to determine which type of dialect to create. If /// the extended meta data model is being used, which is deteced from the drivers, /// then it will load an TExtendMDDialect. Otherwise it will use the static /// implementations, TInterbaseDialect, TOracleDialect, etc... /// </summary> procedure TearDown; override; public constructor Create(MethodName: string); override; destructor Destroy; override; procedure FreeOnTearDown(Item: TObject); function GetName: string; override; procedure SetName(AName: String); ///<summary> /// Will drop the specified table name if it exists. Any exceptions /// thrown will be ignored. ///</summary> procedure DropTable(TableName: WideString); ///<summary> /// This method can be used to generate a string id that can be /// appended to identifiers such as a table or stored procedures /// to help make the identifier more unique. The return value /// is currently not guaranteed to be completely unique. Using /// GetHostId helps to avoid name conflicts when multiple computers /// are executing similar tests against the same database server. ///</summary> function GetHostId: WideString; ///<summary> /// Connection Property that will return a TDBXConnection. /// Note* Since TDBXConnections are returned from the ConnectionFactory /// connected, which may cause problems in a large test environment, /// it is recommended to access Connection as late as possible, /// and to call CloseDbxConnection(). If Close connection is not called, then /// it will be called automatically in TearDown. /// </summary> property DbxConnection: TDBXConnection read GetDbxConnection; procedure CloseDbxConnection; virtual; property MetaDataProvider: TDbxMetaDataProvider read GetMetaDataProvider; property IsCreateTableInMultiStatementTransactionSupported: Boolean read GetIsCreateTableInMultiStatementTransactionSupported; {$IFDEF CLR} property AdoConnection: DbConnection read GetAdoConnection; {$ENDIF} end; implementation uses {$IFNDEF CLR} DBXDataExpressMetaDataProvider, {$ENDIF} {$IFDEF POSIX} Posix.UniStd, {$ENDIF} SysUtils; { TDBXTestCase } procedure TDBXTestCase.CommitFreeAndNilMetaDataTransaction(var Transaction: TObject); begin {$IFDEF CLR} DbTransaction(Transaction).Commit; Transaction := nil; {$ELSE} DbxConnection.CommitFreeAndNil(TDBXTransaction(Transaction)); {$ENDIF} end; constructor TDBXTestCase.Create(MethodName: string); begin inherited Create(MethodName); FTearDownList := TList.Create; FDBXName := MethodName; FConnection := nil; end; destructor TDBXTestCase.Destroy; begin FreeTearDownList; FreeAndNil(FMetaDataProvider); FreeAndNil(FTearDownList); FreeAndNil(FConnection); inherited; end; procedure TDBXTestCase.DropTable(TableName: WideString); begin try MetaDataProvider.DropTable(TableName); except end; end; procedure TDBXTestCase.ExecuteStatement(const CommandText: WideString); var DBXCommand: TDBXCommand; begin try DBXCommand := DbxConnection.CreateCommand; DBXCommand.Text := CommandText; DBXCommand.ExecuteQuery; finally FreeAndNil(DBXCommand); CloseDbxConnection; end; end; procedure TDBXTestCase.ExecuteStatementIgnoreError( const CommandText: WideString); begin try ExecuteStatement(CommandText); except on Ex: Exception do end; end; procedure TDBXTestCase.FreeOnTearDown(Item: TObject); begin FTearDownList.Add(Item); end; procedure TDBXTestCase.FreeTearDownList; begin while FTearDownList.Count > 0 do begin TObject(FTearDownList[0]).Free; FTearDownList[0] := nil; FTearDownList.Delete(0); end; FTearDownList.Clear; end; {$IFDEF CLR} function TDBXTestCase.GetAdoConnectionFromMachineConfig: DbConnection; var Config: Configuration; Settings: ConnectionStringSettings; Factory: DbProviderFactory; begin Result := nil; Config := ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); Settings := Config.ConnectionStrings.ConnectionStrings[Properties.Values[sConnectionName]]; if Assigned(Settings) then begin Factory := DbProviderFactories.GetFactory(Settings.ProviderName); Result := Factory.CreateConnection(); Result.ConnectionString := Settings.ConnectionString; Result.Open(); end; end; function TDBXTestCase.GetAdoConnection: DbConnection; var Connection: System.Data.Common.DbConnection; ConnectionProperties: TDBXProperties; ProviderName: WideString; ConnectionString: WideString; ConnectionName: WideString; begin if FAdoConnection = nil then begin FAdoConnection := GetAdoConnectionFromMachineConfig; if not Assigned(FAdoConnection) then begin ConnectionName := Properties.Values[sConnectionName]; ConnectionProperties := TDBXConnectionFactory.GetConnectionFactory.GetConnectionProperties(ConnectionName); ProviderName := ConnectionProperties['ProviderName']; if ProviderName = '' then begin ProviderName := sAdoDbxClientProvider; ConnectionString := 'ConnectionName=' + ConnectionName; end else begin ConnectionString := ConnectionProperties['ConnectionString']; end; Connection := TAdoDbxConnection.Create(); Connection.ConnectionString := ConnectionString; Connection.Open; FAdoConnection := Connection; end; end; Result := FAdoConnection; end; {$ENDIF} {$IFDEF CLR} function TDBXTestCase.GetMetaDataProvider: TDbxMetaDataProvider; var Provider: TAdoMetaDataProvider; begin if FMetaDataProvider = nil then begin Provider := TAdoMetadataProvider.Create; Provider.Connection := AdoConnection; Provider.Open; FMetaDataProvider := Provider; end; Result := FMetaDataProvider; end; {$ELSE} function TDBXTestCase.GetMetaDataProvider: TDbxMetaDataProvider; var Provider: TDBXDataExpressMetaDataProvider; begin if FMetaDataProvider = nil then begin Provider := TDBXDataExpressMetaDataProvider.Create; Provider.Connection := DbxConnection; Provider.Open; FMetaDataProvider := Provider; end; Result := FMetaDataProvider; end; {$ENDIF} function TDBXTestCase.GetName: string; begin Result := Properties.Values[sConnectionName] + '_' + FDBXName; end; function TDBXTestCase.GetDbxConnection: TDbxConnection; begin if FConnection = nil then begin with TDBXConnectionFactory.GetConnectionFactory do FConnection := GetConnection(Properties.Values[sConnectionName],'',''); end; Result := FConnection; end; function TDBXTestCase.GetHostId: WideString; {$IFDEF POSIX} var MachName: array[0..7] of AnsiChar; {$ENDIF} const ComputerName = 'COMPUTERNAME'; MaxHostLength = 8; begin Result := 'UNKNOWN'; {$IFDEF POSIX} if Posix.Unistd.gethostname(MachName, SizeOf(MachName)) = 0 then Result := WideUpperCase(UTF8ToUnicodeString(MachName)); {$ELSE} if GetEnvironmentVariable(ComputerName)<>'' then Result := GetEnvironmentVariable(ComputerName); {$ENDIF} Result := StringReplace(Result, '.' ,'',[rfReplaceAll]); Result := StringReplace(Result, ' ' ,'',[rfReplaceAll]); Result := StringReplace(Result, '-' ,'',[rfReplaceAll]); if (Length(Result) > MaxHostLength) then Delete(Result,MaxHostLength-1,Length(Result)); end; function TDBXTestCase.GetIsCreateTableInMultiStatementTransactionSupported: Boolean; begin if MetaDataProvider.DatabaseProduct = 'Sybase SQL Server' then Result := False else Result := True; end; function TDBXTestCase.IsExtendedMetaDataBeingUsed(ConnectionName: WideString): Boolean; var CurrentDriver: WideString; MDPackageLoader, MDAssemblyLoader: WideString; begin with TDBXConnectionFactory.GetConnectionFactory do begin //use the current connection to determine which driver it uses CurrentDriver := GetConnectionProperties(ConnectionName).Values[TDBXPropertyNames.DriverName]; //check the dirver params for presence of new Extended MetaData values MDPackageLoader := GetDriverProperties(CurrentDriver).Values[TDBXPropertyNames.MetaDataPackageLoader]; MDAssemblyLoader := GetDriverProperties(CurrentDriver).Values[TDBXPropertyNames.MetaDataAssemblyLoader]; end; {$IFDEF CLR} Result := MDAssemblyLoader <> ''; {$ELSE} Result := MDPackageLoader <> ''; {$ENDIF} end; procedure TDBXTestCase.RollbackMetaDataTransaction(var Transaction: TObject); begin {$IFDEF CLR} DbTransaction(Transaction).Rollback; Transaction := nil; {$ELSE} DbxConnection.RollbackFreeAndNil(TDBXTransaction(Transaction)); {$ENDIF} end; procedure TDBXTestCase.CloseDbxConnection; begin FreeAndNil(FMetaDataProvider); FreeAndNil(FConnection); end; procedure TDBXTestCase.SetName(AName: String); begin FDBXName := AName; end; function TDBXTestCase.StartMetaDataTransaction: TObject; begin {$IFDEF CLR} Result := AdoConnection.BeginTransaction; {$ELSE} Result := DbxConnection.BeginTransaction; {$ENDIF} end; procedure TDBXTestCase.TearDown; begin inherited; FreeTearDownList; FreeAndNil(FMetaDataProvider); FreeAndNil(FConnection); {$IFDEF CLR} FreeAndNil(FAdoConnection); {$ENDIF} end; function TDBXTestCase.IsTypeSupported(DataType, SubType: Integer): Boolean; begin if Pos('{' + IntToStr(DataType) + ',' + IntToStr(SubType), UnicodeString(DbxConnection.GetVendorProperty('DriverDataTypes'))) <> 0 then Result := True else Result := False; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Vcl.DBPWDlg; {$H+,X+} interface uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Data.DB; type TPasswordDialog = class(TForm) GroupBox1: TGroupBox; Edit: TEdit; AddButton: TButton; RemoveButton: TButton; RemoveAllButton: TButton; OKButton: TButton; CancelButton: TButton; procedure EditChange(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure RemoveButtonClick(Sender: TObject); procedure RemoveAllButtonClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); private PasswordAdded: Boolean; FSession: IDBSession; end; function PasswordDialog(const ASession: IDBSession): Boolean; implementation {$R *.dfm} function PasswordDialog(const ASession: IDBSession): Boolean; begin with TPasswordDialog.Create(Application) do try FSession := ASession; Result := ShowModal = mrOk; finally Free; end; end; procedure TPasswordDialog.EditChange(Sender: TObject); var HasText: Boolean; begin HasText := Edit.Text <> ''; AddButton.Enabled := HasText; RemoveButton.Enabled := HasText; OKButton.Enabled := HasText or PasswordAdded; end; procedure TPasswordDialog.AddButtonClick(Sender: TObject); begin FSession.AddPassword(Edit.Text); PasswordAdded := True; Edit.Clear; Edit.SetFocus; end; procedure TPasswordDialog.RemoveButtonClick(Sender: TObject); begin FSession.RemovePassword(Edit.Text); Edit.Clear; Edit.SetFocus; end; procedure TPasswordDialog.RemoveAllButtonClick(Sender: TObject); begin FSession.RemoveAllPasswords; Edit.SetFocus; end; procedure TPasswordDialog.OKButtonClick(Sender: TObject); begin FSession.AddPassword(Edit.Text); end; initialization Data.DB.PasswordDialog := PasswordDialog; finalization Data.DB.PasswordDialog := nil; end.
unit Players; interface uses Windows, Classes, IdContext, ExtCtrls, Contnrs; type TPlayerInfo = class Shape: TShape; Location: TPointFloat; NetContext: TIdContext; Angle: Double; constructor Create(Pattern: TShape); destructor Destroy; override; procedure Move(delta: Single); end; TPlayers = class(TObjectList) private procedure Rearrange; function GetItem(Index: Integer): TPlayerInfo; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public Pattern, Ball: TShape; ClientWidth, ClientHeight: Integer; BallSpeed, BallPos: TPointFloat; procedure CreateNew(NetContext: TIdContext); function FindByContext(NetContext: TIdContext): TPlayerInfo; procedure Move(delta: Single); procedure ResetBall; procedure RestartBall; property Items[Index: Integer]: TPlayerInfo read GetItem; default; end; implementation uses Main; { TPlayerInfo } constructor TPlayerInfo.Create(Pattern: TShape); begin Shape := TShape.Create(nil); Shape.Parent := Pattern.Parent; Shape.Width := Pattern.Width; Shape.Height := Pattern.Height; Shape.Brush.Assign(Pattern.Brush); Shape.Shape := Pattern.Shape; Location.y := Pattern.Top; end; destructor TPlayerInfo.Destroy; begin Shape.Free; inherited; end; procedure TPlayerInfo.Move(delta: Single); begin // Speed := Speed + Angle*delta; // Location.y := Location.y + Speed*delta; Location.y := (Form1.ClientHeight * (1+Angle) - Shape.Height)/2; Shape.Left := Round(Location.x); Shape.Top := Round(Location.y); end; { TPlayers } procedure TPlayers.CreateNew(NetContext: TIdContext); var pi: TPlayerInfo; begin pi := TPlayerInfo.Create(Pattern); pi.NetContext := NetContext; Add(pi); end; function TPlayers.FindByContext(NetContext: TIdContext): TPlayerInfo; var i: Integer; begin Result := nil; for i := 0 to Count-1 do if Items[i].NetContext = NetContext then Result := Items[i]; end; function TPlayers.GetItem(Index: Integer): TPlayerInfo; begin Result := TPlayerInfo(inherited GetItem(index)) end; procedure TPlayers.Move(delta: Single); var i: Integer; begin for i := 0 to Count-1 do Items[i].Move(delta); BallPos.x := BallPos.x + BallSpeed.x * delta; BallPos.y := BallPos.y + BallSpeed.y * delta; end; procedure TPlayers.Notify(Ptr: Pointer; Action: TListNotification); begin inherited; Rearrange; end; procedure TPlayers.Rearrange; var i: Integer; begin for i := 0 to Count-1 do if i mod 2 = 0 then Items[i].Location.x := Pattern.Width*(i+1) else Items[i].Location.x := Form1.ClientWidth - Pattern.Width*(i+1); end; procedure TPlayers.RestartBall; begin BallSpeed.x := ClientWidth / 20; BallSpeed.y := 0; end; procedure TPlayers.ResetBall; begin BallSpeed.x := 0; BallSpeed.y := 0; BallPos.x := (ClientWidth - Ball.Width) div 2; BallPos.y := (ClientHeight - Ball.Height) div 2; end; end.
{***********************************<_INFO>************************************} { <Проект> Компоненты медиа-преобразования } { } { <Область> Мультимедиа } { } { <Задача> Преобразователь медиа-потока в формате BMP. Склеивает кадры } { от разных каналов в один, панорамный } { Декларация } { } { <Автор> Фадеев Р.В. } { } { <Дата> 21.01.2011 } { } { <Примечание> Отсутствует } { } { <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" } { } {***********************************</_INFO>***********************************} unit MediaProcessing.Panorama.RGB; interface uses SysUtils,Windows,Classes, MediaProcessing.Definitions,MediaProcessing.Global,Graphics; type TMediaProcessor_Panorama_Rgb=class (TMediaProcessor,IMediaProcessor_Panorama_Rgb) protected FFPSValue: integer; //Автоматическое совмещение кадров FAutoImageStitching: boolean; FAutoImageStitchingIntervalSecs: integer; // насколько процентов по горизонтали от свой ширины изображения могут пересекаться. FAutoImageStitchingMaxWinWidthPercent, //насколько процентов по вертикали изображение может сдвигаться FAutoImageStitchingMaxYDispPercent: byte; procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override; procedure LoadCustomProperties(const aReader: IPropertiesReader); override; class function MetaInfo:TMediaProcessorInfo; override; public constructor Create; override; destructor Destroy; override; function HasCustomProperties: boolean; override; procedure ShowCustomProperiesDialog;override; end; implementation uses Controls,uBaseClasses,MediaProcessing.Panorama.RGB.SettingsDialog; { TMediaProcessor_Panorama_Rgb } constructor TMediaProcessor_Panorama_Rgb.Create; begin inherited; end; destructor TMediaProcessor_Panorama_Rgb.Destroy; begin inherited; end; function TMediaProcessor_Panorama_Rgb.HasCustomProperties: boolean; begin result:=true; end; class function TMediaProcessor_Panorama_Rgb.MetaInfo: TMediaProcessorInfo; begin result.Clear; result.TypeID:=IMediaProcessor_Panorama_Rgb; result.Name:='Панорама'; result.Description:='Выполняет объединение нескольких видео-потоков в единое панорамное видео '; result.SetInputStreamType(stRGB); result.OutputStreamType:=stRGB; result.ConsumingLevel:=9; end; procedure TMediaProcessor_Panorama_Rgb.LoadCustomProperties(const aReader: IPropertiesReader); begin inherited; FFPSValue:=aReader.ReadInteger('FPSValue',25); FAutoImageStitching:=aReader.ReadBool('ImageStitching',true); FAutoImageStitchingIntervalSecs:=aReader.ReadInteger('ImageStitchingInterval',60); FAutoImageStitchingMaxWinWidthPercent:=aReader.ReadInteger('AutoImageStitchingMaxWinWidthPercent',40); FAutoImageStitchingMaxYDispPercent:=aReader.ReadInteger('AutoImageStitchingMaxYDispPercent',25); end; procedure TMediaProcessor_Panorama_Rgb.SaveCustomProperties(const aWriter: IPropertiesWriter); begin inherited; aWriter.WriteInteger('FPSValue',FFPSValue); aWriter.WriteBool('ImageStitching',FAutoImageStitching); aWriter.WriteInteger('ImageStitchingInterval',FAutoImageStitchingIntervalSecs); aWriter.WriteInteger('AutoImageStitchingMaxWinWidthPercent',FAutoImageStitchingMaxWinWidthPercent); aWriter.WriteInteger('AutoImageStitchingMaxYDispPercent',FAutoImageStitchingMaxYDispPercent); end; procedure TMediaProcessor_Panorama_Rgb.ShowCustomProperiesDialog; var aDialog: TfmMediaProcessingSettingsPanorama_Rgb; begin aDialog:=TfmMediaProcessingSettingsPanorama_Rgb.Create(nil); try aDialog.edFPSValue.Value:=FFPSValue; aDialog.ckImageStitchingEnabled.Checked:=FAutoImageStitching; aDialog.edImageStitchingInterval.Value:=FAutoImageStitchingIntervalSecs; //aDialog.edImageStitchingSnapInterval.Value:=FAutoImageStitchingSnapIntervalSecs; if aDialog.ShowModal=mrOK then begin FFPSValue:=aDialog.edFPSValue.Value; FAutoImageStitching:=aDialog.ckImageStitchingEnabled.Checked; FAutoImageStitchingIntervalSecs:=aDialog.edImageStitchingInterval.Value; //FAutoImageStitchingSnapIntervalSecs:=aDialog.edImageStitchingSnapInterval.Value; end; finally aDialog.Free; end; end; initialization MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Panorama_Rgb); end.
{------------------------------------------------------------} { prOpc Toolkit } { Copyright (c) 2000, 2001 Production Robots Engineering Ltd } { mailto: prOpcKit@prel.co.uk } { http://www.prel.co.uk } {------------------------------------------------------------} unit prOpcKitDsgn; {$I prOpcCompilerDirectives.inc} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ToolsApi, prOpcWizMain, prOpcClient, ComCtrls, StdCtrls, prOpcTypes, prOpcEnum, Buttons, prOpcBrowser, prOpcServerSelect, prOpcItemSelect; procedure Register; implementation uses {$IFDEF D6UP} DesignIntf, DesignEditors, {$ELSE} DsgnIntf, {$ENDIF} TypInfo; type TProgIDProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; TGroupItemsProperty = class(TPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; function GetValue: String; override; end; procedure Register; begin RegisterComponents('prOPC', [TOpcSimpleClient, TOpcPropertyView, TOpcBrowser]); RegisterPropertyEditor(TypeInfo(string), TOpcSimpleClient, 'ProgID', TProgIDProperty); RegisterPropertyEditor(TypeInfo(TStrings), TOpcGroup, 'Items', TGroupItemsProperty); RegisterPackageWizard(TOpcServerWizard.Create) end; { TProgIDProperty } procedure TProgIDProperty.Edit; var sf: TServerSelectDlg; begin Application.CreateForm(TServerSelectDlg, sf); try if sf.Execute(TOpcSimpleClient(GetComponent(0))) then Modified finally sf.Free end end; function TProgIDProperty.GetAttributes: TPropertyAttributes; begin Result:= inherited GetAttributes + [paDialog] - [paMultiSelect] end; { TGroupItemsProperty } procedure TGroupItemsProperty.Edit; var Group: TOpcGroup; Client: TOpcSimpleClient; Form: TItemSelectDlg; begin Group:= TOpcGroup(GetComponent(0)); Client:= TOpcGroupCollection(Group.Collection).Client; Application.CreateForm(TItemSelectDlg, Form); try if Form.Execute(Client, Group) then Modified finally Form.Free end end; function TGroupItemsProperty.GetAttributes: TPropertyAttributes; begin Result:= [paDialog, paReadOnly] end; function TGroupItemsProperty.GetValue: String; begin Result:= 'Opc Items' end; end.
unit oCoverSheetParam_CPRS; { ================================================================================ * * Application: CPRS - CoverSheet * Developer: doma.user@domain.ext * Site: Salt Lake City ISC * Date: 2015-12-04 * * Description: Inherited from TCoverSheetParam this parameter holds * custom items for displaying CPRS data in the CoverSheet. * * Notes: * ================================================================================ } interface uses System.Classes, System.SysUtils, Vcl.Controls, oCoverSheetParam, iCoverSheetIntf; type TCoverSheetParam_CPRS = class(TCoverSheetParam, ICoverSheetParam_CPRS) private fLoadInBackground: boolean; fDateFormat: string; fDatePiece: integer; fDetailRPC: string; fInvert: boolean; fMainRPC: string; fParam1: string; fStatus: string; fTitleCase: boolean; fPollingID: string; fHighlightText: boolean; fAllowDetailPrint: boolean; fOnNewPatient: TNotifyEvent; procedure fOnNewPatientDefault(Sender: TObject); protected function getLoadInBackground: boolean; virtual; function getDateFormat: string; virtual; function getDatePiece: integer; virtual; function getDetailRPC: string; virtual; function getInvert: boolean; virtual; function getMainRPC: string; virtual; function getParam1: string; virtual; function getStatus: string; virtual; function getTitleCase: boolean; virtual; function getPollingID: string; virtual; function getHighlightText: boolean; virtual; function getAllowDetailPrint: boolean; virtual; function getIsApplicable: boolean; virtual; function getOnNewPatient: TNotifyEvent; procedure setLoadInBackground(const aValue: boolean); procedure setAllowDetailPrint(const aValue: boolean); procedure setInvert(const aValue: boolean); procedure setParam1(const aValue: string); procedure setOnNewPatient(const aValue: TNotifyEvent); function NewCoverSheetControl(aOwner: TComponent): TControl; override; public constructor Create(aInitString: string); destructor Destroy; override; end; implementation uses oDelimitedString, mCoverSheetDisplayPanel_CPRS; { TCoverSheetParam_CPRS } constructor TCoverSheetParam_CPRS.Create(aInitString: string); begin inherited Create; fOnNewPatient := fOnNewPatientDefault; with NewDelimitedString(aInitString) do try fID := GetPieceAsInteger(1); fTitle := GetPiece(2); fStatus := GetPiece(3); fMainRPC := GetPiece(6); fInvert := GetPieceAsBoolean(8, False); fDateFormat := GetPiece(10); fDatePiece := GetPieceAsInteger(11, 0); fParam1 := GetPiece(12); fDetailRPC := GetPiece(16); fTitleCase := GetPieceAsBoolean(7); fHighlightText := GetPieceIsNotNull(9); fAllowDetailPrint := True; fPollingID := GetPiece(19); finally Free; end; { Example of aInitString from VistA ZZZ(1)="10^Active Problems^^S^^ORQQPL LIST^1^^^^^A^^2,3^9,10,2^ORQQPL DETAIL^1^28^PROB" ZZZ(2)="20^Allergies / Adverse Reactions^^S^^ORQQAL LIST^1^^^^^^^^2^ORQQAL DETAIL^2^29^" ZZZ(3)="30^Postings^^S^^ORQQPP LIST^1^^Maroon^D^3^^^20^2,3^^3^30^CWAD" ZZZ(4)="40^Active Medications^^S^^ORWPS COVER^1^1^^^^1^^35^2,4^ORWPS DETAIL^4^31^MEDS" ZZZ(5)="50^Clinical Reminders Due Date^^S^^ORQQPX REMINDERS LIST^^^^D^3^^^34,44^2,3^^5^32^RMND" ZZZ(6)="99^Women's Health^^S^^WVRPCOR COVER^1^^^^^^^20^2,3^WVRPCOR DETAIL^6^1606^WHPNL" ZZZ(7)="60^Recent Lab Results^^S^^ORWCV LAB^1^^^D^3^^^34^2,3^ORWOR RESULT^7^33^LABS" ZZZ(8)="70^Vitals^^S^^ORQQVI VITALS^^^^T^4^^^5,17,19,27^2,5,4,6,7,8^^8^34^VITL" ZZZ(9)="80^Appointments/Visits/Admissions^^S^^ORWCV VST^1^1^^T^2^^^16,27^2,3,4^ORWCV DTLVST^9^35^VSIT" } end; destructor TCoverSheetParam_CPRS.Destroy; begin fOnNewPatient := fOnNewPatientDefault; inherited; end; procedure TCoverSheetParam_CPRS.fOnNewPatientDefault(Sender: TObject); begin // Prevent nil pointers end; function TCoverSheetParam_CPRS.getLoadInBackground: boolean; begin Result := fLoadInBackground; end; function TCoverSheetParam_CPRS.getAllowDetailPrint: boolean; begin Result := fAllowDetailPrint; end; function TCoverSheetParam_CPRS.getDateFormat: string; begin Result := fDateFormat; end; function TCoverSheetParam_CPRS.getDatePiece: integer; begin Result := fDatePiece; end; function TCoverSheetParam_CPRS.getDetailRPC: string; begin Result := fDetailRPC; end; function TCoverSheetParam_CPRS.getHighlightText: boolean; begin Result := fHighlightText; end; function TCoverSheetParam_CPRS.getInvert: boolean; begin Result := fInvert; end; function TCoverSheetParam_CPRS.getMainRPC: string; begin Result := fMainRPC; end; function TCoverSheetParam_CPRS.getOnNewPatient: TNotifyEvent; begin Result := fOnNewPatient; end; function TCoverSheetParam_CPRS.getParam1: string; begin Result := fParam1; end; function TCoverSheetParam_CPRS.getPollingID: string; begin Result := fPollingID; end; function TCoverSheetParam_CPRS.getStatus: string; begin Result := fStatus; end; function TCoverSheetParam_CPRS.getTitleCase: boolean; begin Result := fTitleCase; end; function TCoverSheetParam_CPRS.getIsApplicable: boolean; begin Result := True; end; function TCoverSheetParam_CPRS.NewCoverSheetControl(aOwner: TComponent): TControl; begin Result := TfraCoverSheetDisplayPanel_CPRS.Create(aOwner); end; procedure TCoverSheetParam_CPRS.setAllowDetailPrint(const aValue: boolean); begin fAllowDetailPrint := aValue; end; procedure TCoverSheetParam_CPRS.setInvert(const aValue: boolean); begin fInvert := aValue; end; procedure TCoverSheetParam_CPRS.setLoadInBackground(const aValue: boolean); begin fLoadInBackground := aValue; end; procedure TCoverSheetParam_CPRS.setOnNewPatient(const aValue: TNotifyEvent); begin if Assigned(aValue) then fOnNewPatient := aValue else fOnNewPatient := fOnNewPatientDefault; end; procedure TCoverSheetParam_CPRS.setParam1(const aValue: string); begin fParam1 := aValue; end; end.
unit QlpQRCodeGenLibTypes; {$I ..\Include\QRCodeGenLib.inc} interface uses {$IF DEFINED(VCL)} Vcl.Graphics, {$ELSEIF DEFINED(FMX)} FMX.Graphics, UIConsts, UITypes, {$ELSEIF DEFINED(LCL)} Graphics, Interfaces, // Added so that the LCL will Initialize the WidgetSet {$ELSEIF DEFINED(FCL)} FPWriteBMP, // without this, writing to bitmap will fail FPImage, // For FCL Image Support {$IFEND} SysUtils; type EQRCodeGenLibException = class(Exception); EDataTooLongQRCodeGenLibException = class(EQRCodeGenLibException); EInvalidOperationQRCodeGenLibException = class(EQRCodeGenLibException); EIndexOutOfRangeQRCodeGenLibException = class(EQRCodeGenLibException); EArgumentQRCodeGenLibException = class(EQRCodeGenLibException); EArgumentInvalidQRCodeGenLibException = class(EQRCodeGenLibException); EArgumentNilQRCodeGenLibException = class(EQRCodeGenLibException); EArgumentOutOfRangeQRCodeGenLibException = class(EQRCodeGenLibException); EUnsupportedTypeQRCodeGenLibException = class(EQRCodeGenLibException); ENullReferenceQRCodeGenLibException = class(EQRCodeGenLibException); /// <summary> /// Represents a dynamic array of Byte. /// </summary> TQRCodeGenLibByteArray = TBytes; /// <summary> /// Represents a dynamic generic array of Type T. /// </summary> TQRCodeGenLibGenericArray<T> = array of T; {$IFDEF DELPHIXE_UP} /// <summary> /// Represents a dynamic array of Int32. /// </summary> TQRCodeGenLibInt32Array = TArray<Int32>; /// <summary> /// Represents a dynamic array of Boolean. /// </summary> TQRCodeGenLibBooleanArray = TArray<Boolean>; /// <summary> /// Represents a dynamic array of String. /// </summary> TQRCodeGenLibStringArray = TArray<String>; /// <summary> /// Represents a dynamic array of array of Byte. /// </summary> TQRCodeGenLibMatrixByteArray = TArray<TQRCodeGenLibByteArray>; /// <summary> /// Represents a dynamic array of array of Int32. /// </summary> TQRCodeGenLibMatrixInt32Array = TArray<TQRCodeGenLibInt32Array>; {$ELSE} /// <summary> /// Represents a dynamic array of Int32. /// </summary> TQRCodeGenLibInt32Array = array of Int32; /// <summary> /// Represents a dynamic array of Boolean. /// </summary> TQRCodeGenLibBooleanArray = array of Boolean; /// <summary> /// Represents a dynamic array of String. /// </summary> TQRCodeGenLibStringArray = array of String; /// <summary> /// Represents a dynamic array of array of Byte. /// </summary> TQRCodeGenLibMatrixByteArray = array of TQRCodeGenLibByteArray; /// <summary> /// Represents a dynamic array of array of Int32. /// </summary> TQRCodeGenLibMatrixInt32Array = array of TQRCodeGenLibInt32Array; {$ENDIF DELPHIXE_UP} TQRCodeGenLibColor = {$IF DEFINED(VCL_OR_LCL)}TColor{$ELSEIF DEFINED(FCL)}TFPColor{$ELSEIF DEFINED(FMX)}TAlphaColor{$IFEND VCL_OR_LCL}; {$IFDEF FCL} TQRCodeGenLibBitmap = TFPCompactImgRGB16Bit; {$ELSE} TQRCodeGenLibBitmap = TBitmap; {$IFDEF FMX} TQRCodeGenLibBitmapData = TBitmapData; TQRCodeGenLibMapAccess = TMapAccess; TQRCodeGenLibAlphaColorRec = TAlphaColorRec; {$ENDIF FMX} {$ENDIF FCL} // ===========// {$IFDEF VCL} const TwentyFourBitPixelFormat = pf24bit; {$ENDIF VCL} function QRCodeGenLibWhiteColor: TQRCodeGenLibColor; inline; function QRCodeGenLibBlackColor: TQRCodeGenLibColor; inline; {$IF DEFINED(VCL_OR_LCL)} function QRCodeGenLibColorToRGB(AColor: TQRCodeGenLibColor): LongInt; inline; {$IFEND VCL_OR_LCL} implementation function QRCodeGenLibWhiteColor: TQRCodeGenLibColor; begin Result := {$IF DEFINED(VCL_OR_LCL)}clWhite{$ELSEIF DEFINED(FCL)}colWhite{$ELSEIF DEFINED(FMX)}claWhite{$IFEND VCL_OR_LCL}; end; function QRCodeGenLibBlackColor: TQRCodeGenLibColor; begin Result := {$IF DEFINED(VCL_OR_LCL)}clBlack{$ELSEIF DEFINED(FCL)}colBlack{$ELSEIF DEFINED(FMX)}claBlack{$IFEND VCL_OR_LCL}; end; {$IF DEFINED(VCL_OR_LCL)} function QRCodeGenLibColorToRGB(AColor: TQRCodeGenLibColor): LongInt; begin Result := ColorToRGB(AColor); end; {$IFEND VCL_OR_LCL} {$IFDEF FPC} initialization // Set UTF-8 in AnsiStrings, just like Lazarus SetMultiByteConversionCodePage(CP_UTF8); // SetMultiByteFileSystemCodePage(CP_UTF8); not needed, this is the default under Windows SetMultiByteRTLFileSystemCodePage(CP_UTF8); {$ENDIF FPC} end.
(*===========================================================================*) (* TWinRoller *) (*---------------------------------------------------------------------------*) (* *) (* New Property *) (* *) (* Enabled: Boolean Enable TWinRooler *) (* Roller: Boolean Rollup/Rolldown window *) (* Visible: Boolean Roller button visible *) (* OnRoller: TRollerNotifyEvent *) (* *) (*---------------------------------------------------------------------------*) (* Environment: *) (* Windows 95 *) (* Delphi 2.0 *) (* *) (* Author: Sean Hsieh *) (* E-Mail: sean@mail.linkease.com.tw *) (*===========================================================================*) unit WinRoll; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type EOwnerError = class(Exception); TRollerMode = ( mdRollDown, mdRollUp ); TRollerNotifyEvent = procedure ( Sender: TObject; mode: TRollerMode ) of object; TWinRoller = class(TComponent) private { Private declarations } DefWinProc: TFarProc; DefWinProcInstance: Pointer; FEnabled: Boolean; FOnRoller: TRollerNotifyEvent; FOnFormDestroy: TNotifyEvent; FRoller: Boolean; FVisible: Boolean; ButtonArea: TRect; DrawPushed: Boolean; Pushed: Boolean; RestoreWndProc: Boolean; rgn: HRGN; Stop: Boolean; procedure CalcArea; procedure OnRollerDestroy( Sender: TObject ); procedure PaintRollerButton; procedure Rollup; procedure SetEnabled( Val: Boolean ); procedure SetRoller( Val: Boolean ); procedure SetVisible( Val: Boolean ); procedure WinProc(var Message: TMessage); public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; published { Published declarations } property Enabled: Boolean read FEnabled write SetEnabled; property Roller: Boolean read FRoller write SetRoller default False; property Visible: Boolean read FVisible write SetVisible default True; property OnRoller: TRollerNotifyEvent read FOnRoller write FOnRoller; end; procedure Register; var si: UINT; implementation procedure Register; begin RegisterComponents('Samples', [TWinRoller]); end; constructor TWinRoller.Create(Owner: TComponent); begin inherited; FRoller := False; FVisible := True; DrawPushed := False; Pushed := False; rgn := 0; if not (Owner is TForm) then raise EOwnerError.Create('Class of the owner is not a TForm!'); with TForm(Owner) do if not (csDesigning in ComponentState) then begin DefWinProcInstance := MakeObjectInstance(WinProc); DefWinProc := Pointer(SetWindowLong(Handle, GWL_WNDPROC, Longint(DefWinProcInstance))); CalcArea; FOnFormDestroy := OnDestroy; OnDestroy := OnRollerDestroy; end; end; destructor TWinRoller.Destroy; begin if not (csDesigning in ComponentState) and not RestoreWndProc then begin SetWindowLong(TForm(Owner).Handle, GWL_WNDPROC, Longint(DefWinProc)); FreeObjectInstance(DefWinProcInstance); end; if rgn <> 0 then DeleteObject( rgn ); inherited; end; procedure TWinRoller.OnRollerDestroy( Sender: TObject ); begin if Assigned( FOnFormDestroy ) then FOnFormDestroy( Sender ); SetWindowLong(TForm(Owner).Handle, GWL_WNDPROC, Longint(DefWinProc)); FreeObjectInstance(DefWinProcInstance); RestoreWndProc := True; end; procedure TWinRoller.CalcArea; var x1, y1, x2, y2, w: Integer; Icons: TBorderIcons; Style: TFormBorderStyle; // Style, ExStyle: UINT; begin // Style := GetWindowLong( TForm(Owner).Handle, GWL_STYLE ); // ExStyle := GetWindowLong( TForm(Owner).Handle, GWL_EXSTYLE ); with TForm(Owner) do begin if csDesigning in ComponentState then begin Icons := [biSystemMenu, biMinimize, biMaximize]; Style := bsSizeable; end else begin Icons := BorderIcons; Style := BorderStyle; end; end; if Style in [bsSizeToolWin, bsToolWindow] then begin if Style = bsToolWindow then x2 := GetSystemMetrics(SM_CXFIXEDFRAME) + 2 else x2 := GetSystemMetrics(SM_CXSIZEFRAME) + 2; if biSystemMenu in Icons then Inc(x2, GetSystemMetrics(SM_CXSMSIZE) + 2); if Style = bsToolWindow then y1 := GetSystemMetrics(SM_CYFIXEDFRAME) + 2 else y1 := GetSystemMetrics(SM_CYSIZEFRAME) + 2; y2 := y1 + GetSystemMetrics(SM_CYSMSIZE) - 4; x2 := TForm(Owner).Width - x2; x1 := x2 - GetSystemMetrics(SM_CXSMSIZE) + 2; end else begin if Style in [bsSingle, bsSizeable, bsDialog] then begin if Style = bsSingle then x2 := GetSystemMetrics(SM_CYFIXEDFRAME) + 2 else x2 := GetSystemMetrics(SM_CXSIZEFRAME) + 2; if biSystemMenu in Icons then begin Inc(x2, GetSystemMetrics(SM_CXSIZE) + 2); if (Style <> bsDialog) and (Icons * [biMinimize, biMaximize] <> []) then Inc(x2, GetSystemMetrics(SM_CXSIZE) * 2 - 6) else if biHelp in Icons then Inc(x2, GetSystemMetrics(SM_CXSIZE) - 4); end; if Style in [bsSingle, bsDialog] then y1 := GetSystemMetrics(SM_CYFIXEDFRAME) + 2 else y1 := GetSystemMetrics(SM_CYSIZEFRAME) + 2; y2 := y1 + GetSystemMetrics(SM_CYSIZE) - 4; x2 := TForm(Owner).Width - x2; x1 := x2 - GetSystemMetrics(SM_CXSIZE) + 2; end; end; SetRect(ButtonArea, x1, y1, x2, y2); // if FRoller then Rollup; end; procedure TWinRoller.PaintRollerButton; var h: HDC; st: UINT; p: array[0..2] of TPoint; c: Integer; b: HBRUSH; procedure DrawTriangle( Up: Boolean; dd: Integer; co: Integer ); var pen: HPEN; d, x1, x2, y1, y2: Integer; begin if DrawPushed then d := 1 + dd else d := 0 + dd; with ButtonArea do begin x1 := Left + 1 + d; x2 := Right - 3 + d; y1 := Top + d; y2 := Bottom + d; end; p[0].x := x1 + 3; p[1].x := ((x1 + x2) shr 1); p[2].x := x2 - 3; if Up then begin p[0].y := ((y1 + y2) shr 1) - 2; p[1].y := y1 + 2; p[2].y := p[0].y; end else begin p[0].y := ((y1 + y2) shr 1); p[1].y := y2 - 4; p[2].y := p[0].y; end; case co of 0: begin pen := SelectObject( h, GetStockObject( BLACK_PEN ) ); b := SelectObject( h, GetStockObject( BLACK_BRUSH ) ); end; 1: begin pen := SelectObject( h, GetStockObject( WHITE_PEN ) ); b := SelectObject( h, GetStockObject( WHITE_BRUSH ) ); end; 2: begin pen := SelectObject( h, CreatePen( PS_SOLID, 0, GetSysColor( COLOR_BTNSHADOW ) ) ); b := SelectObject( h, GetStockObject( DKGRAY_BRUSH ) ); end; end; if (Up and not FRoller) or (not Up and FRoller) then PolyGon( h, p, 3 ) else begin Inc( p[2].x ); if Up then Inc( p[2].y ) else Dec( p[2].y ); PolyLine( h, p, 3 ); Inc( p[0].x ); Dec( p[2].x ); if Up then Inc( p[1].y ) else Dec( p[1].y ); PolyLine( h, p, 3 ); end; SelectObject( h, b ); if co = 2 then DeleteObject( SelectObject( h, pen ) ) else SelectObject( h, pen ); end; begin if not (csDesigning in ComponentState) then with TForm(Owner) do if not (BorderStyle = bsNone) then begin h := GetWindowDC( Handle ); if FVisible then begin if DrawPushed then st := DFCS_PUSHED else st := 0; DrawFrameControl( h, ButtonArea, DFC_BUTTON, DFCS_BUTTONPUSH or st ); if FEnabled then begin DrawTriangle( True, 0, 0 ); DrawTriangle( False, 0, 0 ); end else begin DrawTriangle( True, 1, 1 ); DrawTriangle( False, 1, 1 ); DrawTriangle( True, 0, 2 ); DrawTriangle( False, 0, 2 ); end; end else begin if Active then c := COLOR_ACTIVECAPTION else c := COLOR_INACTIVECAPTION; b := CreateSolidBrush( GetSysColor( c ) ); FillRect( h, ButtonArea, b ); DeleteObject( b ); end; ReleaseDC( Handle, h ); end; end; procedure TWinRoller.SetEnabled( Val: Boolean ); begin if Val <> FEnabled then begin FEnabled := Val; PaintRollerButton; end; end; procedure TWinRoller.Rollup; var y: Integer; r: TRect; begin with TForm(Owner) do begin y := GetSystemMetrics( SM_CYCAPTION ); if BorderStyle in [bsSingle, bsDialog, bsToolWindow] then Inc( y, GetSystemMetrics(SM_CYFIXEDFRAME) ) else Inc( y, GetSystemMetrics(SM_CYSIZEFRAME) ); SetWindowRgn( Handle, 0, False ); if rgn <> 0 then begin DeleteObject( rgn ); rgn := 0; end; GetWindowRect( Handle, r ); rgn := CreateRectRgn( 0, 0, r.Right - r.Left, y ); SetWindowRgn( Handle, rgn, True ); end; end; procedure TWinRoller.SetRoller( Val: Boolean ); begin if FEnabled and (Val <> FRoller) then begin FRoller := Val; if Val then begin Rollup; if Assigned( FOnRoller ) then FOnRoller( Self, mdRollUp ); end else begin SetWindowRgn( TForm(Owner).Handle, 0, True ); if rgn <> 0 then begin DeleteObject( rgn ); rgn := 0; end; if Assigned( FOnRoller ) then FOnRoller( Self, mdRollDown ); end; PaintRollerButton; end; end; procedure TWinRoller.SetVisible( Val: Boolean ); begin if Val <> FVisible then begin FVisible := Val; CalcArea; PaintRollerButton; end; end; procedure TWinRoller.WinProc(var Message: TMessage); var v: Boolean; procedure Default; begin with Message do Result := CallWindowProc(DefWinProc, TForm(Owner).Handle, Msg, wParam, lParam); end; function InArea( InClient: Boolean ): Boolean; var p: TPoint; begin p.x := Message.lParamLo; p.y := Smallint(Message.lParamHi); if InClient then ClientToScreen( TForm(Owner).Handle, p ); Dec( p.x, TForm(Owner).Left ); Dec( p.y, TForm(Owner).Top ); Result := PtInRect( ButtonArea, p ); end; begin if not FVisible then Default else with Message do case Msg of WM_MOVE: begin Default; Stop := True; end; WM_SIZE, WM_WINDOWPOSCHANGED: begin Default; v := FVisible; FVisible := False; PaintRollerButton; CalcArea; if FRoller and not Stop then Rollup; FVisible := v; // TForm(Owner).Invalidate; PaintRollerButton; Stop := False; end; WM_MOUSEMOVE: begin if Pushed then begin if not InArea( True ) then begin if DrawPushed then begin DrawPushed := False; if FEnabled then PaintRollerButton; end; end else begin if not DrawPushed then begin DrawPushed := True; if FEnabled then PaintRollerButton; end; end; Result := 1; end else Default; end; WM_LBUTTONUP, WM_LBUTTONDBLCLK: begin DrawPushed := False; if Pushed then begin if InArea( True ) then begin Stop := True; Roller := not FRoller; Stop := False; end else if FEnabled then PaintRollerButton; Result := 1; end else Default; Pushed := False; ReleaseCapture; end; WM_NCLBUTTONDOWN, WM_NCLBUTTONDBLCLK: begin if InArea( False ) then begin SetCapture( TForm(Owner).Handle ); DrawPushed := True; Pushed := True; if FEnabled then PaintRollerButton; Result := 1; end; if Msg = WM_NCLBUTTONDOWN then Default; end; WM_SETTINGCHANGE: begin Default; CalcArea; if FRoller then begin Stop := True; Rollup; Stop := False; end; PaintRollerButton; // TForm(Owner).Invalidate; end; WM_NCACTIVATE, WM_NCPAINT: begin Default; // with Message do // if (Msg = WM_NCACTIVATE) and (wParam = 0) then // Result := 1; PaintRollerButton; end; else Default; end; end; end.
{*********************************************************************** Unit gfx_EffectEx.PAS v1.2 0801 (c) by Andreas Moser, amoser@amoser.de, Delphi version : Delphi 4 gfx_EffectEx is part of the gfx_library collection You may use this sourcecode for your freewareproducts. You may modify this source-code for your own use. You may recompile this source-code for your own use. All functions, procedures and classes may NOT be used in commercial products without the permission of the author. For parts of this library not written by me, you have to ask for permission by their respective authors. Disclaimer of warranty: "This software is supplied as is. The author disclaims all warranties, expressed or 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 this software." All brand and product names are marks or registered marks of their respective companies. Please report bugs to: Andreas Moser amoser@amoser.de ********************************************************************************} unit gfx_effectex; interface uses gfx_Effects; // Standard filters & examples //****************************************************************************** // // Linear filters // //****************************************************************************** const cnt_predefined_linflt = 32; cnt_predefined_multipass = 2; var mxEmbossColor:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-1,-1,-1, 0, 0), ( 0, 0, 0, 1, 0, 0, 0), ( 0, 0, 1, 1, 1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:0; FilterName:'Emboss color (Effects linear)';); var mxEmbossLight:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0,-1, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 1, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:192; FilterName:'Emboss light (Effects linear)';); var mxEmbossMedium:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-1,-2,-1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 1, 2, 1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:192; FilterName:'Emboss medium (Effects linear)';); var mxEmbossDark:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-1,-2,-1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 1, 2, 1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:128; FilterName:'Emboss Dark (Effects linear)';); var mxEdgeEnhance:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-1,-2,-1, 0, 0), ( 0, 0,-2,16,-2, 0, 0), ( 0, 0,-1,-2,-1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:4; Bias:0; FilterName:'Edge enhance (Sharpen linear)';); var mxBlurBartlett:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx7; Matrix: (( 1, 2, 3, 4, 3, 2, 1), ( 2, 4, 6, 8, 6, 4, 2), ( 3, 6, 9,12, 9, 6, 3), ( 4, 8,12,16,12, 8, 4), ( 3, 6, 9,12, 9, 6, 3), ( 2, 4, 6, 8, 6, 4, 2), ( 1, 2, 3, 4, 3, 2, 1)); Divisor:256; Bias:0; FilterName:'Blur Bartlett (Blur linear)';); var mxBlurGaussian:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx7; Matrix: (( 1, 4, 8, 10, 8, 4, 1), ( 4,12,25,29,25,12, 4), ( 8,25,49,58,49,25, 8), (10,29,58,67,58,29,10), ( 8,25,49,58,49,25, 8), ( 4,12,25,29,25,12, 4), ( 1, 4, 8, 10, 8, 4, 1)); Divisor:999; Bias:0; FilterName:'Blur Gaussian (Blur linear)';); var mxNegative:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0,-1, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:255; FilterName:'Negative (Effects linear)';); var mxAverage:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 1, 1, 1, 0, 0), ( 0, 0, 1, 1, 1, 0, 0), ( 0, 0, 1, 1, 1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:9; Bias:0; FilterName:'Average (Blur linear)';); var mxBlur:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 1, 2, 1, 0, 0), ( 0, 0, 2, 4, 2, 0, 0), ( 0, 0, 1, 2, 1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:16; Bias:0; FilterName:'Blur (Blur linear)';); var mxBlurSoftly:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 1, 3, 1, 0, 0), ( 0, 0, 3,16, 3, 0, 0), ( 0, 0, 1, 3, 1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:32; Bias:0; FilterName:'Blur softly (Blur linear)';); var mxBlurMore:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx5; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 1, 2, 1, 0, 0), ( 0, 1, 4, 6, 4, 1, 0), ( 0, 2, 6, 8, 6, 2, 0), ( 0, 1, 4, 6, 4, 1, 0), ( 0, 0, 1, 2, 1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:64; Bias:0; FilterName:'Blur more (Blur linear)';); var mxPrewitt:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 1, 1, 1, 0, 0), ( 0, 0, 1,-2, 1, 0, 0), ( 0, 0,-1,-1,-1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:0; FilterName:'Prewitt (Edge detect linear)';); var mxTraceContour:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-6,-2,-6, 0, 0), ( 0, 0,-1,32,-1, 0, 0), ( 0, 0,-6,-2,-6, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:240; FilterName:'Trace contour (Edge detect linear)';); var mxSharpen:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-1,-1,-1, 0, 0), ( 0, 0,-1,16,-1, 0, 0), ( 0, 0,-1,-1,-1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:8; Bias:0; FilterName:'Sharpen (Sharpen linear)';); var mxSharpenMore:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-1,-1,-1, 0, 0), ( 0, 0,-1,12,-1, 0, 0), ( 0, 0,-1,-1,-1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:4; Bias:0; FilterName:'Sharpen more (Sharpen linear)';); var mxSharpenLess:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-1,-1,-1, 0, 0), ( 0, 0,-1,24,-1, 0, 0), ( 0, 0,-1,-1,-1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:16; Bias:0; FilterName:'Sharpen less (Sharpen linear)';); var mxUnSharpMask:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-1,-2,-1, 0, 0), ( 0, 0,-2,16,-2, 0, 0), ( 0, 0,-1,-2,-1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:4; Bias:0; FilterName:'Unsharp mask (Sharpen linear)';); var mxEdgesStrong:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 1, 3, 1, 0, 0), ( 0, 0, 3,-16,3, 0, 0), ( 0, 0, 1, 3, 1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:0; FilterName:'Edges strong (Edge detect linear)';); var mxEdgesWeak:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 1, 0, 0, 0), ( 0, 0, 1,-4, 1, 0, 0), ( 0, 0, 0, 1, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:0; FilterName:'Edges weak (Edge detect linear)';); var mxEtch:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-6, 2,-6, 0, 0), ( 0, 0,-1,32,-1, 0, 0), ( 0, 0,-6,-2,-6, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:240; FilterName:'Etch (Effects linear)';); var mxLaplacianHV:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0,-1, 0, 0, 0), ( 0, 0,-1, 4,-1, 0, 0), ( 0, 0, 0,-1, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:0; FilterName:'Laplacian horz./vert. (Edge detect linear)';); var mxLaplacianOmni:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-1,-1,-1, 0, 0), ( 0, 0,-1, 8,-1, 0, 0), ( 0, 0,-1,-1,-1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:0; FilterName:'Laplacian omnidir. (Edge detect linear)';); var mxSharpenDirectional:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-3,-3,-3, 0, 0), ( 0, 0, 0,16, 0, 0, 0), ( 0, 0, 1, 1, 1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:10; Bias:0; FilterName:'Sharpen directional (Sharpen linear)';); var mxSobelPass:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx3; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 1, 2, 1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0,-1,-2,-1, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:0; FilterName:'Sobel pass (Edge detect linear)';); var mxGlow:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx7; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 1, 2, 2, 2, 1, 0), ( 0, 2, 0, 0, 0, 2, 0), ( 0, 2, 0,-20,0, 2, 0), ( 0, 2, 0, 0, 0, 2, 0), ( 0, 1, 2, 2, 2, 1, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:8; Bias:0; FilterName:'Glow (Effects linear)';); var mxWaggle:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx7; Matrix: (( 0, 1, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 1), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, 1, 0, 0, 0, 0)); Divisor:3; Bias:0; FilterName:'Waggle (Effects linear)';); var mxPattern:TGraphicFilter =(FilterType:ftLinear;MatrixSize:mx5; Matrix: (( 0, 0, 0, 0, 0, 0, 0), ( 0, 0, -4, -9, -4, 0, 0), ( 0, -4, -24, -1, -24, -4, 0), ( 0, -9, -1, 168, -1, -9, 0), ( 0, -4, -24, -1, -24, -4, 0), ( 0, 0, -4, -9, -4, 0, 0), ( 0, 0, 0, 0, 0, 0, 0)); Divisor:1; Bias:0; FilterName:'Pattern (Edge detect linear)';); //****************************************************************************** // // Two-Pass filters // //****************************************************************************** var nmxLaplacianInvert:TMultiPassGraphicFilter= (FilterType:ftMultiPass; Filters:(@mxLaplacianOmni,@mxNegative,@mxZero,@mxZero); Functions:(gaNone,gaNone,gaNone); FilterName:'Laplacian Negative'); var nmxChurchPattern:TMultiPassGraphicFilter= (FilterType:ftMultiPass; Filters:(@mxZero,@mxPattern,@mxZero,@mxZero); Functions:(gaAverage,gaNone,gaNone); FilterName:'Church Pattern'); implementation end.
unit Getter.CodesignVerifier.Publisher; interface uses Windows, OS.Codesign; type TCodesignPublisherVerifier = class private FileHandle: THandle; ExpectedPublisher: String; PathToVerify: String; Certificate: PWinCertificate; function OpenFileHandleAndReturnResult: Boolean; function VerifyPublisherByHandle: Boolean; function TryToVerifyPublisherByHandle: Boolean; function ValidateCertificationCount: Boolean; function TryToVerifyPublisherWithCertificate: Boolean; function GetCertificateHeader: Boolean; function GetCertificateBody: Boolean; function GetCertificateContext: TCertificateContext; function TryToComparePublisherWithContext(ValidContext: PCCERT_CONTEXT): Boolean; public function VerifySignByPublisher( const PathToVerify, ExpectedPublisher: string): Boolean; end; implementation function TCodesignPublisherVerifier.ValidateCertificationCount: Boolean; var CertificateCount: DWORD; begin result := (ImageEnumerateCertificates(FileHandle, CERT_SECTION_TYPE_ANY, CertificateCount, nil, 0)) and (CertificateCount = 1); end; function TCodesignPublisherVerifier.GetCertificateHeader: Boolean; begin result := ImageGetCertificateHeader(FileHandle, 0, Certificate^); end; function TCodesignPublisherVerifier.GetCertificateBody: Boolean; begin result := ImageGetCertificateData(FileHandle, 0, Certificate, Certificate.dwLength); end; function TCodesignPublisherVerifier.GetCertificateContext: TCertificateContext; var VerifyParameter: CRYPT_VERIFY_MESSAGE_PARA; begin ZeroMemory(@VerifyParameter, SizeOf(VerifyParameter)); VerifyParameter.cbSize := SizeOf(VerifyParameter); VerifyParameter.dwMsgAndCertEncodingType := X509_ASN_ENCODING or PKCS_7_ASN_ENCODING; result.IsContextValid := CryptVerifyMessageSignature(VerifyParameter, 0, @Certificate.bCertificate, Certificate.dwLength, nil, nil, @result.Context) end; function TCodesignPublisherVerifier.TryToComparePublisherWithContext( ValidContext: PCCERT_CONTEXT): Boolean; const CERT_NAME_SIMPLE_DISPLAY_TYPE = 4; var Publisher: String; PublisherLength: DWORD; begin PublisherLength := CertGetNameStringW(ValidContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nil, nil, 0); SetLength(Publisher, PublisherLength - 1); CertGetNameStringW(ValidContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nil, PChar(Publisher), PublisherLength); result := ExpectedPublisher = Publisher; end; function TCodesignPublisherVerifier.TryToVerifyPublisherWithCertificate: Boolean; var ResultOfGettingContext: TCertificateContext; begin result := false; if GetCertificateHeader then ReallocMem(Certificate, SizeOf(TWinCertificate) + Certificate.dwLength) else exit; if not GetCertificateBody then Exit; ResultOfGettingContext := GetCertificateContext; if not ResultOfGettingContext.IsContextValid then exit; try result := TryToComparePublisherWithContext(ResultOfGettingContext.Context); finally CertFreeCertificateContext(ResultOfGettingContext.Context); end; end; function TCodesignPublisherVerifier.TryToVerifyPublisherByHandle: Boolean; const Padding = 3; begin result := false; if not ValidateCertificationCount then Exit; GetMem(Certificate, SizeOf(TWinCertificate) + Padding); try Certificate.dwLength := 0; Certificate.wRevision := WIN_CERT_REVISION_1_0; result := TryToVerifyPublisherWithCertificate; finally FreeMem(Certificate); end; end; function TCodesignPublisherVerifier.VerifyPublisherByHandle: Boolean; begin try result := TryToVerifyPublisherByHandle; finally CloseHandle(FileHandle); end; end; function TCodesignPublisherVerifier.OpenFileHandleAndReturnResult: Boolean; begin FileHandle := CreateFile(PChar(PathToVerify), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_RANDOM_ACCESS, 0); result := (FileHandle <> INVALID_HANDLE_VALUE) and (FileHandle <> 0); end; function TCodesignPublisherVerifier.VerifySignByPublisher(const PathToVerify, ExpectedPublisher: string): Boolean; begin Result := false; Self.ExpectedPublisher := ExpectedPublisher; Self.PathToVerify := PathToVerify; if not OpenFileHandleAndReturnResult then exit; Result := VerifyPublisherByHandle; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Winapi.Mshtmhst; {$WEAKPACKAGEUNIT} (*$HPPEMIT '#include <mshtmhst.h>'*) interface uses Winapi.Windows, System.Classes, System.Variants, Winapi.ActiveX; const DOCHOSTUIFLAG_FLAT_SCROLLBAR = $00000080; {$EXTERNALSYM DOCHOSTUIFLAG_FLAT_SCROLLBAR} DOCHOSTUIFLAG_SCROLL_NO = $00000008; {$EXTERNALSYM DOCHOSTUIFLAG_SCROLL_NO} DOCHOSTUIFLAG_NO3DBORDER = $00000004; {$EXTERNALSYM DOCHOSTUIFLAG_NO3DBORDER} DOCHOSTUIFLAG_DIALOG = $00000001; {$EXTERNALSYM DOCHOSTUIFLAG_DIALOG} DOCHOSTUIFLAG_THEME = $00040000; {$EXTERNALSYM DOCHOSTUIFLAG_THEME} DOCHOSTUIFLAG_NOTHEME = $00080000; {$EXTERNALSYM DOCHOSTUIFLAG_NOTHEME} type TDocHostUIInfo = record cbSize: ULONG; dwFlags: DWORD; dwDoubleClick: DWORD; pchHostCss: PWChar; pchHostNS: PWChar; end; IDocHostShowUI = interface(IUnknown) ['{c4d244b0-d43e-11cf-893b-00aa00bdce1a}'] function ShowMessage(hwnd: THandle;lpstrText: POLESTR;lpstrCaption: POLESTR; dwType: longint;lpstrHelpFile: POLESTR;dwHelpContext: longint; var plResult: LRESULT): HRESULT; stdcall; function ShowHelp(hwnd: THandle; pszHelpFile: POLESTR; uCommand: integer; dwData: longint; ptMouse: TPoint; var pDispachObjectHit: IDispatch): HRESULT; stdcall; end; {$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IDocHostShowUI);'} {$EXTERNALSYM IDocHostShowUI} IDocHostUIHandler = interface(IUnknown) ['{BD3F23C0-D43E-11CF-893B-00AA00BDCE1A}'] function ShowContextMenu(const dwID: DWORD; const ppt: PPOINT; const pcmdtReserved: IUnknown; const pdispReserved: IDispatch): HRESULT; stdcall; function GetHostInfo(var pInfo: TDocHostUIInfo): HRESULT; stdcall; function ShowUI(const dwID: DWORD; const pActiveObject: IOleInPlaceActiveObject; const pCommandTarget: IOleCommandTarget; const pFrame: IOleInPlaceFrame; const pDoc: IOleInPlaceUIWindow): HRESULT; stdcall; function HideUI: HRESULT; stdcall; function UpdateUI: HRESULT; stdcall; function EnableModeless(const fEnable: BOOL): HRESULT; stdcall; function OnDocWindowActivate(const fActivate: BOOL): HRESULT; stdcall; function OnFrameWindowActivate(const fActivate: BOOL): HRESULT; stdcall; function ResizeBorder(const prcBorder: PRECT; const pUIWindow: IOleInPlaceUIWindow; const FrameWindow: BOOL): HRESULT; stdcall; function TranslateAccelerator(const lpMsg: PMSG; const pguidCmdGroup: PGUID; const nCmdID: DWORD): HRESULT; stdcall; function GetOptionKeyPath(var pchKey: POLESTR; const dw: DWORD): HRESULT; stdcall; function GetDropTarget(const pDropTarget: IDropTarget; out ppDropTarget: IDropTarget): HRESULT; stdcall; function GetExternal(out ppDispatch: IDispatch): HRESULT; stdcall; function TranslateUrl(const dwTranslate: DWORD; const pchURLIn: POLESTR; var ppchURLOut: POLESTR): HRESULT; stdcall; function FilterDataObject(const pDO: IDataObject; out ppDORet: IDataObject): HRESULT; stdcall; end; {$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IDocHostUIHandler);'} {$EXTERNALSYM IDocHostUIHandler} implementation end.
library yeehaalib; {$mode objfpc}{$H+} {$packrecords c} uses cthreads, SysUtils, Strings, ctypes, fpjson, fgl, Yeehaa; type TBulbData = record IP : PChar; Model : PChar; PoweredOn : cbool; BrightnessPercentage: cuint8; RGB : cint32; end; TValueType = (vtInteger,vtString); TValue = record Key: PChar; // always nil for arrays case ValueType: TValueType of vtInteger: (IntValue: cint32); vtString : (StrValue: PChar); end; PValue = ^TValue; TCommandResult = record IsError: cbool; ValueCount: cint32; Values: PValue; end; TBulbFoundCallback = procedure (constref ANewBulb: TBulbData); cdecl; TCommandResultCallback = procedure (const AID: cint32; constref AResult: TCommandResult); cdecl; TConnectionErrorCallback = procedure (const AMsg: PChar); cdecl; { TYeeBroker } TYeeBroker = class private FConn: TYeeConn; FOnBulbFound: TBulbFoundCallback; FOnCommandResult: TCommandResultCallback; FOnConnectionError: TConnectionErrorCallback; procedure HandleBulbFound(const ANewBulb: TBulbInfo); procedure HandleCommandResult(const AID: Integer; AResult, AError: TJSONData); procedure HandleConnectionError(const AMsg: String); public constructor Create(const AConn: TYeeConn); destructor Destroy; override; property Conn: TYeeConn read FConn; property OnBulbFound: TBulbFoundCallback write FOnBulbFound; property OnCommandResult: TCommandResultCallback write FOnCommandResult; property OnConnectionError: TConnectionErrorCallback write FOnConnectionError; end; { TEventBroker } procedure TYeeBroker.HandleBulbFound(const ANewBulb: TBulbInfo); var LBulbData: TBulbData; begin LBulbData.IP := PChar(ANewBulb.IP); LBulbData.Model := PChar(ANewBulb.Model); LBulbData.PoweredOn := ANewBulb.PoweredOn; LBulbData.BrightnessPercentage := ANewBulb.BrightnessPercentage; LBulbData.RGB := ANewBulb.RGB; if Assigned(FOnBulbFound) then FOnBulbFound(LBulbData); end; procedure TYeeBroker.HandleCommandResult(const AID: Integer; AResult, AError: TJSONData); var LCommandResult: TCommandResult; i: Integer; procedure DecodeCommandResult(ACmdResult: TJSONData); var i: Integer; s: String; LValue: TValue; LData: TJSONData; LResultObj: TJSONObject; LResultArr: TJSONArray; begin case AResult.JSONType of jtArray: begin LResultArr := TJSONArray(ACmdResult); LCommandResult.ValueCount := LResultArr.Count; LCommandResult.Values := GetMem(LCommandResult.ValueCount * SizeOf(TValue)); for i := 0 to LCommandResult.ValueCount - 1 do begin LData := LResultArr[i]; Str(i,s); LValue.Key := StrAlloc(Length(s) + 1); StrPCopy(LValue.Key, s); case LData.JSONType of jtString: begin LValue.ValueType := vtString; LValue.StrValue := PChar(LData.AsString); end; jtNumber: begin LValue.ValueType := vtInteger; LValue.IntValue := LData.AsInteger; end; otherwise raise Exception.CreateFmt('Command Result[%d]: unexpected JSON type "%s"',[i,AResult.JSONType]); end; LCommandResult.Values[i] := LValue; end; end; jtObject: begin LResultObj := TJSONObject(ACmdResult); LCommandResult.ValueCount := LResultObj.Count; LCommandResult.Values := GetMem(LCommandResult.ValueCount * SizeOf(TValue)); for i := 0 to LCommandResult.ValueCount - 1 do begin LData := LResultObj.Items[i]; LValue.Key := StrAlloc(Length(LResultObj.Names[i]) + 1); StrPCopy(LValue.Key, LResultObj.Names[i]); case LData.JSONType of jtString: begin LValue.ValueType := vtString; LValue.StrValue := PChar(LData.AsString); end; jtNumber: begin LValue.ValueType := vtInteger; LValue.IntValue := LData.AsInteger; end; otherwise raise Exception.CreateFmt('Command Result[%d]: unexpected JSON type "%s"',[i,AResult.JSONType]); end; writeln(LValue.ValueType); LCommandResult.Values[i] := LValue; end; end; otherwise raise Exception.CreateFmt('Command Result: unexpected JSON type "%s"',[AResult.JSONType]); end; end; begin if Assigned(FOnCommandResult) then begin // looks stupid, but should work... I guess LCommandResult.IsError := Assigned(AError); if Assigned(AResult) then DecodeCommandResult(AResult); if Assigned(AError) then DecodeCommandResult(AError); FOnCommandResult(AID,LCommandResult); for i := 0 to LCommandResult.ValueCount - 1 do StrDispose(LCommandResult.Values[i].Key); FreeMem(LCommandResult.Values); end; end; procedure TYeeBroker.HandleConnectionError(const AMsg: String); begin if Assigned(FOnConnectionError) then FOnConnectionError(PChar(AMsg)); end; constructor TYeeBroker.Create(const AConn: TYeeConn); begin FConn := AConn; with FConn do begin OnConnectionError := @HandleConnectionError; OnBulbFound := @HandleBulbFound; OnCommandResult := @HandleCommandResult; end; end; destructor TYeeBroker.Destroy; begin FConn.Free; inherited Destroy; end; { exported APIs } function InitializeConnection(const AListenPort: cuint16; const ABroadcastIntervalMillisecond: cint32): TYeeBroker; cdecl; begin Result := TYeeBroker.Create(TYeeConn.Create(AListenPort, ABroadcastIntervalMillisecond)); end; procedure FinalizeConnection(const ABroker: TYeeBroker); cdecl; begin ABroker.Free; end; procedure RegisterOnConnectionErrorCallback(const ABroker: TYeeBroker; const ACallbackEvent: TConnectionErrorCallback) cdecl; begin ABroker.OnConnectionError := ACallbackEvent; end; procedure RegisterOnBulbFoundCallback(const ABroker: TYeeBroker; const ACallbackEvent: TBulbFoundCallback) cdecl; begin ABroker.OnBulbFound := ACallbackEvent; end; procedure RegisterOnCommandResultCallback(const ABroker: TYeeBroker; const ACallbackEvent: TCommandResultCallback) cdecl; begin ABroker.OnCommandResult := ACallbackEvent; end; procedure SetPower(const ABroker: TYeeBroker; const AIP: PChar; const AIsOn: cbool; const ATransitionEfect: TTransitionEfect; const ATransitionDuration: TTransitionDuration); cdecl; begin ABroker.Conn.SetPower(String(AIP),AIsOn,ATransitionEfect,ATransitionDuration); end; exports InitializeConnection, FinalizeConnection, RegisterOnConnectionErrorCallback, RegisterOnBulbFoundCallback, RegisterOnCommandResultCallback, SetPower; end.
program Sample; procedure Change(A : Integer; var B : Integer); begin A := 13; B := B + 1 end; var A,B : Integer; begin A := 3; B := 4; Change(A,B); WriteLn('A = ',A,' B = ',B) end.
unit Vigilante.Build.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vigilante.View.Component.SituacaoBuild, Vigilante.Controller.Build, Vcl.WinXCtrls, 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, Vigilante.Build.Observer, Vigilante.Build.Model, FireDAC.Stan.StorageBin, System.Actions, Vcl.ActnList, Vigilante.DataSet.Build; type TfrmBuildView = class(TFrame, IBuildObserver) dtsDataSet: TDataSource; pnlCliente: TPanel; BuildAtualLabel: TLabel; Label1: TLabel; UltimoBuildSucesso: TDBText; Label2: TLabel; UltimoBuildFalha: TDBText; DBGrid1: TDBGrid; frmSituacaoBuild1: TfrmSituacaoBuild; DBCheckBox1: TDBCheckBox; DBCheckBox2: TDBCheckBox; Bevel1: TBevel; DBNavigator1: TDBNavigator; DBGrid2: TDBGrid; ActionList1: TActionList; actMostrardados: TAction; lblTransformarEmCompilacao: TLinkLabel; procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBNavigator1Click(Sender: TObject; Button: TNavigateBtn); procedure actMostrardadosExecute(Sender: TObject); procedure lblTransformarEmCompilacaoLinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); procedure dtsDataSetDataChange(Sender: TObject; Field: TField); private FController: IBuildController; FDadosClone: TBuildDataSet; procedure SincronizarLink; public procedure DefinirController(const AController: IBuildController); procedure NovaAtualizacao(const ABuild: IBuildModel); procedure MostrarBuild(const AID: TGUID); procedure AdicionarNovoLink; procedure AfterConstruction; override; procedure BeforeDestruction; override; end; implementation {$R *.dfm} uses ContainerDI, Vigilante.Aplicacao.SituacaoBuild, Vigilante.View.URLDialog, Vigilante.Controller.Mediator; procedure TfrmBuildView.AfterConstruction; begin inherited; FDadosClone := TBuildDataSet.Create(nil); dtsDataSet.DataSet := FDadosClone; end; procedure TfrmBuildView.BeforeDestruction; begin inherited; FreeAndNil(FDadosClone); end; procedure TfrmBuildView.actMostrardadosExecute(Sender: TObject); begin DBGrid2.Visible := not DBGrid2.Visible; end; procedure TfrmBuildView.AdicionarNovoLink; var _urlDialog: IURLDialog; begin if FDadosClone.State in dsEditModes then FDadosClone.Cancel; _urlDialog := CDI.Resolve<IURLDialog>('IBuildURLDialog'); if _urlDialog.Executar then FController.AdicionarNovaURL(_urlDialog.URLInformada); end; procedure TfrmBuildView.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin case FDadosClone.Situacao of sbFalhouInfra: begin DBGrid1.Canvas.Brush.Color := clWebLightSalmon; // DBGrid1.Canvas.Font.Color := clWindowText; end; sbAbortado: begin DBGrid1.Canvas.Brush.Color := clWebLightSalmon; // DBGrid1.Canvas.Font.Color := clWindowText; end; sbFalhou: begin DBGrid1.Canvas.Brush.Color := clWebLightSalmon; // DBGrid1.Canvas.Font.Color := clWindowText; end; sbSucesso: begin DBGrid1.Canvas.Brush.Color := clWebLightGreen; DBGrid1.Canvas.Font.Color := clWebSlateGray; end; end; // DBGrid1.Canvas.Font.Style := [fsBold]; DBGrid1.Canvas.FillRect(Rect); DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TfrmBuildView.DBNavigator1Click(Sender: TObject; Button: TNavigateBtn); begin if Button = nbInsert then begin AdicionarNovoLink; end; end; procedure TfrmBuildView.DefinirController(const AController: IBuildController); begin FController := AController; FDadosClone.CloneCursor(FController.DataSet); frmSituacaoBuild1.DataSet := FDadosClone; frmSituacaoBuild1.NomeFieldName := 'Nome'; frmSituacaoBuild1.SituacaoBuildFieldName := 'Situacao'; frmSituacaoBuild1.URLFieldName := 'URL'; end; procedure TfrmBuildView.dtsDataSetDataChange(Sender: TObject; Field: TField); begin if (not Assigned(FDadosClone)) or (not FDadosClone.Active) then Exit; SincronizarLink; end; procedure TfrmBuildView.lblTransformarEmCompilacaoLinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); begin FController.TransformarEmCompilacao(FDadosClone.ID); end; procedure TfrmBuildView.NovaAtualizacao(const ABuild: IBuildModel); begin if not(ABuild.Situacao in SITUACOES_NOTIFICAVEIS) then Exit; if not FController.DataSet.Locate('ID', ABuild.ID.ToString, []) then Exit; if not FController.DataSet.Notificar then Exit; MostrarBuild(ABuild.ID); end; procedure TfrmBuildView.MostrarBuild(const AID: TGUID); begin if FDadosClone.IsEmpty then Exit; FDadosClone.Locate('ID', AID.ToString, []); end; procedure TfrmBuildView.SincronizarLink; const Link = '<a href="#">%d</a>'; HINT = 'Envia informações para tela de compilação'; begin lblTransformarEmCompilacao.Caption := EmptyStr; if FDadosClone.UltimoBuild > 0 then lblTransformarEmCompilacao.Caption := Format(Link, [FDadosClone.UltimoBuild]); lblTransformarEmCompilacao.HINT := HINT; end; end.
PROGRAM Morse; TYPE TreeNodePtr = ^TreeNode; TreeNode = RECORD left, right: TreeNodePtr; ch : CHAR; code: STRING; END; Tree = TreeNodePtr; PROCEDURE InitTree(VAR t: Tree); BEGIN t := NIL; END; PROCEDURE DisposeTree(t: Tree); BEGIN IF t = NIL THEN ELSE BEGIN DisposeTree(t^.left); DisposeTree(t^.right); Dispose(t); END; END; PROCEDURE InsertEmptyNode(VAR t: Tree); VAR newNode: TreeNodePtr; BEGIN IF t = NIL THEN BEGIN New(newNode); newNode^.left := NIL; newNode^.right := NIL; t := newNode; END; END; PROCEDURE InsertMorseCode(VAR t: Tree; ch: CHAR; code: STRING); VAR newNode: Tree; BEGIN IF t = NIL THEN BEGIN New(newNode); newNode^.left := NIL; newNode^.right := NIL; newNode^.ch := ch; t := newNode; END ELSE IF code[1] = '.' THEN InsertMorseCode(t^.left, ch, Copy(code, 2, length(code))) ELSE InsertMorseCode(t^.right, ch, Copy(code, 2, length(code))); END; (* ALTERNATIVE PROCEDURE InsertMorseCode(VAR tree: MorseTreePtr; ch: CHAR; code: STRING); VAR n: TreeNodePtr; BEGIN IF tree = NIL THEN BEGIN New(n); n^.value := ch; n^.left := NIL; n^.right := NIL; tree := n; END ELSE IF code[1] = left THEN InsertMorseCode(tree^.left, ch, RightStr(code, Length(code) - 1)) ELSE IF code[1] = right THEN InsertMorseCode(tree^.right, ch, RightStr(code, Length(code) - 1)) ELSE // Illegal code sign END; *) PROCEDURE DisplayTree(t: Tree); BEGIN IF t = NIL THEN ElSE BEGIN (* in-order*) DisplayTree(t^.left); Write(t^.ch, ' '); DisplayTree(t^.right); END; END; FUNCTION Lookup(t: Tree; code: STRING): CHAR; VAR n: Tree; i: INTEGER; BEGIN n := t; FOR i := 1 TO length(code) DO BEGIN IF (code[i] = '.') AND (n^.left <> NIL) THEN n := n^.left ELSE IF (code[i] = '-') AND (n^.right <> NIL) THEN n := n^.right; END; Lookup := n^.ch; END; (* ALTERNATIVE FUNCTION Lookup(tree: MorseTreePtr; code: STRING): CHAR; BEGIN IF tree = NIL THEN // Illegal code Lookup := ' ' ELSE IF Length(code) = 0 THEN Lookup := tree^.value ELSE IF code[1] = left THEN Lookup := Lookup(tree^.left, RightStr(code, Length(code) - 1)) ELSE IF code[1] = right THEN Lookup := Lookup(tree^.right, RightStr(code, Length(code) - 1)) ELSE // Illegal code sign Lookup := ' '; END; *) PROCEDURE TranslateCode(VAR t: Tree; code: STRING); VAR x, y, i: INTEGER; BEGIN x := 1; y := 0; FOR i := 1 TO length(code) DO BEGIN IF (code[i] = '.') OR (code[i] = '-') THEN y := y + 1 ELSE IF (code[i] = ' ') THEN BEGIN Write(Lookup(t, Copy(code, x, y))); x := i + 1; y := 0; END ELSE IF (code[i] = ';') THEN BEGIN Write(Lookup(t, Copy(code, x, y)), ' '); x := i + 1; y := 0; END ELSE BEGIN WriteLn('Wrong Input: '); END END; WriteLn; WriteLn; END; (* ALTERNATIVE FUNCTION DecodeMessage(tree: MorseTreePtr; message: STRING): STRING; VAR i: INTEGER; code: STRING; decodedMessage: STRING; BEGIN code := ''; decodedMessage := ''; FOR i := 1 TO Length(message) DO BEGIN IF message[i] = endOfWord THEN BEGIN decodedMessage := decodedMessage + Lookup(tree, code) + ' '; code := ''; END ELSE IF message[i] = endOfChar THEN BEGIN decodedMessage := decodedMessage + Lookup(tree, code); code := ''; END ELSE code := code + message[i]; END; DecodeMessage := decodedMessage + Lookup(tree, code); END; *) VAR t: Tree; BEGIN InitTree(t); InsertEmptyNode(t); InsertMorseCode(t, 'E', '.'); InsertMorseCode(t, 'I', '..'); InsertMorseCode(t, 'A', '.-'); InsertMorseCode(t, 'S', '...'); InsertMorseCode(t, 'U', '..-'); InsertMorseCode(t, 'H', '....'); InsertMorseCode(t, 'V', '...-'); InsertMorseCode(t, 'R', '.-.'); InsertMorseCode(t, 'L', '.-..'); InsertMorseCode(t, 'W', '.--'); InsertMorseCode(t, 'P', '.--.'); InsertMorseCode(t, 'J', '.---'); InsertMorseCode(t, 'T', '-'); InsertMorseCode(t, 'N', '-.'); InsertMorseCode(t, 'D', '-..'); InsertMorseCode(t, 'K', '-.-'); InsertMorseCode(t, 'X', '-..-'); InsertMorseCode(t, 'B', '-...'); InsertMorseCode(t, 'C', '-.-.'); InsertMorseCode(t, 'M', '--'); InsertMorseCode(t, 'G', '--.'); InsertMorseCode(t, 'Z', '--..'); InsertMorseCode(t, 'Q', '--.-'); InsertMorseCode(t, 'O', '---'); InsertMorseCode(t, 'F', '..-.'); InsertMorseCode(t, 'Y', '-.--'); WriteLn(Lookup(t, '.-')); WriteLn(Lookup(t, '-...')); WriteLn(Lookup(t, '-.-.')); WriteLn(Lookup(t, '-..')); WriteLn(Lookup(t, '.')); WriteLn(Lookup(t, '..-.')); WriteLn(Lookup(t, '--.')); WriteLn(Lookup(t, '....')); WriteLn(Lookup(t, '..')); WriteLn(Lookup(t, '.---')); WriteLn(Lookup(t, '-.-')); WriteLn(Lookup(t, '.-..')); WriteLn(Lookup(t, '--')); WriteLn(Lookup(t, '-.')); WriteLn(Lookup(t, '---')); WriteLn(Lookup(t, '.--.')); WriteLn(Lookup(t, '--.-')); WriteLn(Lookup(t, '.-.')); WriteLn(Lookup(t, '...')); WriteLn(Lookup(t, '-')); WriteLn(Lookup(t, '..-')); WriteLn(Lookup(t, '...-')); WriteLn(Lookup(t, '.--')); WriteLn(Lookup(t, '-..-')); WriteLn(Lookup(t, '-.--')); WriteLn(Lookup(t, '--..')); WriteLn; TranslateCode(t, '... .;.... .- --. . -. -... . .-. --. '); TranslateCode(t, '.... .- .-.. .-.. ---;.... .- -.- .- -. '); TranslateCode(t, '..d. .;.... .- --. . -. -... . .-. --. '); DisposeTree(t); END.
{$mode objfpc} {$m+} program Queue; const MAX_SIZE = 5; type ArrayQueue = class private arr : array[0..MAX_SIZE] of integer; first : 0..MAX_SIZE; last : 0..MAX_SIZE; count : 0..MAX_SIZE; public constructor create(); procedure push(i : integer); function pop() : integer; end; Node = record val : integer; prev : ^Node; end; LinkedListQueue = class private first : ^Node; last : ^Node; public function pop(): integer; procedure push(i : integer); end; constructor ArrayQueue.Create(); begin first := 0; last := 0; count := 0; end; procedure ArrayQueue.push(i : integer); begin if count < MAX_SIZE then begin writeln('adding ', i); count := count + 1; arr[last] := i; last := (last + 1) mod MAX_SIZE; end else writeln('queue is full'); end; function ArrayQueue.pop() : integer; begin if count <= 0 then begin pop := -1; writeln('nothing left in queue'); end else begin count := count - 1; writeln('poping ', arr[first]); pop := arr[first]; arr[first] := 0; first := (first + 1) mod MAX_SIZE; end; end; function LinkedListQueue.pop() : integer; begin if first <> nil then begin writeln('poping ', first^.val); pop := first^.val; first := first^.prev; end else begin pop := -1; writeln('nothing left in queue'); end; end; procedure LinkedListQueue.push(i : integer); var A : ^Node; begin writeln('pushing ', i); new(A); A^.val := i; if first = nil then first := A else last^.prev := A; last := A; end; var Q : ArrayQueue; L : LinkedListQueue; a : integer; begin writeln('--ArrayQueue--'); Q := ArrayQueue.Create(); Q.push(9); Q.push(8); Q.push(7); Q.push(6); Q.push(5); Q.pop(); Q.push(4); repeat a := Q.pop(); until a = -1; writeln('--LinkedListQueue--'); L := LinkedListQueue.Create(); L.push(1); L.push(2); L.push(9); L.push(8); L.push(7); L.push(9); repeat a := L.pop(); until a = -1; end.
unit ClassPack; interface uses ClassTree; type TPack = class private FTree : TTree; procedure AddWordToTree( Word : string; Tree : TTree ); function ReadWord( var F : TextFile ) : string; procedure CreateTree( Src : string ); procedure PackTreeToFile( var F : File; Tree : TTree ); procedure PackTree( Dest : string ); public constructor Create; destructor Destroy; override; procedure Pack( Src, Dest : string ); end; implementation //============================================================================== // Constructor/destructor //============================================================================== constructor TPack.Create; begin inherited Create; FTree := TTree.Create( #0 , false ); end; destructor TPack.Destroy; begin FTree.Free; inherited; end; //============================================================================== // P R I V A T E //============================================================================== procedure TPack.AddWordToTree( Word : string; Tree : TTree ); var T : TTree; IsWord : boolean; begin T := Tree.GetTreeByData( Word[1] ); if (Length( Word ) = 1) then IsWord := true else IsWord := false; if (T = nil) then begin T := TTree.Create( Word[1] , IsWord ); Tree.AddTree( T ); end else if (IsWord) then T.SetWord( Word[1] ); if (not IsWord) then begin Delete( Word , 1 , 1 ); AddWordToTree( Word , T ); end; end; function TPack.ReadWord( var F : TextFile ) : string; var C : char; begin Result := ''; C := #0; while ((not EoF( F )) and (C <> #10)) do begin Read( F , C ); if (C <> #10) then Result := Result + C; end; end; procedure TPack.CreateTree( Src : string ); var F : TextFile; Word : string; begin AssignFile( F , Src ); Reset( F ); while (not EoF( F )) do begin Word := ReadWord( F ); if (Word = '') then break; AddWordToTree( Word , FTree ); end; CloseFile( F ); end; procedure TPack.PackTreeToFile( var F : File; Tree : TTree ); var I : integer; B : byte; begin for I := Low( Tree.FLeaves ) to High( Tree.FLeaves ) do begin B := Tree.FLeaves[I].Pack; if (I = High( Tree.FLeaves )) then B := B or LAST_FLAG; BlockWrite( F , B , SizeOf( B ) ); end; for I := Low( Tree.FLeaves ) to High( Tree.FLeaves ) do if (Tree.FLeaves[I] <> nil) then PackTreeToFile( F , Tree.FLeaves[I] ); end; procedure TPack.PackTree( Dest : string ); var F : File; begin AssignFile( F , Dest ); Rewrite( F , 1 ); PackTreeToFile( F , FTree ); CloseFile( F ); end; //============================================================================== // P U B L I C //============================================================================== procedure TPack.Pack( Src, Dest : string ); begin CreateTree( Src ); PackTree( Dest ); end; end.
{覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧- 15-APR-2003 Gerard Vanderveken Ghia bvba - Added stateimages and data loaded from the database. Usage: * property StateImgIdxField = datbase (integer) field with selection for imagelist from property StateImages. * property DBDataFieldNames holds list of databasefieldnames (separated by ; ) These are put in a variant or variantarray at userdatarec.DBData. Works fine for normal data (numbers, dates, strings). Problems for int64. Don't overdue for memo's etc. To display the data: Add Header columns to the treeview (First column is reserved for the tree). Add an ongettext event like this: procedure TForm1.DBTreeview1GetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var CellData: Variant; Data: PDBNodeData; begin Data := TVirtualDBTreeEx(Sender).GetDBNodeData(Node); CellData := Data.DBData; case Column of // -1,0: // this is the tree, allready handled 1: // second column = first data begin if VarIsArray( CellData ) then // 1 or many fields begin CellText := CellData[0]; // select from array end else begin Celltext := Celldata; // one and only end; // Eventually format here as you like end; // 2: // etc end; end; Possible usefull ToDo's: * field properties selectable from dataset with adapted property editor * eventually autocreate columns as in dbgrid 02-JAN-2002 C.S. Phua - Modified from work of Vadim Sedulin and Adem Baba. Renamed all VirtualDBTree components to VirtualDBTreeEx to preserve the work previously done. Can't find a way to make it a descendant of VirtualDBTree though. - Changes made: * Changed integer type ID and Parent ID to type Double. This is done because integer type might not be enough to hold a hugh database's records. With Double type, one can store a number greater than zero (>0) up to 15 digits without the loss of accuracy in ID field. This gives more room to play with ID, for instance, I need to do this in ID:- xxxxxyyyyyyyyyy where xxxxx is site ID, yyyyyyyyyy is record ID of each site. Note: It still works with integer field as ID and ParentID even the codes expecting a Double field. * Added an ImgIdxFieldName property that can be assigned an integer field. When an ImageList is specified, it will take the ImageList's image as Icon of VirtualTree nodes by indexing it with the field specified in ImgIdxFieldName property. I need this feature to show different icons of treenodes, based on the type of treenodes, i.e. I have field ID, ParentID, NType in my database to form a tree. * Modified sorting options to enable OnCompareNodes event for custom sorting options. The original default sorting codes will be used if user does not supply OnCompareNodes event codes. * Changed the type name TSimpleData to TDBNodeData and move it to Interface section so that user who uses the method GetDBNodeData can type cast the pointer returned to TDBNodeData and access its member. Added an integer member named ImgIdx in the structure too. * Fixed the TreeOptions issue (finally). Now VirtualDBTreeEx user can play with settings in TreeOptions :) * Lastly, spent 10 minutes to produce new .dcr for VirtualDBTreeEx based on .dcr of VirtualDBTree. 22-OCT-2001 Vadim Sedulin - TBaseVirtualDBTree::GoTo TBaseVirtualDBTree.GoToRec - TBaseVirtualDBTree::Update TBaseVirtualDBTree.UpdateTree 23-OCT-2001 Adem Baba - I haven't done much other than to reorganize the code so that it is now one unit as oppsed to two units it originally was. I believe this is justifiable since this code is about 2,000 lines, there is, IMHO, no need to split them. Just look at VirtualTrees's line count --easily over 20,000 lines in a single unit. - I have removed all comments from the original code since they were Cyrillic, and they would have lost a lot in translation especially since I do not know Russian at all (I am only assuming they were Russian) :-) - I have renamed TSimpleVirtualDBTree to TVirtualDBTree. I believe it reflects its purpose better. - I have also merged the code in TCustomSimpleVirtualDBTree into TBaseVirtualDBTree; since everything else is derived from TBaseVirtualDBTree. - I got rid of TCheckDataLink, in favor of TVirtualDBTreeDataLink (which is renamed from TVTDataLink). There was no need for two descendants of TDataLink. - Finally, I have renamed the resultant file VirtualDBTree. Things to do: - Check to see if we really need these classes separately: TCustomCheckVirtualDBTree and TCheckVirtualDBTree. It looks as if they should be merged into a single class. - DCRs must be designed for - TVirtualDBTree, - TDBCheckVirtualDBTree, - TCheckVirtualDBTree - A demo. A demo is badly needed. I hope someone does come along and do it, as I am simply hopeless with those things. 覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧} Unit VirtualDBTreeEx; Interface Uses Windows, Classes, Controls, ActiveX, DB, Variants, VirtualTrees, ImgList; Type TDBVTOption = ( dboAllowChecking, dboAllowStructureChange, dboAlwaysStructured, dboCheckChildren, dboCheckDBStructure, dboListView, dboParentStructure, dboPathStructure, dboReadOnly, dboShowChecks, dboTrackActive, dboTrackChanges, dboTrackCursor, dboViewAll, dboWriteLevel, dboWriteSecondary ); TDBVTOptions = Set Of TDBVTOption; TDBVTStatus = ( dbtsChanged, dbtsChecking, dbtsDataChanging, dbtsDataOpening, dbtsDragDrop, dbtsEditing, dbtsEmpty, dbtsInsert, dbtsStructured, dbtsToggleAll ); TDBVTStatuses = Set Of TDBVTStatus; TDBVTChangeMode = ( dbcmEdit, dbcmInsert, dbcmStructure ); TDBVTGoToMode = ( gtmFromFirst, gtmNext, gtmPrev ); TDBVTNodeStatus = ( dbnsDelete, dbnsEdit, dbnsInited, dbnsNew, dbnsNone, dbnsRefreshed ); PDBVTData = ^TDBVTData; TDBVTData = Record ID: Double; Level: Integer; Status: TDBVTNodeStatus; Parent: PVirtualNode; End; TBaseVirtualDBTreeEx = Class; TVirtualDBTreeExDataLink = Class; TVTDBOpenQueryEvent = Procedure(Sender: TBaseVirtualDBTreeEx; Var Allow: Boolean) Of Object; TVTDBWriteQueryEvent = Procedure(Sender: TBaseVirtualDBTreeEx; Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode; Var Allow: Boolean) Of Object; TVTNodeDataChangedEvent = Procedure(Sender: TBaseVirtualDBTreeEx; Node: PVirtualNode; Field: TField; Var UpdateNode: Boolean) Of Object; TVTNodeFromDBEvent = Procedure(Sender: TBaseVirtualDBTreeEx; Node: PVirtualNode) Of Object; TVTPathToDBEvent = Procedure(Sender: TBaseVirtualDBTreeEx; Var Path: String) Of Object; TVirtualDBTreeExDataLink = Class(TDataLink) Private FVirtualDBTreeEx: TBaseVirtualDBTreeEx; Public Constructor Create(ATree: TBaseVirtualDBTreeEx); Virtual; Protected Procedure ActiveChanged; Override; Procedure DataSetChanged; Override; Procedure DataSetScrolled(Distance: Integer); Override; Procedure EditingChanged; Override; Procedure RecordChanged(Field: TField); Override; End; TBaseVirtualDBTreeEx = Class(TCustomVirtualStringTree) Private FCurID: Double; FDBDataSize: Integer; FDBOptions: TDBVTOptions; FDBStatus: TDBVTStatuses; FDataLink: TVirtualDBTreeExDataLink; FKeyField: TField; FKeyFieldName: String; FLevelField: TField; FLevelFieldName: String; FMaxLevel: Integer; FOnNodeDataChanged: TVTNodeDataChangedEvent; FOnOpeningDataSet: TVTDBOpenQueryEvent; FOnReadNodeFromDB: TVTNodeFromDBEvent; FOnReadPathFromDB: TVTPathToDBEvent; FOnWritePathToDB: TVTPathToDBEvent; FOnWritingDataSet: TVTDBWriteQueryEvent; FParentField: TField; FParentFieldName: String; FPathField: TField; FPathFieldName: String; FViewField: TField; FViewFieldName: String; FImgIdxField: TField; FImgIdxFieldName: String; FStImgIdxField: TField; FSTImgIdxFieldName: String; FDBDataFieldNames: String; Function GetDBNodeDataSize: Integer; Function GetDBOptions: TDBVTOptions; Function GetDBStatus: TDBVTStatuses; Function GetDataSource: TDataSource; Procedure RefreshListNode; Procedure RefreshNodeByParent; Procedure RefreshNodeByPath; Procedure SetDBNodeDataSize(Value: Integer); Procedure SetDBOptions(Value: TDBVTOptions); Procedure SetDataSource(Value: TDataSource); Procedure SetKeyFieldName(Const Value: String); Procedure SetLevelFieldName(Const Value: String); Procedure SetParentFieldName(Const Value: String); Procedure SetPathFieldName(Const Value: String); Procedure SetViewFieldName(Const Value: String); Procedure SetImgIdxFieldName(Const Value: String); Procedure SetStImgIdxFieldName(Const Value: String); Procedure SetDBDataFieldNames(Const Value: String); Protected Function CanEdit(Node: PVirtualNode; Column: TColumnIndex): Boolean; Override; Function CanOpenDataSet: Boolean; Virtual; Function CanWriteToDataSet(Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode): Boolean; Virtual; Function DoCancelEdit: Boolean; Override; Function DoChecking(Node: PVirtualNode; Var NewCheckState: TCheckState): Boolean; Override; Function DoEndEdit: Boolean; Override; Function FindChild(Node: PVirtualNode; ID: Double): PVirtualNode; Function FindNode(Start: PVirtualNode; ID: Double): PVirtualNode; Function HasVisibleChildren(Node: PVirtualNode): Boolean; Procedure DataLinkActiveChanged; Virtual; Procedure DataLinkChanged; Virtual; Procedure DataLinkEditingChanged; Virtual; Procedure DataLinkRecordChanged(Field: TField); Virtual; Procedure DataLinkScrolled; Virtual; Procedure DoChecked(Node: PVirtualNode); Override; Procedure DoCollapsed(Node: PVirtualNode); Override; Procedure DoDragDrop(Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; Var Effect: Integer; Mode: TDropMode); Override; Procedure DoEdit; Override; Procedure DoFocusChange(Node: PVirtualNode; Column: TColumnIndex); Override; Procedure DoFreeNode(Node: PVirtualNode); Override; Procedure DoInitNode(Parent, Node: PVirtualNode; Var InitStates: TVirtualNodeInitStates); Override; Procedure DoNodeDataChanged(Node: PVirtualNode; Field: TField; Var UpdateNode: Boolean); Virtual; Procedure DoNodeMoved(Node: PVirtualNode); Override; Procedure DoOpeningDataSet(Var Allow: Boolean); Virtual; Procedure DoReadNodeFromDB(Node: PVirtualNode); Virtual; Procedure DoReadPathFromDB(Var Path: String); Virtual; Procedure DoWritePathToDB(Var Path: String); Virtual; Procedure DoWritingDataSet(Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode; Var Allow: Boolean); Virtual; Procedure InitFields; Virtual; Procedure Notification(AComponent: TComponent; Operation: TOperation); Override; Procedure ReadNodeFromDB(Node: PVirtualNode); Virtual; Procedure RefreshNode; Virtual; Procedure RefreshNodes; Procedure ResetFields; Virtual; Procedure SetFocusToNode(Node: PVirtualNode); Procedure ToggleListView; Procedure ToggleViewMode; function GetOptions: TStringTreeOptions; procedure SetOptions(const Value: TStringTreeOptions); function GetOptionsClass: TTreeOptionsClass; override; function DoGetImageIndex(Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var Index: Integer):TCustomImageList; override; Public Constructor Create(Owner: TComponent); Override; Destructor Destroy; Override; Function GetDBNodeData(Node: PVirtualNode): Pointer; Function GoToRec(ID: Double): Boolean; Overload; Procedure AddNode(Parent: PVirtualNode); Procedure CheckAllChildren(Node: PVirtualNode); Procedure CollapseAll; Procedure DeleteSelection; Procedure ExpandAll; Procedure GoToRec(AString: WideString; Mode: TDBVTGoToMode); Overload; Procedure OnDragOverHandler(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; Var Effect: Integer; Var Accept: Boolean); Procedure UnCheckAll(Node: PVirtualNode; OnlyChildren: Boolean); Procedure UpdateTree; Property DBNodeDataSize: Integer Read GetDBNodeDataSize Write SetDBNodeDataSize; Property DBStatus: TDBVTStatuses Read GetDBStatus; Property KeyField: TField Read FKeyField; Property LevelField: TField Read FLevelField; Property OnNodeDataChanged: TVTNodeDataChangedEvent Read FOnNodeDataChanged Write FOnNodeDataChanged; Property OnReadNodeFromDB: TVTNodeFromDBEvent Read FOnReadNodeFromDB Write FOnReadNodeFromDB; Property ParentField: TField Read FParentField; Property PathField: TField Read FPathField; Property ViewField: TField Read FViewField; Property ImgIdxField: TField Read FImgIdxField; Property StateImgIdxField: TField Read FStImgIdxField; property Canvas; Published {Since all these properties are published for all descendants, we might as well publish them here and save whitespace} {$IFDEF COMPILER_5_UP} Property OnContextPopup; {$ENDIF COMPILER_5_UP} // property Action; Property Align; Property Alignment; Property Anchors; Property AnimationDuration; Property AutoExpandDelay; Property AutoScrollDelay; Property AutoScrollInterval; Property Background; Property BackgroundOffsetX; Property BackgroundOffsetY; Property BevelEdges; Property BevelInner; Property BevelKind; Property BevelOuter; Property BevelWidth; Property BiDiMode; Property BorderStyle; Property BorderWidth; Property ButtonFillMode; Property ButtonStyle; Property ChangeDelay; Property CheckImageKind; Property ClipboardFormats; Property Color; Property Colors; Property Constraints; Property Ctl3D; Property CustomCheckImages; Property DBOptions: TDBVTOptions Read GetDBOptions Write SetDBOptions; Property DataSource: TDataSource Read GetDataSource Write SetDataSource; Property DefaultNodeHeight; Property DefaultPasteMode; Property DefaultText; property DragCursor; Property DragHeight; Property DragImageKind; Property DragKind; Property DragMode; Property DragOperations; Property DragType; Property DragWidth; Property DrawSelectionMode; Property EditDelay; Property Enabled; Property Font; Property Header; Property HintAnimation; Property HintMode; Property HotCursor; Property Images; Property IncrementalSearch; Property IncrementalSearchDirection; Property IncrementalSearchStart; Property IncrementalSearchTimeout; Property Indent; Property KeyFieldName: String Read FKeyFieldName Write SetKeyFieldName; Property LevelFieldName: String Read FLevelFieldName Write SetLevelFieldName; Property LineMode; Property LineStyle; Property Margin; Property NodeAlignment; Property OnAfterCellPaint; Property OnAfterItemErase; Property OnAfterItemPaint; Property OnAfterPaint; Property OnBeforeCellPaint; Property OnBeforeItemErase; Property OnBeforeItemPaint; Property OnBeforePaint; Property OnChange; Property OnChecked; Property OnChecking; Property OnClick; Property OnCollapsed; Property OnCollapsing; Property OnColumnClick; Property OnColumnDblClick; Property OnColumnResize; Property OnCompareNodes; {$ifdef COMPILER_5_UP} property OnContextPopup; {$endif COMPILER_5_UP} Property OnCreateDataObject; Property OnCreateDragManager; Property OnCreateEditor; Property OnDblClick; Property OnDragAllowed; property OnDragOver; Property OnDragDrop; Property OnEditCancelled; Property OnEdited; Property OnEditing; Property OnEndDock; Property OnEndDrag; Property OnEnter; Property OnExit; Property OnExpanded; Property OnExpanding; Property OnFocusChanged; Property OnFocusChanging; Property OnFreeNode; property OnGetCursor; property OnGetHeaderCursor; Property OnGetHelpContext; Property OnGetHint; Property OnGetImageIndex; Property OnGetLineStyle; Property OnGetPopupMenu; Property OnGetText; Property OnGetUserClipboardFormats; Property OnHeaderClick; Property OnHeaderDblClick; Property OnHeaderDragged; Property OnHeaderDragging; Property OnHeaderDraw; Property OnHeaderMouseDown; Property OnHeaderMouseMove; Property OnHeaderMouseUp; Property OnHotChange; Property OnIncrementalSearch; Property OnInitNode; Property OnKeyAction; Property OnKeyDown; Property OnKeyPress; Property OnKeyUp; Property OnLoadNode; Property OnMouseDown; Property OnMouseMove; Property OnMouseUp; Property OnNewText; property OnNodeCopied; property OnNodeCopying; property OnNodeMoved; Property OnOpeningDataSet: TVTDBOpenQueryEvent Read FOnOpeningDataSet Write FOnOpeningDataSet; Property OnPaintBackground; Property OnPaintText; Property OnReadPathFromDB: TVTPathToDBEvent Read FOnReadPathFromDB Write FOnReadPathFromDB; Property OnRenderOLEData; Property OnResetNode; Property OnResize; Property OnSaveNode; Property OnScroll; Property OnShortenString; Property OnStartDock; Property OnStartDrag; property OnStructureChange; Property OnUpdating; Property OnWritePathToDB: TVTPathToDBEvent Read FOnWritePathToDB Write FOnWritePathToDB; Property OnWritingDataSet: TVTDBWriteQueryEvent Read FOnWritingDataSet Write FOnWritingDataSet; Property ParentBiDiMode; Property ParentColor Default False; Property ParentCtl3D; Property ParentFieldName: String Read FParentFieldName Write SetParentFieldName; Property ParentFont; Property ParentShowHint; Property PathFieldName: String Read FPathFieldName Write SetPathFieldName; Property PopupMenu; Property ScrollBarOptions; Property SelectionCurveRadius; Property ShowHint; Property StateImages; Property TabOrder; Property TabStop Default True; Property TextMargin; property TreeOptions: TStringTreeOptions read GetOptions write SetOptions; Property ViewFieldName: String Read FViewFieldName Write SetViewFieldName; Property ImgIdxFieldName: String Read FImgIdxFieldName Write SetImgIdxFieldName; Property StateImgIdxFieldName: String Read FStImgIdxFieldName Write SetStImgIdxFieldName; Property DBDataFieldNames: String Read FDBDataFieldNames Write SetDBDataFieldNames; Property Visible; Property WantTabs; End; TVirtualDBTreeEx = Class(TBaseVirtualDBTreeEx) Private Function GetNodeText(Node: PVirtualNode): WideString; Procedure SetNodeText(Node: PVirtualNode; Const Value: WideString); Protected Function DoCompare(Node1, Node2: PVirtualNode; Column: TColumnIndex): Integer; Override; Procedure DoGetText(Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; Var Text: WideString); Override; Procedure DoNewText(Node: PVirtualNode; Column: TColumnIndex; Text: WideString); Override; Procedure DoNodeDataChanged(Node: PVirtualNode; Field: TField; Var UpdateNode: Boolean); Override; Procedure DoReadNodeFromDB(Node: PVirtualNode); Override; Procedure DoWritingDataSet(Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode; Var Allow: Boolean); Override; Public Constructor Create(Owner: TComponent); Override; Property Canvas; Property NodeText[Node: PVirtualNode]: WideString Read GetNodeText Write SetNodeText; End; TCustomDBCheckVirtualDBTreeEx = Class(TBaseVirtualDBTreeEx) Private FCheckDataLink: TVirtualDBTreeExDataLink; FResultField: TField; FResultFieldName: String; Function GetCheckDataSource: TDataSource; Function GetCheckList: TStringList; Procedure SetCheckDataSource(Value: TDataSource); Procedure SetResultFieldName(Const Value: String); Protected Function DoChecking(Node: PVirtualNode; Var NewCheckState: TCheckState): Boolean; Override; Procedure CheckDataLinkActiveChanged; Virtual; Procedure DoChecked(Node: PVirtualNode); Override; Procedure DoOpeningDataSet(Var Allow: Boolean); Override; Procedure DoReadNodeFromDB(Node: PVirtualNode); Override; Procedure Notification(AComponent: TComponent; Operation: TOperation); Override; Public Constructor Create(Owner: TComponent); Override; Destructor Destroy; Override; Property CheckList: TStringList Read GetCheckList; Property ResultField: TField Read FResultField; Property CheckDataSource: TDataSource Read GetCheckDataSource Write SetCheckDataSource; Property ResultFieldName: String Read FResultFieldName Write SetResultFieldName; End; TDBCheckVirtualDBTreeEx = Class(TCustomDBCheckVirtualDBTreeEx) Private Function GetNodeText(Node: PVirtualNode): WideString; Procedure SetNodeText(Node: PVirtualNode; Const Value: WideString); Protected Function DoCompare(Node1, Node2: PVirtualNode; Column: TColumnIndex): Integer; Override; Procedure DoGetText(Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; Var Text: WideString); Override; Procedure DoNewText(Node: PVirtualNode; Column: TColumnIndex; Text: WideString); Override; Procedure DoNodeDataChanged(Node: PVirtualNode; Field: TField; Var UpdateNode: Boolean); Override; Procedure DoReadNodeFromDB(Node: PVirtualNode); Override; Procedure DoWritingDataSet(Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode; Var Allow: Boolean); Override; Public Constructor Create(Owner: TComponent); Override; Property Canvas; Property NodeText[Node: PVirtualNode]: WideString Read GetNodeText Write SetNodeText; Published Property CheckDataSource; Property ResultFieldName; End; TCustomCheckVirtualDBTreeEx = Class(TBaseVirtualDBTreeEx) Private FList: TStringList; Function GetCheckList: TStrings; Procedure SetCheckList(Value: TStrings); Protected Procedure DoChecked(Node: PVirtualNode); Override; Procedure DoReadNodeFromDB(Node: PVirtualNode); Override; Public Constructor Create(Owner: TComponent); Override; Destructor Destroy; Override; Property CheckList: TStrings Read GetCheckList Write SetCheckList; End; TCheckVirtualDBTreeEx = Class(TCustomCheckVirtualDBTreeEx) Private Function GetNodeText(Node: PVirtualNode): WideString; Procedure SetNodeText(Node: PVirtualNode; Const Value: WideString); Protected Function DoCompare(Node1, Node2: PVirtualNode; Column: TColumnIndex): Integer; Override; Procedure DoGetText(Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; Var Text: WideString); Override; Procedure DoNewText(Node: PVirtualNode; Column: TColumnIndex; Text: WideString); Override; Procedure DoNodeDataChanged(Node: PVirtualNode; Field: TField; Var UpdateNode: Boolean); Override; Procedure DoReadNodeFromDB(Node: PVirtualNode); Override; Procedure DoWritingDataSet(Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode; Var Allow: Boolean); Override; Public Constructor Create(Owner: TComponent); Override; Property Canvas; Property NodeText[Node: PVirtualNode]: WideString Read GetNodeText Write SetNodeText; End; Procedure Register; Type TDBNodeData = Record Text: WideString; ImgIdx: Integer; StImgIdx: Integer; DBData: Variant; End; PDBNodeData = ^TDBNodeData; Implementation Uses SysUtils, Math; Procedure Register; Begin RegisterComponents('Virtual Controls', [TVirtualDBTreeEx, TDBCheckVirtualDBTreeEx, TCheckVirtualDBTreeEx]); End; Type THackedTreeOptions = Class(TCustomVirtualTreeOptions); {------------------------------------------------------------------------------} Constructor TVirtualDBTreeExDataLink.Create(ATree: TBaseVirtualDBTreeEx); Begin Inherited Create; FVirtualDBTreeEx := ATree; End; Procedure TVirtualDBTreeExDataLink.ActiveChanged; Begin FVirtualDBTreeEx.DataLinkActiveChanged; End; Procedure TVirtualDBTreeExDataLink.DataSetScrolled(Distance: Integer); Begin FVirtualDBTreeEx.DataLinkScrolled; End; Procedure TVirtualDBTreeExDataLink.DataSetChanged; Begin FVirtualDBTreeEx.DataLinkChanged; End; Procedure TVirtualDBTreeExDataLink.RecordChanged(Field: TField); Begin FVirtualDBTreeEx.DataLinkRecordChanged(Field); End; Procedure TVirtualDBTreeExDataLink.EditingChanged; Begin FVirtualDBTreeEx.DataLinkEditingChanged; End; {------------------------------------------------------------------------------} Constructor TBaseVirtualDBTreeEx.Create(Owner: TComponent); Begin Inherited; FDataLink := TVirtualDBTreeExDataLink.Create(Self); FDBDataSize := sizeof(TDBVTData); NodeDataSize := FDBDataSize; FDBOptions := [dboCheckDBStructure, dboParentStructure, dboWriteLevel, dboWriteSecondary, dboTrackActive, dboTrackChanges, dboTrackCursor, dboAlwaysStructured, dboViewAll]; OnDragOver := OnDragOverHandler; with TStringTreeOptions(inherited TreeOptions) do begin PaintOptions := PaintOptions + [toShowHorzGridLines,toShowTreeLines, toShowVertGridLines,toShowRoot]; MiscOptions := MiscOptions + [toGridExtensions]; end; End; Destructor TBaseVirtualDBTreeEx.Destroy; Begin FDataLink.Free; Inherited; End; Procedure TBaseVirtualDBTreeEx.SetDataSource(Value: TDataSource); Begin FDataLink.DataSource := Value; If Assigned(Value) Then Value.FreeNotification(Self); End; Function TBaseVirtualDBTreeEx.GetDataSource: TDataSource; Begin Result := FDataLink.DataSource; End; Procedure TBaseVirtualDBTreeEx.Notification(AComponent: TComponent; Operation: TOperation); Begin Inherited; If (Operation = opRemove) And Assigned(FDataLink) And (AComponent = DataSource) Then DataSource := Nil; End; Procedure TBaseVirtualDBTreeEx.SetKeyFieldName(Const Value: String); Begin If FKeyFieldName <> Value Then Begin FKeyFieldName := Value; If dboTrackActive In FDBOptions Then DataLinkActiveChanged Else Begin FDBStatus := FDBStatus + [dbtsChanged]; FKeyField := Nil; If FDataLink.Active And (FKeyFieldName <> '') Then FKeyField := FDataLink.DataSet.FieldByName(FPathFieldName); End; End; End; Procedure TBaseVirtualDBTreeEx.SetParentFieldName(Const Value: String); Begin If (FParentFieldName <> Value) Then Begin FParentFieldName := Value; FParentField := Nil; If (dboParentStructure In FDBOptions) And (dboTrackActive In FDBOptions) Then Begin If Not (dboListView In FDBOptions) Then DataLinkActiveChanged Else If (dboAlwaysStructured In FDBOptions) Then DataLinkActiveChanged Else Begin FDBStatus := FDBStatus + [dbtsStructured]; If FDataLink.Active And (FParentFieldName <> '') Then FParentField := FDataLink.DataSet.FieldByName(FParentFieldName); End; End Else Begin If Not (dboTrackActive In FDBOptions) Then FDBStatus := FDBStatus + [dbtsChanged]; If FDataLink.Active And (FParentFieldName <> '') Then FParentField := FDataLink.DataSet.FieldByName(FParentFieldName); End; End; End; Procedure TBaseVirtualDBTreeEx.SetPathFieldName(Const Value: String); Begin If (FPathFieldName <> Value) Then Begin FPathFieldName := Value; FPathField := Nil; If (dboPathStructure In FDBOptions) And (dboTrackActive In FDBOptions) Then Begin If Not (dboListView In FDBOptions) Then DataLinkActiveChanged Else If (dboAlwaysStructured In FDBOptions) Then DataLinkActiveChanged Else Begin FDBStatus := FDBStatus + [dbtsStructured]; If FDataLink.Active And (FPathFieldName <> '') Then FPathField := FDataLink.DataSet.FieldByName(FPathFieldName); End; End Else Begin If Not (dboTrackActive In FDBOptions) Then FDBStatus := FDBStatus + [dbtsChanged]; If FDataLink.Active And (FPathFieldName <> '') Then FPathField := FDataLink.DataSet.FieldByName(FPathFieldName); End; End; End; Procedure TBaseVirtualDBTreeEx.SetLevelFieldName(Const Value: String); Begin If (FLevelFieldName <> Value) Then Begin FLevelFieldName := Value; FLevelField := Nil; If FDataLink.Active And (FLevelFieldName <> '') Then FLevelField := FDataLink.DataSet.FieldByName(FLevelFieldName); End; End; Procedure TBaseVirtualDBTreeEx.DataLinkActiveChanged; Begin If Not (csDesigning In ComponentState) Then Begin ResetFields; If (dboTrackActive In FDBOptions) Then Begin If FDataLink.Active Then InitFields; UpdateTree; End Else FDBStatus := FDBStatus + [dbtsChanged]; End; End; Procedure TBaseVirtualDBTreeEx.DataLinkScrolled; Var KeyID: Double; Begin If Not (csDesigning In ComponentState) Then Begin If Assigned(FKeyField) And Not (dbtsDataChanging In FDBStatus) And (dboTrackCursor In FDBOptions) Then Begin FDBStatus := FDBStatus + [dbtsDataChanging]; KeyID := FKeyField.AsFloat; If (KeyID <> 0.0) And (KeyID <> FCurID) Then SetFocusToNode(FindNode(Nil, KeyID)); FDBStatus := FDBStatus - [dbtsDataChanging]; If Not Assigned(FocusedNode) Then SetFocusToNode(GetFirst); End; End; End; Procedure TBaseVirtualDBTreeEx.DataLinkChanged; Begin If Not (csDesigning In ComponentState) Then Begin If Not FDataLink.Editing And Not (dbtsDataChanging In FDBStatus) Then Begin If (dboTrackChanges In FDBOptions) Then RefreshNodes Else FDBStatus := FDBStatus + [dbtsChanged]; End; End; End; Procedure TBaseVirtualDBTreeEx.DataLinkRecordChanged(Field: TField); Var UpdateField: Boolean; Node: PVirtualNode; Begin If Not (csDesigning In ComponentState) Then Begin If Assigned(Field) And (dboTrackChanges In FDBOptions) Then Begin UpdateField := False; If dboTrackCursor In FDBOptions Then Node := FocusedNode Else Node := FindNode(Nil, FKeyField.AsFloat); If Assigned(Node) Then Begin DoNodeDataChanged(Node, Field, UpdateField); If UpdateField Then InvalidateNode(Node); End; End; End; End; Procedure TBaseVirtualDBTreeEx.DataLinkEditingChanged; Var Data: PDBVTData; Node: PVirtualNode; Begin If Not (csDesigning In ComponentState) Then Begin If FDataLink.Editing And Not (dbtsEditing In FDBStatus) And Not (dbtsInsert In FDBStatus) Then Begin If dboTrackChanges In FDBOptions Then Begin If (dboTrackCursor In FDBOptions) And (FDataLink.DataSet.State = dsEdit) Then Begin If Assigned(FocusedNode) And (dboTrackCursor In FDBOptions) Then Begin Data := GetNodeData(FocusedNode); Data.Status := dbnsEdit; End; End Else If FDataLink.DataSet.State = dsInsert Then Begin Node := AddChild(Nil); ValidateNode(Node, False); Data := GetNodeData(Node); Data.ID := 0.0; Data.Level := 0; Data.Parent := Nil; Data.Status := dbnsInited; ReadNodeFromDB(Node); Data.Status := dbnsNew; If (dboTrackCursor In FDBOptions) Then SetFocusToNode(Node); End; End Else FDBStatus := FDBStatus + [dbtsChanged]; End; If Assigned(FocusedNode) And (dboTrackChanges In FDBOptions) And (dboTrackCursor In FDBOptions) Then InvalidateNode(FocusedNode); End; End; Procedure TBaseVirtualDBTreeEx.DoFocusChange(Node: PVirtualNode; Column: TColumnIndex); Var Data: PDBVTData; Begin If Assigned(Node) Then Begin Data := GetNodeData(Node); If Data.ID <> FCurID Then Begin FCurID := Data.ID; If (FCurID <> 0.0) And Not (dbtsDataChanging In FDBStatus) And (dboTrackCursor In FDBOptions) Then Begin FDBStatus := FDBStatus + [dbtsDataChanging]; FDataLink.DataSet.Locate(FKeyFieldName, Data.ID, []); FDBStatus := FDBStatus - [dbtsDataChanging]; End; End; End; Inherited; End; Function TBaseVirtualDBTreeEx.CanEdit(Node: PVirtualNode; Column: TColumnIndex): Boolean; Begin If Not (dbtsEditing In FDBStatus) And Not (dbtsInsert In FDBStatus) Then Result := CanWriteToDataSet(Node, Column, dbcmEdit) Else Result := True; End; Procedure TBaseVirtualDBTreeEx.DoEdit; Var Data: PDBVTData; Begin Inherited; If IsEditing Then Begin Data := GetNodeData(FocusedNode); If Data.Status = dbnsEdit Then FDBStatus := FDBStatus + [dbtsEditing] Else If Data.Status = dbnsNew Then FDBStatus := FDBStatus + [dbtsInsert] Else If Not (dbtsInsert In FDBStatus) Then Begin FDBStatus := FDBStatus + [dbtsEditing]; FDataLink.DataSet.Edit; End; End; End; Function TBaseVirtualDBTreeEx.DoEndEdit: Boolean; Var Data: PDBVTData; Begin Result := Inherited DoEndEdit; If Result Then Begin Data := GetNodeData(FocusedNode); Data.Status := dbnsRefreshed; If (dbtsEditing In FDBStatus) Then Begin FDBStatus := FDBStatus - [dbtsEditing] + [dbtsDataChanging]; If FDataLink.Editing Then FDataLink.DataSet.Post; FDBStatus := FDBStatus - [dbtsDataChanging]; End Else If (dbtsInsert In FDBStatus) Then Begin FDBStatus := FDBStatus - [dbtsInsert] + [dbtsDataChanging]; If FDataLink.Editing Then FDataLink.DataSet.Post; FDBStatus := FDBStatus - [dbtsDataChanging]; Data.ID := FKeyField.AsFloat; FCurID := Data.ID; End; End; End; Function TBaseVirtualDBTreeEx.DoCancelEdit: Boolean; Var Data: PDBVTData; Begin If dbtsInsert In FDBStatus Then Begin FDBStatus := FDBStatus - [dbtsInsert] + [dbtsDataChanging]; If FDataLink.Editing Then FDataLink.DataSet.Cancel; FDBStatus := FDBStatus - [dbtsDataChanging]; Result := Inherited DoCancelEdit; DeleteNode(FocusedNode); DataLinkScrolled; Exit; End Else If (dbtsEditing In FDBStatus) Then Begin FDBStatus := FDBStatus - [dbtsEditing] + [dbtsDataChanging]; If FDataLink.Editing Then FDataLink.DataSet.Cancel; FDBStatus := FDBStatus - [dbtsDataChanging]; Data := GetNodeData(FocusedNode); Data.Status := dbnsRefreshed; End; Result := Inherited DoCancelEdit; End; Procedure TBaseVirtualDBTreeEx.DoCollapsed(Node: PVirtualNode); Var Focus: PVirtualNode; Begin If Assigned(Node) Then Begin If Assigned(FocusedNode) And HasAsParent(FocusedNode, Node) Then Begin Focus := Node; If Not Selected[Focus] Then Begin Focus := GetNextSibling(Node); While Assigned(Focus) And Not Selected[Focus] Do Focus := GetNextVisible(Focus); If Not Assigned(Focus) Then Begin Focus := GetPreviousVisible(Node); While Assigned(Focus) And Not Selected[Focus] Do Focus := GetPreviousVisible(Focus); If Not Assigned(Focus) Then Focus := Node; End; End; FocusedNode := Focus; Selected[Focus] := True; End; Focus := GetNextSibling(Node); If Not Assigned(Focus) Then Begin Focus := GetLastChild(Node); If Not Assigned(Focus) Then Focus := Node; Focus := GetNext(Focus); End; Node := GetNext(Node); While Node <> Focus Do Begin Selected[Node] := False; Node := GetNext(Node); End; End; Inherited; End; Procedure TBaseVirtualDBTreeEx.DoDragDrop(Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; Var Effect: Integer; Mode: TDropMode); Var CanProcess: Boolean; Focus: PVirtualNode; Begin Effect := DROPEFFECT_MOVE; If CanWriteToDataSet(DropTargetNode, 0, dbcmStructure) Then Begin CanProcess := True; If CanProcess Then Begin Focus := FocusedNode; BeginUpdate; FDataLink.DataSet.DisableControls; FDBStatus := FDBStatus + [dbtsDataChanging, dbtsDragDrop]; ProcessDrop(DataObject, DropTargetNode, Effect, amAddChildLast); Effect := DROPEFFECT_LINK; FocusedNode := Nil; EndUpdate; FDataLink.DataSet.EnableControls; FDBStatus := FDBStatus - [dbtsDataChanging, dbtsDragDrop]; FCurID := 0.0; FocusedNode := Focus; End Else Effect := DROPEFFECT_NONE; End Else Effect := DROPEFFECT_NONE; Inherited; End; Procedure TBaseVirtualDBTreeEx.OnDragOverHandler(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; Var Effect: Integer; Var Accept: Boolean); Begin Accept := CanWriteToDataSet(DropTargetNode, 0, dbcmStructure); End; Procedure TBaseVirtualDBTreeEx.DoNodeMoved(Node: PVirtualNode); Var Data: PDBVTData; Path: String; Parent: PVirtualNode; ParentID: Double; Level: Integer; Begin If (dbtsDragDrop In FDBStatus) Then Begin ParentID := 0.0; Level := 0; Parent := Node.Parent; If Parent <> RootNode Then Begin Data := GetNodeData(Parent); Level := Data.Level + 1; ParentID := Data.ID; If (dboPathStructure In FDBOptions) Or (dboWriteSecondary In FDBOptions) Then Begin Path := FloatToStr(ParentID); Parent := Parent.Parent; While Parent <> RootNode Do Begin Data := GetNodeData(Parent); Path := Format('%1.0f.%s', [Data.ID, Path]); Parent := Parent.Parent; End; End; End; Data := GetNodeData(Node); Data.Level := Level; FDataLink.DataSet.Locate(FKeyFieldName, Data.ID, []); FDataLink.DataSet.Edit; If (dboPathStructure In FDBOptions) Or (dboWriteSecondary In FDBOptions) Then Begin DoWritePathToDB(Path); FPathField.AsString := Path; End; If (dboParentStructure In FDBOptions) Or (dboWriteSecondary In FDBOptions) Then Begin FParentField.AsFloat := ParentID; End; If (dboWriteLevel In FDBOptions) Then Begin FLevelField.AsInteger := Level; End; FDataLink.DataSet.Post; Inherited; Node := GetFirstChild(Node); While Assigned(Node) Do Begin DoNodeMoved(Node); Node := GetNextSibling(Node); End; End; End; Procedure TBaseVirtualDBTreeEx.DoFreeNode(Node: PVirtualNode); Var Data: PDBVTData; Begin Data := GetNodeData(Node); If (Data.Status = dbnsDelete) Then Begin If FDataLink.DataSet.Locate(FKeyFieldName, Data.ID, []) Then FDataLink.DataSet.Delete; End; Inherited; End; Procedure TBaseVirtualDBTreeEx.SetFocusToNode(Node: PVirtualNode); Begin If Assigned(FocusedNode) Then Selected[FocusedNode] := False; FocusedNode := Node; If Assigned(Node) Then Begin Selected[Node] := True; FullyVisible[Node] := True; End; End; Function TBaseVirtualDBTreeEx.FindChild(Node: PVirtualNode; ID: Double): PVirtualNode; Var Data: PDBVTData; Begin Result := GetFirstChild(Node); While Assigned(Result) Do Begin Data := GetNodeData(Result); If Data.ID = ID Then break; Result := GetNextSibling(Result); End; End; Function TBaseVirtualDBTreeEx.FindNode(Start: PVirtualNode; ID: Double): PVirtualNode; Var Data: PDBVTData; Begin If Assigned(Start) Then Result := Start Else Result := GetFirst; While Assigned(Result) Do Begin Data := GetNodeData(Result); If Data.ID = ID Then break; Result := GetNext(Result); End; End; Procedure TBaseVirtualDBTreeEx.GoToRec(AString: WideString; Mode: TDBVTGoToMode); Var Text: WideString; Node: PVirtualNode; Column: TColumnIndex; Begin EndEditNode; Column := Header.MainColumn; Case Mode Of gtmFromFirst: Begin Node := GetFirst; Mode := gtmNext; End; gtmNext: Node := GetNext(FocusedNode); gtmPrev: Node := GetPrevious(FocusedNode); Else Node := Nil; End; While Assigned(Node) Do Begin DoGetText(Node, Column, ttNormal, Text); If Pos(AString, Text) = 1 Then break; If Mode = gtmNext Then Node := GetNext(Node) Else Node := GetPrevious(Node); End; If Assigned(Node) Then SetFocusToNode(Node); End; Function TBaseVirtualDBTreeEx.GoToRec(ID: Double): Boolean; Var Node: PVirtualNode; Begin Node := FindNode(Nil, ID); If Assigned(Node) Then SetFocusToNode(Node); Result := Node <> Nil; End; Procedure TBaseVirtualDBTreeEx.AddNode(Parent: PVirtualNode); Var Level: Integer; ParentID: Double; Path: String; Node: PVirtualNode; Data: PDBVTData; Begin EndEditNode; If CanWriteToDataSet(Parent, 0, dbcmInsert) Then Begin FDBStatus := FDBStatus + [dbtsDataChanging]; Node := AddChild(Parent); If (Parent = Nil) Or (Parent = RootNode) Then Begin Level := 0; ParentID := 0.0; Path := ''; End Else Begin Data := GetNodeData(Parent); Level := Data.Level + 1; ParentID := Data.ID; If (dboPathStructure In FDBOptions) Or (dboWriteSecondary In FDBOptions) Then Begin Path := FloatToStr(ParentID); Parent := Parent.Parent; While Parent <> RootNode Do Begin Data := GetNodeData(Parent); Path := Format('%1.0f.%s', [Data.ID, Path]); Parent := Parent.Parent; End; End; End; Data := GetNodeData(Node); Data.ID := 0.0; Data.Level := Level; Data.Parent := Nil; FDBStatus := FDBStatus + [dbtsInsert]; FDataLink.DataSet.Insert; If Not (dboListView In FDBOptions) Then Begin If (dboPathStructure In FDBOptions) Or (dboWriteSecondary In FDBOptions) Then Begin DoWritePathToDB(Path); FPathField.AsString := Path; End; If (dboParentStructure In FDBOptions) Or (dboWriteSecondary In FDBOptions) Then FParentField.AsFloat := ParentID; If (dboWriteLevel In FDBOptions) Then FLevelField.AsInteger := Level; End; DoReadNodeFromDB(Node); FCurID := 0.0; SetFocusToNode(Node); FDBStatus := FDBStatus - [dbtsDataChanging]; EditNode(Node, Header.MainColumn); End; End; Procedure TBaseVirtualDBTreeEx.DeleteSelection; Var Data: PDBVTData; Node: PVirtualNode; Temp: PVirtualNode; Last: PVirtualNode; Focus: PVirtualNode; Begin If Not (dbtsDataChanging In FDBStatus) And Assigned(FocusedNode) And (SelectedCount > 0) And Not (dboReadOnly In FDBOptions) And FDataLink.Active And Assigned(FKeyField) And Not FDataLink.ReadOnly Then Begin Node := GetFirst; Focus := FocusedNode; While Selected[Focus.Parent] Do Focus := Focus.Parent; Temp := Focus; Repeat Focus := GetNextSibling(Focus); Until Not Assigned(Focus) Or Not Selected[Focus]; If Not Assigned(Focus) Then Begin Focus := Temp; Repeat Focus := GetPreviousSibling(Focus); Until Not Assigned(Focus) Or Not Selected[Focus]; If Not Assigned(Focus) Then Focus := Temp.Parent; If Focus = RootNode Then Focus := Nil; End; FDBStatus := FDBStatus + [dbtsDataChanging]; BeginUpdate; FDataLink.DataSet.DisableControls; While Assigned(Node) Do Begin If Selected[Node] Then Begin Temp := Node; Last := GetNextSibling(Node); Repeat Data := GetNodeData(Temp); Data.Status := dbnsDelete; Temp := GetNext(Temp); Until Temp = Last; If Not Assigned(Temp) And (Node.Parent <> RootNode) Then Temp := GetNextSibling(Node.Parent); DeleteNode(Node); Node := Temp; End Else Node := GetNextVisible(Node); End; FDataLink.DataSet.EnableControls; EndUpdate; FDBStatus := FDBStatus - [dbtsDataChanging]; If Assigned(Focus) And (Focus <> RootNode) Then SetFocusToNode(Focus); End; End; Function TBaseVirtualDBTreeEx.GetDBNodeData(Node: PVirtualNode): Pointer; Begin If Not Assigned(Node) Or (DBNodeDataSize = 0) Then Result := Nil Else Result := PChar(GetNodeData(Node)) + FDBDataSize; End; Procedure TBaseVirtualDBTreeEx.RefreshNodes; Var Data: PDBVTData; Node: PVirtualNode; Temp: PVirtualNode; I: Integer; Begin If Not (dbtsDataChanging In FDBStatus) And CanOpenDataSet Then Begin FDBStatus := FDBStatus + [dbtsDataChanging]; BeginUpdate; FMaxLevel := 0; FCurID := 0.0; If (dboAlwaysStructured In FDBOptions) Then Begin If Not (dbtsStructured In FDBStatus) Then Clear Else If (dboListView In FDBOptions) Then Begin FDBOptions := FDBOptions - [dboListView]; ToggleListView; FDBOptions := FDBOptions + [dboListView]; End; FDBStatus := FDBStatus + [dbtsStructured]; End Else Begin If (dboListView In FDBOptions) Then FDBStatus := FDBStatus - [dbtsStructured] Else Begin If Not (dbtsStructured In FDBStatus) Then Clear; FDBStatus := FDBStatus + [dbtsStructured]; End; End; Temp := GetFirst; If Not Assigned(Temp) Then FDBStatus := FDBStatus + [dbtsEmpty]; While Assigned(Temp) Do Begin Data := GetNodeData(Temp); If Data.Status = dbnsRefreshed Then Data.Status := dbnsNone; Temp := GetNext(Temp); End; FDataLink.DataSet.DisableControls; If Not FDataLink.DataSet.EOF Or Not FDataLink.DataSet.Bof Then FCurID := FKeyField.AsFloat; I := 0; While Not FDataLink.DataSet.EOF Do Begin RefreshNode; FDataLink.DataSet.Next; Inc(I); End; If (I > 0) Then FDataLink.DataSet.MoveBy(-I); I := 0; While Not (FDataLink.DataSet.Bof) Do Begin RefreshNode; FDataLink.DataSet.Prior; Inc(I); End; If (I > 0) Then FDataLink.DataSet.MoveBy(I); If (dboTrackCursor In FDBOptions) And Assigned(FocusedNode) Then Begin Selected[FocusedNode] := False; FocusedNode := Nil; End; Temp := GetFirst; While Assigned(Temp) Do Begin Data := GetNodeData(Temp); If (Data.Status <> dbnsRefreshed) Then Begin Node := GetNextSibling(Temp); DeleteNode(Temp); End Else Begin If (dbtsStructured In FDBStatus) And (dboParentStructure In FDBOptions) Then Begin Data.Level := GetNodeLevel(Temp); FMaxLevel := Max(FMaxLevel, Data.Level); End; If (dboTrackCursor In FDBOptions) And Not Assigned(FocusedNode) And (Data.ID = FCurID) Then Begin Selected[Temp] := True; FocusedNode := Temp; FullyVisible[Temp] := True; End; Node := GetNext(Temp); End; Temp := Node; End; FDataLink.DataSet.EnableControls; FDBStatus := FDBStatus - [dbtsDataChanging, dbtsChanged, dbtsEmpty]; If (dboAlwaysStructured In FDBOptions) And (dboListView In FDBOptions) Then ToggleListView; If Not (dboListView In FDBOptions) And Not (dboViewAll In FDBOptions) And Not (dbtsToggleAll In FDBStatus) Then ToggleViewMode; EndUpdate; End; End; Procedure TBaseVirtualDBTreeEx.RefreshNode; Begin If Not (dbtsStructured In FDBStatus) Then RefreshListNode Else If (dboPathStructure In FDBOptions) Then RefreshNodeByPath Else RefreshNodeByParent End; Procedure TBaseVirtualDBTreeEx.RefreshListNode; Var Data: PDBVTData; Node: PVirtualNode; ID: Double; Begin ID := FKeyField.AsFloat; If dbtsEmpty In FDBStatus Then Node := Nil Else Node := FindChild(Nil, ID); If Not Assigned(Node) Then Begin Node := AddChild(Nil); ValidateNode(Node, False); Data := GetNodeData(Node); Data.ID := ID; Data.Parent := Nil; Data.Status := dbnsInited; End; ReadNodeFromDB(Node); End; Procedure TBaseVirtualDBTreeEx.RefreshNodeByPath; Var Pos: Integer; ID: Double; Level: Integer; Node: PVirtualNode; Last: PVirtualNode; Data: PDBVTData; Temp: String; Path: String; Begin Data := Nil; Path := FPathField.AsString; Last := RootNode; DoReadPathFromDB(Path); Temp := FloatToStr(FKeyField.AsFloat); If Path = '' Then Path := Temp Else Path := Format('%s.%s', [Path, Temp]); Repeat Node := Last; Pos := System.Pos('.', Path); If (Pos = 0) Then Begin Temp := Path; Pos := Length(Path); End Else Temp := Copy(Path, 1, Pos - 1); Try ID := StrToFloat(Temp); Last := FindChild(Node, ID); Except Exit; End; If Assigned(Last) Then Delete(Path, 1, Pos); Until Not Assigned(Last) Or (Path = ''); If Path = '' Then Begin Node := Last; Data := GetNodeData(Node); End Else Begin If (Node = RootNode) Then Level := -1 Else Begin Data := GetNodeData(Node); Level := Data.Level; End; Repeat Pos := System.Pos('.', Path); If (Pos = 0) Then Begin Temp := Path; Pos := Length(Path); End Else Temp := Copy(Path, 1, Pos - 1); Try ID := StrToFloat(Temp); Node := AddChild(Node); ValidateNode(Node, False); Data := GetNodeData(Node); Inc(Level); Data.ID := ID; Data.Level := Level; Data.Status := dbnsInited; Data.Parent := Nil; Delete(Path, 1, Pos); Except Exit; End; Until Path = ''; End; If Data <> Nil Then FMaxLevel := Max(FMaxLevel, Data.Level); If Node <> Nil Then ReadNodeFromDB(Node); End; Procedure TBaseVirtualDBTreeEx.RefreshNodeByParent; Var ID: Double; ParentID: Double; Data: PDBVTData; This: PVirtualNode; Parent: PVirtualNode; Temp: PVirtualNode; Created: Boolean; Begin ID := FKeyField.AsFloat; ParentID := FParentField.AsFloat; If (ID = 0.0) Then Begin Exit; End; This := Nil; Parent := Nil; Temp := GetFirst; If (ParentID = 0.0) Or (ParentID = ID) Then Begin Parent := RootNode; ParentID := 0.0; End; While Assigned(Temp) And (Not Assigned(This) Or Not Assigned(Parent)) Do Begin Data := GetNodeData(Temp); If (Data.ID = ID) Then Begin If (Data.Status = dbnsRefreshed) Then Begin Exit; End; This := Temp; End; If (Data.ID = ParentID) And (ParentID <> 0.0) Then Parent := Temp; Temp := GetNext(Temp); End; If Not Assigned(Parent) Then Begin Parent := AddChild(Nil); ValidateNode(Parent, False); Data := GetNodeData(Parent); Data.ID := ParentID; Data.Status := dbnsInited; Data.Parent := Nil; End; Created := True; If Assigned(This) Then Begin If (This.Parent <> Parent) Then Begin If HasAsParent(Parent, This) Then Begin Data := GetNodeData(Parent); If (Data.Status = dbnsRefreshed) Then Begin Exit; End; Temp := This; This := Parent; Parent := Temp; Data := GetNodeData(Parent); Data.ID := ParentID; End Else Begin MoveTo(This, Parent, amAddChildLast, False); End; End; End Else Begin Created := False; This := AddChild(Parent); ValidateNode(This, False); End; Data := GetNodeData(This); Data.ID := ID; If Not Created Then Data.Status := dbnsInited; ReadNodeFromDB(This); End; Procedure TBaseVirtualDBTreeEx.UpdateTree; Begin Clear; RefreshNodes; End; Procedure TBaseVirtualDBTreeEx.ToggleListView; Var Data: PDBVTData; Node: PVirtualNode; Temp: PVirtualNode; Begin If dbtsDragDrop In FDBStatus Then Exit; BeginUpdate; If (dboListView In FDBOptions) Then Begin Node := GetFirst; While Assigned(Node) Do Begin Data := GetNodeData(Node); If (Node.Parent <> RootNode) Then Begin Data.Parent := Node.Parent; Temp := GetNextSibling(Node); If Not Assigned(Temp) Then Begin Temp := GetLastChild(Node); If Assigned(Temp) Then Begin Temp := GetNext(Temp); If Not Assigned(Temp) Then Temp := GetNext(Node); End Else Temp := GetNext(Node); End; MoveTo(Node, RootNode, amAddChildLast, False); Node := Temp; End Else Node := GetNext(Node); End; If Not (dboViewAll In FDBOptions) Then ToggleViewMode; End Else Begin Node := GetFirst; While Assigned(Node) Do Begin Data := GetNodeData(Node); If Data.Parent <> Nil Then Begin Temp := GetNextSibling(Node); MoveTo(Node, Data.Parent, amAddChildLast, False); Data.Parent := Nil; Node := Temp; End Else Node := GetNextSibling(Node); End; If Not (dboViewAll In FDBOptions) Then Begin FDBStatus := FDBStatus + [dbtsToggleAll]; ToggleViewMode; FDBStatus := FDBStatus - [dbtsToggleAll]; End; End; If Assigned(FocusedNode) Then FullyVisible[FocusedNode] := True; EndUpdate; End; Procedure TBaseVirtualDBTreeEx.ResetFields; Begin FKeyField := Nil; FParentField := Nil; FPathField := Nil; FLevelField := Nil; FViewField := Nil; FImgIdxField := Nil; FStImgIdxField := Nil; End; Procedure TBaseVirtualDBTreeEx.InitFields; var Pos: Integer; Field: TField; Begin If (FKeyFieldName <> '') Then FKeyField := FDataLink.DataSet.FieldByName(FKeyFieldName); If (FParentFieldName <> '') Then FParentField := FDataLink.DataSet.FieldByName(FParentFieldName); If (FPathFieldName <> '') Then FPathField := FDataLink.DataSet.FieldByName(FPathFieldName); If (FLevelFieldName <> '') Then FLevelField := FDataLink.DataSet.FieldByName(FLevelFieldName); If FViewFieldName <> '' Then FViewField := DataSource.DataSet.FieldByName(FViewFieldName); If FImgIdxFieldName <> '' Then FImgIdxField := DataSource.DataSet.FieldByName(FImgIdxFieldName); If FStImgIdxFieldName <> '' Then FStImgIdxField := DataSource.DataSet.FieldByName(FStImgIdxFieldName); If FDBDataFieldNames <> '' Then begin Pos := 1; while Pos <= Length(FDBDataFieldNames) do begin // just checking existence Field := DataSource.DataSet.FieldByName(ExtractFieldName(DBDataFieldNames, Pos)); end; end; End; Procedure TBaseVirtualDBTreeEx.SetDBNodeDataSize(Value: Integer); Begin If (Value <> DBNodeDataSize) And (Value >= 0) Then Begin NodeDataSize := FDBDataSize + Value; UpdateTree; End; End; Function TBaseVirtualDBTreeEx.GetDBNodeDataSize: Integer; Begin Result := NodeDataSize - FDBDataSize; End; Function TBaseVirtualDBTreeEx.GetDBStatus: TDBVTStatuses; Begin Result := FDBStatus; End; Function TBaseVirtualDBTreeEx.GetDBOptions: TDBVTOptions; Begin Result := FDBOptions; End; Procedure TBaseVirtualDBTreeEx.SetDBOptions(Value: TDBVTOptions); Var ToBeSet, ToBeCleared: TDBVTOptions; Begin EndEditNode; ToBeSet := Value - FDBOptions; ToBeCleared := FDBOptions - Value; FDBOptions := Value; If (dboTrackCursor In ToBeSet) Then Begin If Not (dboTrackActive In FDBOptions) Or Not (dboTrackChanges In FDBOptions) Then Begin FDBOptions := FDBOptions + [dboTrackActive, dboTrackChanges]; FDBOptions := FDBOptions - [dboAllowChecking]; If (dbtsChanged In FDBStatus) Then DataLinkActiveChanged; End Else DataLinkScrolled; End Else If (dboTrackChanges In ToBeSet) Then Begin If Not (dboTrackActive In FDBOptions) Then FDBOptions := FDBOptions + [dboTrackActive]; If dbtsChanged In FDBStatus Then DataLinkActiveChanged; End Else If dboTrackActive In ToBeSet Then Begin If dbtsChanged In FDBStatus Then DataLinkActiveChanged; End Else If dboTrackActive In ToBeCleared Then Begin FDBOptions := FDBOptions - [dboTrackCursor, dboTrackChanges]; FDBOptions := FDBOptions + [dboReadOnly]; End Else If dboTrackChanges In ToBeCleared Then Begin FDBOptions := FDBOptions - [dboTrackCursor]; FDBOptions := FDBOptions + [dboReadOnly]; End Else If dboTrackCursor In ToBeCleared Then FDBOptions := FDBOptions + [dboReadOnly]; If dboShowChecks In ToBeSet Then Begin If dboTrackCursor In FDBOptions Then Begin FDBOptions := FDBOptions - [dboShowChecks]; FDBOptions := FDBOptions + [dboViewAll]; End Else Begin BeginUpdate; THackedTreeOptions(TreeOptions).MiscOptions := THackedTreeOptions(TreeOptions).MiscOptions + [toCheckSupport]; If Not (dboViewAll In FDBOptions) Then ToggleViewMode; EndUpdate; End; End Else If dboShowChecks In ToBeCleared Then Begin BeginUpdate; THackedTreeOptions(TreeOptions).MiscOptions := THackedTreeOptions(TreeOptions).MiscOptions - [toCheckSupport]; If Not (dboViewAll In FDBOptions) Then Begin FDBOptions := FDBOptions + [dboViewAll]; RefreshNodes; End; EndUpdate; End Else If dboViewAll In ToBeSet Then Begin If dboShowChecks In FDBOptions Then ToggleViewMode; End Else If dboViewAll In ToBeCleared Then Begin If dboShowChecks In FDBOptions Then ToggleViewMode Else FDBOptions := FDBOptions + [dboViewAll]; End; If dboPathStructure In ToBeSet Then Begin FDBOptions := FDBOptions - [dboParentStructure]; If dboTrackActive In FDBOptions Then UpdateTree; End Else If dboParentStructure In ToBeSet Then Begin FDBOptions := FDBOptions - [dboPathStructure]; If dboTrackActive In FDBOptions Then UpdateTree; End Else If dboPathStructure In ToBeCleared Then Begin FDBOptions := FDBOptions + [dboParentStructure]; If dboTrackActive In FDBOptions Then UpdateTree; End Else If dboParentStructure In ToBeCleared Then Begin FDBOptions := FDBOptions + [dboPathStructure]; If dboTrackActive In FDBOptions Then UpdateTree; End; If dboAlwaysStructured In ToBeSet Then Begin If Not (dbtsStructured In FDBStatus) Then RefreshNodes; End Else If dboAlwaysStructured In ToBeCleared Then Begin If dboShowChecks In FDBOptions Then FDBOptions := FDBOptions + [dboAlwaysStructured]; End; If dboListView In ToBeSet Then ToggleListView Else If dboListView In ToBeCleared Then Begin If dbtsStructured In FDBStatus Then ToggleListView Else RefreshNodes; End; If (dboReadOnly In ToBeCleared) And (Not (dboTrackCursor In FDBOptions) Or Not (dboTrackChanges In FDBOptions) Or Not (dboTrackActive In FDBOptions)) Then FDBOptions := FDBOptions + [dboReadOnly]; End; Function TBaseVirtualDBTreeEx.CanOpenDataSet: Boolean; Begin Result := (FKeyField <> Nil); If Result And (Not (dboListView In FDBOptions) Or (dboAlwaysStructured In FDBOptions)) Then Result := ((dboPathStructure In FDBOptions) And Assigned(FPathField)) Or ((dboParentStructure In FDBOptions) And Assigned(FParentField)); If Result Then DoOpeningDataSet(Result); End; Procedure TBaseVirtualDBTreeEx.DoOpeningDataSet(Var Allow: Boolean); Begin Allow := (FViewField <> Nil); If Allow Then Begin If Assigned(FOnOpeningDataSet) Then FOnOpeningDataSet(Self, Allow); End; End; Procedure TBaseVirtualDBTreeEx.DoNodeDataChanged(Node: PVirtualNode; Field: TField; Var UpdateNode: Boolean); Begin If Assigned(FOnNodeDataChanged) Then FOnNodeDataChanged(Self, Node, Field, UpdateNode); End; Procedure TBaseVirtualDBTreeEx.DoReadPathFromDB(Var Path: String); Begin If Assigned(FOnReadPathFromDB) Then FOnReadPathFromDB(Self, Path); End; Procedure TBaseVirtualDBTreeEx.DoWritePathToDB(Var Path: String); Begin If Assigned(FOnWritePathToDB) Then FOnWritePathToDB(Self, Path); End; Procedure TBaseVirtualDBTreeEx.ReadNodeFromDB(Node: PVirtualNode); Var Data: PDBVTData; Begin Data := GetNodeData(Node); If (Data.Status <> dbnsNone) And (Data.Status <> dbnsRefreshed) Then DoReadNodeFromDB(Node); Data.Status := dbnsRefreshed; End; Procedure TBaseVirtualDBTreeEx.DoReadNodeFromDB(Node: PVirtualNode); Begin If Assigned(FOnReadNodeFromDB) Then FOnReadNodeFromDB(Self, Node); End; Function TBaseVirtualDBTreeEx.CanWriteToDataSet(Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode): Boolean; Begin Result := Not (dboReadOnly In FDBOptions) And Assigned(FKeyField) And FDataLink.DataSet.CanModify; If Result Then Begin If dboListView In DBOptions Then Begin If (ChangeMode = dbcmStructure) Or (ChangeMode = dbcmInsert) Then Result := (Node = Nil) Or (Node = RootNode); End Else If (ChangeMode = dbcmStructure) Or (ChangeMode = dbcmInsert) Then Begin Result := (((dboPathStructure In FDBOptions) Or (dboWriteSecondary In FDBOptions)) And Assigned(FPathField) And FPathField.CanModify) Or (((dboParentStructure In FDBOptions) Or (dboWriteSecondary In FDBOptions)) And Assigned(FParentField) And FParentField.CanModify); If Result And (dboWriteLevel In FDBOptions) Then Result := Assigned(FLevelField) And FLevelField.CanModify; End; If Result Then DoWritingDataSet(Node, Column, ChangeMode, Result); End; End; Procedure TBaseVirtualDBTreeEx.DoWritingDataSet(Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode; Var Allow: Boolean); Begin If (ChangeMode = dbcmEdit) And (Column = Header.MainColumn) Then Allow := FViewField.CanModify; If Allow Then Begin If Assigned(FOnWritingDataSet) Then FOnWritingDataSet(Self, Node, Column, ChangeMode, Allow); End; End; Function TBaseVirtualDBTreeEx.DoChecking(Node: PVirtualNode; Var NewCheckState: TCheckState): Boolean; Begin If dbtsDataChanging In FDBStatus Then Result := True Else If (dboShowChecks In FDBOptions) And (dboAllowChecking In FDBOptions) Then Result := Inherited DoChecking(Node, NewCheckState) Else Result := False; End; Procedure TBaseVirtualDBTreeEx.DoChecked(Node: PVirtualNode); Begin If Not (dbtsDataChanging In FDBStatus) Then Begin BeginUpdate; If CheckState[Node] = csCheckedNormal Then Begin If dboCheckChildren In FDBOptions Then CheckAllChildren(Node); End Else If Not (dboViewAll In FDBOptions) Then ToggleViewMode; If Not (dbtsChecking In FDBStatus) And (dboPathStructure In FDBOptions) Then RefreshNodes; EndUpdate; Inherited; End; End; Procedure TBaseVirtualDBTreeEx.CheckAllChildren(Node: PVirtualNode); Begin If (dboShowChecks In FDBOptions) And (dboAllowChecking In FDBOptions) Then Begin FDBStatus := FDBStatus + [dbtsChecking]; Node := GetFirstChild(Node); While Assigned(Node) Do Begin CheckState[Node] := csCheckedNormal; Node := GetNextSibling(Node); End; FDBStatus := FDBStatus - [dbtsChecking]; End; End; Procedure TBaseVirtualDBTreeEx.UnCheckAll(Node: PVirtualNode; OnlyChildren: Boolean); Var Changed: Boolean; Last: PVirtualNode; Begin If (dboShowChecks In FDBOptions) And (dboAllowChecking In FDBOptions) Then Begin Changed := False; Last := GetNextSibling(Node); If Not Assigned(Last) Then Begin Last := GetLastChild(Node); If Not Assigned(Last) Then Last := Node; Last := GetNext(Last); End; If OnlyChildren Then Node := GetNext(Node); While Node <> Last Do Begin If CheckState[Node] <> csUncheckedNormal Then Begin CheckState[Node] := csUncheckedNormal; If CheckState[Node] = csUncheckedNormal Then Changed := True; End; End; If Changed Then ToggleViewMode; End; End; Procedure TBaseVirtualDBTreeEx.DoInitNode(Parent: PVirtualNode; Node: PVirtualNode; Var InitStates: TVirtualNodeInitStates); Begin Inherited; Node.CheckType := ctCheckBox; Node.CheckState := csUncheckedNormal; End; Procedure TBaseVirtualDBTreeEx.ToggleViewMode; Var Node: PVirtualNode; Begin If Not (dbtsDataChanging In FDBStatus) And (dboShowChecks In FDBOptions) Then Begin BeginUpdate; If dboViewAll In FDBOptions Then RefreshNodes() Else Begin If dbtsToggleAll In FDBStatus Then RefreshNodes; Node := GetLastChild(RootNode); While Assigned(Node) And (Node <> RootNode) Do Begin If (CheckState[Node] <> csCheckedNormal) And Not Assigned(GetFirstChild(Node)) Then Begin DeleteNode(Node); If dboListView In FDBOptions Then FDBStatus := FDBStatus - [dbtsStructured]; End; Node := GetPrevious(Node); End; End; EndUpdate; End; End; Function TBaseVirtualDBTreeEx.HasVisibleChildren(Node: PVirtualNode): Boolean; Var Last: PVirtualNode; Begin Result := False; If Assigned(Node) Then Begin Last := GetNextSibling(Node); If Not Assigned(Last) Then Begin Last := GetLastChild(Node); If Not Assigned(Last) Then Last := Node; Last := GetNext(Last); End; Node := GetNext(Node); While Node <> Last Do Begin If IsVisible[Node] Then Begin Result := True; Break; End; Node := GetNext(Node); End; End; End; Procedure TBaseVirtualDBTreeEx.ExpandAll; Var Node: PVirtualNode; Begin Node := GetFirst; BeginUpdate; While Assigned(Node) Do Begin Expanded[Node] := True; Node := GetNext(Node); End; EndUpdate; End; Procedure TBaseVirtualDBTreeEx.CollapseAll; Var Node: PVirtualNode; Begin Node := GetFirst; BeginUpdate; While Assigned(Node) Do Begin Expanded[Node] := False; Node := GetNext(Node); End; EndUpdate; End; Procedure TBaseVirtualDBTreeEx.SetViewFieldName(Const Value: String); Begin If FViewFieldName <> Value Then Begin FViewField := Nil; FViewFieldName := Value; DataLinkActiveChanged; End; End; Procedure TBaseVirtualDBTreeEx.SetImgIdxFieldName(Const Value: String); Begin If FImgIdxFieldName <> Value Then Begin FImgIdxField := Nil; FImgIdxFieldName := Value; DataLinkActiveChanged; End; End; Procedure TBaseVirtualDBTreeEx.SetStImgIdxFieldName(Const Value: String); Begin If FStImgIdxFieldName <> Value Then Begin FStImgIdxField := Nil; FStImgIdxFieldName := Value; DataLinkActiveChanged; End; End; Procedure TBaseVirtualDBTreeEx.SetDBDataFieldNames(Const Value: String); Begin If FDBDataFieldNames <> Value Then Begin FDBDataFieldNames := Value; DataLinkActiveChanged; End; End; function TBaseVirtualDBTreeEx.GetOptions: TStringTreeOptions; begin Result := TStringTreeOptions(inherited TreeOptions); end; procedure TBaseVirtualDBTreeEx.SetOptions(const Value: TStringTreeOptions); begin inherited TreeOptions := Value; end; function TBaseVirtualDBTreeEx.GetOptionsClass: TTreeOptionsClass; begin Result := TStringTreeOptions; end; function TBaseVirtualDBTreeEx.DoGetImageIndex(Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var Index: Integer):TCustomImageList; begin Result:=inherited DoGetImageIndex(Node, Kind, Column, Ghosted, Index); if (Column = Header.MainColumn) then begin if (Kind = ikNormal) or (Kind = ikSelected) then Index := PDBNodeData(GetDBNodeData(Node)).ImgIdx; end; if (Column = Header.MainColumn) then begin if (Kind = ikState) then Index := PDBNodeData(GetDBNodeData(Node)).StImgIdx; end; if Assigned(OnGetImageIndex) then OnGetImageIndex(self, Node, Kind, Column, Ghosted, Index); end; {------------------------------------------------------------------------------} Constructor TVirtualDBTreeEx.Create(Owner: TComponent); Begin Inherited; DBNodeDataSize := sizeof(TDBNodeData); End; Procedure TVirtualDBTreeEx.DoReadNodeFromDB(Node: PVirtualNode); var Data: PDBNodeData; Begin NodeText[Node] := ViewField.AsString; Data := PDBNodeData(GetDBNodeData(Node)); if DBDataFieldNames <> '' then Data.DBData := DataSource.DataSet.FieldValues[FDBDataFieldNames] else Data.DBData :=Null; if ImgIdxField <> nil then Data.ImgIdx := ImgIdxField.AsInteger else Data.ImgIdx := -1; if StateImgIdxField <> nil then Data.StImgIdx := StateImgIdxField.AsInteger else Data.StImgIdx := -1; End; Procedure TVirtualDBTreeEx.DoNodeDataChanged(Node: PVirtualNode; Field: TField; Var UpdateNode: Boolean); var Data: PDBNodeData; Begin If Field = ViewField Then Begin NodeText[Node] := Field.AsString; UpdateNode := True; End else if (Field = ImgIdxField) then begin Data := PDBNodeData(GetDBNodeData(Node)); Data.ImgIdx := Field.AsInteger; UpdateNode := true; End else if (Field = StateImgIdxField) then begin Data := PDBNodeData(GetDBNodeData(Node)); Data.StImgIdx := Field.AsInteger; UpdateNode := true; end; End; Procedure TVirtualDBTreeEx.DoGetText(Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; Var Text: WideString); Begin If Assigned(Node) And (Node <> RootNode) Then Begin If (Column = Header.MainColumn) And (TextType = ttNormal) Then Text := NodeText[Node] Else Inherited; End; End; Procedure TVirtualDBTreeEx.DoNewText(Node: PVirtualNode; Column: TColumnIndex; Text: WideString); Begin If Column = Header.MainColumn Then ViewField.AsString := Text; End; Procedure TVirtualDBTreeEx.DoWritingDataSet(Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode; Var Allow: Boolean); Begin If ChangeMode = dbcmEdit Then Begin If Column = Header.MainColumn Then Inherited Else Allow := False; End; End; Function TVirtualDBTreeEx.DoCompare(Node1, Node2: PVirtualNode; Column: TColumnIndex): Integer; Begin Result := 0; if Assigned(OnCompareNodes) then OnCompareNodes(Self, Node1, Node2, Column, Result) else begin If Column = Header.MainColumn Then begin If NodeText[Node1] > NodeText[Node2] Then Result := 1 Else Result := -1 end; end; End; Procedure TVirtualDBTreeEx.SetNodeText(Node: PVirtualNode; Const Value: WideString); Begin If Assigned(Node) Then PDBNodeData(GetDBNodeData(Node)).Text := Value; End; Function TVirtualDBTreeEx.GetNodeText(Node: PVirtualNode): WideString; Begin If Assigned(Node) Then Result := PDBNodeData(GetDBNodeData(Node)).Text; End; {------------------------------------------------------------------------------} Constructor TCustomDBCheckVirtualDBTreeEx.Create(Owner: TComponent); Begin Inherited; FCheckDataLink := TVirtualDBTreeExDataLink.Create(Self); DBOptions := DBOptions - [dboTrackChanges]; DBOptions := DBOptions + [dboShowChecks, dboAllowChecking]; FResultField := Nil; End; Destructor TCustomDBCheckVirtualDBTreeEx.Destroy; Begin FCheckDataLink.Free; Inherited; End; Procedure TCustomDBCheckVirtualDBTreeEx.CheckDataLinkActiveChanged; Begin If Not (csDesigning In ComponentState) Then Begin FResultField := Nil; If FCheckDataLink.Active Then Begin If FResultFieldName <> '' Then FResultField := FCheckDataLink.DataSet.FieldByName(FResultFieldName); End; UpdateTree; End; End; Procedure TCustomDBCheckVirtualDBTreeEx.DoOpeningDataSet(Var Allow: Boolean); Begin If Assigned(FResultField) Then Inherited Else Allow := False; End; Procedure TCustomDBCheckVirtualDBTreeEx.SetCheckDataSource(Value: TDataSource); Begin FCheckDataLink.DataSource := Value; If Assigned(Value) Then Value.FreeNotification(Self); End; Function TCustomDBCheckVirtualDBTreeEx.GetCheckDataSource: TDataSource; Begin Result := FCheckDataLink.DataSource; End; Procedure TCustomDBCheckVirtualDBTreeEx.Notification(AComponent: TComponent; Operation: TOperation); Begin Inherited; If (Operation = opRemove) And Assigned(FCheckDataLink) And (AComponent = CheckDataSource) Then CheckDataSource := Nil; End; Procedure TCustomDBCheckVirtualDBTreeEx.SetResultFieldName(Const Value: String); Begin If FResultFieldName <> Value Then Begin FResultFieldName := Value; CheckDataLinkActiveChanged; End; End; Function TCustomDBCheckVirtualDBTreeEx.DoChecking(Node: PVirtualNode; Var NewCheckState: TCheckState): Boolean; Begin If dbtsDataChanging In DBStatus Then Result := Inherited DoChecking(Node, NewCheckState) Else If Assigned(FResultField) And FResultField.CanModify Then Result := Inherited DoChecking(Node, NewCheckState) Else Result := False; End; Procedure TCustomDBCheckVirtualDBTreeEx.DoChecked(Node: PVirtualNode); Var Data: PDBVTData; Begin If Not (dbtsDataChanging In DBStatus) Then Begin Data := GetNodeData(Node); If CheckState[Node] = csCheckedNormal Then Begin FCheckDataLink.DataSet.Insert; FResultField.AsFloat := Data.ID; FCheckDataLink.DataSet.Post; End Else If FCheckDataLink.DataSet.Locate(FResultFieldName, Data.ID, []) Then FCheckDataLink.DataSet.Delete; End; Inherited; End; Procedure TCustomDBCheckVirtualDBTreeEx.DoReadNodeFromDB(Node: PVirtualNode); Var Data: PDBVTData; Begin Inherited; Data := GetNodeData(Node); If FCheckDataLink.DataSet.Locate(FResultFieldName, Data.ID, []) Then CheckState[Node] := csCheckedNormal Else CheckState[Node] := csUncheckedNormal; End; {------------------------------------------------------------------------------} Constructor TDBCheckVirtualDBTreeEx.Create(Owner: TComponent); Begin Inherited; DBNodeDataSize := sizeof(TDBNodeData); End; Procedure TDBCheckVirtualDBTreeEx.DoReadNodeFromDB(Node: PVirtualNode); var Data: PDBNodeData; Begin NodeText[Node] := ViewField.AsString; Data := PDBNodeData(GetDBNodeData(Node)); if ImgIdxField <> nil then Data.ImgIdx := ImgIdxField.AsInteger else Data.ImgIdx := -1; if StateImgIdxField <> nil then Data.StImgIdx := StateImgIdxField.AsInteger else Data.StImgIdx := -1; Inherited; End; Procedure TDBCheckVirtualDBTreeEx.DoNodeDataChanged(Node: PVirtualNode; Field: TField; Var UpdateNode: Boolean); var Data: PDBNodeData; Begin If Field = ViewField Then Begin NodeText[Node] := Field.AsString; UpdateNode := True; End else if Field = ImgIdxField then begin Data := PDBNodeData(GetDBNodeData(Node)); Data.ImgIdx := Field.AsInteger; UpdateNode := True; End else if Field = StateImgIdxField then begin Data := PDBNodeData(GetDBNodeData(Node)); Data.StImgIdx := Field.AsInteger; UpdateNode := True; end; End; Procedure TDBCheckVirtualDBTreeEx.DoGetText(Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; Var Text: WideString); Begin If Assigned(Node) And (Node <> RootNode) Then Begin If (Column = Header.MainColumn) And (TextType = ttNormal) Then Text := NodeText[Node] Else Inherited; End; End; Procedure TDBCheckVirtualDBTreeEx.DoNewText(Node: PVirtualNode; Column: TColumnIndex; Text: WideString); Begin If Column = Header.MainColumn Then ViewField.AsString := Text; End; Procedure TDBCheckVirtualDBTreeEx.DoWritingDataSet(Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode; Var Allow: Boolean); Begin If ChangeMode = dbcmEdit Then Begin If Column = Header.MainColumn Then Inherited Else Allow := False; End; End; Function TDBCheckVirtualDBTreeEx.DoCompare(Node1, Node2: PVirtualNode; Column: TColumnIndex): Integer; Begin // If Column = Header.MainColumn Then If NodeText[Node1] > NodeText[Node2] Then Result := 1 // Else Result := -1 // Else Result := 0; Result := 0; if Assigned(OnCompareNodes) then OnCompareNodes(Self, Node1, Node2, Column, Result) else begin If Column = Header.MainColumn Then begin If NodeText[Node1] > NodeText[Node2] Then Result := 1 Else Result := -1 end; end; End; Procedure TDBCheckVirtualDBTreeEx.SetNodeText(Node: PVirtualNode; Const Value: WideString); Begin If Assigned(Node) Then PDBNodeData(GetDBNodeData(Node)).Text := Value; End; Function TDBCheckVirtualDBTreeEx.GetNodeText(Node: PVirtualNode): WideString; Begin If Assigned(Node) Then Result := PDBNodeData(GetDBNodeData(Node)).Text; End; {------------------------------------------------------------------------------} Constructor TCustomCheckVirtualDBTreeEx.Create(Owner: TComponent); Begin Inherited; FList := TStringList.Create; FList.Sorted := True; DBOptions := DBOptions - [dboTrackChanges]; DBOptions := DBOptions + [dboShowChecks, dboAllowChecking]; End; Destructor TCustomCheckVirtualDBTreeEx.Destroy; Begin FList.Free; Inherited; End; Function TCustomCheckVirtualDBTreeEx.GetCheckList: TStrings; Begin Result := TStringList.Create; Result.Assign(FList); End; Procedure TCustomCheckVirtualDBTreeEx.SetCheckList(Value: TStrings); Begin FList.Assign(Value); UpdateTree; End; Procedure TCustomCheckVirtualDBTreeEx.DoChecked(Node: PVirtualNode); Var Data: PDBVTData; Index: Integer; Begin If Not (dbtsDataChanging In DBStatus) Then Begin Data := GetNodeData(Node); If CheckState[Node] = csCheckedNormal Then FList.Add(FloatToStr(Data.ID)) Else Begin Index := FList.IndexOf(FloatToStr(Data.ID)); If Index <> -1 Then FList.Delete(Index); End; End; Inherited; End; Procedure TCustomCheckVirtualDBTreeEx.DoReadNodeFromDB(Node: PVirtualNode); Var Data: PDBVTData; Index: Integer; Begin Inherited; Data := GetNodeData(Node); If FList.Find(FloatToStr(Data.ID), Index) Then CheckState[Node] := csCheckedNormal Else CheckState[Node] := csUncheckedNormal; End; {------------------------------------------------------------------------------} Constructor TCheckVirtualDBTreeEx.Create(Owner: TComponent); Begin Inherited; DBNodeDataSize := sizeof(TDBNodeData); End; Procedure TCheckVirtualDBTreeEx.DoReadNodeFromDB(Node: PVirtualNode); var Data: PDBNodeData; Begin NodeText[Node] := ViewField.AsString; Data := PDBNodeData(GetDBNodeData(Node)); if ImgIdxField <> nil then Data.ImgIdx := ImgIdxField.AsInteger else Data.ImgIdx := -1; if StateImgIdxField <> nil then Data.StImgIdx := StateImgIdxField.AsInteger else Data.StImgIdx := -1; Inherited; End; Procedure TCheckVirtualDBTreeEx.DoNodeDataChanged(Node: PVirtualNode; Field: TField; Var UpdateNode: Boolean); var Data: PDBNodeData; Begin If Field = ViewField Then Begin NodeText[Node] := Field.AsString; UpdateNode := True; End else if Field = ImgIdxField then begin Data := PDBNodeData(GetDBNodeData(Node)); Data.ImgIdx := Field.AsInteger; UpdateNode := True; End else if Field = StateImgIdxField then begin Data := PDBNodeData(GetDBNodeData(Node)); Data.StImgIdx := Field.AsInteger; UpdateNode := True; end; End; Procedure TCheckVirtualDBTreeEx.DoGetText(Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; Var Text: WideString); Begin If Assigned(Node) And (Node <> RootNode) Then Begin If (Column = Header.MainColumn) And (TextType = ttNormal) Then Text := NodeText[Node] Else Inherited; End; End; Procedure TCheckVirtualDBTreeEx.DoNewText(Node: PVirtualNode; Column: TColumnIndex; Text: WideString); Begin If Column = Header.MainColumn Then ViewField.AsString := Text; End; Procedure TCheckVirtualDBTreeEx.DoWritingDataSet(Node: PVirtualNode; Column: TColumnIndex; ChangeMode: TDBVTChangeMode; Var Allow: Boolean); Begin If ChangeMode = dbcmEdit Then Begin If Column = Header.MainColumn Then Inherited Else Allow := False; End; End; Function TCheckVirtualDBTreeEx.DoCompare(Node1, Node2: PVirtualNode; Column: TColumnIndex): Integer; Begin // If Column = Header.MainColumn Then If NodeText[Node1] > NodeText[Node2] Then Result := 1 // Else Result := -1 // Else Result := 0; Result := 0; if Assigned(OnCompareNodes) then OnCompareNodes(Self, Node1, Node2, Column, Result) else begin If Column = Header.MainColumn Then begin If NodeText[Node1] > NodeText[Node2] Then Result := 1 Else Result := -1 end; end; End; Procedure TCheckVirtualDBTreeEx.SetNodeText(Node: PVirtualNode; Const Value: WideString); Begin If Assigned(Node) Then PDBNodeData(GetDBNodeData(Node)).Text := Value; End; Function TCheckVirtualDBTreeEx.GetNodeText(Node: PVirtualNode): WideString; Begin Result := ''; If Assigned(Node) And (Node <> RootNode) Then Result := PDBNodeData(GetDBNodeData(Node)).Text; End; Function TCustomDBCheckVirtualDBTreeEx.GetCheckList: TStringList; Var Data: PDBVTData; Node: PVirtualNode; Begin Result := TStringList.Create; Node := GetFirst; While Assigned(Node) Do Begin Data := GetNodeData(Node); If CheckState[Node] = csCheckedNormal Then Result.Add(FloatToStr(Data.ID)); Node := GetNext(Node); End; End; End. 
unit MainFrm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.DateTimeCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.ListBox, FMX.Effects, FMX.Objects, FMX.Layouts, FMX.Colors; type TFormMain = class(TForm) EditToastMessage: TEdit; Button1: TButton; ComboBoxDurationType: TComboBox; ListBoxItem1: TListBoxItem; ShadowEffect1: TShadowEffect; ListBoxItem2: TListBoxItem; Image1: TImage; SwitchShowIcon: TSwitch; ListBox1: TListBox; ListBoxItem3: TListBoxItem; ListBoxGroupHeader1: TListBoxGroupHeader; ListBoxItem4: TListBoxItem; ListBoxGroupHeader2: TListBoxGroupHeader; ListBoxItem5: TListBoxItem; ListBoxItem6: TListBoxItem; ListBoxGroupHeader3: TListBoxGroupHeader; ListBoxItem7: TListBoxItem; ListBoxItem8: TListBoxItem; Button2: TButton; ShadowEffect2: TShadowEffect; ColorComboBoxMessage: TComboColorBox; ColorComboBoxBackground: TComboColorBox; Button3: TButton; Image2: TImage; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.fmx} uses FGX.Toasts, FGX.Graphics; procedure TFormMain.Button1Click(Sender: TObject); begin TfgToast.Show(EditToastMessage.Text, TfgToastDuration(ComboBoxDurationType.ItemIndex)); end; procedure TFormMain.Button2Click(Sender: TObject); var Toast: TfgToast; begin Toast := TfgToast.Create(EditToastMessage.Text, TfgToastDuration(ComboBoxDurationType.ItemIndex)); try if SwitchShowIcon.IsChecked then Toast.Icon.Assign(Image1.Bitmap); Toast.MessageColor := ColorComboBoxMessage.Color; Toast.BackgroundColor := ColorComboBoxBackground.Color; Toast.Show; finally Toast.Free; end; end; procedure TFormMain.Button3Click(Sender: TObject); begin ColorComboBoxBackground.Color := $FF2A2A2A; ColorComboBoxMessage.Color := TAlphaColorRec.White; end; end.
unit Rx.Observable.Map; interface uses Rx, Rx.Subjects, Rx.Implementations, SyncObjs, Generics.Collections; type TMap<X, Y> = class(TObservableImpl<X>, IObservable<Y>) strict private FRoutine: Rx.TMap<X, Y>; FRoutineStatic: Rx.TMapStatic<X, Y>; FDest: TPublishSubject<Y>; procedure OnDestSubscribe(Subscriber: IObserver<Y>); protected function RoutineDecorator(const Data: X): Y; dynamic; public constructor Create(Source: IObservable<X>; const Routine: Rx.TMap<X, Y>); constructor CreateStatic(Source: IObservable<X>; const Routine: Rx.TMapStatic<X, Y>); destructor Destroy; override; function Subscribe(const OnNext: TOnNext<Y>): ISubscription; overload; function Subscribe(const OnNext: TOnNext<Y>; const OnError: TOnError): ISubscription; overload; function Subscribe(const OnNext: TOnNext<Y>; const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription; overload; function Subscribe(const OnNext: TOnNext<Y>; const OnCompleted: TOnCompleted): ISubscription; overload; function Subscribe(const OnError: TOnError): ISubscription; overload; function Subscribe(const OnCompleted: TOnCompleted): ISubscription; overload; function Subscribe(A: ISubscriber<Y>): ISubscription; overload; procedure OnNext(const Data: Y); reintroduce; overload; procedure OnNext(const Data: X); overload; override; procedure OnError(E: IThrowable); override; procedure OnCompleted; override; end; TOnceSubscriber<X, Y> = class(TInterfacedObject, ISubscriber<X>) protected FRoutine: Rx.TMap<X, Y>; FRoutineStatic: Rx.TMapStatic<X, Y>; FSource: IObserver<Y>; public constructor Create(Source: IObserver<Y>; const Routine: Rx.TMap<X, Y>; const RoutineStatic: Rx.TMapStatic<X, Y>); destructor Destroy; override; procedure OnNext(const A: X); dynamic; procedure OnError(E: IThrowable); procedure OnCompleted; procedure Unsubscribe; function IsUnsubscribed: Boolean; procedure SetProducer(P: IProducer); end; implementation { TMap<X, Y> } constructor TMap<X, Y>.Create(Source: IObservable<X>; const Routine: Rx.TMap<X, Y>); begin inherited Create; FDest := TPublishSubject<Y>.Create(OnDestSubscribe); inherited Merge(Source); FRoutine := Routine; end; constructor TMap<X, Y>.CreateStatic(Source: IObservable<X>; const Routine: Rx.TMapStatic<X, Y>); begin inherited Create; FDest := TPublishSubject<Y>.Create(OnDestSubscribe); inherited Merge(Source); FRoutineStatic := Routine; end; destructor TMap<X, Y>.Destroy; begin FDest.Free; inherited; end; procedure TMap<X, Y>.OnCompleted; begin FDest.OnCompleted; end; procedure TMap<X, Y>.OnDestSubscribe(Subscriber: IObserver<Y>); var Decorator: ISubscriber<X>; begin // In case when Source is initialized by generator-base function manner // let it to run once Decorator := TOnceSubscriber<X, Y>.Create(Subscriber, RoutineDecorator, nil); try Inputs[0].GetObservable.Subscribe(Decorator) finally Decorator.Unsubscribe end; end; procedure TMap<X, Y>.OnError(E: IThrowable); begin FDest.OnError(E); end; procedure TMap<X, Y>.OnNext(const Data: X); begin FDest.OnNext(RoutineDecorator(Data)) end; function TMap<X, Y>.RoutineDecorator(const Data: X): Y; begin if Assigned(FRoutine) then Result := FRoutine(Data) else Result := FRoutineStatic(Data) end; procedure TMap<X, Y>.OnNext(const Data: Y); begin FDest.OnNext(Data) end; function TMap<X, Y>.Subscribe(const OnNext: TOnNext<Y>; const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription; begin Result := FDest.Subscribe(OnNext, OnError, OnCompleted); end; function TMap<X, Y>.Subscribe(const OnNext: TOnNext<Y>; const OnError: TOnError): ISubscription; begin Result := FDest.Subscribe(OnNext, OnError); end; function TMap<X, Y>.Subscribe(const OnNext: TOnNext<Y>): ISubscription; begin Result := FDest.Subscribe(OnNext); end; function TMap<X, Y>.Subscribe(const OnCompleted: TOnCompleted): ISubscription; begin Result := FDest.Subscribe(OnCompleted); end; function TMap<X, Y>.Subscribe(A: ISubscriber<Y>): ISubscription; begin Result := FDest.Subscribe(A); end; function TMap<X, Y>.Subscribe(const OnNext: TOnNext<Y>; const OnCompleted: TOnCompleted): ISubscription; begin Result := FDest.Subscribe(OnNext, OnCompleted); end; function TMap<X, Y>.Subscribe(const OnError: TOnError): ISubscription; begin Result := FDest.Subscribe(OnError); end; { TOnceSubscriber<X, Y> } constructor TOnceSubscriber<X, Y>.Create(Source: IObserver<Y>; const Routine: Rx.TMap<X, Y>; const RoutineStatic: Rx.TMapStatic<X, Y>); begin FSource := Source; FRoutine := Routine; FRoutineStatic := RoutineStatic; end; destructor TOnceSubscriber<X, Y>.Destroy; begin FSource := nil; inherited; end; function TOnceSubscriber<X, Y>.IsUnsubscribed: Boolean; begin Result := FSource = nil end; procedure TOnceSubscriber<X, Y>.OnCompleted; begin if not IsUnsubscribed then begin FSource.OnCompleted; Unsubscribe; end; end; procedure TOnceSubscriber<X, Y>.OnError(E: IThrowable); begin if not IsUnsubscribed then begin FSource.OnError(E); Unsubscribe; end; end; procedure TOnceSubscriber<X, Y>.OnNext(const A: X); begin if not IsUnsubscribed then if Assigned(FRoutine) then FSource.OnNext(FRoutine(A)) else FSource.OnNext(FRoutineStatic(A)) end; procedure TOnceSubscriber<X, Y>.SetProducer(P: IProducer); begin // nothing end; procedure TOnceSubscriber<X, Y>.Unsubscribe; begin FSource := nil; end; end.
{ @html(<b>) HTTP Client Connection @html(</b>) - Copyright (c) Danijel Tkalcec @html(<br><br>) Introducing the @html(<b>) @Link(TRtcHttpClient) @html(</b>) component: @html(<br>) Client connection component for TCP/IP communication using HTTP requests. } unit rtcHttpCli; {$INCLUDE rtcDefs.inc} interface uses Classes, rtcInfo, rtcConn, rtcFastStrings, rtcPlugins, rtcDataCli; type // @exclude TRtcHttpClient=class; { @Abstract(Login info or authenticating the user on a secure server) } TRtcHttpUserLogin=class(TPersistent) private FUserName: string; FUserPassword: string; FCertSubject: string; FCertStoreType: TRtcCertStoreType; procedure SetUserName(const Value: string); procedure SetUserPassword(const Value: string); procedure SetCertStoreType(const Value: TRtcCertStoreType); procedure SetCertSubject(const Value: string); public Con:TRtcHttpClient; { Will be created by TRtcHttpClient component. @exclude } constructor Create; { Will be destroyed by TRtcHttpClient component. @exclude } destructor Destroy; override; published // Username property UserName:string read FUserName write SetUserName; // Password property UserPassword:string read FUserPassword write SetUserPassword; // Certificate store tye property CertStoreType:TRtcCertStoreType read FCertStoreType write SetCertStoreType default certAny; { String under "CN" in Certificate's "Subject" property under "Details", or "Issued to" in Certificate's "General" Tab. } property CertSubject:string read FCertSubject write SetCertSubject; end; { @Abstract(Client Connection component for TCP/IP communication using HTTP requests) Received data will be processed by TRtcHttpClient to gather Request information and make it easily accessible through the @Link(TRtcDataClient.Request) property. The same way, your response will be packed into a HTTP result header and sent out as a valid HTTP result, readable by any Web Browser. @html(<br>) @Link(TRtcHttpClient) also makes sure that you receive requests one by one and get the chance to answer them one-by-one, even if the client side sends all the requests at once (as one big request list), so you can relax and process all incomming requests, without worrying about overlapping your responses for different requests. @html(<br><br>) Properties to check first: @html(<br>) @Link(TRtcConnection.ServerAddr) - Local Address to bind the server to (leave empty for ALL) @html(<br>) @Link(TRtcConnection.ServerPort) - Port to listen on and wait for connections @html(<br><br>) Methods to check first: @html(<br>) @Link(TRtcClient.Connect) - Connect to Server @html(<br>) @Link(TRtcDataClient.Request), @Link(TRtcHttpClient.WriteHeader), @Link(TRtcHttpClient.Write) - Write (send) Request to Server @html(<br>) @Link(TRtcDataClient.Response), @Link(TRtcConnection.Read) - Read Server's Response @html(<br>) @Link(TRtcConnection.Disconnect) - Disconnect from Server @html(<br><br>) Events to check first: @html(<br>) @Link(TRtcConnection.OnConnect) - Connected to Server @html(<br>) @Link(TRtcConnection.OnDataSent) - Data sent to server (buffer now empty) @html(<br>) @Link(TRtcConnection.OnDataReceived) - Data available from server (check @Link(TRtcDataClient.Response)) @html(<br>) @Link(TRtcHttpClient.OnInvalidResponse) - Received invalid response from Server @html(<br>) @Link(TRtcConnection.OnDisconnect) - Disconencted from Server @html(<br><br>) Check @Link(TRtcClient) and @Link(TRtcConnection) for more info. } TRtcHttpClient = class(TRtcDataClient) private FCryptPlugin:TRtcCryptPlugin; FUseProxy:boolean; FUseSSL:boolean; FUseWinHTTP:boolean; // User Parameters FMaxResponseSize:cardinal; FMaxHeaderSize:cardinal; FOnInvalidResponse:TRtcNotifyEvent; // Internal variables FWritten:boolean; FWriteBuffer:TRtcHugeString; FUserLogin: TRtcHttpUserLogin; function GetUseProxy: boolean; procedure SetUseProxy(const Value: boolean); function GetUseSSL: boolean; procedure SetUseSSL(const Value: boolean); function GetUseWinHTTP: boolean; procedure SetUseWinHTTP(const Value: boolean); protected // @exclude procedure UserDataChange; // @exclude procedure SetTriggers; override; // @exclude procedure ClearTriggers; override; // @exclude procedure SetParams; override; // @exclude function CreateProvider:TObject; override; // @exclude procedure TriggerDataSent; override; // @exclude procedure TriggerDataReceived; override; // @exclude procedure TriggerDataOut; override; // @exclude procedure TriggerInvalidResponse; virtual; // @exclude procedure CallInvalidResponse; virtual; // @exclude procedure SetRequest(const Value: TRtcClientRequest); override; // @exclude procedure SetResponse(const Value: TRtcClientResponse); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function New:TRtcHttpClient; // @exclude procedure LeaveEvent; override; { Flush all buffered data. @html(<br>) When using 'Write' without calling 'WriteHeader' before, all data prepared by calling 'Write' will be buffered until your event returns to its caller (automatically upon your event completion) or when you first call 'Flush'. Flush will check if Request.ContentLength is set and if not, will set the content length to the number of bytes buffered. @html(<br>) Flush does nothing if WriteHeader was called for this response. @exclude} procedure Flush; override; // You can call WriteHeader to send the Request header out. procedure WriteHeader(SendNow:boolean=True); overload; override; { You can call WriteHeader with empty 'HeaderText' parameter to tell the component that you do not want any HTTP header to be sent. } procedure WriteHeader(const HeaderText: string; SendNow:boolean=True); overload; override; // Use Write to send any Content (document body) out. procedure Write(const s:string=''); override; published { UserLogin data is ignored when CryptPlugin is assigned. If CryptPlugin is NOT assigned (not using third-party components for encryption) ... Using this property, you can define login information for a server which requires user authentication and/or a client certificate (using WinInet API). If you want to use Third-party SSL/SSH components for encryption, simply assign the plug-in to the CryptPlugin property. } property UserLogin:TRtcHttpUserLogin read FUserLogin write FUserLogin; { UseProxy is ignored (assumed to be FALSE) when CryptPlugin is assigned. If CryptPlugin is NOT assigned (not using third-party components for encryption) ... When UseProxy is TRUE, connection component will use a WinInet connection provider, which supports transfering data over HTTP proxy servers. When UseProxy is FALSE, proxy servers will be ignored and component will always try to open a direct connection to the server, ignoring any proxy settings in the system. } property UseProxy:boolean read GetUseProxy write SetUseProxy default False; { UseSSL is ignored (assumed to be TRUE) when CryptPlugin is assigned. If CryptPlugin is NOT assigned (not using third-party components for encryption) ... When UseSSL is TRUE, connection component will use a connection provider which supports transfering data using the Secure-Socket-Layer (SSL) over the HTTPS protocol and send all requests using the HTTPS protocol instead of the standard HTTP protocol. When UseSSL is FALSE, standard HTTP protocol will be used. Note that RTC Servers do NOT support SSL. } property UseSSL:boolean read GetUseSSL write SetUseSSL default False; { Set this property if you want to use the WinHTTP API. WinHTTP API is blocking, it supports Proxy and SSL options, but it ignores any parameters set in the "UserLogin" property. WinHTTP can be used instead of WinINET for applications running as Windows Services which do not have access to Internet Explorer settings. } property UseWinHTTP:boolean read GetUseWinHTTP write SetUseWinHTTP default False; { Maximum allowed size of the first response line, without header (0 = no limit). This is the first line in a HTTP response and includes Response.StatusCode and Response.StatusText } property MaxResponseSize:cardinal read FMaxResponseSize write FMaxResponseSize default 0; { Maximum allowed size of each response's header size (0 = no limit). This are all the remaining header lines in a HTTP response, which come after the first line and end with an empty line, after which usually comes the content (document body). } property MaxHeaderSize:cardinal read FMaxHeaderSize write FMaxHeaderSize default 0; { This event will be called if the received response exceeds your defined maximum response or header size. If both values are 0, this event will never be called. } property OnInvalidResponse:TRtcNotifyEvent read FOnInvalidResponse write FOnInvalidResponse; { To use SSL/SSH encryption using third-party components, simply assign the encryption plug-in here before you start using the Client connection (before first connect). } property CryptPlugin:TRtcCryptPlugin read FCryptPlugin write FCryptPlugin; end; implementation uses SysUtils, rtcConnProv, rtcWinHttpCliProv, // WinHTTP HTTP Client Provider rtcWInetHttpCliProv, // WinInet HTTP Client Provider rtcWSockHttpCliProv; // WSocket HTTP Client Provider type TMyProvider1 = TRtcWSockHttpClientProvider; // direct TCP/IP TMyProvider2 = TRtcWInetHttpClientProvider; // WinInet over Proxy TMyProvider3 = TRtcWinHttpClientProvider; // WinHTTP over Proxy { TRtcHttpClient } constructor TRtcHttpClient.Create(AOwner: TComponent); begin inherited Create(AOwner); FUserLogin:=TRtcHttpUserLogin.Create; FUserLogin.Con:=self; FUseProxy:=False; FUseSSL:=False; FUseWinHTTP:=False; FWriteBuffer:=TRtcHugeString.Create; FWritten:=False; end; destructor TRtcHttpClient.Destroy; begin FUserLogin.Free; FWriteBuffer.Free; inherited; end; class function TRtcHttpClient.New: TRtcHttpClient; begin Result:=Create(nil); end; function TRtcHttpClient.CreateProvider:TObject; begin if not assigned(Con) then begin if assigned(FCryptPlugin) then Con:=TMyProvider1.Create else if FUseWinHTTP then begin if HaveWinHTTP then Con:=TMyProvider3.Create else Con:=TMyProvider2.Create; end else if FUseProxy or FUseSSL or (FUserLogin.UserName<>'') or (FUserLogin.UserPassword<>'') then Con:=TMyProvider2.Create else Con:=TMyProvider1.Create; SetTriggers; end; Result:=Con; end; procedure TRtcHttpClient.SetParams; begin inherited; if assigned(Con) then begin if Con is TMyProvider1 then begin TMyProvider1(Con).Request:=Request; TMyProvider1(Con).Response:=Response; TMyProvider1(Con).MaxResponseSize:=MaxResponseSize; TMyProvider1(Con).MaxHeaderSize:=MaxHeaderSize; end else if Con is TMyProvider2 then begin TMyProvider2(Con).useHttps:=FUseSSL; TMyProvider2(Con).UserName:=FUserLogin.UserName; TMyProvider2(Con).UserPassword:=FUserLogin.UserPassword; TMyProvider2(Con).CertStoreType:=FUserLogin.CertStoreType; TMyProvider2(Con).CertSubject:=FUserLogin.CertSubject; TMyProvider2(Con).Request:=Request; TMyProvider2(Con).Response:=Response; TMyProvider2(Con).MaxResponseSize:=MaxResponseSize; TMyProvider2(Con).MaxHeaderSize:=MaxHeaderSize; end else if Con is TMyProvider3 then begin TMyProvider3(Con).useHttps:=FUseSSL; TMyProvider3(Con).CertStoreType:=FUserLogin.CertStoreType; TMyProvider3(Con).CertSubject:=FUserLogin.CertSubject; TMyProvider3(Con).Request:=Request; TMyProvider3(Con).Response:=Response; TMyProvider3(Con).MaxResponseSize:=MaxResponseSize; TMyProvider3(Con).MaxHeaderSize:=MaxHeaderSize; end else raise Exception.Create('Connection Provider not recognized.'); end; end; procedure TRtcHttpClient.SetTriggers; begin inherited; if assigned(Con) then begin if Con is TMyProvider1 then TMyProvider1(Con).CryptPlugin:=CryptPlugin; {$IFDEF FPC} if Con is TMyProvider1 then TMyProvider1(Con).SetTriggerInvalidResponse(@TriggerInvalidResponse) else if Con is TMyProvider2 then TMyProvider2(Con).SetTriggerInvalidResponse(@TriggerInvalidResponse) else if Con is TMyProvider3 then TMyProvider3(Con).SetTriggerInvalidResponse(@TriggerInvalidResponse); {$ELSE} if Con is TMyProvider1 then TMyProvider1(Con).SetTriggerInvalidResponse(TriggerInvalidResponse) else if Con is TMyProvider2 then TMyProvider2(Con).SetTriggerInvalidResponse(TriggerInvalidResponse) else if Con is TMyProvider3 then TMyProvider3(Con).SetTriggerInvalidResponse(TriggerInvalidResponse); {$ENDIF} end; end; procedure TRtcHttpClient.ClearTriggers; begin inherited; if assigned(Con) then begin if Con is TMyProvider1 then begin TMyProvider1(Con).CryptPlugin:=nil; TMyProvider1(Con).SetTriggerInvalidResponse(nil); end else if Con is TMyProvider2 then TMyProvider2(Con).SetTriggerInvalidResponse(nil) else if Con is TMyProvider3 then TMyProvider3(Con).SetTriggerInvalidResponse(nil); end; end; procedure TRtcHttpClient.WriteHeader(SendNow:boolean=True); begin if assigned(Con) and (State<>conInactive) then begin if Request.Active then raise Exception.Create('Error! Sending multiple headers for one request.'); Timeout.DataSending; if Con is TMyProvider1 then TMyProvider1(Con).WriteHeader(SendNow) else if Con is TMyProvider2 then TMyProvider2(Con).WriteHeader(SendNow) else if Con is TMyProvider3 then TMyProvider3(Con).WriteHeader(SendNow); end; end; procedure TRtcHttpClient.WriteHeader(const HeaderText: string; SendNow:boolean=True); begin if assigned(Con) and (State<>conInactive) then begin if Request.Active then raise Exception.Create('Error! Sending multiple headers for one request.'); Timeout.DataSending; if Con is TMyProvider1 then TMyProvider1(Con).WriteHeader(HeaderText, SendNow) else if Con is TMyProvider2 then TMyProvider2(Con).WriteHeader(HeaderText, SendNow) else if Con is TMyProvider3 then TMyProvider3(Con).WriteHeader(HeaderText, SendNow); end; end; procedure TRtcHttpClient.Write(const s: string=''); begin if assigned(Con) and (State<>conInactive) then begin if Request.Complete then raise Exception.Create('Error! Request already sent, can not send more request data now! Request Header wrong?'); if Request.Active then begin { Header is out } if Request['Content-Length']<>'' then if Request.ContentLength - Request.ContentOut < length(s) then raise Exception.Create('Error! Sending more data out than specified in header.'); { Data size is known or unimportant. We can just write the string out, without buffering } Con.Write(s); end else begin if (Request['CONTENT-LENGTH']<>'') and not FWritten then begin { Content length defined and no data buffered, send out header prior to sending first content bytes } WriteHeader(length(s)=0); if Request.ContentLength - Request.ContentOut < length(s) then raise Exception.Create('Error! Sending more data out than specified in header.'); Con.Write(s); end else begin { Header is not out. Buffer all Write() operations, so we can determine content size and write it all out in a flush. } FWritten:=True; FWriteBuffer.Add(s); end; end; end; end; procedure TRtcHttpClient.Flush; var Temp:string; begin if not FWritten then Exit else FWritten:=False; // so we don't re-enter this method. if assigned(Con) and (State<>conInactive) then begin Timeout.DataSending; if Request.Complete then raise Exception.Create('Error! Request was already sent! Can not send more data now! Request Header wrong?'); if not Request.Active then begin if Request['CONTENT-LENGTH']='' then // length not specified begin Request.AutoLength:=True; Request.ContentLength:=FWriteBuffer.Size; end; if Con is TMyProvider1 then TMyProvider1(Con).WriteHeader(FWriteBuffer.Size=0) else if Con is TMyProvider2 then TMyProvider2(Con).WriteHeader(FWriteBuffer.Size=0) else if Con is TMyProvider3 then TMyProvider3(Con).WriteHeader(FWriteBuffer.Size=0); end; if FWriteBuffer.Size>0 then begin Temp:=FWriteBuffer.Get; FWriteBuffer.Clear; Con.Write(Temp); Temp:=''; end; end; end; procedure TRtcHttpClient.CallInvalidResponse; begin if assigned(OnInvalidResponse) then OnInvalidResponse(self); end; procedure TRtcHttpClient.TriggerDataReceived; begin inherited; Flush; end; procedure TRtcHttpClient.TriggerDataSent; begin if FWriteCount>0 then Timeout.DataSent; EnterEvent; try if FWriteCount>0 then begin CallDataSent; Flush; end; if not isClosing then begin CallReadyToSend; Flush; end; finally LeaveEvent; end; end; procedure TRtcHttpClient.TriggerDataOut; begin inherited; Flush; end; procedure TRtcHttpClient.TriggerInvalidResponse; begin EnterEvent; try CallInvalidResponse; Flush; Disconnect; finally LeaveEvent; end; end; procedure TRtcHttpClient.SetRequest(const Value: TRtcClientRequest); begin inherited SetRequest(Value); if assigned(Con) then if Con is TMyProvider1 then TMyProvider1(Con).Request:=Request else if Con is TMyProvider2 then TMyProvider2(Con).Request:=Request else if Con is TMyProvider3 then TMyProvider3(Con).Request:=Request; end; procedure TRtcHttpClient.SetResponse(const Value: TRtcClientResponse); begin inherited SetResponse(Value); if assigned(Con) then if Con is TMyProvider1 then TMyProvider1(Con).Response:=Response else if Con is TMyProvider2 then TMyProvider2(Con).Response:=Response else if Con is TMyProvider3 then TMyProvider3(Con).Response:=Response; end; function TRtcHttpClient.GetUseProxy: boolean; begin Result:=FUseProxy; end; procedure TRtcHttpClient.SetUseProxy(const Value: boolean); begin if Value<>FUseProxy then begin if assigned(Con) then if isConnected or isConnecting then Error('Can not change UseProxy after Connect.') else ReleaseProvider; FUseProxy:=Value; end; end; function TRtcHttpClient.GetUseSSL: boolean; begin Result:=FUseSSL; end; procedure TRtcHttpClient.SetUseSSL(const Value: boolean); begin if Value<>FUseSSL then begin if assigned(Con) then if isConnected or isConnecting then Error('Can not change UseSSL after Connect.') else ReleaseProvider; FUseSSL:=Value; end; end; function TRtcHttpClient.GetUseWinHTTP: boolean; begin Result:=FUseWinHTTP; end; procedure TRtcHttpClient.SetUseWinHTTP(const Value: boolean); begin if Value<>FUseWinHTTP then begin if assigned(Con) then if isConnected or isConnecting then Error('Can not change UseWinHTTP after Connect.') else ReleaseProvider; FUseWinHTTP:=Value; end; end; procedure TRtcHttpClient.UserDataChange; begin if assigned(Con) then if isConnected or isConnecting then Error('Can not change UserLogin data after Connect.') else ReleaseProvider; end; procedure TRtcHttpClient.LeaveEvent; begin inherited; if not InsideEvent then if assigned(Con) then if Con is TMyProvider2 then TMyProvider2(Con).LeavingEvent else if Con is TMyProvider3 then TMyProvider3(Con).LeavingEvent; end; { TRtcHttpUserLogin } constructor TRtcHttpUserLogin.Create; begin end; destructor TRtcHttpUserLogin.Destroy; begin inherited; end; procedure TRtcHttpUserLogin.SetCertStoreType(const Value: TRtcCertStoreType); begin if Value<>FCertStoreType then begin Con.UserDataChange; FCertStoreType := Value; end; end; procedure TRtcHttpUserLogin.SetCertSubject(const Value: string); begin if Value<>FCertSubject then begin Con.UserDataChange; FCertSubject := Value; end; end; procedure TRtcHttpUserLogin.SetUserName(const Value: string); begin if Value<>FUserName then begin Con.UserDataChange; FUserName := Value; end; end; procedure TRtcHttpUserLogin.SetUserPassword(const Value: string); begin if Value<>FUserPassword then begin Con.UserDataChange; FUserPassword := Value; end; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.PGDef; interface uses System.Types, System.SysUtils, System.Classes, FireDAC.Stan.Intf; type // TFDPhysPGConnectionDefParams // Generated for: FireDAC PG driver TFDPGCharacterSet = (csNone, csBIG5, csEUC_CN, csEUC_JP, csEUC_KR, csEUC_TW, csGB18030, csGBK, csISO_8859_5, csISO_8859_6, csISO_8859_7, csISO_8859_8, csJOHAB, csKOI8, csLATIN1, csLATIN2, csLATIN3, csLATIN4, csLATIN5, csLATIN6, csLATIN7, csLATIN8, csLATIN9, csLATIN10, csMULE_INTERNAL, csSJIS, csSQL_ASCII, csUHC, csUTF8, csWIN866, csWIN874, csWIN1250, csWIN1251, csWIN1252, csWIN1256, csWIN1258); TFDPGOidAsBlob = (oabNo, oabYes, oabChoose); TFDPGUnknownFormat = (ufError, ufBYTEA); /// <summary> TFDPhysPGConnectionDefParams class implements FireDAC PG driver specific connection definition class. </summary> TFDPhysPGConnectionDefParams = class(TFDConnectionDefParams) private function GetDriverID: String; procedure SetDriverID(const AValue: String); function GetServer: String; procedure SetServer(const AValue: String); function GetPort: Integer; procedure SetPort(const AValue: Integer); function GetLoginTimeout: Integer; procedure SetLoginTimeout(const AValue: Integer); function GetCharacterSet: TFDPGCharacterSet; procedure SetCharacterSet(const AValue: TFDPGCharacterSet); function GetExtendedMetadata: Boolean; procedure SetExtendedMetadata(const AValue: Boolean); function GetOidAsBlob: TFDPGOidAsBlob; procedure SetOidAsBlob(const AValue: TFDPGOidAsBlob); function GetUnknownFormat: TFDPGUnknownFormat; procedure SetUnknownFormat(const AValue: TFDPGUnknownFormat); function GetArrayScanSample: String; procedure SetArrayScanSample(const AValue: String); function GetApplicationName: String; procedure SetApplicationName(const AValue: String); function GetPGAdvanced: String; procedure SetPGAdvanced(const AValue: String); function GetMetaDefSchema: String; procedure SetMetaDefSchema(const AValue: String); function GetMetaCurSchema: String; procedure SetMetaCurSchema(const AValue: String); function GetGUIDEndian: TEndian; procedure SetGUIDEndian(const AValue: TEndian); published property DriverID: String read GetDriverID write SetDriverID stored False; property Server: String read GetServer write SetServer stored False; property Port: Integer read GetPort write SetPort stored False default 5432; property LoginTimeout: Integer read GetLoginTimeout write SetLoginTimeout stored False default 0; property CharacterSet: TFDPGCharacterSet read GetCharacterSet write SetCharacterSet stored False; property ExtendedMetadata: Boolean read GetExtendedMetadata write SetExtendedMetadata stored False; property OidAsBlob: TFDPGOidAsBlob read GetOidAsBlob write SetOidAsBlob stored False default oabChoose; property UnknownFormat: TFDPGUnknownFormat read GetUnknownFormat write SetUnknownFormat stored False default ufError; property ArrayScanSample: String read GetArrayScanSample write SetArrayScanSample stored False; property ApplicationName: String read GetApplicationName write SetApplicationName stored False; property PGAdvanced: String read GetPGAdvanced write SetPGAdvanced stored False; property MetaDefSchema: String read GetMetaDefSchema write SetMetaDefSchema stored False; property MetaCurSchema: String read GetMetaCurSchema write SetMetaCurSchema stored False; property GUIDEndian: TEndian read GetGUIDEndian write SetGUIDEndian stored False; end; implementation uses FireDAC.Stan.Consts; // TFDPhysPGConnectionDefParams // Generated for: FireDAC PG driver {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetDriverID: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_DriverID]; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetDriverID(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetServer: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_Server]; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetServer(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_Server] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetPort: Integer; begin if not FDef.HasValue(S_FD_ConnParam_Common_Port) then Result := 5432 else Result := FDef.AsInteger[S_FD_ConnParam_Common_Port]; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetPort(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_Common_Port] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetLoginTimeout: Integer; begin Result := FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout]; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetLoginTimeout(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetCharacterSet: TFDPGCharacterSet; var s: String; begin s := FDef.AsString[S_FD_ConnParam_Common_CharacterSet]; if CompareText(s, '') = 0 then Result := csNone else if CompareText(s, 'BIG5') = 0 then Result := csBIG5 else if CompareText(s, 'EUC_CN') = 0 then Result := csEUC_CN else if CompareText(s, 'EUC_JP') = 0 then Result := csEUC_JP else if CompareText(s, 'EUC_KR') = 0 then Result := csEUC_KR else if CompareText(s, 'EUC_TW') = 0 then Result := csEUC_TW else if CompareText(s, 'GB18030') = 0 then Result := csGB18030 else if CompareText(s, 'GBK') = 0 then Result := csGBK else if CompareText(s, 'ISO_8859_5') = 0 then Result := csISO_8859_5 else if CompareText(s, 'ISO_8859_6') = 0 then Result := csISO_8859_6 else if CompareText(s, 'ISO_8859_7') = 0 then Result := csISO_8859_7 else if CompareText(s, 'ISO_8859_8') = 0 then Result := csISO_8859_8 else if CompareText(s, 'JOHAB') = 0 then Result := csJOHAB else if CompareText(s, 'KOI8') = 0 then Result := csKOI8 else if CompareText(s, 'LATIN1') = 0 then Result := csLATIN1 else if CompareText(s, 'LATIN2') = 0 then Result := csLATIN2 else if CompareText(s, 'LATIN3') = 0 then Result := csLATIN3 else if CompareText(s, 'LATIN4') = 0 then Result := csLATIN4 else if CompareText(s, 'LATIN5') = 0 then Result := csLATIN5 else if CompareText(s, 'LATIN6') = 0 then Result := csLATIN6 else if CompareText(s, 'LATIN7') = 0 then Result := csLATIN7 else if CompareText(s, 'LATIN8') = 0 then Result := csLATIN8 else if CompareText(s, 'LATIN9') = 0 then Result := csLATIN9 else if CompareText(s, 'LATIN10') = 0 then Result := csLATIN10 else if CompareText(s, 'MULE_INTERNAL') = 0 then Result := csMULE_INTERNAL else if CompareText(s, 'SJIS') = 0 then Result := csSJIS else if CompareText(s, 'SQL_ASCII') = 0 then Result := csSQL_ASCII else if CompareText(s, 'UHC') = 0 then Result := csUHC else if CompareText(s, 'UTF8') = 0 then Result := csUTF8 else if CompareText(s, 'WIN866') = 0 then Result := csWIN866 else if CompareText(s, 'WIN874') = 0 then Result := csWIN874 else if CompareText(s, 'WIN1250') = 0 then Result := csWIN1250 else if CompareText(s, 'WIN1251') = 0 then Result := csWIN1251 else if CompareText(s, 'WIN1252') = 0 then Result := csWIN1252 else if CompareText(s, 'WIN1256') = 0 then Result := csWIN1256 else if CompareText(s, 'WIN1258') = 0 then Result := csWIN1258 else Result := csNone; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetCharacterSet(const AValue: TFDPGCharacterSet); const C_CharacterSet: array[TFDPGCharacterSet] of String = ('', 'BIG5', 'EUC_CN', 'EUC_JP', 'EUC_KR', 'EUC_TW', 'GB18030', 'GBK', 'ISO_8859_5', 'ISO_8859_6', 'ISO_8859_7', 'ISO_8859_8', 'JOHAB', 'KOI8', 'LATIN1', 'LATIN2', 'LATIN3', 'LATIN4', 'LATIN5', 'LATIN6', 'LATIN7', 'LATIN8', 'LATIN9', 'LATIN10', 'MULE_INTERNAL', 'SJIS', 'SQL_ASCII', 'UHC', 'UTF8', 'WIN866', 'WIN874', 'WIN1250', 'WIN1251', 'WIN1252', 'WIN1256', 'WIN1258'); begin FDef.AsString[S_FD_ConnParam_Common_CharacterSet] := C_CharacterSet[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetExtendedMetadata: Boolean; begin Result := FDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata]; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetExtendedMetadata(const AValue: Boolean); begin FDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetOidAsBlob: TFDPGOidAsBlob; var s: String; begin s := FDef.AsString[S_FD_ConnParam_PG_OidAsBlob]; if CompareText(s, 'No') = 0 then Result := oabNo else if CompareText(s, 'Yes') = 0 then Result := oabYes else if CompareText(s, 'Choose') = 0 then Result := oabChoose else Result := oabChoose; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetOidAsBlob(const AValue: TFDPGOidAsBlob); const C_OidAsBlob: array[TFDPGOidAsBlob] of String = ('No', 'Yes', 'Choose'); begin FDef.AsString[S_FD_ConnParam_PG_OidAsBlob] := C_OidAsBlob[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetUnknownFormat: TFDPGUnknownFormat; var s: String; begin s := FDef.AsString[S_FD_ConnParam_PG_UnknownFormat]; if CompareText(s, 'Error') = 0 then Result := ufError else if CompareText(s, 'BYTEA') = 0 then Result := ufBYTEA else Result := ufError; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetUnknownFormat(const AValue: TFDPGUnknownFormat); const C_UnknownFormat: array[TFDPGUnknownFormat] of String = ('Error', 'BYTEA'); begin FDef.AsString[S_FD_ConnParam_PG_UnknownFormat] := C_UnknownFormat[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetArrayScanSample: String; begin Result := FDef.AsString[S_FD_ConnParam_PG_ArrayScanSample]; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetArrayScanSample(const AValue: String); begin FDef.AsString[S_FD_ConnParam_PG_ArrayScanSample] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetApplicationName: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_ApplicationName]; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetApplicationName(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_ApplicationName] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetPGAdvanced: String; begin Result := FDef.AsString[S_FD_ConnParam_PG_PGAdvanced]; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetPGAdvanced(const AValue: String); begin FDef.AsString[S_FD_ConnParam_PG_PGAdvanced] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetMetaDefSchema: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema]; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetMetaDefSchema(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetMetaCurSchema: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema]; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetMetaCurSchema(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysPGConnectionDefParams.GetGUIDEndian: TEndian; var s: String; begin s := FDef.AsString[S_FD_ConnParam_Common_GUIDEndian]; if CompareText(s, S_FD_Little) = 0 then Result := Little else if CompareText(s, S_FD_Big) = 0 then Result := Big else Result := Little; end; {-------------------------------------------------------------------------------} procedure TFDPhysPGConnectionDefParams.SetGUIDEndian(const AValue: TEndian); const C_GUIDEndian: array[TEndian] of String = (S_FD_Big, S_FD_Little); begin FDef.AsString[S_FD_ConnParam_Common_GUIDEndian] := C_GUIDEndian[AValue]; end; end.
unit IWCompLabel; {PUBDIST} interface uses {$IFDEF Linux}QGraphics, {$ELSE}Graphics, {$ENDIF} {$IFDEF Linux}QControls, {$ELSE}Controls, {$ENDIF} Classes, IWControl, IWHTMLTag; type TIWCustomLabel = class(TIWControl) protected FRawText: Boolean; // procedure SetAutoSize(Value: Boolean); override; public constructor Create(AOwner: TComponent); override; function RenderHTML: TIWHTMLTag; override; // property AutoSize; property RawText: Boolean read FRawText write FRawText default True; published property Font; end; TIWLabel = class(TIWCustomLabel) published property AutoSize; //@@ This is the text which is displayed to the user. You may use the font to change how the // text is displayed to the user. // //SeeAlso: Font property Caption; property RawText; end; implementation uses SysUtils; function TIWCustomLabel.RenderHTML: TIWHTMLTag; begin Result := TIWHTMLTag.CreateTag('SPAN'); try if not RawText then begin Result.Contents.AddText(TextToHTML(Caption)); end else begin Result.Contents.AddText(Caption); end; except FreeAndNil(Result); raise; end; end; constructor TIWCustomLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); Height := 21; Width := 121; AutoSize := true; FRawText := true; end; procedure TIWCustomLabel.SetAutoSize(Value: Boolean); begin inherited SetAutoSize(Value); Invalidate; end; end.
{ *************************************************************************** } { } { Kylix and Delphi Cross-Platform Visual Component Library } { } { Copyright (c) 1997, 2001 Borland Software Corporation } { } { *************************************************************************** } unit DBLocal; {$R-,T-,H+,X+} interface {$IFDEF MSWINDOWS} uses Windows, SysUtils, Variants, Classes, DB, DBCommon, Midas, SqlTimSt, DBClient, Provider; {$ENDIF} {$IFDEF LINUX} uses Libc, SysUtils, Variants, Classes, DB, DBCommon, Midas, SqlTimSt, DBClient, Provider; {$ENDIF} type TSqlDBType = (typeDBX, typeBDE, typeADO, typeIBX); { TCustomCachedDataSet } TCustomCachedDataSet = class(TCustomClientDataSet) private FProvider: TDataSetProvider; FSqlDBType: TSqlDBType; function GetBeforeUpdateRecord : TBeforeUpdateRecordEvent; procedure SetBeforeUpdateRecord( Value: TBeforeUpdateRecordEvent); function GetAfterUpdateRecord: TAfterUpdateRecordEvent; procedure SetAfterUpdateRecord(Value: TAfterUpdateRecordEvent); function GetOnGetTableName: TGetTableNameEvent; procedure SetOnGetTableName(Value: TGetTableNameEvent); function GetOnUpdateData: TProviderDataEvent; procedure SetOnUpdateData(Value: TProviderDataEvent); function GetOnUpdateError: TResolverErrorEvent; procedure SetOnUpdateError(Value: TResolverErrorEvent); protected procedure CloseCursor; override; function GetCommandText: string; virtual; function GetOptions: TProviderOptions; function GetUpdateMode: TUpdateMode; procedure SetActive(Value: Boolean); override; procedure SetAggregates(Value: TAggregates); override; procedure SetCommandText(Value: string); override; procedure SetOptions(Value: TProviderOptions); procedure SetUpdateMode(Value: TUpdateMode); property Provider: TDataSetProvider read FProvider write FProvider; property SqlDBType: TSqlDBType read FSqlDBType write FSqlDBType; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure LoadFromFile(const AFileName: string = ''); published { overridden by TCustomCachedDataSet descendants } property Active; property CommandText; { public in TClientDataSet } property Aggregates; property AggregatesActive; property AutoCalcFields; property Constraints stored ConstraintsStored; property DisableStringTrim; property FetchOnDemand; property FieldDefs; property FileName; property Filter; property Filtered; property FilterOptions; property IndexDefs; property IndexFieldNames; property IndexName; property MasterFields; property MasterSource; { from TDataSetProvider } property Options: TProviderOptions read GetOptions write SetOptions default []; { more public in TClientDataSet } property ObjectView; property PacketRecords; property Params; property ReadOnly; { from TDataSetProvider again} property UpdateMode: TUpdateMode read GetUpdateMode write SetUpdateMode default upWhereAll; { TClientDataSet events } property BeforeOpen; property AfterOpen; property BeforeClose; property AfterClose; property BeforeInsert; property AfterInsert; property BeforeEdit; property AfterEdit; property BeforePost; property AfterPost; property BeforeCancel; property AfterCancel; property BeforeDelete; property AfterDelete; property BeforeScroll; property AfterScroll; property BeforeRefresh; property AfterRefresh; property OnCalcFields; property OnDeleteError; property OnEditError; property OnFilterRecord; property OnNewRecord; property OnPostError; property OnReconcileError; property BeforeApplyUpdates; property AfterApplyUpdates; property BeforeGetRecords; property AfterGetRecords; property BeforeRowRequest; property AfterRowRequest; property BeforeExecute; property AfterExecute; property BeforeGetParams; property AfterGetParams; { TDataSetProvider events } property BeforeUpdateRecord: TBeforeUpdateRecordEvent read GetBeforeUpdateRecord write SetBeforeUpdateRecord; property AfterUpdateRecord: TAfterUpdateRecordEvent read GetAfterUpdateRecord write SetAfterUpdateRecord; property OnGetTableName: TGetTableNameEvent read GetOnGetTableName write SetOnGetTableName; property OnUpdateData: TProviderDataEvent read GetOnUpdateData write SetOnUpdateData; property OnUpdateError: TResolverErrorEvent read GetOnUpdateError write SetOnUpdateError; end; implementation uses DBConsts; { TCustomCachedDataSet } constructor TCustomCachedDataSet.Create(AOwner: TComponent); begin inherited; FProvider := TDataSetProvider.Create(nil); FProvider.Name := Self.Name + 'Provider1'; FProvider.Options := [poAllowCommandText]; FProvider.UpdateMode := upWhereAll; SetProvider(FProvider); end; destructor TCustomCachedDataSet.Destroy; begin if Assigned(FProvider) then FreeAndNil(FProvider); inherited; end; function TCustomCachedDataSet.GetCommandText: String; begin Result := ''; end; procedure TCustomCachedDataSet.CloseCursor; begin inherited; SetProvider(FProvider); end; procedure TCustomCachedDataSet.SetCommandText(Value: String); begin if inherited CommandText <> Value then inherited SetCommandText(Value); end; procedure TCustomCachedDataSet.SetAggregates(Value: TAggregates); begin if Active then DatabaseError(SDataSetOpen); inherited SetAggregates(Value); end; procedure TCustomCachedDataSet.SetActive(Value: Boolean); begin if Value then begin if (FileName <> '') and (CommandText = '') then SetProvider(Nil) else if Assigned(FProvider) then SetProvider(FProvider); end; inherited SetActive(Value); if (not Value) and Assigned(FProvider) then SetProvider(FProvider); end; function TCustomCachedDataSet.GetOptions: TProviderOptions; begin Result := FProvider.Options; end; procedure TCustomCachedDataSet.SetOptions(Value: TProviderOptions); begin FProvider.Options := Value; end; procedure TCustomCachedDataSet.SetUpdateMode(Value: TUpdateMode); begin FProvider.UpdateMode := Value; end; function TCustomCachedDataSet.GetUpdateMode: TUpdateMode; begin Result := FProvider.UpdateMode; end; function TCustomCachedDataSet.GetBeforeUpdateRecord : TBeforeUpdateRecordEvent; begin Result := FProvider.BeforeUpdateRecord; end; procedure TCustomCachedDataSet.SetBeforeUpdateRecord( Value: TBeforeUpdateRecordEvent); begin FProvider.BeforeUpdateRecord := Value; end; function TCustomCachedDataSet.GetAfterUpdateRecord: TAfterUpdateRecordEvent; begin Result := FProvider.AfterUpdateRecord; end; procedure TCustomCachedDataSet.SetAfterUpdateRecord( Value: TAfterUpdateRecordEvent ); begin FProvider.AfterUpdateRecord := Value; end; function TCustomCachedDataSet.GetOnGetTableName: TGetTableNameEvent; begin Result := FProvider.OnGetTableName; end; procedure TCustomCachedDataSet.SetOnGetTableName( Value: TGetTableNameEvent ); begin FProvider.OnGetTableName := Value; end; function TCustomCachedDataSet.GetOnUpdateData: TProviderDataEvent; begin Result := FProvider.OnUpdateData; end; procedure TCustomCachedDataSet.SetOnUpdateData(Value: TProviderDataEvent); begin FProvider.OnUpdateData := Value; end; function TCustomCachedDataSet.GetOnUpdateError: TResolverErrorEvent; begin Result := FProvider.OnUpdateError; end; procedure TCustomCachedDataSet.SetOnUpdateError(Value: TResolverErrorEvent); begin FProvider.OnUpdateError := Value; end; procedure TCustomCachedDataSet.LoadFromFile(const AFileName: string = ''); var SaveFile: string; begin SaveFile := AFileName; inherited FileName := AFileName; inherited LoadFromFile(AFileName); inherited FileName := SaveFile; end; end.
unit SpriteAnimate; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, Dialogs, SpriteTimer, SpriteDevelop; type TSpriteAnimate = class(TGraphicControl) private //FDevelopControl : TSpriteDevelop; //FLayer: integer; FPaused: boolean; BmWorking, BmSaveGeneral: HBitmap; BmWorkingOld, BmSaveGeneralOld: HBitmap; HdcWorking, HdcSaveGeneral: HDC; FAnimateInterval : integer; FEnabled: boolean; Controls: TList; procedure SetEnabled(Value: boolean); procedure Animate(Sender: TObject); procedure SetAnimateInterval(Value: integer); //procedure SetFLayer(Value: integer); //procedure SetDevelopControl(Value: TSpriteDevelop); protected procedure Loaded; override; procedure Paint; override; public function IsRegisteredControl(Sprite: tGraphicControl): boolean; procedure RegisterControl(Sprite: TGraphicControl); procedure UnRegisterControl(Sprite: TGraphicControl); procedure Pause; procedure Resume; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property ShowHint; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnClick; property OnDblClick; property PopupMenu; property AnimateInterval: integer read FAnimateInterval write SetAnimateInterval; property Enabled : boolean read FEnabled write SetEnabled; property Paused: boolean read FPaused; property Visible; //property Layer: integer read FLayer write SetFLayer; //property DevelopControl: TSpriteDevelop read FDevelopControl write SetDevelopControl; end; procedure Register; implementation uses SpriteClass; constructor TSpriteAnimate.Create(AOwner: TComponent); begin inherited Create(AOwner); FPaused:=False; HdcWorking := 0; HdcSaveGeneral := 0; Controls := TList.Create; FAnimateInterval := 100; Width := 100; Height := 100; Enabled := True; end; destructor TSpriteAnimate.Destroy; begin if not(csDesigning in ComponentState) then AnimateTimer.UnregisterControl(Self); if Controls <> nil then Controls.Free; if HdcSaveGeneral <> 0 then begin DeleteObject (SelectObject (bmSaveGeneral, bmSaveGeneralOld)); DeleteObject (SelectObject (bmWorking, bmWorkingOld)); DeleteDC(hdcWorking); DeleteDC (hdcSaveGeneral); end; inherited Destroy; end; procedure TSpriteAnimate.RegisterControl(Sprite: TGraphicControl); begin Controls.Add(Sprite); if csDesigning in ComponentState then Invalidate; end; procedure TSpriteAnimate.UnRegisterControl(Sprite: TGraphicControl); begin Controls.Remove(Sprite); if csDesigning in ComponentState then Invalidate //else if Controls.Count = 0 then Self.Destroy; end; procedure TSpriteAnimate.SetEnabled(Value: boolean); begin if Value <> FEnabled then FEnabled := Value; end; procedure TSpriteAnimate.Animate(Sender: TObject); var k: integer; begin {if Assigned(DevelopControl) then if DevelopControl.GetCurrentLayer <> FLayer then exit;} if FPaused or (not Visible) then exit; if (hdcWorking <> 0) then begin BitBlt (hdcWorking, 0, 0, Width, Height, hdcSaveGeneral, 0, 0, SRCCOPY); for k:=0 to Controls.Count - 1 do TSprite(Controls[k]).StepForward(hdcWorking); BitBlt (Canvas.Handle, 0, 0, Width, Height, hdcWorking, 0, 0, SRCCOPY); end; if csDesigning in ComponentState then begin for k:=0 to Controls.Count - 1 do TSprite(Controls[k]).StepForward(Canvas.Handle); end; end; procedure TSpriteAnimate.Paint; begin {if Assigned(DevelopControl) then if DevelopControl.GetCurrentLayer <> FLayer then exit;} if (hdcSaveGeneral = 0) or (csDesigning in ComponentState) then begin hdcSaveGeneral := CreateCompatibleDC(Canvas.Handle); BmSaveGeneral := CreateCompatibleBitmap (Canvas.Handle, Width, Height); BmSaveGeneralOld := SelectObject (hdcSaveGeneral, bmSaveGeneral); hdcWorking := CreateCompatibleDC(Canvas.Handle); BmWorking := CreateCompatibleBitmap (Canvas.Handle, Width, Height); BmWorkingOld := SelectObject (hdcWorking, BmWorking); BitBlt (hdcSaveGeneral, 0, 0, Width, Height, Canvas.Handle, 0, 0, SRCCOPY); end; if csDesigning in ComponentState then begin Animate(Self); Canvas.Pen.Style := psDot; Canvas.Brush.Style := bsClear; Canvas.Pen.Color := clBlack; Canvas.Rectangle(0, 0, Width, Height); end; end; procedure TSpriteAnimate.SetAnimateInterval(Value: integer); begin FAnimateInterval := Value; end; function TSpriteAnimate.IsRegisteredControl(Sprite: tGraphicControl): boolean; var i: integer; begin i := Controls.IndexOf(Sprite); if i >= 0 then Result:=True else Result:=False; end; procedure TSpriteAnimate.Pause; begin FPaused:=True; end; procedure TSpriteAnimate.Resume; begin FPaused:=False; end; procedure TSpriteAnimate.Loaded; begin if not(csDesigning in ComponentState) then begin if (AnimateTimer = nil) then AnimateTimer := TSpriteTimer.Create; if FEnabled then begin AnimateTimer.RegisterControl(Self, FAnimateInterval, FEnabled, Animate); end else AnimateTimer.UnregisterControl(Self); end; end; {procedure TSpriteAnimate.SetFLayer(Value: integer); begin if Value <> FLayer then begin Flayer:=Value; Repaint; end; end;} {procedure TSpriteAnimate.SetDevelopControl(Value: TSpriteDevelop); begin FDevelopControl := Value; Repaint; end;} procedure Register; begin RegisterComponents('Sprites', [TSprite, TSpriteAnimate]); end; end.
{$R-} {$Q-} unit ncEncTea; // To disable as much of RTTI as possible (Delphi 2009/2010), // Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position {$IF CompilerVersion >= 21.0} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$ENDIF} interface uses System.Classes, System.Sysutils, ncEnccrypt2, ncEncblockciphers; type TncEnc_tea = class(TncEnc_blockcipher64) protected KeyData: array [0 .. 3] of dword; procedure InitKey(const Key; Size: longword); override; public class function GetAlgorithm: string; override; class function GetMaxKeySize: integer; override; class function SelfTest: boolean; override; procedure Burn; override; procedure EncryptECB(const InData; var OutData); override; procedure DecryptECB(const InData; var OutData); override; end; { ****************************************************************************** } { ****************************************************************************** } implementation uses ncEncryption; const Delta = $9E3779B9; Rounds = 32; function SwapDword(a: dword): dword; begin Result := ((a and $FF) shl 24) or ((a and $FF00) shl 8) or ((a and $FF0000) shr 8) or ((a and $FF000000) shr 24); end; class function TncEnc_tea.GetAlgorithm: string; begin Result := 'Tea'; end; class function TncEnc_tea.GetMaxKeySize: integer; begin Result := 128; end; class function TncEnc_tea.SelfTest: boolean; const Key: array [0 .. 3] of dword = ($12345678, $9ABCDEF0, $0FEDCBA9, $87654321); PT: array [0 .. 1] of dword = ($12345678, $9ABCDEF0); var Data: array [0 .. 1] of dword; Cipher: TncEnc_tea; begin Cipher := TncEnc_tea.Create(nil); Cipher.Init(Key, Sizeof(Key) * 8, nil); Cipher.EncryptECB(PT, Data); Result := not CompareMem(@Data, @PT, Sizeof(PT)); Cipher.DecryptECB(Data, Data); Result := Result and CompareMem(@Data, @PT, Sizeof(PT)); Cipher.Burn; Cipher.Free; end; procedure TncEnc_tea.InitKey(const Key; Size: longword); begin FillChar(KeyData, Sizeof(KeyData), 0); Move(Key, KeyData, Size div 8); KeyData[0] := SwapDword(KeyData[0]); KeyData[1] := SwapDword(KeyData[1]); KeyData[2] := SwapDword(KeyData[2]); KeyData[3] := SwapDword(KeyData[3]); end; procedure TncEnc_tea.Burn; begin FillChar(KeyData, Sizeof(KeyData), 0); inherited Burn; end; procedure TncEnc_tea.EncryptECB(const InData; var OutData); var a, b, c, d, x, y, n, sum: dword; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); x := SwapDword(pdword(@InData)^); y := SwapDword(pdword(longword(@InData) + 4)^); sum := 0; a := KeyData[0]; b := KeyData[1]; c := KeyData[2]; d := KeyData[3]; for n := 1 to Rounds do begin Inc(sum, Delta); Inc(x, (y shl 4) + (a xor y) + (sum xor (y shr 5)) + b); Inc(y, (x shl 4) + (c xor x) + (sum xor (x shr 5)) + d); end; pdword(@OutData)^ := SwapDword(x); pdword(longword(@OutData) + 4)^ := SwapDword(y); end; procedure TncEnc_tea.DecryptECB(const InData; var OutData); var a, b, c, d, x, y, n, sum: dword; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); x := SwapDword(pdword(@InData)^); y := SwapDword(pdword(longword(@InData) + 4)^); sum := Delta shl 5; a := KeyData[0]; b := KeyData[1]; c := KeyData[2]; d := KeyData[3]; for n := 1 to Rounds do begin Dec(y, (x shl 4) + (c xor x) + (sum xor (x shr 5)) + d); Dec(x, (y shl 4) + (a xor y) + (sum xor (y shr 5)) + b); Dec(sum, Delta); end; pdword(@OutData)^ := SwapDword(x); pdword(longword(@OutData) + 4)^ := SwapDword(y); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Dataset Designer Define Field Dialog } { } { Copyright (c) 1997-2001 Borland Software Corporation } { } {*******************************************************} unit DSDefine; interface {$IFDEF MSWINDOWS} uses Windows, SysUtils, Messages, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, Buttons, DB, DesignIntf; {$ENDIF} {$IFDEF LINUX} uses Windows, SysUtils, Messages, Classes, QGraphics, QControls, QForms, QStdCtrls, QExtCtrls, QButtons, DB, DesignIntf; {$ENDIF} type TDefineField = class(TForm) OkBtn: TButton; CancelBtn: TButton; HelpBtn: TButton; FieldGroup: TGroupBox; ComponentNameLabel: TLabel; FieldNameLabel: TLabel; ComponentNameEdit: TEdit; FieldNameEdit: TEdit; FieldTypeList: TComboBox; SizeEditLabel: TLabel; SizeEdit: TEdit; FieldKind: TRadioGroup; LookupGroup: TGroupBox; DatasetList: TComboBox; DatasetLabel: TLabel; KeyFieldsList: TComboBox; LookupKeysList: TComboBox; ResultFieldList: TComboBox; KeyFieldsLabel: TLabel; LookupKeysLabel: TLabel; ResultFieldLabel: TLabel; FieldTypeLabel: TLabel; procedure FieldNameEditChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure OkBtnClick(Sender: TObject); procedure DatasetListDropDown(Sender: TObject); procedure LookupKeysListDropDown(Sender: TObject); procedure KeyFieldsListDropDown(Sender: TObject); procedure ResultFieldListDropDown(Sender: TObject); procedure FieldKindClick(Sender: TObject); procedure DatasetListChange(Sender: TObject); procedure HelpBtnClick(Sender: TObject); procedure FieldTypeListChange(Sender: TObject); private FDataset: TDataset; FDesigner: IDesigner; FDSDesigner: TDatasetDesigner; FField: TField; function GetCalculated: Boolean; function GetComponentName: string; function GetFieldClass: TFieldClass; function GetFieldName: string; function GetLookup: Boolean; function GetLookupDataset: TDataset; function GetKeyFields: string; function GetLookupKeyFields: string; function GetLookupResultField: string; procedure GetLookupFields(Items: TStrings); function GetSize: Integer; procedure SetCalculated(Value: Boolean); procedure SetComponentName(const Value: string); procedure SetDataset(Value: TDataset); procedure SetFieldClass(Value: TFieldClass); procedure SetFieldName(const Value: string); procedure SetLookup(Value: Boolean); procedure SetSize(Value: Integer); procedure UpdateLookupControls; public procedure ConfigureForLookupOnly(const ADataSet, AKey, ALookup, AResult, AType: string; ASize: Word); property Calculated: Boolean read GetCalculated write SetCalculated; property Lookup: Boolean read GetLookup write SetLookup; property ComponentName: string read GetComponentName write SetComponentName; property FieldClass: TFieldClass read GetFieldClass write SetFieldClass; property FieldName: string read GetFieldName write SetFieldName; property Field: TField read FField; property Size: Integer read GetSize write SetSize; property LookupDataset: TDataset read GetLookupDataset; property KeyFields: string read GetKeyFields; property LookupKeyFields: string read GetLookupKeyFields; property LookupResultField: string read GetLookupResultField; property Dataset: TDataset read FDataset write SetDataset; property Designer: IDesigner read FDesigner write FDesigner; property DSDesigner: TDatasetDesigner read FDSDesigner write FDSDesigner; end; function ClassNameNoT(FieldClass: TFieldClass): string; var DefineField: TDefineField; implementation uses DsnDBCst, DBConsts, Dialogs, DSDesign, LibHelp, TypInfo; {$IFDEF MSWINDOWS} {$R *.dfm} {$ENDIF} var FieldClasses: TList; function ClassNameNoT(FieldClass: TFieldClass): string; begin Result := FieldClass.ClassName; if Result[1] = 'T' then Delete(Result, 1, 1); if CompareText('Field', Copy(Result, Length(Result) - 4, 5)) = 0 then { do not localize } Delete(Result, Length(Result) - 4, 5); end; procedure RegFields(const AFieldClasses: array of TFieldClass); far; var I: Integer; begin if FieldClasses = nil then FieldClasses := TList.Create; for I := Low(AFieldClasses) to High(AFieldClasses) do if FieldClasses.IndexOf(AFieldClasses[I]) = -1 then begin FieldClasses.Add(AFieldClasses[I]); RegisterClass(AFieldClasses[I]); end; end; function FindFieldClass(const FieldClassName: string): TFieldClass; var I: Integer; begin for I := 0 to FieldClasses.Count - 1 do begin Result := FieldClasses[I]; if (CompareText(FieldClassName, Result.ClassName) = 0) or (CompareText(FieldClassName, ClassNameNoT(Result)) = 0) then Exit; end; Result := nil; end; { TNewField } procedure TDefineField.FormCreate(Sender: TObject); var I: Integer; begin for I := 0 to FieldClasses.Count - 1 do FieldTypeList.Items.Add(ClassNameNoT(FieldClasses[I])); HelpContext := hcDDefineField; end; function TDefineField.GetCalculated: Boolean; begin Result := FieldKind.ItemIndex = 1; end; function TDefineField.GetComponentName: string; begin Result := ComponentNameEdit.Text; end; function TDefineField.GetFieldClass: TFieldClass; begin Result := FindFieldClass(FieldTypeList.Text); end; function TDefineField.GetFieldName: string; begin Result := FieldNameEdit.Text; end; function TDefineField.GetLookup: Boolean; begin Result := FieldKind.ItemIndex = 2; end; function TDefineField.GetLookupDataset: TDataset; begin Result := Designer.GetComponent(DatasetList.Text) as TDataset; end; function TDefineField.GetKeyFields: string; begin Result := KeyFieldsList.Text; end; function TDefineField.GetLookupKeyFields: string; begin Result := LookupKeysList.Text; end; function TDefineField.GetLookupResultField: string; begin Result := ResultFieldList.Text; end; function TDefineField.GetSize: Integer; begin Result := -1; if SizeEdit.Text <> '' then Result := StrToInt(SizeEdit.Text); end; procedure TDefineField.SetCalculated(Value: Boolean); begin if Value or not Lookup then FieldKind.ItemIndex := Ord(Value); end; procedure TDefineField.SetComponentName(const Value: string); begin ComponentNameEdit.Text := Value; end; procedure TDefineField.SetDataset(Value: TDataset); begin FDataset := Value; FieldNameEdit.Text := ''; end; procedure TDefineField.SetFieldClass(Value: TFieldClass); begin if Value <> nil then with FieldTypeList do ItemIndex := Items.IndexOf(ClassNameNoT(Value)); end; procedure TDefineField.SetFieldName(const Value: string); begin FieldNameEdit.Text := Value; end; procedure TDefineField.SetLookup(Value: Boolean); begin if Value or not Calculated then FieldKind.ItemIndex := Ord(Value) * 2; end; procedure TDefineField.SetSize(Value: Integer); begin SizeEdit.Text := IntToStr(Value); end; procedure TDefineField.FieldNameEditChange(Sender: TObject); var I: Integer; begin if FieldName <> '' then ComponentName := CreateUniqueName(Dataset, FieldName, FieldClass, nil) else ComponentName := ''; I := Dataset.FieldDefs.IndexOf(FieldName); if I >= 0 then FieldClass := Dataset.FieldDefs[I].FieldClass; if (Dataset.FieldDefs.Count <> 0) and (FieldKind.ItemIndex = 0) then Calculated := I < 0; end; procedure TDefineField.OkBtnClick(Sender: TObject); var ErrorFound: Boolean; procedure ErrorMsg(const Msg: string; L: TLabel); begin MessageDlg(Msg, mtError, [mbOK], 0); if L.FocusControl <> nil then L.FocusControl.SetFocus; ErrorFound := True; end; procedure Error(L: TLabel); var C: string; I: Integer; begin C := L.Caption; if SysLocale.FarEast then // Far East label shortcuts are 'xxxx(&s):' begin I := Length(C) - 4; if (I > 0) and (C[I] = '(') and (C[I+1] = '&') and (C[I+3] = ')') and (C[I+4] = ':') then Delete(C, I, 4); end else for I := Length(C) downto 1 do if C[I] in ['&',':'] then Delete(C, I, 1); ErrorMsg(Format(SDSMustBeSpecified, [C]), L); end; begin ModalResult := mrNone; ErrorFound := False; if FieldName = '' then Error(FieldNameLabel) else if FieldClass = nil then Error(FieldTypeLabel) else if ComponentName = '' then Error(ComponentNameLabel) else if Lookup then if LookupDataset = nil then Error(DatasetLabel) else if LookupDataset = Dataset then ErrorMsg(SCircularDataLink, DatasetLabel) else if LookupKeyFields = '' then Error(LookupKeysLabel) else if KeyFields = '' then Error(KeyFieldsLabel) else if LookupResultField = '' then Error(ResultFieldLabel); if ErrorFound then Exit; FField := FieldClass.Create(Dataset.Owner); if (Field.FieldKind = fkData) and (DataSet.Active) then begin ErrorMsg(SDSDataFieldOnOpenTable, FieldTypeLabel); exit; end; try Field.Name := ComponentName; Field.FieldName := FieldName; if Calculated then Field.FieldKind := fkCalculated else if Lookup then begin Field.FieldKind := fkLookup; Field.LookupDataset := LookupDataset; Field.KeyFields := KeyFields; Field.LookupKeyFields := LookupKeyFields; Field.LookupResultField := LookupResultField; end else if FieldKind.ItemIndex = 3 then Field.FieldKind := fkInternalCalc else if FieldKind.ItemIndex = 4 then begin Field.FieldKind := fkAggregate; Field.Visible := False; end; if Size <> -1 then Field.Size := Size; DSDesigner.BeginDesign; try Field.Dataset := Dataset; finally DSDesigner.EndDesign; end; except Field.Free; raise; end; ModalResult := mrOK; end; procedure TDefineField.UpdateLookupControls; var LookupDatasetValid: Boolean; begin LookupDatasetValid := Lookup and (Designer.GetComponent(DatasetList.Text) <> nil); DatasetList.Enabled := Lookup; DatasetLabel.Enabled := Lookup; KeyFieldsList.Enabled := Lookup; KeyFieldsLabel.Enabled := Lookup; LookupKeysList.Enabled := LookupDatasetValid; LookupKeysLabel.Enabled := LookupDatasetValid; ResultFieldList.Enabled := LookupDatasetValid; ResultFieldLabel.Enabled := LookupDatasetValid; end; procedure TDefineField.DatasetListDropDown(Sender: TObject); var OldValue: string; begin OldValue := DatasetList.Text; DatasetList.Clear; Designer.GetComponentNames(GetTypeData(TDataset.ClassInfo), DatasetList.Items.Append); DatasetList.Text := OldValue; end; procedure TDefineField.KeyFieldsListDropDown(Sender: TObject); var OldValue: string; begin OldValue := KeyFieldsList.Text; KeyFieldsList.Clear; Dataset.GetFieldNames(KeyFieldsList.Items); KeyFieldsList.Text := OldValue; end; procedure TDefineField.GetLookupFields(Items: TStrings); var LookupDataset: TDataset; begin LookupDataset := Designer.GetComponent(DatasetList.Text) as TDataset; if LookupDataset <> nil then LookupDataset.GetFieldNames(Items); end; procedure TDefineField.LookupKeysListDropDown(Sender: TObject); var OldValue: string; begin OldValue := LookupKeysList.Text; LookupKeysList.Clear; GetLookupFields(LookupKeysList.Items); LookupKeysList.Text := OldValue; end; procedure TDefineField.ResultFieldListDropDown(Sender: TObject); var OldValue: string; begin OldValue := ResultFieldList.Text; ResultFieldList.Clear; GetLookupFields(ResultFieldList.Items); ResultFieldList.Text := OldValue; end; procedure TDefineField.FieldKindClick(Sender: TObject); begin if FieldKind.ItemIndex = 4 then FieldTypeList.Text := 'Aggregate'; { do not localize } UpdateLookupControls; end; procedure TDefineField.DatasetListChange(Sender: TObject); begin UpdateLookupControls; end; procedure TDefineField.HelpBtnClick(Sender: TObject); begin {$IFDEF MSWINDOWS} Application.HelpContext(HelpContext); {$ENDIF} end; type TFieldAccess = class(TField); TFieldAccessClass = class of TFieldAccess; procedure TDefineField.FieldTypeListChange(Sender: TObject); var FieldClass: TFieldClass; begin if (FieldTypeList.Text <> '') then try FieldClass := Self.FieldClass; if Assigned(FieldClass) then TFieldAccessClass(FieldClass).CheckTypeSize(1); SizeEdit.Enabled := True; except SizeEdit.Text := '0'; { do not localize } SizeEdit.Enabled := False; end; end; procedure TDefineField.ConfigureForLookupOnly(const ADataSet, AKey, ALookup, AResult, AType: string; ASize: Word); var vDelta: Integer; begin Lookup := True; FieldKind.Hide; vDelta := LookupGroup.Top - FieldKind.Top; LookupGroup.Top := FieldKind.Top; OkBtn.Top := OkBtn.Top - vDelta; CancelBtn.Top := CancelBtn.Top - vDelta; HelpBtn.Top := HelpBtn.Top - vDelta; Height := Height - vDelta; Caption := SNewLookupFieldCaption; DataSetList.Text := ADataSet; KeyFieldsList.Text := AKey; LookupKeysList.Text := ALookup; ResultFieldList.Text := AResult; SizeEdit.Text := IntToStr(ASize); FieldTypeList.Text := AType; UpdateLookupControls; end; initialization RegisterFieldsProc := RegFields; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Generics.Collections, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.CheckLst, Vcl.Mask, Vcl.Menus, Vcl.ExtCtrls, Vcl.ComCtrls, JvExControls, JvExMask, JvToolEdit, JvgProgress, JvComponentBase, JvThread, Vcl.Clipbrd, System.Math, System.Hash, CalcCRC32; type TForm1 = class(TForm) JvFilenameEdit1: TJvFilenameEdit; CheckListBox1: TCheckListBox; Button1: TButton; Button2: TButton; CheckBox1: TCheckBox; Label1: TLabel; Label2: TLabel; ListView1: TListView; JvgProgress1: TJvgProgress; PopupMenu1: TPopupMenu; SelectAll1: TMenuItem; ReverseSelect1: TMenuItem; N1: TMenuItem; CopyValue1: TMenuItem; N2: TMenuItem; Compare1: TMenuItem; Timer1: TTimer; JvThread1: TJvThread; JvThread2: TJvThread; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure JvFilenameEdit1Change(Sender: TObject); procedure JvThread1Begin(Sender: TObject); procedure JvThread1Execute(Sender: TObject; Params: Pointer); procedure JvThread1FinishAll(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure CheckListBox1ClickCheck(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure ListView1ContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); procedure SelectAll1Click(Sender: TObject); procedure ReverseSelect1Click(Sender: TObject); procedure CopyValue1Click(Sender: TObject); procedure Compare1Click(Sender: TObject); procedure JvThread2Execute(Sender: TObject; Params: Pointer); private type THashType = ( _HT_CRC32, _HT_MD5, _HT_SHA1, _HT_SHA224, _HT_SHA256, _HT_SHA384, _HT_SHA512, _HT_SHA512_224, _HT_SHA512_256 ); TProgressBarState = ( PBS_Clear, PBS_Process, PBS_Pause, PBS_Stop, PBS_Complete, PBS_FileError ); private const // HashSHA2_Count = Ord(SHA512_256) - Ord(SHA224) + 1; // THashSHA2::TSHA2Version BufferSize = 1024 * 1024; // 16 * 1024 BufferPages = 2; private type THashParam = record Name: string; Value: string; end; PHashParam = ^THashParam; TBuffer = array[0..BufferSize-1] of Byte; TBufferPage = record Length: UInt64; Buffer: TBuffer; end; PBufferPage = ^TBufferPage; PHashMD5 = ^THashMD5; PHashSHA1 = ^THashSHA1; PHashSHA2 = ^THashSHA2; TSHA2Ver = THashSHA2.TSHA2Version; private FileName: string; BaseThread: TJvBaseThread; HashParam: THashParam; Percent: Integer; ThreadProcessing: Boolean; Paused: Boolean; Completed: Boolean; Pages: array[0..BufferPages-1] of TBufferPage; Page: PBufferPage; FileStream: TFileStream; // HashCRC32: TIdHashCRC32; crc32: Cardinal; HashCrc32: Boolean; HashMD5: PHashMD5; HashSHA1: PHashSHA1; HashSHA2: array[TSHA2Ver] of PHashSHA2; TotalPauseTime: DWORD; PauseStartTime: DWORD; ExecuteStartTime: DWORD; procedure FinishAll; procedure Reset; procedure CopyToClipboard(Full: Boolean); procedure StartHashThread; inline; procedure WaitHashThread; inline; procedure ProgressUpdate; procedure SetProgressBarState(State: TProgressBarState); procedure ProgressActive(Active: Boolean); procedure AddListViewItem; procedure ShowRead; function ListChecked: Boolean; public { Public declarations } end; var Form1: TForm1; implementation uses Winapi.MMSystem; {$R *.dfm} function FormatBytes(Bytes: UInt64; Float: Boolean = True): string; const btc: array[0..4] of string = ('Bytes','KB','MB','GB','TB'); var I: Integer; f: Double; begin I := 0; if Float then begin f := Bytes; while f >= 1024 do begin f := f / 1024; Inc(I); end; Result := FormatFloat('#,##0.00', f) + ' ' + btc[i]; end else begin while Bytes >= 1024 do begin Bytes := Bytes div 1024; Inc(i); end; Result := FormatFloat('#,##0', Bytes) + ' ' + btc[i]; end; end; procedure TForm1.FormCreate(Sender: TObject); begin CheckListBox1.CheckAll(cbChecked, False, True); CheckListBox1ClickCheck(CheckListBox1); Reset; // JvFilenameEdit1.FileName := Application.ExeName; BaseThread := nil; end; procedure TForm1.FormDestroy(Sender: TObject); begin JvThread1.TerminateWaitFor; end; procedure TForm1.JvFilenameEdit1Change(Sender: TObject); begin Reset; end; procedure TForm1.JvThread1Begin(Sender: TObject); var iSHA2: TSHA2Ver; FileSize: Int64; sha2: PHashSHA2; begin JvFilenameEdit1.Enabled := False; CheckListBox1.Enabled := False; ListView1.Enabled := False; ListView1.Items.BeginUpdate; ListView1.Clear; Button1.Caption := 'Stop'; FileName := JvFilenameEdit1.FileName; // HashCRC32 = 0; crc32 := 0; HashCrc32 := False; HashMD5 := nil; HashSHA1 := nil; FillChar(HashSHA2, SizeOf(HashSHA2), 0); try FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except on E: Exception do begin FileStream := nil; // JvgProgress1->Caption = SysErrorMessage(GetLastError()); JvgProgress1.Caption := E.Message; SetProgressBarState(PBS_FileError); end; end; if Assigned(FileStream) then begin FileSize := FileStream.Size; if FileSize < 1024 then Label1.Caption := Format('File size: %s bytes', [FormatCurr('#,##0', FileSize)]) else Label1.Caption := Format('File size: %s (%s bytes)', [FormatBytes(FileSize), FormatCurr('#,##0', FileSize)]); Label2.Caption := ''; TotalPauseTime := 0; PauseStartTime := 0; ExecuteStartTime := timeGetTime; Timer1.Enabled := True; end else Exit; Completed := False; Percent := 0; JvgProgress1.Percent := 0; ProgressActive(False); Button2.Enabled := True; if CheckListBox1.Checked[0] then begin // HashCRC32 := TIdHashCRC32.Create(); crc32 := _Crc32Initial; HashCrc32 := True; end; if CheckListBox1.Checked[1] then begin New(HashMD5); HashMD5.Reset; end; if CheckListBox1.Checked[2] then begin New(HashSHA1); HashSHA1.Reset; end; for iSHA2 := Low(TSHA2Ver) to High(TSHA2Ver) do begin if CheckListBox1.Checked[Integer(iSHA2) + 3] then begin New(sha2); HashSHA2[iSHA2] := sha2; sha2.FVersion := iSHA2; sha2.Reset; end; end; end; procedure TForm1.JvThread1Execute(Sender: TObject; Params: Pointer); label gotoContinue; var PageIndex: Integer; FileSize: Int64; FilePosition: Int64; Position: Integer; Timeout, ms: DWORD; NextPage: PBufferPage; sha2: PHashSHA2; iSHA2: TSHA2Ver; Strings: TStrings; f: Single; procedure SetSyncBuffer(const Name, Value: string); begin HashParam.Name := Name; HashParam.Value := Value; end; begin if Assigned(FileStream) then begin if HashCrc32 or Assigned(HashMD5) or Assigned(HashSHA1) then goto gotoContinue else begin for iSHA2 := Low(TSHA2Ver) to High(TSHA2Ver) do begin if Assigned(HashSHA2[iSHA2]) then goto gotoContinue; end; end; end; Exit; gotoContinue: PageIndex := 0; NextPage := @Pages[PageIndex]; NextPage.Length := FileStream.Read(NextPage.Buffer, BufferSize); FileSize := FileStream.Size; FilePosition := FileStream.Position; TThread.Synchronize(BaseThread, ProgressUpdate); Timeout := timeGetTime() + 50; repeat if BaseThread.Terminated then begin WaitHashThread; Exit; end; Page := NextPage; StartHashThread; if FilePosition >= FileSize then begin WaitHashThread; Break; end; Inc(PageIndex); if PageIndex >= BufferPages then PageIndex := 0; NextPage := @Pages[PageIndex]; NextPage.Length := FileStream.Read(NextPage.Buffer, BufferSize); FilePosition := FileStream.Position; f := FilePosition; Position := Round(f / FileSize * 100); WaitHashThread; if Position <> Percent then begin Percent := Position; ms := timeGetTime; if ms > Timeout then begin Timeout := ms + 25; TThread.Synchronize(BaseThread, ProgressUpdate); end; end; until (False); Strings := CheckListBox1.Items; if HashCrc32 then begin // crc32 := not crc32; SetSyncBuffer(Strings.Strings[0], IntToHex(not crc32, SizeOf(crc32) * 2)); TThread.Synchronize(BaseThread, AddListViewItem); end; if Assigned(HashMD5) then begin SetSyncBuffer(Strings.Strings[1], HashMD5.HashAsString); TThread.Synchronize(BaseThread, AddListViewItem); end; if Assigned(HashSHA1) then begin SetSyncBuffer(Strings.Strings[2], HashSHA1.HashAsString); TThread.Synchronize(BaseThread, AddListViewItem); end; for iSHA2 := Low(TSHA2Ver) to High(TSHA2Ver) do begin sha2 := HashSHA2[iSHA2]; if Assigned(sha2) then begin SetSyncBuffer(Strings.Strings[Integer(iSHA2) + 3], sha2.HashAsString); TThread.Synchronize(BaseThread, AddListViewItem); end; end; Percent := 100; Completed := True; TThread.Synchronize(BaseThread, ProgressUpdate); end; procedure TForm1.FinishAll; var iSHA2: TSHA2Ver; sha2: PHashSHA2; begin if Assigned(FileStream) then begin Timer1.Enabled := False; ShowRead; FileStream.Free; end else begin // SetProgressBarState(PBS_FileError); end; for iSHA2 := Low(TSHA2Ver) to High(TSHA2Ver) do begin sha2 := HashSHA2[iSHA2]; if Assigned(sha2) then Dispose(sha2); end; if Assigned(HashMD5) then Dispose(HashMD5); if Assigned(HashSHA1) then Dispose(HashSHA1); Button2.Enabled := False; Button1.Caption := 'Get hash'; Button2.Caption := 'Paused'; JvFilenameEdit1.Enabled := True; CheckListBox1.Enabled := True; ListView1.Enabled := True; ListView1.Items.EndUpdate; BaseThread := nil; Button1.Enabled := True; end; procedure TForm1.JvThread1FinishAll(Sender: TObject); begin JvThread1.Synchronize(FinishAll); end; procedure TForm1.JvThread2Execute(Sender: TObject; Params: Pointer); var HashType: THashType; begin HashType := THashType(Params); case HashType of _HT_CRC32: crc32 := UpdateCRC32(crc32, Page.Buffer, Page.Length); _HT_MD5: HashMD5.Update(Page.Buffer, Page.Length); _HT_SHA1: HashSHA1.Update(Page.Buffer, Page.Length); _HT_SHA224: HashSHA2[TSHA2Ver.SHA224].Update(Page.Buffer, Page.Length); _HT_SHA256: HashSHA2[TSHA2Ver.SHA256].Update(Page.Buffer, Page.Length); _HT_SHA384: HashSHA2[TSHA2Ver.SHA384].Update(Page.Buffer, Page.Length); _HT_SHA512: HashSHA2[TSHA2Ver.SHA512].Update(Page.Buffer, Page.Length); _HT_SHA512_224: HashSHA2[TSHA2Ver.SHA512_224].Update(Page.Buffer, Page.Length); _HT_SHA512_256: HashSHA2[TSHA2Ver.SHA512_256].Update(Page.Buffer, Page.Length); end; end; procedure TForm1.Timer1Timer(Sender: TObject); begin ShowRead; end; procedure TForm1.CheckListBox1ClickCheck(Sender: TObject); var b: Boolean; begin b := ListChecked; if Button1.Enabled <> b then Button1.Enabled := b; end; procedure TForm1.CheckBox1Click(Sender: TObject); var CheckBox: TCheckBox ABSOLUTE Sender; b: Boolean; I: Integer; Items: TListItems; Strings: TStrings; begin b := CheckBox.Checked; Items := ListView1.Items; Items.BeginUpdate; try I := 0; while I < Items.Count do begin Strings := Items.Item[I].SubItems; if Strings.Count > 0 then if b then Strings.Strings[0] := UpperCase(Strings.Strings[0]) else Strings.Strings[0] := LowerCase(Strings.Strings[0]); Inc(I); end; finally Items.EndUpdate; end; end; procedure TForm1.Button1Click(Sender: TObject); begin if Assigned(BaseThread) then begin if not BaseThread.Terminated then begin Button1.Enabled := False; Button2.Enabled := False; SetProgressBarState(PBS_Stop); JvThread1.Terminate; JvThread1.WaitFor; end; end else begin if JvThread1.Terminated then begin BaseThread := JvThread1.Execute(nil); JvThread1.Resume; end; end; end; procedure TForm1.Button2Click(Sender: TObject); begin ProgressActive(not Paused); if Paused then begin JvThread1.Suspend; PauseStartTime := timeGetTime; ShowRead(); end else begin TotalPauseTime := TotalPauseTime + timeGetTime - PauseStartTime; JvThread1.Resume; ShowRead(); end; end; procedure TForm1.ListView1ContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); var Item: TListItem; begin Item := ListView1.Selected; if not Assigned(Item) then if ListView1.Items.Count <> 0 then MousePos.SetLocation(ListView1.Left, ListView1.Top) else Handled := True; if not Handled then CopyValue1.Enabled := Item <> nil; end; procedure TForm1.SelectAll1Click(Sender: TObject); begin ListView1.SelectAll; end; procedure TForm1.ReverseSelect1Click(Sender: TObject); var Items: TListItems; I: Integer; begin Items := ListView1.Items; Items.BeginUpdate; try I := 0; while I < Items.Count do begin Items.Item[I].Selected := not Items.Item[I].Selected; Inc(I); end; finally Items.EndUpdate; end; end; procedure TForm1.CopyValue1Click(Sender: TObject); begin CopyToClipboard(ListView1.SelCount > 1); end; procedure TForm1.Compare1Click(Sender: TObject); begin // end; procedure TForm1.Reset; begin Label1.Caption := ''; Label2.Caption := ''; SetProgressBarState(PBS_Clear); ListView1.Clear; end; procedure TForm1.CopyToClipboard(Full: Boolean); var cb: TClipboard; Strings: TStringList; Item: TListItem; begin cb := Clipboard; if Assigned(cb) then begin Strings := TStringList.Create; try Item := ListView1.Selected; while Assigned(Item) do begin if Full then Strings.Add(Item.Caption + ': ' + Item.SubItems.Strings[0]) else Strings.Add(Item.SubItems.Strings[0]); Item := ListView1.GetNextItem(Item, sdAll, [isSelected]); end; if Strings.Count <> 0 then cb.AsText := Strings.Text; finally Strings.Free; end; end; end; procedure TForm1.StartHashThread; var sha2: PHashSHA2; iSHA2: TSHA2Ver; begin ThreadProcessing := True; if HashCrc32 then JvThread2.Execute(Pointer(_HT_CRC32)); if Assigned(HashMD5) then JvThread2.Execute(Pointer(_HT_MD5)); if Assigned(HashSHA1) then JvThread2.Execute(Pointer(_HT_SHA1)); for iSHA2 := Low(TSHA2Ver) to High(TSHA2Ver) do begin sha2 := HashSHA2[iSHA2]; if Assigned(sha2) then JvThread2.Execute(Pointer(NativeInt(_HT_SHA224) + NativeInt(iSHA2))); end; JvThread2.Resume; end; procedure TForm1.WaitHashThread; begin repeat Sleep(1); until JvThread2.Terminated; end; procedure TForm1.ProgressUpdate; begin JvgProgress1.Percent := Percent; if Completed then SetProgressBarState(PBS_Complete); end; procedure TForm1.SetProgressBarState(State: TProgressBarState); begin case State of PBS_Clear: begin JvgProgress1.Percent := 0; JvgProgress1.Caption := ''; end; PBS_Process: begin JvgProgress1.Gradient.FromColor := clGreen; JvgProgress1.Gradient.ToColor := clGreen; JvgProgress1.Caption := 'Progress...[%d%%]'; end; PBS_Pause: begin JvgProgress1.Gradient.FromColor := clYellow; JvgProgress1.Gradient.ToColor := clYellow; JvgProgress1.Caption := 'Paused [%d%%]'; end; PBS_Stop: begin JvgProgress1.Gradient.FromColor := clRed; JvgProgress1.Gradient.ToColor := clRed; JvgProgress1.Caption := 'Stop [%d%%]'; end; PBS_Complete: begin JvgProgress1.Gradient.FromColor := clLime; JvgProgress1.Gradient.ToColor := clLime; JvgProgress1.Caption := 'Completed.'; end; PBS_FileError: begin // JvgProgress1.Percent = 0; // JvgProgress1.Caption = 'Can''t open file.'; end; end; end; procedure TForm1.ProgressActive(Active: Boolean); begin Paused := Active; if Active then begin SetProgressBarState(PBS_Pause); Button2.Caption := 'Continue'; end else begin Button2.Caption := 'Pause'; SetProgressBarState(PBS_Process); end; end; procedure TForm1.AddListViewItem; var Item: TListItem; begin Item := ListView1.Items.Add; Item.Caption := HashParam.Name; if CheckBox1.Checked then Item.SubItems.Add(UpperCase(HashParam.Value)) else Item.SubItems.Add(LowerCase(HashParam.Value)); end; procedure TForm1.ShowRead; var ms, pt, Reads: DWORD; sec: Single; str: string; begin ms := timeGetTime(); if Paused then pt := ms - PauseStartTime + TotalPauseTime else pt := TotalPauseTime; sec := ms - ExecuteStartTime - pt; sec := sec / 1000; if sec < 1 then Reads := FileStream.Position else Reads := FileStream.Position div Ceil(sec); if PauseStartTime <> 0 then str := 'Read: %s/sec in %ssec (roughly)' else str := 'Read: %s/sec in %ssec'; Label2.Caption := Format(str, [FormatBytes(Reads), FormatFloat('#,##0.000', sec)]); end; function TForm1.ListChecked: Boolean; var I: Integer; begin I := 0; while I < CheckListBox1.Count do begin if CheckListBox1.Checked[I] then Exit(True); Inc(I); end; Exit(False); end; end.
Unit Types; {DS: This unit contains all of the data Types, key constants, etc for all applications } INTERFACE type (* Str255 = String[255]; anystr = string[255]; Str251 = String[251]; Str150= string[150]; Str120= string[120]; Str100= string[100]; str80 = string[80]; Str78 = String[78]; Str77 = String[77]; Str75 = String[75]; Str70 = String[70]; Str60 = String[60]; Str65 = String[65]; Str64 = String[64]; Str55 = String[55]; Str52 = String[52]; Str51 = String[51]; Str50 = String[50]; str49 = string[49]; str48 = string[48]; str46 = string[46]; Str45 = String[45]; Str44 = String[44]; Str42 = String[42]; Str41 = String[41]; Str40 = string[40]; Str38 = String[38]; Str37 = String[37]; Str36 = String[36]; Str35 = String[35]; Str34 = String[34]; str33 = string[33]; str32 = string[32]; str31 = string[31]; str30 = string[30]; str29 = string[29]; str28 = string[28]; str26 = string[26]; Str25 = string[25]; str24 = string[24]; str23 = string[23]; str22 = string[22]; Str21 = string[21]; str20 = string[20]; Str19 = String[19]; Str18 = String[18]; str17 = string[17]; str16 = string[16]; str15 = string[15]; str14 = String[14]; str13 = String[13]; str12 = string[12]; Str11 = String[11]; str10 = string[10]; str9 = string[9]; str8 = string[8]; str7 = string[7]; str6 = string[6]; str5 = string[5]; str4 = string[4]; str3 = string[3]; str2 = string[2]; str1 = string[1]; ArrayC1 = Array[1..1] of Char; ArrayC2 = Array[1..2] of Char; ArrayC3 = Array[1..3] of Char; ArrayC4 = Array[1..4] of Char; ArrayC5 = Array[1..5] of Char; ArrayC6 = Array[1..6] of Char; ArrayC7 = Array[1..7] of Char; ArrayC8 = Array[1..8] of Char; ArrayC9 = Array[1..9] of Char; ArrayC10 = Array[1..10] of Char; ArrayC11 = Array[1..11] of Char; ArrayC12 = Array[1..12] of Char; ArrayC13 = Array[1..13] of Char; ArrayC14 = Array[1..14] of Char; ArrayC15 = Array[1..15] of Char; ArrayC16 = Array[1..16] of Char; ArrayC17 = Array[1..17] of Char; ArrayC18 = Array[1..18] of Char; ArrayC19 = Array[1..19] of Char; ArrayC20 = Array[1..20] of Char; ArrayC21 = Array[1..21] of Char; ArrayC22 = Array[1..22] of Char; ArrayC23 = Array[1..23] of Char; ArrayC25 = Array[1..25] of Char; ArrayC26 = Array[1..26] of Char; ArrayC28 = Array[1..28] of Char; ArrayC30 = Array[1..30] of Char; ArrayC31 = Array[1..31] of Char; ArrayC32 = Array[1..32] of Char; ArrayC34 = Array[1..34] of Char; ArrayC35 = Array[1..35] of Char; ArrayC36 = Array[1..36] of Char; ArrayC37 = Array[1..37] of Char; ArrayC40 = Array[1..40] of Char; ArrayC41 = Array[1..41] of Char; ArrayC42 = Array[1..42] of Char; ArrayC44 = Array[1..44] of Char; ArrayC45 = Array[1..45] of Char; ArrayC46 = Array[1..46] of Char; ArrayC48 = Array[1..48] of Char; ArrayC49 = Array[1..49] of Char; ArrayC50 = Array[1..50] of Char; ArrayC51 = Array[1..51] of Char; ArrayC52 = Array[1..52] of Char; ArrayC54 = Array[1..54] of Char; ArrayC60 = Array[1..60] of Char; ArrayC80 = Array[1..80] of Char; *) charset = set of char; MenuArray = Array[1..15] of string; Const ScanRecLen = 400; MaxNumChars = 5000; Type RecField1 = Array[1..ScanRecLen] of char; {temp buffer for raw record} {x for prompt, len, x for input, y, Text Prompt len} ScrArr = Array[1..5] of Integer; MonthArr = Array[1..12] of String; LongMonthArr = Array[1..12] of String; MonthLenArray = Array[1..12] of Integer; LongString = Array[1..MaxNumChars] of Char; LineStringType = Array[1..MaxNumChars] of Char; const WaitArray : Array[1..4] of Char = ('\', Chr(196), '/', Chr(196)); LengthOfMonths : MonthLenArray = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); Months : MonthArr = ('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'); LongMonths:LongMonthArr = ('January ', 'February ', 'March ', 'April ', 'May ', 'June ', 'July ', 'August ', 'September', 'October ', 'November ', 'December '); AllKeys : set of Chr(0)..Chr(255) = [Chr(0)..Chr(255)]; Numbers : CharSet = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; NonFunctionKeys : set of '!'..'~' = ['!'..'~']; Letters : Set of 'A'..'z' = ['A'..'Z', 'a'..'z']; LettersPreceededBy_An_ : Charset = ['a', 'e', 'f', 'h', 'i', 'l', 'm', 'n', 'o', 'r', 's', 'x', 'A', 'E', 'F', 'H', 'I', 'L', 'M', 'N', 'O', 'R', 'S', 'X']; Zero = 0.0; ZeroInt = 0; const ExitButtonXOffset = 5; ExitButtonYOffset = 8; IMPLEMENTATION { Implementation section is vacuous } END.
unit ClassBoard; interface uses Types, ExtCtrls; type TBoard = class private FBoard : TImage; public procedure Repaint( Figures : TFigures ); constructor Create( BoardImage : TImage ); destructor Destroy; override; end; implementation uses Windows, Graphics, SysUtils; //============================================================================== // Constructor //============================================================================== constructor TBoard.Create( BoardImage : TImage ); begin inherited Create; FBoard := BoardImage; end; //============================================================================== // Destructor //============================================================================== destructor TBoard.Destroy; begin inherited; end; //============================================================================== // Painting //============================================================================== procedure TBoard.Repaint( Figures : TFigures ); const Pismena : array[0..7] of char = ('A','B','C','D','E','F','G','H'); Figurky : array[0..6] of char = (' ','P','V','J','S','D','K'); var I, J : integer; Rect : TRect; begin for I := 0 to 7 do for J := 0 to 7 do begin with Rect do begin Left := 20+I*( (FBoard.Width-20) div 8 ); Right := 20+(I+1)*( (FBoard.Width-20) div 8 ); Top := J*( (FBoard.Height-20) div 8 ); Bottom := (J+1)*( (FBoard.Height-20) div 8 ); end; with FBoard.Canvas do begin if (((I+J) mod 2) = 0) then begin Brush.Color := clWhite; Font.Color := clBlack; end else begin Brush.Color := clBlack; Font.Color := clWhite; end; FillRect( Rect ); if (Figures[1+I,8-J] < 0) then Font.Style := [fsBold,fsUnderline] else Font.Style := []; TextOut( 30+I*( (FBoard.Width-20) div 8 ) + 10 , 10+J*( (FBoard.Height-20) div 8 ) + 10 , Figurky[ Abs( Figures[1+I,8-J] ) ] ) end; end; with FBoard.Canvas do begin Font.Style := []; Pen.Color := clBlack; Brush.Style := bsClear; with Rect do begin Left := 20; Right := FBoard.Width; Top := 0; Bottom := FBoard.Height-20; end; Rectangle( Rect ); for I := 0 to 7 do TextOut( 6 , ((FBoard.Height-20) div 16)-5+I*((FBoard.Height-20) div 8) , IntToStr( 8-I ) ); for I := 0 to 7 do TextOut( 20+((FBoard.Width-20) div 16)-5+I*((FBoard.Width-20) div 8) , FBoard.Height - 15 , Pismena[I] ); end; end; end.
unit uMAP_debug_log; interface uses windows, sysutils, math, classes, uFIFO_map, uMAP_file, u_millesecond_timer; type tMAP_debug_log = class(tstringlist) public log_name : string; log_title : string; end; tMAP_debug_string_event = procedure(list:tMAP_debug_log; num:integer; name:string; msg:string) of object; tMAP_deubg_new_event = procedure(list:tMAP_debug_log; num:integer; name:string) of object; tMAP_debug_main = class(tobject) private timer : tmillisecond_timer; log_file : file; log_enable : boolean; title_countout : integer; f_log_name : string; f_log_title : string; f_list: tlist; procedure file_open; function file_get_name(filename:string; dirname:string):string; procedure file_write(msg:string); procedure file_close; procedure fifo_send_title; procedure fifo_send(msg:string); function list_get(index:integer):tMAP_debug_log; function list_get_count:integer; procedure list_add(name:string; msg:string; istitle : boolean); function get_time_str:string; public fifo : tFIFO_map; num_width : integer; evMessage : tMAP_debug_string_event; evTitle : tMAP_debug_string_event; evNewLog : tMAP_deubg_new_event; constructor create(v_log_name:string; v_title:string; evlog:tMapFileLog); destructor destroy;override; function create_log : boolean; function open_logs : boolean; procedure send(msg:string); procedure send_common(msg:string); procedure send_nums(nums : array of const); procedure recive_check; property log_name:string read f_log_name; property log_title:string read f_log_title; property list[index:integer]:tMAP_debug_log read list_get; property list_count:integer read list_get_count; end; implementation {$I-} const //0123456701234567 !!!!!!!!! need: size mod 8 = 0 for tabs //'00:00:00 ' time_title = 'Time '; //'000.00' ms_title = ' dlt_T'; add_title = time_title + ms_title; key_title = '#`@~'; key_message = ':@~`'; common_name = '<no_name>'; procedure fix_length(var s:string; len:integer); begin if length(s) > len then begin // if len = 1 then s := copy(s,1, len) // else // s := copy(s,1, len-1)+'~'; end else while length(s) < len do s := s + ' '; end; constructor tMAP_debug_main.create(v_log_name:string; v_title:string; evlog:tMapFileLog); var name : string; begin inherited create; name := ExtractFileName(ParamStr(0)); if pos('.exe', name) > 0 then delete(name, length(name)-3, 4); f_log_name := v_log_name; // f_log_name := name + '#' + v_log_name; f_log_title := add_title + ' ' + v_title; fifo := tFIFO_map.create('Debug_Main', $40000, evLog); end; destructor tMAP_debug_main.destroy; var k : integer; begin send_common('Debug log close, name = "' + log_name + '", title = "' + log_title + '"'); fifo_send(get_time_str + '================ DISCONNECT ================'); fifo_send(' '); file_close; fifo.close; fifo.Free; if f_list <> nil then begin for k:=0 to list_count-1 do (list[k] as tMAP_debug_log).Free; f_list.Free; f_list := nil; end; inherited destroy; end; function tMAP_debug_main.file_get_name(filename:string; dirname:string):string; var s : string; k : integer; // old_dir : string; begin s:=DateToStr(Date)+'_'+timetostr(Time); for k:=1 to length(s)-1 do if not(s[k] in ['0'..'9']) then s[k]:='_'; { old_dir := GetCurrentDir; IOResult; chdir(ExtractFilePath(ParamStr(0))); IOResult; MkDir(dirname); IOResult; chdir(old_dir); IOResult; } result:=dirname+'\'+s+'_'+filename; end; procedure tMAP_debug_main.file_open; begin log_enable := false; AssignFile(log_file, file_get_name(log_name, 'logs_m')); Rewrite(log_file, 1); log_enable := ioresult = 0; end; procedure tMAP_debug_main.file_write; begin if not log_enable then exit; msg := msg + #13#10; BlockWrite(log_file, msg[1], length(msg)*sizeof(msg[1])); log_enable := IOResult = 0; end; procedure tMAP_debug_main.file_close; begin CloseFile(log_file); IOResult; log_enable := false; end; function tMAP_debug_main.create_log:boolean; begin result := false; if not fifo.open_as_writer then exit; file_open; file_write(log_name); file_write(log_title); file_write(''); send_common('Debug log open, name = "' + log_name + '", title = "' + log_title + '"'); fifo_send_title; fifo_send(' '); fifo_send(get_time_str + '================ CONNECT ================'); title_countout := 0; result := true; end; function tMAP_debug_main.open_logs:boolean; var new_log : tMAP_debug_log; begin result := false; if not fifo.open_as_writer then exit; f_list := tlist.Create; new_log := tMAP_debug_log.Create; new_log.log_name := common_name; new_log.log_title := add_title + ' ================ Message ================'; f_list.Add(new_log); result := true; end; procedure tMAP_debug_main.recive_check; var old_rx : int64; pos_message : integer; pos_title : integer; name : string; msg : string; istitle : boolean; timeout : cardinal; begin if self = nil then exit; if f_list = nil then exit; old_rx := fifo.stat.readed.count; timeout := GetTickCount + 100; while ((fifo.stat.readed.count - old_rx) < fifo.bytes_size) and (GetTickCount < timeout) do begin if not fifo.read_string(msg) then break; pos_message := pos(key_message, msg); pos_title := pos(key_title, msg); if (pos_message = 0) and (pos_title = 0) then begin list_add(common_name, msg, false); continue; end; if (pos_message <> 0) and (pos_title <> 0) then begin if pos_message <= pos_title then pos_title := 0 else pos_message := 0; end; istitle := pos_title <> 0; pos_message := pos_message or pos_title; name := copy(msg, 1, pos_message-1); delete(msg, 1, pos_message + length(key_message)-1); list_add(name, msg, istitle); end; end; procedure tMAP_debug_main.list_add(name:string; msg:string; istitle : boolean); var k : integer; new_log : tMAP_debug_log; begin for k:=0 to list_count-1 do if list[k].log_name = name then begin if istitle then begin list[k].log_title := msg; if @evTitle <> nil then evTitle(list[k], k, name, msg); end else begin list[k].Add(msg); if @evMessage <> nil then evMessage(list[k], k, name, msg); end; exit; end; new_log := tMAP_debug_log.Create; new_log.log_name := name; f_list.Add(new_log); k := f_list.IndexOf(new_log); if (@evNewLog <> nil) and (k >= 0) then evNewLog(list[k], k, name); if k >= 0 then if istitle then begin list[k].log_title := msg; if @evTitle <> nil then evTitle(list[k], k, name, msg); end else begin new_log.Add(msg); if @evMessage <> nil then evMessage(list[k], k, name, msg); end; end; function tMAP_debug_main.list_get(index:integer):tMAP_debug_log; begin result := nil; if index >= f_list.Count then exit; result := tobject(f_list.Items[index]) as tMAP_debug_log; end; function tMAP_debug_main.list_get_count; begin result := 0; if f_list = nil then exit; result := f_list.Count; end; procedure tMAP_debug_main.fifo_send_title; begin fifo.write_string(log_name + key_title + log_title); end; procedure tMAP_debug_main.fifo_send(msg:string); begin dec(title_countout); if title_countout < 0 then begin title_countout := 10; fifo_send_title; end; fifo.write_string(log_name + key_message + msg); end; function tMAP_debug_main.get_time_str:string; var s : string; t : double; begin result := ''; if self = nil then exit; t := milliseconds_get(timer); milliseconds_start(timer); s:=''; s := s + timetostr(time); fix_length(s, length(time_title)); s := s + ' '; if t>99999 then s := s + '99999+' else s := s + FloatToStrF(t, ffFixed, 4, 3); fix_length(s, length(add_title) + 1); s := s + ' '; result := s; end; procedure tMAP_debug_main.send(msg : string); var s : string; begin if self = nil then exit; s := get_time_str; file_write(s + msg); fifo_send(s + msg); end; procedure tMAP_debug_main.send_common(msg : string); begin if self = nil then exit; if fifo = nil then exit; fifo.write_string(get_time_str + msg); end; procedure tMAP_debug_main.send_nums(nums : array of const); var msg : string; s : string; i : integer; begin if self = nil then exit; s:=''; msg := ''; for I := 0 to High(nums) do begin with TVarRec(nums[I]) do case VType of vtInteger : s := IntToStr(math.min(9999999, max(-999999, VInteger))); vtInt64 : s := IntToStr(math.min(9999999, max(-999999, VInt64^))); vtBoolean : s := BoolToStr(VBoolean, true); vtChar : s := vchar; vtExtended : s := FloatToStrF(vextended^, ffFixed, 4,3); vtString : s := vstring^; vtPointer : s := IntToHex(cardinal(VPointer), 8); vtPChar : s := vpchar^; vtObject : s := vobject.ClassName; vtClass : s := vclass.ClassName; else s:= '???'; end; if num_width = 0 then s:=s + #9 else fix_length(s, num_width); msg := msg + s; end; send(msg); end; end.
unit Dump; interface uses {$IFDEF FPC} LResources, {$ENDIF} {$IFNDEF LINUX} Windows, Messages, {$ENDIF} Classes, SysUtils, Db, Graphics, Controls, Forms, Dialogs, Buttons, DBCtrls, ExtCtrls, Grids, DBGrids, StdCtrls, ToolWin, ComCtrls, UniDacVcl, DBAccess, Uni, UniDump, DADump, DemoFrame, UniDacDemoForm; type TDumpFrame = class(TDemoFrame) UniDump: TUniDump; meSQL: TMemo; Panel2: TPanel; Panel3: TPanel; btBackup: TSpeedButton; btBackupSQL: TSpeedButton; btRestore: TSpeedButton; Panel6: TPanel; edTbNames: TEdit; Label1: TLabel; Panel7: TPanel; Label2: TLabel; edQuery: TEdit; pnResult: TPanel; ProgressBar: TProgressBar; lbTableName: TLabel; Label3: TLabel; Label4: TLabel; Panel4: TPanel; cbAddDrop: TCheckBox; Panel5: TPanel; cbQuoteNames: TCheckBox; procedure btBackupClick(Sender: TObject); procedure btRestoreClick(Sender: TObject); procedure btBackupSQLClick(Sender: TObject); procedure UniDumpRestoreProgress(Sender: TObject; Percent: Integer); procedure UniDumpBackupProgress(Sender: TObject; TableName: String; ObjectNum, TableCount, Percent: Integer); private { Private declarations } public procedure SetOptions; // Demo management procedure Initialize; override; end; implementation {$IFNDEF FPC} {$IFDEF CLR} {$R *.nfm} {$ELSE} {$R *.dfm} {$ENDIF} {$ENDIF} procedure TDumpFrame.SetOptions; begin UniDump.TableNames := edTbNames.Text; UniDump.Options.AddDrop := cbAddDrop.Checked; UniDump.Options.QuoteNames := cbQuoteNames.Checked; end; procedure TDumpFrame.btBackupClick(Sender: TObject); begin try SetOptions; UniDump.SQL.Clear; UniDump.Backup; finally ProgressBar.Position := 0; lbTableName.Caption := ''; lbTableName.Parent.Repaint; meSQL.Lines.Assign(UniDump.SQL); end; end; procedure TDumpFrame.btRestoreClick(Sender: TObject); begin ProgressBar.Position := 0; lbTableName.Caption := ''; lbTableName.Parent.Repaint; UniDump.SQL.Assign(meSQL.Lines); try UniDump.Restore; finally ProgressBar.Position := 0; end; end; procedure TDumpFrame.btBackupSQLClick(Sender: TObject); begin try SetOptions; UniDump.BackupQuery(edQuery.Text); finally ProgressBar.Position := 0; lbTableName.Caption := ''; lbTableName.Parent.Repaint; meSQL.Lines.Assign(UniDump.SQL); end; end; procedure TDumpFrame.UniDumpRestoreProgress(Sender: TObject; Percent: Integer); begin ProgressBar.Position := Percent; end; procedure TDumpFrame.UniDumpBackupProgress(Sender: TObject; TableName: String; ObjectNum, TableCount, Percent: Integer); begin if lbTableName.Caption <> TableName then begin lbTableName.Caption := TableName; pnResult.Repaint; end; ProgressBar.Position := Percent; end; // Demo management procedure TDumpFrame.Initialize; begin UniDump.Connection := Connection as TUniConnection; end; initialization {$IFDEF FPC} {$I Dump.lrs} {$ENDIF} end.
unit tfSettings; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ButtonPanel, StdCtrls, ExtCtrls, EditBtn, JvTFUtils, JvTFDays; type TGlobalSettings = record StartToday: Boolean; StartDate: TDate; Hr2400: Boolean; // 24 hour or 12 hour AM/PM format FirstDayOfWeek: TTFDayOfWeek; PrimeTimeStart: TTime; PrimeTimeEnd: TTime; PrimeTimeColor: TColor; IconSet: Integer; end; var GlobalSettings: TGlobalSettings = ( StartToday: true; StartDate: 0; Hr2400: false; FirstDayOfWeek: dowSunday; PrimeTimeStart: 8 * ONE_HOUR; PrimeTimeEnd: 17 * ONE_HOUR; PrimeTimeColor: $00C4FFFF; IconSet: 0 ); type { TSettingsForm } TSettingsForm = class(TForm) Bevel1: TBevel; Bevel2: TBevel; Bevel3: TBevel; ButtonPanel1: TButtonPanel; cbTimeFormat: TComboBox; cbFirstDayOfWeek: TComboBox; clbPrimeTimeColor: TColorButton; cbIconSet: TComboBox; deStartDate: TDateEdit; Label1: TLabel; lblIconSet: TLabel; lblPrimeTimeStart: TLabel; lblPrimeTimeEnd: TLabel; lblFirstDayOfWeek: TLabel; lblTimeFormat: TLabel; Panel1: TPanel; edPrimeTimeStart: TTimeEdit; edPrimeTimeEnd: TTimeEdit; StartDatePanel: TPanel; rbStartDate: TRadioButton; rbStartToday: TRadioButton; procedure deStartDateAcceptDate(Sender: TObject; var ADate: TDateTime; var AcceptDate: Boolean); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure OKButtonClick(Sender: TObject); private FOKPressed: Boolean; procedure ControlsToSettings; procedure SettingsToControls; end; var SettingsForm: TSettingsForm; implementation {$R *.lfm} procedure TSettingsForm.ControlsToSettings; begin GlobalSettings.StartToday := rbStartToday.Checked; if not GlobalSettings.StartToday and (GlobalSettings.StartDate = Date) then GlobalSettings.StartDate := 0 else GlobalSettings.StartDate := deStartDate.Date; GlobalSettings.Hr2400 := cbTimeFormat.ItemIndex = 0; GlobalSettings.FirstDayOfWeek := TTFDayOfWeek(cbFirstDayOfWeek.ItemIndex); GlobalSettings.PrimeTimeStart := frac(edPrimeTimeStart.Time); GlobalSettings.PrimeTimeEnd := frac(edPrimeTimeEnd.Time); GlobalSettings.PrimeTimeColor := clbPrimeTimeColor.ButtonColor; GlobalSettings.IconSet := cbIconSet.ItemIndex; end; procedure TSettingsForm.deStartDateAcceptDate(Sender: TObject; var ADate: TDateTime; var AcceptDate: Boolean); begin rbStartDate.Checked := true; end; procedure TSettingsForm.SettingsToControls; begin if GlobalSettings.StartToday then rbStartToday.Checked := true else rbStartDate.Checked := true; if GlobalSettings.StartDate = 0 then deStartDate.Date := Date() else deStartDate.Date := GlobalSettings.StartDate; cbTimeFormat.ItemIndex := ord(not GlobalSettings.Hr2400); cbFirstDayOfWeek.ItemIndex := ord(GlobalSettings.FirstDayOfWeek); edPrimeTimeStart.Time := GlobalSettings.PrimeTimeStart; edPrimeTimeEnd.Time := GlobalSettings.PrimeTimeEnd; clbPrimeTimeColor.ButtonColor := GlobalSettings.PrimeTimeColor; cbIconSet.ItemIndex := GlobalSettings.IconSet; end; procedure TSettingsForm.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin if FOKPressed then ControlsToSettings; end; procedure TSettingsForm.FormCreate(Sender: TObject); var i: Integer; begin cbFirstDayOfWeek.Items.BeginUpdate; try cbFirstDayOfWeek.Clear; for i:=1 to 7 do cbFirstDayOfWeek.Items.Add(FormatSettings.LongDayNames[i]); finally cbFirstDayOfWeek.Items.EndUpdate; end; end; procedure TSettingsForm.FormShow(Sender: TObject); begin FOKPressed := false; SettingsToControls; end; procedure TSettingsForm.OKButtonClick(Sender: TObject); begin FOKPressed := true; end; end.
unit uStrings; interface const intFileIconIndex = 1; strLocDefLang = 'En'; CrLf = sLineBreak; strDefaultExt = '.xml'; strCryptedExt = '.opwd'; strRootNode = 'Root'; strHeaderNode = 'Header'; strDataNode = 'Data'; strFolderNode = 'Folder'; strItemNode = 'Item'; strDefItemNode = 'DefItem'; strConfigFile = 'config.xml'; strLanguagesFolder = '..\..\Languages'; strLink = 'https://github.com/Mrgnstrn/OmgPass/releases/'; strSaveDialogDefFileName = 'NewCryptedBase'; strBackupFilePrefix = 'Backup_'; strBackupDTformat = 'yymmdd_hhmmss_'; strDefaultBackupFolder = '.\Backups'; strAssociateParam = 'fa'; strDeassociateParam = 'dfa'; strDefaultLanguageName = 'Default (English)'; const arrFieldFormats: array[0..8] of String = ('title', 'text', 'pass', 'web', 'comment', 'date', 'mail', 'file', ''); const arrNodeTypes: array[0..9] of String = ('root', 'header', 'data', 'page', 'folder', 'deffolder', 'item', 'defitem', 'field', ''); const arrDefFieldNames: array[0..8] of String = ('Title', 'Login', 'Password', 'Website', 'Comment', 'Date', 'Mail', 'File', 'Text or Login'); resourcestring rsFileTypeDescription = 'OmgPass crypted container'; //Описание для файловой ассоциации rsFileTypeName = 'OmgPass.Crypted'; rsTypes ='Title|Text|Pass|Link|Memo|Date|Mail|File'; //rsDefFieldNames = 'Title|Login|Password|Website|Comment|Date|Mail|File|Text or Login'; //rsTitleDefName = 'Title'; // rsTextDefName = 'Login'; // rsPassDefName = 'Password'; // rsCommentDefName = 'Comment'; // rsLinkDefName = 'Website'; // rsDateDefName = 'Date'; // rsMailDefName = 'Mail'; // rsFileDefName = 'File'; //Название новой записи, папки, страницы rsNewItemText = 'New record'; rsNewFolderTitle = 'New folder'; rsNewPageTitle = 'Page'; //Серый текст в поле поиска rsSearchText = 'Search'; //Инфо блок для папок rsInfoTitle = 'Title: '; rsInfoSubfolders = 'Subfolders: '; rsInfoTotalFolders = 'Total folders: '; rsInfoSubItems = 'Subrecords: '; rsInfoTotalItems = 'Total records: '; //MessageBoxes rsDelFieldConfirmationText = 'Confirm to delete field "%s"?' + CrLf + 'Value will be deleted too'; rsDelFieldConfirmationCaption = 'Deleting field'; rsCantDelTitleField = 'Can''t delete unique title of record'; //DeleteNode rsDelNodeTitle = 'Deleting'; rsDelItem = 'Warning!' + CrLf + 'Are you sure you want to delete the record %s?'; rsDelFolder ='Warning!' + CrLf + 'Are you sure you want to delete the folder %s?' + CrLf + 'This will delete all subfolders and records!'; rsDelPage = 'WARNING!' + CrLf + 'Are you sure you want to delete the page %s?' + CrLf + 'This will delete all subfolders and records!!!' + CrLf + 'CONFIRM DELETING?'; rsCantDelPage = 'Sorry! Can''t delete unique page.'; // rsChangeTitleWarningCaption = 'Deleting field'; // rsChangeTitleWarning = 'Can''t change format for only title of record'; rsFieldNotSelected = 'Field not selected'; rsDemo = 'Sorry, you''ve reached the limit of the records count for the test version of program'; rsDocumentIsEmpty = 'Hmm, it looks like your document is empty!' + CrLf + 'Before working with the document,' + CrLf + 'you must add at least one page.' + CrLf + CrLf + 'Would you like to do this?'; rsDocumentIsEmptyTitle = 'Ooops!'; // //Window captions //Заголовки окошек rsFrmAccountsCaption = ' welcomes you!'; //rsFrmAccountsCaptionOpen = 'Open base'; rsFrmAccountsCaptionChange = ' - Document manager'; rsFrmEditItemCaption = 'Edit record'; rsFrmEditItemCaptionDef = 'Edit default record'; rsFrmEditItemCaptionNew = 'New record'; rsFrmEditFieldCaption = 'Edit field properties'; rsFrmEditFieldCaptionNew = 'New field...'; //Modal buttons //Модальные кнопочки rsClose = 'Close'; rsCancel = 'Cancel'; rsOK = 'OK'; rsExit = 'Exit'; rsOpen = 'Open'; rsCopy = 'Copy'; //Smart-buttons hints //Подсказки для кнопулек // rsHintOpenLink = 'Open link'; // rsHintCopyToClipboard = 'Copy to clipboard'; // rsHintCopyFromClipboard = 'Copy from clipboard'; // rsHintGenerate = 'Generate password'; // rsHintEditField = 'Edit field properties'; // rsHintSaveFile = 'Save file(s)'; // rsHintAddFile = 'Add file(s)'; //frmAccounts rsSaveDialogFilter = 'Omg!Pass Crypted files (*.opwd)|*.opwd|Omg!Pass XML files (*.xml)|*.xml'; rsOpenDialogFilter = 'Omg!Pass Crypted files (*.opwd)|*.opwd|Omg!Pass XML files (*.xml)|*.xml|All files|*.*'; rsOpenDialogFilterCryptedOnly = 'Omg!Pass Crypted (*.opwd)|*.opwd'; rsCreateNewNeedFile = 'Please select location for new base' + CrLf + 'and type main password if it needed.'; rsCreateNewNeedFileTitle = 'Can''t create new base'; rsCreateNewWrongConfirm = 'Confirm field is not equal to password'; rsCreateNewWrongConfirmTitle = 'Can''t create new base'; rsFileNotFoundMsg = 'File not found on the stored path!' + CrLf + 'Would you like to create a new document' + CrLf + '%s ?'; rsFileNotFoundMsgTitle = 'File not found'; rsSaveDialogFileExists = 'You have selected an existing file:' + CrLf + '%s' + CrLf+ 'Overwrite it?'; rsSaveDialogTitle = 'Save new document as...'; rsOpenDialogTitle = 'Open document...'; rsOpenDocumentError = 'Can''t open file' + CrLf + '%s' + CrLf + 'Please, make sure it is the correct file' + CrLf + '(Error class: %s)'; rsOpenDocumentErrorTitle = 'Open document error'; rsWrongPasswordError = 'Wrong or incorrect password! You can try again.' + CrLf + ' Please, check CapsLock and see on hint image'; rsWrongPasswordErrorTitle = 'Wrong password'; {rsDeletingDocument = 'Warning!' + CrLf + 'Are you sure you want to delete the document' + CrLf + '%s ?'; rsDeletingDocumentTitle = 'Deleting...';} rsTxtPassFileNotFound = 'File not found'; rsTxtPassFileNotSelected = 'File not selected'; rsTxtPassFileIsBad = 'Bad or corupted file'; rsTxtPassPassEmpty = 'Empty password used'; rsTxtPassAlrOpened = 'File already opened'; rsTxtPassPassNotReq = 'Not required'; //frmMain rsAbout = '%s ver. %s' + CrLf +'An simple app for store and managment yours passwords' + CrLF + 'Copyright by Nazarov Timur (vk.com/id1669165)'+ CrLf + CrLf + 'Boomy icons by Milosz Wlazlo (miloszwl.deviantart.com)' + CrLf + 'Class TRyMenu by Alexey Rumyancev (skitl@mail.ru)'; rsAboutTitle = 'About...'; //frmOptions rsCantCreateBackupFolder = 'Can''t create backup folder '; rsCantCreateBackup = 'Can''t create backup of '; rsSelectBackupDirectoryDialog = 'Select folder for backups...'; rsWrongBackupFolderTitle = 'Wrong backup folder'; rsWrongBackupFolder = 'Can''t find or create folder' + CrLf + '%s' + CrLf + 'Would you like set default folder?' + CrLf + CrLf + 'Yes - set default value' + CrLf + 'No - try another value' + CrLf + 'Cancel - set previous value'; rsBackupHintTitle = 'Full path of backup folder:'; //frmPassword rsWrongOldPassword = 'Wrong old password'; rsWrongOldPasswordTitle = 'Error'; rsWrongNewPassword = 'New password equals to old password'; rsWrongNewPasswordTitle = 'Error'; rsNewPasswordEmpty = 'Confirm using empty password?'; rsNewPasswordEmptyTitle = 'New password is empty'; rsWrongConfirmPassword = 'Wrong confirm password'; rsWrongConfirmPasswordTitle = 'Error'; rsPasswordChanged = 'Password has been succesfully changed!'; rsPasswordChangedTitle = 'Excellent news'; //frmGenerator rsGeneratorError = 'Selected set of characters and settings are not compatible!'; rsGeneratorErrorTitle = 'Warning'; implementation end.
unit Points; interface uses SysUtils, Classes; type TPoint = class X : Real; Y : Real; Name : String; constructor Create(x, y: Real; name : String); overload; constructor Create(x, y: Real); overload; function ToString() : String; end; function ComparePoints(item1, item2 : Pointer) : Integer; function VectorProduction(item1, item2, item3 : Pointer) : Real; implementation constructor TPoint.Create(x, y: Real; name : String); begin self.X:= x; self.Y:= y; self.Name := name; end; constructor TPoint.Create(x, y: Real); begin self.X:= x; self.Y:= y; end; function TPoint.ToString() : String; begin Result := 'name = ' + name + 'x = ' + FloatToStr(X) + ', y = ' + FloatToStr(Y); end; function ComparePoints(item1, item2 : Pointer) : Integer; var point1, point2 : TPoint; begin point1 := TPoint(item1); point2 := TPoint(item2); if (point1.X < point2.X) OR ((point1.X = point2.X) AND (point1.Y < point2.Y)) then Result := -1 else if (point1.X = point2.X) AND (point1.Y = point2.Y) then Result := 0 else Result := 1; end; function VectorProduction(item1, item2, item3 : Pointer) : Real; var a, b, c : TPoint; begin a := TPoint(item1); b := TPoint(item2); c := TPoint(item3); Result := a.X * (b.Y - c.Y) + b.X * (c.Y - a.Y) + c.X * (a.Y - b.Y); end; end.
unit osDispatchFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, osFrm, ImgList, ActnList, osActionList, ComCtrls, ToolWin, Buttons, ExtCtrls; type TosDispatchForm = class(TosForm) MainControlBar: TControlBar; ControlBarPanel: TPanel; ConfirmButton: TSpeedButton; tbrFilter: TToolBar; btnFilter: TToolButton; OnExecute: TAction; ConfirmAction: TAction; OnConfirm: TAction; procedure ConfirmActionExecute(Sender: TObject); private FSelectedList: TStringlist; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Execute(PSelectedList: TStringList): boolean; property SelectedList: TStringList read FSelectedList; end; var osDispatchForm: TosDispatchForm; implementation {$R *.dfm} { TosDispatchForm } constructor TosDispatchForm.Create(AOwner: TComponent); begin inherited; FSelectedList := TStringList.Create; end; destructor TosDispatchForm.Destroy; begin FSelectedList.Free; inherited; end; function TosDispatchForm.Execute(PSelectedList: TStringList): boolean; begin try ModalResult := mrNone; FSelectedList.Assign(PSelectedList); OnExecute.Execute; ShowModal; finally Result := (ModalResult = mrOK); end; end; procedure TosDispatchForm.ConfirmActionExecute(Sender: TObject); begin inherited; ModalResult := mrNone; OnConfirm.Execute; ModalResult := mrOK; Close; end; end.
{***************************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 2000-2001 Borland Software Corporation } { } {***************************************************************} unit SvrLogDetailDlg; interface uses {$IFDEF MSWINDOWS} Registry, {$ENDIF} SysUtils, Classes, QControls, QForms, QDialogs, QStdCtrls, QActnList, SvrLogFrame, SvrLogDetailFrame, IniFiles, QTypes, QMenus; type TLogDetail = class(TForm) ActionList1: TActionList; PrevAction: TAction; NextAction: TAction; CloseAction: TAction; Button1: TButton; Button2: TButton; Button3: TButton; LogDetailFrame: TLogDetailFrame; procedure PrevActionExecute(Sender: TObject); procedure PrevActionUpdate(Sender: TObject); procedure NextActionExecute(Sender: TObject); procedure NextActionUpdate(Sender: TObject); procedure CloseActionExecute(Sender: TObject); procedure FormShow(Sender: TObject); private FLogFrame: TLogFrame; public constructor Create(AOwner: TComponent); override; procedure Load(Reg: TCustomIniFile; const Section: string); procedure Save(Reg: TCustomIniFile; const Section: string); property LogFrame: TLogFrame read FLogFrame write FLogFrame; end; var FLogDetail: TLogDetail; implementation {$R *.xfm} procedure TLogDetail.PrevActionExecute(Sender: TObject); begin FLogFrame.Previous; FLogFrame.ShowDetail(LogDetailFrame); end; procedure TLogDetail.PrevActionUpdate(Sender: TObject); begin (Sender as TAction).Enabled := FLogFrame.Index > 0; if not ((Sender as TAction).Enabled) and (FocusedControl = Button1) then Button3.SetFocus; end; procedure TLogDetail.NextActionExecute(Sender: TObject); begin FLogFrame.Next; FLogFrame.ShowDetail(LogDetailFrame); end; procedure TLogDetail.NextActionUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (FLogFrame.Count > 0) and (FLogFrame.Index < FLogFrame.Count - 1); if (not (Sender as TAction).Enabled) and (FocusedControl = Button2) then Button3.SetFocus; end; constructor TLogDetail.Create(AOwner: TComponent); begin inherited Create(AOwner); HelpContext := 4310; HelpType := htContext; end; procedure TLogDetail.CloseActionExecute(Sender: TObject); begin ModalResult := mrOk; end; const sLeft = 'Left'; sTop = 'Top'; sWidth = 'Width'; sHeight = 'Height'; procedure TLogDetail.Load(Reg: TCustomIniFile; const Section: string); begin if Reg.ReadInteger(Section, sLeft, 0) <> 0 then begin Position := poDesigned; Self.Left := Reg.ReadInteger(Section, sLeft, Self.Left); Self.Top := Reg.ReadInteger(Section, sTop, Self.Top); Self.Width := Reg.ReadInteger(Section, sWidth, Self.Width); Self.Height := Reg.ReadInteger(Section, sHeight, Self.Height); end; LogDetailFrame.Load(Reg, Section); end; procedure TLogDetail.Save(Reg: TCustomIniFile; const Section: string); begin LogDetailFrame.Save(Reg, Section); Reg.WriteInteger(Section, sLeft, Self.Left); Reg.WriteInteger(Section, sTop, Self.Top); Reg.WriteInteger(Section, sWidth, Self.Width); Reg.WriteInteger(Section, sHeight, Self.Height); end; procedure TLogDetail.FormShow(Sender: TObject); begin FLogFrame.ShowDetail(LogDetailFrame); LogDetailFrame.Memo1.SetFocus; end; end.
unit Options; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TOptionsForm = class(TForm) Button1: TButton; Button2: TButton; cbInputDevices: TComboBox; Label1: TLabel; cbOutputDevices: TComboBox; Label2: TLabel; DevicePropsLabel: TLabel; procedure FormCreate(Sender: TObject); procedure cbOutputDevicesChange(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } Procedure CreateDeviceLists(sender:TObject) ; end; var OptionsForm: TOptionsForm; implementation uses MIDI,MMSystem; {$R *.dfm} procedure TOptionsForm.FormCreate(Sender: TObject); begin CreateDeviceLists(Sender); end; procedure TOptionsForm.Button1Click(Sender: TObject); begin Self.Close; end; procedure TOptionsForm.cbOutputDevicesChange(Sender: TObject); begin DevicePropsLabel.Caption:= MidiOutput_DeviceProps(cbOutputDevices.ItemIndex); MidiOut_Open (cbOutputDevices.ItemIndex); end; procedure TOptionsForm.CreateDeviceLists(sender:TObject) ; var NumOfMIDIOutDevs:UINT; OutCaps:TMidiOutCaps; lpOutCaps:PMidiOutCaps; NumOfMIDIInDevs:UINT; InCaps:TMidiInCaps; lpInCaps:PMidiInCaps; i:integer; begin //MIDI Output devices lpOutCaps:=PMidiOutCaps(Addr(OutCaps)); NumOfMIDIOutDevs:=midiOutGetNumDevs; if NumOfMIDIOutDevs <1 then exit; For i:=0 to NumOfMIDIOutDevs-1 do begin midiOutGetDevCaps(UINT(i),lpOutCaps,SizeOf(TMidiOutCaps)); cbOutputDevices.Items.Insert(i,OutCaps.szPname); end; //MIDI Input devices lpInCaps:=PMidiInCaps(Addr(InCaps)); NumOfMIDIInDevs:=midiInGetNumDevs; if NumOfMIDIInDevs <1 then exit; For i:=0 to NumOfMIDIInDevs-1 do begin midiInGetDevCaps(UINT(i),lpInCaps,SizeOf(TMidiInCaps)); cbInputDevices.Items.Insert(i,InCaps.szPname); end; end; end.
unit UFSearchUser; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UFSearchBase, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Imaging.pngimage, Vcl.ExtCtrls, 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, FireDAC.Phys.MongoDBDataSet, UDMMongo, Vcl.DBCtrls, JvExDBGrids, JvDBGrid; type TFSearchUser = class(TFSearchBase) lblActiveTitle: TLabel; rbOnlyActive: TRadioButton; lblRbOnlyActive: TLabel; lblRbOnlyNotActive: TLabel; rbOnlyNotActive: TRadioButton; rbAll: TRadioButton; lblRbAll: TLabel; procedure lblRbOnlyActiveClick(Sender: TObject); procedure lblRbOnlyNotActiveClick(Sender: TObject); procedure lblRbAllClick(Sender: TObject); private dbActive : TDBCheckBox; procedure InitializeCheckBoxActive; { Private declarations } public { Public declarations } end; var FSearchUser: TFSearchUser; implementation {$R *.dfm} procedure TFSearchUser.InitializeCheckBoxActive; begin dbActive := TDBCheckBox.Create(nil); dbActive.DataSource := DSMain; dbActive.DataField := 'active'; dbActive.Color := dbgrdData.Color; dbActive.Caption := ''; end; procedure TFSearchUser.lblRbAllClick(Sender: TObject); begin inherited; rbAll.Checked := true; end; procedure TFSearchUser.lblRbOnlyActiveClick(Sender: TObject); begin inherited; rbOnlyActive.Checked := true; end; procedure TFSearchUser.lblRbOnlyNotActiveClick(Sender: TObject); begin inherited; rbOnlyNotActive.Checked := true; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Data.Win.ADODB, Vcl.StdCtrls, System.ImageList, Vcl.ImgList, Vcl.ButtonGroup, Vcl.ToolWin, Vcl.ActnMan, Vcl.ActnCtrls, System.Actions, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.DBGrids; type TForm1 = class(TForm) con: TADOConnection; tbl: TADOTable; dsTbl: TDataSource; dbgTbl: TDBGrid; cbbTabls: TComboBox; imlMain: TImageList; amTbl: TActionManager; actInsert: TAction; actDelete: TAction; acttb: TActionToolBar; actCancel: TAction; actPost: TAction; actEdit: TAction; qry: TADOQuery; procedure actCancelExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actInsertExecute(Sender: TObject); procedure actInsertUpdate(Sender: TObject); procedure actPostExecute(Sender: TObject); procedure actPostUpdate(Sender: TObject); procedure cbbTablsChange(Sender: TObject); procedure dbgTblKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbgTblKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormActivate(Sender: TObject); procedure tblAfterOpen(DataSet: TDataSet); private FInited: Boolean; property Inited: Boolean read FInited; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.actCancelExecute(Sender: TObject); begin tbl.Cancel(); end; procedure TForm1.actDeleteExecute(Sender: TObject); begin tbl.Delete(); end; procedure TForm1.actEditExecute(Sender: TObject); begin tbl.Edit(); end; procedure TForm1.actInsertExecute(Sender: TObject); begin tbl.Append(); tbl.FieldByName('name').AsString:='new'; end; procedure TForm1.actInsertUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (tbl.State in [dsBrowse]); end; procedure TForm1.actPostExecute(Sender: TObject); begin tbl.Post(); end; procedure TForm1.actPostUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (tbl.State in dsEditModes ); end; procedure TForm1.cbbTablsChange(Sender: TObject); begin tbl.Close(); tbl.TableName:=(Sender as TComboBox).Text; tbl.Open(); end; procedure TForm1.dbgTblKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_INSERT: Key:=0; VK_DOWN: if (Sender as TDBGrid).DataSource.DataSet.Eof then Key:=0; VK_DELETE: if ssCtrl in Shift then Key:=0; end; end; procedure TForm1.dbgTblKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_DOWN: if (Sender as TDBGrid).DataSource.DataSet.Eof then (Sender as TDBGrid).DataSource.DataSet.Cancel; end; end; procedure TForm1.FormActivate(Sender: TObject); begin if not Inited then begin con.Connected:=True; con.GetTableNames(cbbTabls.Items); FInited:=True; end; end; procedure TForm1.tblAfterOpen(DataSet: TDataSet); {ikaplya Limit of display size for fields } const C_DisplayWidth_Limiter = 75; var f: TField; begin for f in DataSet.Fields do begin if f.DisplayWidth>C_DisplayWidth_Limiter then f.DisplayWidth:=C_DisplayWidth_Limiter; end; end; end.
{ Copyright (C) 1998-2018, written by Mike Shkolnik, Scalabium Software E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com In this unit I described the visual dialog for TDBGrid's Columns property tuning. } unit SMDBGSet; interface {$I SMVersion.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, stdctrls, extctrls, checklst, DBGrids, Menus, Buttons; type {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TSMSetDBGridDialog = class(TComponent) private { Private declarations } FCaption: TCaption; FDBGrid: TCustomDBGrid; FAllowedFields: TStrings; FOnBeforeExecute: TNotifyEvent; FOnAfterExecute: TNotifyEvent; FOnShow: TNotifyEvent; procedure SetAllowedFields(Value: TStrings); protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Execute: Boolean; published { Published declarations } property Caption: TCaption read FCaption write FCaption; property DBGrid: TCustomDBGrid read FDBGrid write FDBGrid; property AllowedFields: TStrings read FAllowedFields write SetAllowedFields; property OnBeforeExecute: TNotifyEvent read FOnBeforeExecute write FOnBeforeExecute; property OnAfterExecute: TNotifyEvent read FOnAfterExecute write FOnAfterExecute; property OnShow: TNotifyEvent read FOnShow write FOnShow; end; TSMGridSetupItem = class FieldIndex: Integer; FieldName: string; TitleAlignment: TAlignment; TitleCaption: string; TitleColor: TColor; TitleFont: TFont; DataAlignment: TAlignment; DataColor: TColor; DataFont: TFont; Width: Integer; end; TfrmGridSetup = class(TForm) btnOk: TButton; btnCancel: TButton; bvlButton: TBevel; clbFields: TCheckListBox; gbTitle: TGroupBox; lblTitleCaption: TLabel; lblTitleAlignment: TLabel; lblTitleColor: TLabel; lblTitleFont: TLabel; edTitleCaption: TEdit; edTitleFont: TEdit; cbTitleAlignment: TComboBox; gbData: TGroupBox; lblDataAlignment: TLabel; lblDataColor: TLabel; lblDataFont: TLabel; edDataFont: TEdit; cbDataAlignment: TComboBox; lblWidth: TLabel; lblWidthFix: TLabel; edWidth: TEdit; FontDlg: TFontDialog; SMColorsCBTitle: TComboBox; SMColorsCBData: TComboBox; btnTitleFont: TButton; btnDataFont: TButton; pmColumns: TPopupMenu; miSelectAll: TMenuItem; miUnselectAll: TMenuItem; miInvertSelection: TMenuItem; btnApplyAll: TButton; procedure PropertyExit(Sender: TObject); procedure clbFieldsClick(Sender: TObject); procedure clbFieldsDragDrop(Sender, Source: TObject; X, Y: Integer); procedure clbFieldsDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure edTitleFontButtonClick(Sender: TObject); procedure SMColorsCBTitleDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure miSelectAllClick(Sender: TObject); procedure SMColorsCBTitleClick(Sender: TObject); procedure SMColorsCBTitleChange(Sender: TObject); procedure btnApplyAllClick(Sender: TObject); private { Private declarations } function GetItemCaption(item: TSMGridSetupItem): string; function GetCaptionFont(Font: TFont): string; public { Public declarations } end; procedure Register; implementation {$R *.DFM} uses SMCnst; procedure Register; begin RegisterComponents('SMComponents', [TSMSetDBGridDialog]); end; const clCream = TColor($A6CAF0); clMoneyGreen = TColor($C0DCC0); clSkyBlue = TColor($FFFBF0); ColorsInList = 46; var ColorValues: array [0..ColorsInList - 1] of TColor = ( clBlack, clMaroon, clGreen, clOlive, clNavy, clPurple, clTeal, clGray, clSilver, clRed, clLime, clYellow, clBlue, clFuchsia, clAqua, clWhite, clScrollBar, clBackground, clActiveCaption, clInactiveCaption, clMenu, clWindow, clWindowFrame, clMenuText, clWindowText, clCaptionText, clActiveBorder, clInactiveBorder, clAppWorkSpace, clHighlight, clHighlightText, clBtnFace, clBtnShadow, clGrayText, clBtnText, clInactiveCaptionText, clBtnHighlight, cl3DDkShadow, cl3DLight, clInfoText, clInfoBk, clCream, clMoneyGreen, clSkyBlue, 0, 0); { TSMSetDBGridDialog } constructor TSMSetDBGridDialog.Create(AOwner: TComponent); begin inherited Create(AOwner); FCaption := 'Grid setup'; FDBGrid := nil; FAllowedFields := TStringList.Create; end; destructor TSMSetDBGridDialog.Destroy; begin FAllowedFields.Free; inherited Destroy; end; procedure TSMSetDBGridDialog.SetAllowedFields(Value: TStrings); begin FAllowedFields.Assign(Value); end; type THackDBGrid = class(TDBGrid); function TSMSetDBGridDialog.Execute: Boolean; var i, j: Integer; item: TSMGridSetupItem; TM: TTextMetric; IsSMDBGrid: Boolean; begin if Assigned(FOnBeforeExecute) then FOnBeforeExecute(Self); Result := False; with TDBGrid(DBGrid), TfrmGridSetup.Create(Application) do try if not (Assigned(DataSource) and Assigned(DataSource.DataSet)) then exit; Caption := FCaption; btnApplyAll.Caption := SApplyAll; btnOk.Caption := SBtnOk; btnCancel.Caption := SBtnCancel; gbTitle.Caption := SgbTitle; lblTitleCaption.Caption := STitleCaption; lblTitleAlignment.Caption := STitleAlignment; cbTitleAlignment.Items.Add(SAlignLeft); cbTitleAlignment.Items.Add(SAlignRight); cbTitleAlignment.Items.Add(SAlignCenter); lblTitleColor.Caption := STitleColor; lblTitleFont.Caption := STitleFont; gbData.Caption := SgbData; lblDataAlignment.Caption := STitleAlignment; cbDataAlignment.Items.Add(SAlignLeft); cbDataAlignment.Items.Add(SAlignRight); cbDataAlignment.Items.Add(SAlignCenter); lblDataColor.Caption := STitleColor; lblDataFont.Caption := STitleFont; lblWidth.Caption := SWidth; lblWidthFix.Caption := SWidthFix; {fill the field list} with Columns do for i := 0 to Count-1 do begin if (AllowedFields.Count = 0) or (AllowedFields.IndexOf(Items[i].FieldName) > -1) then begin item := TSMGridSetupItem.Create; item.TitleFont := TFont.Create; item.DataFont := TFont.Create; item.FieldIndex := i; item.FieldName := Items[i].FieldName; item.TitleAlignment := Items[i].Title.Alignment; item.TitleCaption := Items[i].Title.Caption; item.TitleColor := Items[i].Title.Color; item.TitleFont.Assign(Items[i].Title.Font); item.DataAlignment := Items[i].Alignment; item.DataColor := Items[i].Color; item.DataFont.Assign(Items[i].Font); if (Items[i].Width > 0) then begin GetTextMetrics(Canvas.Handle, TM); item.Width := (Items[i].Width - TM.tmOverhang - 4) div (Canvas.TextWidth('0') - TM.tmOverhang); end; j := clbFields.Items.AddObject(GetItemCaption(item), item); {$IFDEF VER120} //D4 clbFields.Checked[j] := Items[i].Visible; {$ELSE} {$IFDEF VER125} //CB4 clbFields.Checked[j] := Items[i].Visible; {$ELSE} {$IFDEF VER130} //D5 clbFields.Checked[j] := Items[i].Visible; {$ELSE} clbFields.Checked[j] := True; {$ENDIF} {$ENDIF} {$ENDIF} end; end; IsSMDBGrid := (Columns.Count > 0); for i := 0 to DataSource.DataSet.FieldCount - 1 do if (AllowedFields.Count = 0) or (AllowedFields.IndexOf(DataSource.DataSet.Fields[i].FieldName) > -1) then begin for j := 0 to clbFields.Items.Count-1 do begin IsSMDBGrid := (TSMGridSetupItem(clbFields.Items.Objects[j]).FieldName = DataSource.DataSet.Fields[i].FieldName); if IsSMDBGrid then break; end; if not IsSMDBGrid then begin item := TSMGridSetupItem.Create; item.TitleFont := TFont.Create; item.DataFont := TFont.Create; item.FieldIndex := clbFields.Items.Count; item.FieldName := DataSource.DataSet.Fields[i].FieldName; item.TitleAlignment := DataSource.DataSet.Fields[i].Alignment; item.TitleCaption := DataSource.DataSet.Fields[i].DisplayName; item.TitleColor := FixedColor; item.TitleFont.Assign(TDBGrid(DBGrid).TitleFont); item.DataAlignment := DataSource.DataSet.Fields[i].Alignment; item.DataColor := TDBGrid(DBGrid).Color; item.DataFont.Assign(TDBGrid(DBGrid).Font); item.Width := DataSource.DataSet.Fields[i].DisplayWidth; j := clbFields.Items.AddObject(GetItemCaption(item), item); clbFields.Checked[j] := False; end; end; clbFields.ItemIndex := 0; clbFieldsClick(clbFields); if Assigned(FOnShow) then FOnShow(Self); Result := (ShowModal = mrOk); if Result then begin THackDBGrid(DBGrid).BeginLayout; // Columns.BeginUpdate; try if (Columns.Count > 0) then begin Columns.Clear; for i := 0 to clbFields.Items.Count-1 do if clbFields.Checked[i] then begin item := TSMGridSetupItem(clbFields.Items.Objects[i]); with Columns.Add do begin FieldName := item.FieldName; Title.Alignment := item.TitleAlignment; Title.Caption := item.TitleCaption; Title.Color := item.TitleColor; Title.Font.Assign(item.TitleFont); Alignment := item.DataAlignment; Color := item.DataColor; Font.Assign(item.DataFont); if (item.Width > 0) then begin GetTextMetrics(Canvas.Handle, TM); Width := item.Width*(Canvas.TextWidth('0') - TM.tmOverhang) + TM.tmOverhang + 4; end; end; end; end else begin for i := 0 to clbFields.Items.Count-1 do begin item := TSMGridSetupItem(clbFields.Items.Objects[i]); with DataSource.DataSet.Fields[i] do begin FieldName := item.FieldName; Alignment := item.DataAlignment; DisplayLabel := item.TitleCaption; Color := item.DataColor; Font.Assign(item.DataFont); if (item.Width > 0) then begin GetTextMetrics(Canvas.Handle, TM); DisplayWidth := item.Width*(Canvas.TextWidth('0') - TM.tmOverhang) + TM.tmOverhang + 4; end; Visible := clbFields.Checked[i]; end; end; end finally THackDBGrid(DBGrid).EndLayout; //Columns.EndUpdate; end end finally for i := clbFields.Items.Count-1 downto 0 do with TSMGridSetupItem(clbFields.Items.Objects[i]) do begin TitleFont.Free; DataFont.Free; Free; end; Free end; if Assigned(FOnAfterExecute) then FOnAfterExecute(Self); end; { TfrmGridSetup } procedure TfrmGridSetup.clbFieldsClick(Sender: TObject); function GetColorID(cl: TColor): Integer; var i: Integer; begin Result := -1; for i := 0 to ColorsInList do if ColorValues[i] = cl then begin Result := i; break; end; if Result < 0 then Result := 0; end; begin if clbFields.ItemIndex > -1 then with TSMGridSetupItem(clbFields.Items.Objects[clbFields.ItemIndex]) do begin edTitleCaption.Text := TitleCaption; cbTitleAlignment.ItemIndex := Ord(TitleAlignment); SMColorsCBTitle.ItemIndex := GetColorID(TitleColor); edTitleFont.Font.Assign(TitleFont); edTitleFont.Text := GetCaptionFont(edTitleFont.Font); cbDataAlignment.ItemIndex := Ord(DataAlignment); SMColorsCBData.ItemIndex := GetColorID(DataColor); edDataFont.Font.Assign(DataFont); edDataFont.Text := GetCaptionFont(edDataFont.Font); edWidth.Text := IntToStr(Width); ColorValues[ColorsInList-2] := TitleColor; ColorValues[ColorsInList-1] := DataColor; SMColorsCBTitleChange(SMColorsCBTitle) end; end; procedure TfrmGridSetup.clbFieldsDragDrop(Sender, Source: TObject; X, Y: Integer); var intItemIndex, intNewItemIndex: Integer; boolChecked: Boolean; coordXY: TPoint; begin with Source as TCheckListBox do begin intItemIndex := clbFields.ItemIndex; coordXY.x := X; coordXY.y := Y; intNewItemIndex := clbFields.ItemAtPos(coordXY, True); if (intNewItemIndex <> -1) then begin boolChecked := clbFields.Checked[intItemIndex]; clbFields.Items.Move(intItemIndex, intNewItemIndex); clbFields.Checked[intNewItemIndex] := boolChecked; clbFields.ItemIndex := intNewItemIndex; end; end; end; procedure TfrmGridSetup.clbFieldsDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin if (Source = clbFields) then Accept := True else Accept := False; end; procedure TfrmGridSetup.PropertyExit(Sender: TObject); var item: TSMGridSetupItem; boolChecked: Boolean; begin if clbFields.ItemIndex > -1 then begin item := TSMGridSetupItem(clbFields.Items.Objects[clbFields.ItemIndex]); if not Assigned(item) then exit; boolChecked := clbFields.Checked[clbFields.ItemIndex]; case (Sender as TControl).Tag of 1: begin item.TitleCaption := edTitleCaption.Text; clbFields.Items[clbFields.ItemIndex] := GetItemCaption(item); end; 2: item.TitleAlignment := TAlignment(cbTitleAlignment.ItemIndex); 3: item.TitleColor := ColorValues[SMColorsCBTitle.ItemIndex]; 4: item.TitleFont.Assign(edTitleFont.Font); 5: item.DataAlignment := TAlignment(cbDataAlignment.ItemIndex); 6: if (SMColorsCBData.ItemIndex = SMColorsCBData.Items.Count-1) then item.DataColor := ColorValues[SMColorsCBData.ItemIndex+1] else item.DataColor := ColorValues[SMColorsCBData.ItemIndex]; 7: item.DataFont.Assign(edDataFont.Font); 8, 9: item.Width := StrToIntDef(edWidth.Text, 0); 10: item.Width := 10; end; clbFields.Checked[clbFields.ItemIndex] := boolChecked; end; end; procedure TfrmGridSetup.edTitleFontButtonClick(Sender: TObject); var cntr: TEdit; begin if TButton(Sender) = btnTitleFont then cntr := edTitleFont else cntr := edDataFont; with FontDlg do begin Font.Assign(cntr.Font); if Execute then begin cntr.Font.Assign(Font); cntr.Text := GetCaptionFont(Font); PropertyExit(Sender); end; end; end; function TfrmGridSetup.GetItemCaption(item: TSMGridSetupItem): string; begin Result := item.FieldName + ' : ' + item.TitleCaption; end; function TfrmGridSetup.GetCaptionFont(Font: TFont): string; begin Result := Font.Name + ', ' + IntToStr(Font.Size); end; procedure TfrmGridSetup.SMColorsCBTitleDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var ARect: TRect; Safer: TColor; i: Integer; begin ARect := Rect; InflateRect(ARect, -2, -2); with (Control as TComboBox) do begin Canvas.FillRect(Rect); Safer := Canvas.Brush.Color; Canvas.Pen.Color := clWindowText; Canvas.Rectangle(ARect.Left, ARect.Top, ARect.Right, ARect.Bottom); i := Index; if (Control = SMColorsCBData) and (i = SMColorsCBData.Items.Count-1) then Inc(i); Canvas.Brush.Color := ColorValues[i]; try InflateRect(ARect, -1, -1); Canvas.FillRect(ARect); { if (Index = Items.Count-1) then begin Canvas.Pen.Color := clWhite; Canvas.TextOut(ARect.Left, ARect.Top, 'Custom...') end; } finally Canvas.Brush.Color := Safer; end; end; end; procedure TfrmGridSetup.miSelectAllClick(Sender: TObject); var i, intTag: Integer; begin intTag := TComponent(Sender).Tag; for i := 0 to clbFields.Items.Count-1 do case intTag of 1: //unselect all clbFields.Checked[i] := False; 2: //invert selection clbFields.Checked[i] := not clbFields.Checked[i]; else //select all clbFields.Checked[i] := True; end; clbFields.Invalidate end; procedure TfrmGridSetup.SMColorsCBTitleClick(Sender: TObject); var i: Integer; begin with TCombobox(Sender) do if (ItemIndex = ColorsInList-2) then begin with TColorDialog.Create(Self) do try i := ColorsInList-1; if (Sender = SMColorsCBTitle) then Dec(i); Color := ColorValues[i]; if Execute then ColorValues[i] := Color finally Free end end; end; procedure TfrmGridSetup.SMColorsCBTitleChange(Sender: TObject); begin edTitleFont.Color := ColorValues[SMColorsCBTitle.ItemIndex]; if (SMColorsCBData.ItemIndex = SMColorsCBData.Items.Count-1) then edDataFont.Color := ColorValues[SMColorsCBData.ItemIndex+1] else edDataFont.Color := ColorValues[SMColorsCBData.ItemIndex]; end; procedure TfrmGridSetup.btnApplyAllClick(Sender: TObject); var item, subItem: TSMGridSetupItem; i: Integer; begin if clbFields.ItemIndex > -1 then item := TSMGridSetupItem(clbFields.Items.Objects[clbFields.ItemIndex]) else item := nil; if Assigned(item) then begin for i := 0 to clbFields.Items.Count-1 do begin if (clbFields.ItemIndex <> i) and clbFields.Checked[i] then begin subItem := TSMGridSetupItem(clbFields.Items.Objects[i]); if Assigned(subItem) then begin subItem.TitleAlignment := item.TitleAlignment; subItem.TitleColor := item.TitleColor; subItem.TitleFont.Assign(item.TitleFont); subItem.DataAlignment := item.DataAlignment; subItem.DataColor := item.DataColor; subItem.DataFont.Assign(item.DataFont); subItem.Width := item.Width; end end end; end; end; end.
{ Double Commander ------------------------------------------------------------------------- Drag&drop options page Copyright (C) 2006-2016 Alexander Koblov (alexx2000@mail.ru) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. } unit fOptionsDragDrop; {$mode objfpc}{$H+} interface uses Controls, Classes, SysUtils, StdCtrls, fOptionsFrame, Types; type { TfrmOptionsDragDrop } TfrmOptionsDragDrop = class(TOptionsEditor) cbShowConfirmationDialog: TCheckBox; cbDragAndDropAskFormatEachTime: TCheckBox; cbDragAndDropSaveUnicodeTextInUFT8: TCheckBox; cbDragAndDropTextAutoFilename: TCheckBox; gbTextDragAndDropRelatedOptions: TGroupBox; lblMostDesiredTextFormat1: TLabel; lblMostDesiredTextFormat2: TLabel; lblWarningForAskFormat: TLabel; lbMostDesiredTextFormat: TListBox; procedure lbMostDesiredTextFormatDragOver(Sender, Source: TObject; {%H-}X, {%H-}Y: integer; {%H-}State: TDragState; var Accept: boolean); procedure lbMostDesiredTextFormatDragDrop(Sender, {%H-}Source: TObject; {%H-}X, Y: integer); protected slUserLanguageName, slLegacyName: TStringList; procedure Init; override; procedure Done; override; procedure Load; override; function IsSignatureComputedFromAllWindowComponents: boolean; override; function ExtraOptionsSignature(CurrentSignature: dword): dword; override; function Save: TOptionsEditorSaveFlags; override; function GetUserNameFromLegacyName(sLegacyName: string): string; procedure LoadDesiredOrderTextFormatList; procedure SaveDesiredOrderTextFormatList; public class function GetIconIndex: integer; override; class function GetTitle: string; override; end; procedure SortThisListAccordingToDragAndDropDesiredFormat(ListToSort: TStringList); implementation {$R *.lfm} uses DCStrUtils, crc, uGlobs, uLng; { TfrmOptionsDragDrop } { TfrmOptionsDragDrop.Init } procedure TfrmOptionsDragDrop.Init; var iFormat: integer; begin slUserLanguageName := TStringList.Create; ParseLineToList(rsDragAndDropTextFormat, slUserLanguageName); slLegacyName := TStringList.Create; for iFormat := 0 to pred(NbOfDropTextFormat) do slLegacyName.Add(gDragAndDropDesiredTextFormat[iFormat].Name); end; { TfrmOptionsDragDrop.Done } procedure TfrmOptionsDragDrop.Done; begin FreeAndNil(slUserLanguageName); FreeAndNil(slLegacyName); end; { TfrmOptionsDragDrop.GetUserNameFromLegacyName } function TfrmOptionsDragDrop.GetUserNameFromLegacyName(sLegacyName: string): string; var iPos: integer; begin Result := '???'; iPos := slLegacyName.indexof(sLegacyName); if (iPos >= 0) and (iPos < NbOfDropTextFormat) then Result := slUserLanguageName.Strings[iPos]; end; { TfrmOptionsDragDrop.Load } procedure TfrmOptionsDragDrop.Load; begin cbShowConfirmationDialog.Checked := gShowDialogOnDragDrop; {$IFDEF MSWINDOWS} gbTextDragAndDropRelatedOptions.Visible := True; LoadDesiredOrderTextFormatList; cbDragAndDropAskFormatEachTime.Checked := gDragAndDropAskFormatEachTime; cbDragAndDropTextAutoFilename.Checked := gDragAndDropTextAutoFilename; cbDragAndDropSaveUnicodeTextInUFT8.Checked := gDragAndDropSaveUnicodeTextInUFT8; {$ENDIF} end; { TfrmOptionsDragDrop.IsSignatureComputedFromAllWindowComponents } function TfrmOptionsDragDrop.IsSignatureComputedFromAllWindowComponents: boolean; begin lbMostDesiredTextFormat.ItemIndex := -1; // Tricky pass but nothing was selected when we initially did the signature so let's unselect them all. Result := True; end; { TfrmOptionsDragDrop.ExtraOptionsSignature } function TfrmOptionsDragDrop.ExtraOptionsSignature(CurrentSignature: dword): dword; var iFormat: integer; begin Result := CurrentSignature; for iFormat := 0 to pred(lbMostDesiredTextFormat.Items.Count) do Result := crc32(Result, @lbMostDesiredTextFormat.Items.Strings[iFormat][1], length(lbMostDesiredTextFormat.Items.Strings[iFormat])); end; { TfrmOptionsDragDrop.Save } function TfrmOptionsDragDrop.Save: TOptionsEditorSaveFlags; begin gShowDialogOnDragDrop := cbShowConfirmationDialog.Checked; {$IFDEF MSWINDOWS} SaveDesiredOrderTextFormatList; gDragAndDropAskFormatEachTime := cbDragAndDropAskFormatEachTime.Checked; gDragAndDropTextAutoFilename := cbDragAndDropTextAutoFilename.Checked; gDragAndDropSaveUnicodeTextInUFT8 := cbDragAndDropSaveUnicodeTextInUFT8.Checked; {$ENDIF} Result := []; end; class function TfrmOptionsDragDrop.GetIconIndex: integer; begin Result := 28; end; class function TfrmOptionsDragDrop.GetTitle: string; begin Result := rsOptionsEditorDragAndDrop; end; procedure TfrmOptionsDragDrop.lbMostDesiredTextFormatDragOver(Sender, Source: TObject; X, Y: integer; State: TDragState; var Accept: boolean); begin Accept := (Source = lbMostDesiredTextFormat) and (lbMostDesiredTextFormat.ItemIndex <> -1); end; procedure TfrmOptionsDragDrop.lbMostDesiredTextFormatDragDrop(Sender, Source: TObject; X, Y: integer); var SrcIndex, DestIndex: integer; begin SrcIndex := lbMostDesiredTextFormat.ItemIndex; if SrcIndex = -1 then Exit; DestIndex := lbMostDesiredTextFormat.GetIndexAtY(Y); if (DestIndex < 0) or (DestIndex >= lbMostDesiredTextFormat.Count) then DestIndex := lbMostDesiredTextFormat.Count - 1; lbMostDesiredTextFormat.Items.Move(SrcIndex, DestIndex); lbMostDesiredTextFormat.ItemIndex := DestIndex; end; { TfrmOptionsDragDrop.LoadDesiredOrderTextFormatList } procedure TfrmOptionsDragDrop.LoadDesiredOrderTextFormatList; var IndexDropTextFormat, ExpectedPosition, ActualPosition: integer; TempoString: string; begin lbMostDesiredTextFormat.Clear; for IndexDropTextFormat := 0 to pred(NbOfDropTextFormat) do lbMostDesiredTextFormat.Items.Add(gDragAndDropDesiredTextFormat[IndexDropTextFormat].Name); for IndexDropTextFormat := 0 to pred(NbOfDropTextFormat) do begin ExpectedPosition := gDragAndDropDesiredTextFormat[IndexDropTextFormat].DesireLevel; if (ExpectedPosition < 0) or (ExpectedPosition > pred(NbOfDropTextFormat)) then ExpectedPosition := pred(NbOfDropTextFormat); ActualPosition := lbMostDesiredTextFormat.Items.IndexOf(gDragAndDropDesiredTextFormat[IndexDropTextFormat].Name); if (ActualPosition <> -1) and (ExpectedPosition <> ActualPosition) then begin TempoString := lbMostDesiredTextFormat.Items.Strings[ActualPosition]; lbMostDesiredTextFormat.Items.Strings[ActualPosition] := lbMostDesiredTextFormat.Items.Strings[ExpectedPosition]; lbMostDesiredTextFormat.Items.Strings[ExpectedPosition] := TempoString; end; end; // At the last minutes, we translate to user's language the format names for ActualPosition := 0 to pred(lbMostDesiredTextFormat.Items.Count) do lbMostDesiredTextFormat.Items.Strings[ActualPosition] := GetUserNameFromLegacyName(lbMostDesiredTextFormat.Items.Strings[ActualPosition]); lbMostDesiredTextFormat.ItemIndex := -1; end; procedure TfrmOptionsDragDrop.SaveDesiredOrderTextFormatList; var IndexDropTextFormat, ActualPosition: integer; begin for IndexDropTextFormat := 0 to pred(NbOfDropTextFormat) do begin ActualPosition := lbMostDesiredTextFormat.Items.IndexOf(GetUserNameFromLegacyName(gDragAndDropDesiredTextFormat[IndexDropTextFormat].Name)); if (ActualPosition <> -1) then gDragAndDropDesiredTextFormat[IndexDropTextFormat].DesireLevel := ActualPosition; end; end; // Arrange the list in such way that the most desired format is on top. // This routine is also used in "uOleDragDrop" for offering user's suggestion so the list is arranged according to user's desire procedure SortThisListAccordingToDragAndDropDesiredFormat(ListToSort: TStringList); function GetDesireLevel(SearchingText: string): integer; var SearchingIndex: integer; begin Result := -1; SearchingIndex := 0; while (SearchingIndex < NbOfDropTextFormat) and (Result = -1) do begin if gDragAndDropDesiredTextFormat[SearchingIndex].Name = SearchingText then Result := gDragAndDropDesiredTextFormat[SearchingIndex].DesireLevel; Inc(SearchingIndex); end; end; var Index, InnerIndex, DesireLevelIndex, DesireLevelInnerIndex: integer; TempoString: string; begin //It's a poor sort... But we don't have too many so we keep it simple. for Index := 0 to (ListToSort.Count - 2) do begin for InnerIndex := Index + 1 to pred(ListToSort.Count) do begin DesireLevelIndex := GetDesireLevel(ListToSort.Strings[Index]); DesireLevelInnerIndex := GetDesireLevel(ListToSort.Strings[InnerIndex]); if (DesireLevelIndex > DesireLevelInnerIndex) and (DesireLevelIndex <> -1) and (DesireLevelInnerIndex <> -1) then begin TempoString := ListToSort.Strings[Index]; ListToSort.Strings[Index] := ListToSort.Strings[InnerIndex]; ListToSort.Strings[InnerIndex] := TempoString; end; end; end; end; end.
unit IdTrivialFTP; interface uses Classes, IdAssignedNumbers, IdTrivialFTPBase, IdUDPClient; const GTransferMode = tfOctet; GFRequestedBlockSize = 1500; GReceiveTimeout = 4000; type TIdTrivialFTP = class(TIdUDPClient) protected FMode: TIdTFTPMode; FRequestedBlockSize: Integer; FPeerPort: Integer; FPeerIP: String; function ModeToStr: string; procedure CheckOptionAck(const optionpacket: string); protected procedure SendAck(const BlockNumber: Word); procedure RaiseError(const errorpacket: string); public constructor Create(AnOwner: TComponent); override; procedure Get(const ServerFile: String; DestinationStream: TStream); overload; procedure Get(const ServerFile, LocalFile: String); overload; procedure Put(SourceStream: TStream; const ServerFile: String); overload; procedure Put(const LocalFile, ServerFile: String); overload; published property TransferMode: TIdTFTPMode read FMode write FMode Default GTransferMode; property RequestedBlockSize: Integer read FRequestedBlockSize write FRequestedBlockSize default 1500; property OnWork; property OnWorkBegin; property OnWorkEnd; end; implementation uses IdComponent, IdException, IdGlobal, IdResourceStrings, IdStack, SysUtils; procedure TIdTrivialFTP.CheckOptionAck(const optionpacket: string); var optionname: string; begin optionname := pchar(optionpacket) + 2; if AnsiSameText(optionname, 'blksize') then begin {Do not Localize} BufferSize := StrToInt(pchar(optionpacket) + 10) + hdrsize; end; end; constructor TIdTrivialFTP.Create(AnOwner: TComponent); begin inherited; TransferMode := GTransferMode; Port := IdPORT_TFTP; FRequestedBlockSize := GFRequestedBlockSize; ReceiveTimeout := GReceiveTimeout; end; procedure TIdTrivialFTP.Get(const ServerFile: String; DestinationStream: TStream); var s: string; RcvTimeout, DataLen: Integer; PrevBlockCtr, BlockCtr: Integer; TerminateTransfer: Boolean; begin BeginWork(wmRead); try BufferSize := 516; // BufferSize as specified by RFC 1350 Send(WordToStr(GStack.WSHToNs(TFTP_RRQ)) + ServerFile + #0 + ModeToStr + #0 + sBlockSize + IntToStr(FRequestedBlockSize) + #0); PrevBlockCtr := -1; BlockCtr := 0; TerminateTransfer := False; RcvTimeout := ReceiveTimeout; while true do begin if TerminateTransfer then begin RcvTimeout := Min(500, ReceiveTimeout); end; s := ReceiveString(FPeerIP, FPeerPort, RcvTimeout); if (s = '') then begin {Do not Localize} if TerminateTransfer then begin break; end else begin raise EIdTFTPException.Create(RSTimeOut); end; end; case GStack.WSNToHs(StrToWord(s)) of TFTP_DATA: begin BlockCtr := GStack.WSNToHs(StrToWord(Copy(s, 3, 2))); if TerminateTransfer then // hang around just once more begin SendAck(BlockCtr); Break; end; if (BlockCtr <= 1) and (PrevBlockCtr = MaxWord) then begin PrevBlockCtr := -1; // counter wrapped around (1-65535 blocks) end; if BlockCtr > PrevBlockCtr then begin DataLen := Length(s) - 4; try DestinationStream.WriteBuffer(s[5], DataLen); DoWork(wmRead, DataLen) except on E:Exception do begin SendError(self, FPeerIP, FPeerPort, E); raise; end; end; TerminateTransfer := DataLen < BufferSize - hdrsize; PrevBlockCtr := BlockCtr; end; { if } end; TFTP_ERROR: RaiseError(s); TFTP_OACK: begin CheckOptionAck(s); BlockCtr := 0; end; else raise EIdTFTPException.CreateFmt(RSTFTPUnexpectedOp, [Host, Port]); end; { case } SendAck(BlockCtr); end; { while } finally EndWork(wmRead); Binding.CloseSocket; end; end; procedure TIdTrivialFTP.Get(const ServerFile, LocalFile: String); var fs: TFileStream; begin fs := TFileStream.Create(LocalFile, fmCreate); try Get(ServerFile, fs); finally fs.Free; end; end; function TIdTrivialFTP.ModeToStr: string; begin case TransferMode of tfNetAscii: result := 'netascii'; {Do not Localize} tfOctet: result := 'octet'; {Do not Localize} end; end; procedure TIdTrivialFTP.Put(SourceStream: TStream; const ServerFile: String); var CurrentDataBlk, s: string; DataLen: Integer; PrevBlockCtr, BlockCtr: Integer; TerminateTransfer: Boolean; begin BeginWork(wmWrite, SourceStream.Size - SourceStream.Position); try BufferSize := 516; // BufferSize as specified by RFC 1350 Send(WordToStr(GStack.WSHToNs(TFTP_WRQ)) + ServerFile + #0 + ModeToStr + #0 + sBlockSize + IntToStr(FRequestedBlockSize) + #0); PrevBlockCtr := 0; BlockCtr := 1; TerminateTransfer := False; while true do begin s := ReceiveString(FPeerIP, FPeerPort); if (s = '') then begin {Do not Localize} if TerminateTransfer then begin Break; end else begin raise EIdTFTPException.Create(RSTimeOut); end; end; case GStack.WSNToHs(StrToWord(s)) of TFTP_ACK: begin BlockCtr := GStack.WSNToHs(StrToWord(Copy(s, 3, 2))); inc(BlockCtr); if Word(BlockCtr) = 0 then begin BlockCtr := 0; PrevBlockCtr := -1; // counter wrapped around (1-65535 blocks) end; if TerminateTransfer then begin Break; end; end; TFTP_ERROR: RaiseError(s); TFTP_OACK: CheckOptionAck(s); end; { case } if BlockCtr > PrevBlockCtr then begin DataLen := Min(BufferSize - hdrsize, SourceStream.Size - SourceStream.Position); SetLength(CurrentDataBlk, DataLen + hdrsize); CurrentDataBlk := WordToStr(GStack.WSHToNs(TFTP_DATA)) + WordToStr(GStack.WSHToNs(BlockCtr)); SetLength(CurrentDataBlk, DataLen + hdrsize); SourceStream.ReadBuffer(CurrentDataBlk[hdrsize+1], DataLen); DoWork(wmWrite, DataLen); TerminateTransfer := DataLen < BufferSize - hdrsize; PrevBlockCtr := BlockCtr; end; Send(FPeerIP, FPeerPort, CurrentDataBlk); end; { while } finally EndWork(wmWrite); Binding.CloseSocket; end; end; procedure TIdTrivialFTP.Put(const LocalFile, ServerFile: String); var fs: TFileStream; begin fs := TFileStream.Create(LocalFile, fmOpenRead); try Put(fs, ServerFile); finally fs.Free; end; end; procedure TIdTrivialFTP.RaiseError(const errorpacket: string); var errmsg: string; begin errmsg := pchar(errorpacket)+4; case GStack.WSNToHs(StrToWord(Copy(errorpacket, 3, 2))) of ErrFileNotFound: raise EIdTFTPFileNotFound.Create(errmsg); ErrAccessViolation: raise EIdTFTPAccessViolation.Create(errmsg); ErrAllocationExceeded: raise EIdTFTPAllocationExceeded.Create(errmsg); ErrIllegalOperation: raise EIdTFTPIllegalOperation.Create(errmsg); ErrUnknownTransferID: raise EIdTFTPUnknownTransferID.Create(errmsg); ErrFileAlreadyExists: raise EIdTFTPFileAlreadyExists.Create(errmsg); ErrNoSuchUser: raise EIdTFTPNoSuchUser.Create(errmsg); ErrOptionNegotiationFailed: raise EIdTFTPOptionNegotiationFailed.Create(errmsg); else // usually ErrUndefined (see EIdTFTPException.Message if any) raise EIdTFTPException.Create(errmsg); end; end; procedure TIdTrivialFTP.SendAck(const BlockNumber: Word); begin Send(FPeerIP, FPeerPort, MakeAckPkt(BlockNumber)); end; end.
{ AD.A.P.T. Library Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved Original Source Location: https://github.com/LaKraven/ADAPT Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md } unit ADAPT.Math.Common.Intf; {$I ADAPT.inc} interface uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, {$ELSE} Classes, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} ADAPT, ADAPT.Intf; {$I ADAPT_RTTI.inc} type { Exceptions } EADMathException = class(EADException); EADMathAveragerException = class(EADMathException); EADMathAveragerListNotSorted = class(EADMathAveragerException); /// <summary><c>An Extrapolator calculates Values beyond the range of Known (Reference) Values.</c></summary> IADExtrapolator<TKey, TValue> = interface(IADInterface) end; /// <summary><c>An Object containing an Extrapolator.</c></summary> IADExtrapolatable<TKey, TValue> = interface(IADInterface) // Getters /// <returns><c>The Extrapolator used by this Object.</c></returns> function GetExtrapolator: IADExtrapolator<TKey, TValue>; // Setters /// <summary><c>Defines the Extrapolator to be used by this Object.</c></returns> procedure SetExtrapolator(const AExtrapolator: IADExtrapolator<TKey, TValue>); // Properties /// <summary><c>Defines the Extrapolator to be used by this Object.</c></returns> /// <returns><c>The Extrapolator used by this Object.</c></returns> property Extrapolator: IADExtrapolator<TKey, TValue> read GetExtrapolator write SetExtrapolator; end; /// <summary><c>An Interpolator calculates Values between Known (Reference) Values.</c></summary> IADInterpolator<TKey, TValue> = interface(IADInterface) end; /// <summary><c>An Object containing an Interpolator.</c></summary> IADInterpolatable<TKey, TValue> = interface(IADInterface) // Getters /// <returns>The Interpolator used by this Object.</c></returns> function GetInterpolator: IADInterpolator<TKey, TValue>; // Setters /// <summary><c>Defines the Interpolator to be used by this Object.</c></summary> procedure SetInterpolator(const AInterpolator: IADInterpolator<TKey, TValue>); // Properties /// <summary><c>Defines the Interpolator to be used by this Object.</c></summary> /// <returns>The Interpolator used by this Object.</c></returns> property Interpolator: IADInterpolator<TKey, TValue> read GetInterpolator write SetInterpolator; end; implementation end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Backend.ServiceFactory; interface uses System.Classes, System.SysUtils, REST.Backend.Providers; type TProviderServiceFactory = class private FProviderID: string; FUnitNames: TArray<string>; protected function CreateService(const AProvider: IBackendProvider; const IID: TGUID): IBackendService; virtual; abstract; function GetServiceIID: TGUID; virtual; abstract; public public constructor Create(const AProviderID: string); overload; constructor Create(const AProviderID, AUnitName: string); overload; procedure Register; procedure Unregister; end; TProviderServiceFactory<T: IBackendService> = class(TProviderServiceFactory) protected function GetServiceIID: TGUID; override; end; implementation uses System.TypInfo; { TProviderServiceFactory } procedure TProviderServiceFactory.Register; begin TBackendProviders.Instance.RegisterService(FProviderID, GetServiceIID, CreateService, FUnitNames); end; procedure TProviderServiceFactory.Unregister; begin TBackendProviders.Instance.UnregisterService(FProviderID, GetServiceIID); end; constructor TProviderServiceFactory.Create(const AProviderID: string); begin FProviderID := AProviderID; end; constructor TProviderServiceFactory.Create(const AProviderID, AUnitName: string); begin Create(AProviderID); FUnitNames := TArray<string>.Create(AUnitName); end; function TProviderServiceFactory<T>.GetServiceIID: TGUID; begin Result := GetTypeData(TypeInfo(T))^.Guid; end; end.
unit uxPLHalConnexion; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IdTelnet, u_xPL_Address; type TxPLHalConfigured = procedure of object; { TxPLHalConnexion } TxPLHalConnexion = class(TIdTelnet) protected bWaitingAnswer : integer; sLastQuestion : string; procedure DataAvailable(Sender: TIdTelnet; const Buffer: String); private fHalVersion : string; fXHCPVersion : string; fAddress : TxPLAddress; fGlobals : TStringList; fOnInitialized : TxPLHalConfigured; // Capabilities bConfigurationManager : char; bXAPSupport : char; sDefaultScripting : char; bxPLDeterminators : char; bEvents : char; sPlatform : char; bStateTracking : char; public constructor Create; destructor Destroy; override; procedure Connect; override; procedure Send(aString : string); property Address : TxPLAddress read fAddress; property OnInitialized : TxPLHalConfigured read fOnInitialized write fOnInitialized; end; implementation { TxPLHalConnexion } uses StrUtils; procedure TxPLHalConnexion.DataAvailable(Sender: TIdTelnet; const Buffer: String); function AnalyseReponse(const input : string; out comment : string) : integer; var code : string; begin Result := -1; code := AnsiLeftStr(input,3); if StrIsInteger(code) then begin Result := StrToInt( code ); Comment := SysUtils.Trim(AnsiRightStr(input, length(input)-3)); end end; procedure Handle_200_Response(aString : string); // 200 xpl-xplhal2.lapfr0005 Version 2.2.3508.37921 XHCP 1.5.0 var sArray : StringArray; begin sArray := StrSplit(aString,' '); fAddress.Tag := sArray[0]; fHalVersion := sArray[2]; fXHCPVersion := sArray[4]; end; procedure Handle_236_Response(aString : string); // 236 1-P11W0 begin bConfigurationManager := aString[1]; bXAPSupport := aString[2]; sDefaultScripting := aString[3]; bxPLDeterminators := aString[4]; bEvents := aString[5]; sPlatform := aString[6]; bStateTracking := aString[7]; end; var sChaine : string; Start, Stop : Integer; sList : TStringList; ResponseCode : integer; Comment : string; begin sList := TStringList.Create; Start := 1; Stop := Pos(asciiCR, Buffer); if Stop = 0 then Stop := Length(Buffer) + 1; while Start <= Length(Buffer) do begin sChaine := Copy(Buffer, Start, Stop - Start); Start := Stop + 1; if Start>Length(Buffer) then Break; if Buffer[Start] = asciiLF then Start := Start + 1; Stop := Start; while (Buffer[Stop] <>asciiCR) and (Stop <= Length(Buffer)) do Stop := Stop + 1; sList.Add(sChaine); end; ResponseCode := AnalyseReponse(sList[0],Comment); // if ResponseCode = bWaitingAnswer then begin Case ResponseCode of 200 : begin // Welcome banner received Handle_200_Response(Comment); bWaitingAnswer := 236; Send('capabilities'); end; 236 : begin // Capabilities received Handle_236_Response(Comment); bWaitingAnswer := 231; Send('listglobals'); end; 231: begin // Globals list received fGlobals.Clear; start := 1; while Start<sList.Count-1 do begin // We skip then ending '.' sChaine :=sList[start] ; fGlobals.Add(sList[start]); inc(start); end; if assigned(fOnInitialized) then OnInitialized; end; end; //end // else Send(''); // Relaunch last question end; constructor TxPLHalConnexion.Create; begin inherited Create; fAddress := TxPLAddress.Create; fGlobals := TStringList.Create; end; destructor TxPLHalConnexion.Destroy; begin if Connected then Disconnect; fAddress.destroy; fGlobals.destroy; inherited Destroy; end; procedure TxPLHalConnexion.Connect; begin Port := 3865; ThreadedEvent := True; OnDataAvailable := @DataAvailable; bWaitingAnswer := 200; inherited Connect; end; procedure TxPLHalConnexion.Send(aString: string); var i : integer; begin //if aString<>'' then sLastQuestion := UpperCase(aString); for i := 1 to length(sLastQuestion) do SendCh(sLastQuestion[i]); SendCh(#13); end; end.
// // Created by the DataSnap proxy generator. // 2015-01-30 ¿ÀÀü 2:37:41 // unit UClient; interface uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TServerMethods1Client = class(TDSAdminClient) private FEchoStringCommand: TDBXCommand; FReverseStringCommand: TDBXCommand; FInsert_BookRentalCommand: TDBXCommand; FInsert_JoinCommand: TDBXCommand; FDelete_RentalCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function EchoString(Value: string): string; function ReverseString(Value: string): string; function Insert_BookRental(RentalNum: string; Period: string; BookNum: string): Integer; function Insert_Join(ID: string; Jumin: string; Name: string; Age: string; Phone: string; Address: string): Integer; function Delete_Rental(Value: string; BookNum: string): Integer; end; implementation function TServerMethods1Client.EchoString(Value: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FDBXConnection.CreateCommand; FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FEchoStringCommand.Text := 'TServerMethods1.EchoString'; FEchoStringCommand.Prepare; end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.ExecuteUpdate; Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.ReverseString(Value: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FDBXConnection.CreateCommand; FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FReverseStringCommand.Text := 'TServerMethods1.ReverseString'; FReverseStringCommand.Prepare; end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.ExecuteUpdate; Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.Insert_BookRental(RentalNum: string; Period: string; BookNum: string): Integer; begin if FInsert_BookRentalCommand = nil then begin FInsert_BookRentalCommand := FDBXConnection.CreateCommand; FInsert_BookRentalCommand.CommandType := TDBXCommandTypes.DSServerMethod; FInsert_BookRentalCommand.Text := 'TServerMethods1.Insert_BookRental'; FInsert_BookRentalCommand.Prepare; end; FInsert_BookRentalCommand.Parameters[0].Value.SetWideString(RentalNum); FInsert_BookRentalCommand.Parameters[1].Value.SetWideString(Period); FInsert_BookRentalCommand.Parameters[2].Value.SetWideString(BookNum); FInsert_BookRentalCommand.ExecuteUpdate; Result := FInsert_BookRentalCommand.Parameters[3].Value.GetInt32; end; function TServerMethods1Client.Insert_Join(ID: string; Jumin: string; Name: string; Age: string; Phone: string; Address: string): Integer; begin if FInsert_JoinCommand = nil then begin FInsert_JoinCommand := FDBXConnection.CreateCommand; FInsert_JoinCommand.CommandType := TDBXCommandTypes.DSServerMethod; FInsert_JoinCommand.Text := 'TServerMethods1.Insert_Join'; FInsert_JoinCommand.Prepare; end; FInsert_JoinCommand.Parameters[0].Value.SetWideString(ID); FInsert_JoinCommand.Parameters[1].Value.SetWideString(Jumin); FInsert_JoinCommand.Parameters[2].Value.SetWideString(Name); FInsert_JoinCommand.Parameters[3].Value.SetWideString(Age); FInsert_JoinCommand.Parameters[4].Value.SetWideString(Phone); FInsert_JoinCommand.Parameters[5].Value.SetWideString(Address); FInsert_JoinCommand.ExecuteUpdate; Result := FInsert_JoinCommand.Parameters[6].Value.GetInt32; end; function TServerMethods1Client.Delete_Rental(Value: string; BookNum: string): Integer; begin if FDelete_RentalCommand = nil then begin FDelete_RentalCommand := FDBXConnection.CreateCommand; FDelete_RentalCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDelete_RentalCommand.Text := 'TServerMethods1.Delete_Rental'; FDelete_RentalCommand.Prepare; end; FDelete_RentalCommand.Parameters[0].Value.SetWideString(Value); FDelete_RentalCommand.Parameters[1].Value.SetWideString(BookNum); FDelete_RentalCommand.ExecuteUpdate; Result := FDelete_RentalCommand.Parameters[2].Value.GetInt32; end; constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FInsert_BookRentalCommand.DisposeOf; FInsert_JoinCommand.DisposeOf; FDelete_RentalCommand.DisposeOf; inherited; end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2012-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Data.Bind.ObjectScope; interface uses System.Classes, System.SysUtils, System.Generics.Collections, System.Bindings.EvalProtocol, Data.Bind.Components, System.Bindings.CustomScope, System.Rtti, System.TypInfo, System.Bindings.Expression; type TBindSourceAdapter = class; TBindSourceAdapterLink = class; TBindSourceAdapterField = class; /// <summary>Event signature for creating an adapter</summary> TCreateAdapterEvent = procedure(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter) of object; /// <summary>Bind source which supports adapters to connect to different types of data</summary> /// <remarks>Adapter my be provided by setting a property or by implementing /// the OnCreateAdapter event</remarks> TBaseObjectBindSource = class(TBaseLinkingBindSource, IScopeEditLink, IScopeRecordEnumerable, IScopeNavigator, IScopeState, IScopeEditor, IScopeMemberNames, IScopeCurrentRecord, IScopeActive, IScopeMemberScripting, IScopeGetRecord, IScopeLookup, IScopeNavigatorUpdates, IScopeLocate) private FConnectedAdapter: TBindSourceAdapter; FDataLink: TBindSourceAdapterLink; FAdapterLinks: TDictionary<TBasicBindComponent, TBindSourceAdapterLink>; FActiveChanged: TBindEventList; FDataSetChanged: TBindEventList; FEditingChanged: TBindEventList; FDataSetScrolled: TBindEventList1<Integer>; FAutoActivate: Boolean; FDeferActivate: Boolean; FOnCreateAdapter: TCreateAdapterEvent; FRuntimeAdapter: TBindSourceAdapter; FCheckRuntimeAdapter: Boolean; FAutoEdit: Boolean; procedure SetAutoActivate(const Value: Boolean); procedure SetItemIndex(const Value: Integer); function GetItemIndex: Integer; //procedure ActivateExpressions; procedure GetRowMember(ARow: Integer; const AMemberName: string; ACallback: TProc<TObject>); function AdapterLookup(const KeyFields: string; const KeyValues: TValue; const ResultFields: string): TValue; function AdapterLocate(const KeyFields: string; const KeyValues: TValue): Boolean; function AdapterFindValues(LEnumerator: IScopeRecordEnumerator; const KeyFields: string; const KeyValues: TValue; AProc: TProc<Integer, TValue>): Boolean; protected procedure UpdateAdapterChanged; virtual; procedure UpdateAdapterChanging; virtual; procedure SetInternalAdapter(const Value: TBindSourceAdapter; AAssignProc: TProc<TBindSourceAdapter>); function CheckRuntimeAdapter: Boolean; function GetRuntimeAdapter: TBindSourceAdapter; procedure ConnectAdapter(AAdapter: TBindSourceAdapter); procedure DisconnectAdapter(AAdapter: TBindSourceAdapter); procedure DoMemberRenamed(const CurName, PrevName: string); procedure DoMemberRenaming(const CurName, NewName: string); procedure OnAdapterUpdateState(Sender: TObject); procedure OnAdapterDataSetChanged(Sender: TObject); procedure OnAdapterDataSetScrolled(Sender: TObject; ADistance: Integer); procedure OnAdapterEdit(Sender: TObject; var Allow: Boolean); procedure OnAdapterEditingChanged(Sender: TObject); procedure OnAdapterLayoutChanged(Sender: TObject); procedure OnAdapterUpdateRecord(Sender: TObject); procedure OnAdapterRecordChanged(Sender: TObject; AField: TBindSourceAdapterField); procedure SetActive(const Value: Boolean); virtual; function CheckAdapter: Boolean; virtual; function GetInternalAdapter: TBindSourceAdapter; virtual; procedure SetRuntimeAdapter(AAdapter: TBindSourceAdapter); virtual; function GetValue: TObject; override; function GetMember(const AMemberName: string): TObject; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Loaded; override; procedure AddExpression(AExpression: TBasicBindComponent); override; procedure RemoveExpression(AExpression: TBasicBindComponent); override; { IScopeEditLink } function Edit(ABindComp: TBasicBindComponent): Boolean; overload; virtual; function GetIsEditing(ABindComp: TBasicBindComponent): Boolean; virtual; procedure SetModified(ABindComp: TBasicBindComponent); virtual; function GetIsModified(ABindComp: TBasicBindComponent): Boolean; virtual; function GetCanModify(ABindComp: TBasicBindComponent): Boolean; overload; virtual; procedure UpdateRecord(ABindComp: TBasicBindComponent); virtual; procedure Reset(ABindComp: TBasicBindComponent); virtual; procedure SetField(ABindComp: TBasicBindComponent; const FieldName: string); virtual; procedure SetReadOnly(ABindComp: TBasicBindComponent; const Value: Boolean); virtual; procedure ClearModified(ABindComp: TBasicBindComponent); virtual; procedure PosChanging(ABindComp: TBasicBindComponent); virtual; { IScopeRecordEnumerable } function GetEnumerator(const AMemberName: string; ABufferCount: Integer = -1): IScopeRecordEnumerator; { IScopeNavigator } function GetBOF: Boolean; virtual; function GetEOF: Boolean; virtual; function GetSelected: Boolean; virtual; { IScopeState } function GetActive: Boolean; virtual; function GetCanModify: Boolean; overload; virtual; function GetCanInsert: Boolean; virtual; function GetCanDelete: Boolean; virtual; function GetEditing: Boolean; virtual; function GetCanRefresh: Boolean; virtual; procedure AddActiveChanged(LNotify: TNotifyEvent); virtual; procedure RemoveActiveChanged(LNotify: TNotifyEvent); virtual; procedure AddEditingChanged(LNotify: TNotifyEvent); virtual; procedure RemoveEditingChanged(LNotify: TNotifyEvent); virtual; procedure AddDataSetScrolled(LNotify: TNotifyDistanceEvent); virtual; procedure RemoveDataSetScrolled(LNotify: TNotifyDistanceEvent); virtual; procedure AddDataSetChanged(LNotify: TNotifyEvent); virtual; procedure RemoveDataSetChanged(LNotify: TNotifyEvent); virtual; { IScopeMemberNames } procedure GetMemberNames(AList: TStrings); virtual; { IScopeCurrentRecord } function GetCurrentRecord(const AMemberName: string): IScope; { IScopeMemberScripting } function GetMemberGetter(const AMemberName: string; var AGetter: string): Boolean; function GetMemberSetter(const AMemberName: string; var ASetter: string): Boolean; function GetMemberType(const AMemberName: string; var AType: TScopeMemberType): Boolean; function GetPositionGetter(var AGetter: string; var ABase: Integer): Boolean; function GetPositionSetter(var ASetter: string; var ABase: Integer): Boolean; { IScopeGetRecord } procedure GetRecord(ARow: Integer; const AMemberName: string; ACallback: TProc<IScope>); procedure DoCreateAdapter(var ADataObject: TBindSourceAdapter); virtual; procedure GetLookupMemberNames(AList: TStrings); virtual; { IScopeNavigatorUpdates } function GetCanApplyUpdates: Boolean; virtual; function GetCanCancelUpdates: Boolean; virtual; public { IScopeLocate } function Locate(const KeyFields: string; const KeyValues: TValue): Boolean; virtual; { IScopeLookup } function Lookup(const KeyFields: string; const KeyValues: TValue; const ResultFields: string): TValue; virtual; { IScopeNavigatorUpdates } procedure ApplyUpdates; virtual; procedure CancelUpdates; virtual; { IScopeNavigator } procedure Next; virtual; procedure Prior; virtual; procedure First; virtual; procedure Last; virtual; { IScopeEditor } procedure Insert; virtual; procedure Delete; virtual; procedure Cancel; virtual; procedure Post; virtual; procedure Edit; overload; virtual; procedure Refresh; virtual; function IsValidChar(const AFieldName: string; const AChar: Char): Boolean; virtual; function IsRequired(const AFieldName: string): Boolean; virtual; property Eof: Boolean read GetEOF; property BOF: Boolean read GetBOF; property CanModify: Boolean read GetCanModify; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; [Default(True)] property Active: Boolean read GetActive write SetActive default True; property AutoActivate: Boolean read FAutoActivate write SetAutoActivate; property ItemIndex: Integer read GetItemIndex write SetItemIndex; property Editing: Boolean read GetEditing; property OnCreateAdapter: TCreateAdapterEvent read FOnCreateAdapter write FOnCreateAdapter; property Members[const AName: string]: TObject read GetMember; property InternalAdapter: TBindSourceAdapter read GetInternalAdapter; end; /// <summary>Bind source which delegates</summary> TBaseObjectBindSourceDelegate = class(TBaseLinkingBindSource, IScopeEditLink, IScopeRecordEnumerable, IScopeNavigator, IScopeState, IScopeEditor, IScopeMemberNames, IScopeCurrentRecord, IScopeActive, IScopeMemberScripting, IScopeGetRecord, IScopeLookup, IScopeNavigatorUpdates, IScopeLocate) private FBindSource: TBaseObjectBindSource; protected function GetValue: TObject; override; function GetMember(const AMemberName: string): TObject; override; procedure AddExpression(AExpression: TBasicBindComponent); override; procedure RemoveExpression(AExpression: TBasicBindComponent); override; { IScopeEditLink } function Edit(ABindComp: TBasicBindComponent): Boolean; overload; function GetIsEditing(ABindComp: TBasicBindComponent): Boolean; procedure SetModified(ABindComp: TBasicBindComponent); function GetIsModified(ABindComp: TBasicBindComponent): Boolean; function GetCanModify(ABindComp: TBasicBindComponent): Boolean; overload; procedure UpdateRecord(ABindComp: TBasicBindComponent); procedure Reset(ABindComp: TBasicBindComponent); procedure SetField(ABindComp: TBasicBindComponent; const FieldName: string); procedure SetReadOnly(ABindComp: TBasicBindComponent; const Value: Boolean); procedure ClearModified(ABindComp: TBasicBindComponent); procedure PosChanging(ABindComp: TBasicBindComponent); { IScopeRecordEnumerable } function GetEnumerator(const AMemberName: string; ABufferCount: Integer = -1): IScopeRecordEnumerator; { IScopeNavigator } function GetBOF: Boolean; function GetEOF: Boolean; function GetSelected: Boolean; { IScopeState } function GetActive: Boolean; function GetCanModify: Boolean; overload; function GetCanInsert: Boolean; function GetCanDelete: Boolean; function GetEditing: Boolean; function GetCanRefresh: Boolean; procedure AddActiveChanged(LNotify: TNotifyEvent); procedure RemoveActiveChanged(LNotify: TNotifyEvent); procedure AddEditingChanged(LNotify: TNotifyEvent); procedure RemoveEditingChanged(LNotify: TNotifyEvent); procedure AddDataSetScrolled(LNotify: TNotifyDistanceEvent); procedure RemoveDataSetScrolled(LNotify: TNotifyDistanceEvent); procedure AddDataSetChanged(LNotify: TNotifyEvent); procedure RemoveDataSetChanged(LNotify: TNotifyEvent); { IScopeMemberNames } procedure GetMemberNames(AList: TStrings); virtual; { IScopeCurrentRecord } function GetCurrentRecord(const AMemberName: string): IScope; { IScopeMemberScripting } function GetMemberGetter(const AMemberName: string; var AGetter: string): Boolean; function GetMemberSetter(const AMemberName: string; var ASetter: string): Boolean; function GetMemberType(const AMemberName: string; var AType: TScopeMemberType): Boolean; function GetPositionGetter(var AGetter: string; var ABase: Integer): Boolean; function GetPositionSetter(var ASetter: string; var ABase: Integer): Boolean; { IScopeGetRecord } procedure GetRecord(ARow: Integer; const AMemberName: string; ACallback: TProc<IScope>); { IScopeNavigatorUpdates } function GetCanApplyUpdates: Boolean; function GetCanCancelUpdates: Boolean; { IScopeLocate } function Locate(const KeyFields: string; const KeyValues: TValue): Boolean; { IScopeLookup } function Lookup(const KeyFields: string; const KeyValues: TValue; const ResultFields: string): TValue; procedure GetLookupMemberNames(AList: TStrings); { IScopeNavigatorUpdates } procedure ApplyUpdates; procedure CancelUpdates; { IScopeNavigator } procedure Next; procedure Prior; procedure First; procedure Last; { IScopeEditor } procedure Insert; procedure Delete; procedure Cancel; procedure Post; procedure Edit; overload; procedure Refresh; function IsValidChar(const AFieldName: string; const AChar: Char): Boolean; function IsRequired(const AFieldName: string): Boolean; function CreateBindSource: TBaseObjectBindSource; virtual; abstract; public constructor Create(AOwner: TComponent); override; end; TCustomDataGeneratorAdapter = class; TCustomAdapterBindSource = class(TBaseObjectBindSource) private FAdapter: TBindSourceAdapter; procedure SetAdapter(Value: TBindSourceAdapter); protected function GetInternalAdapter: TBindSourceAdapter; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public destructor Destroy; override; property Adapter: TBindSourceAdapter read FAdapter write SetAdapter; end; /// <summary>Bind source which supports adapters to connect to different types of data</summary> TAdapterBindSource = class(TCustomAdapterBindSource) published property AutoActivate; property OnCreateAdapter; property Adapter; property ScopeMappings; end; TGeneratorFieldDefs = class; TCustomPrototypeBindSource = class(TBaseObjectBindSource) private FDataGenerator: TCustomDataGeneratorAdapter; FAdapter: TBindSourceAdapter; function GetFieldDefs: TGeneratorFieldDefs; function GetRecordCount: Integer; procedure SetFieldDefs(const Value: TGeneratorFieldDefs); procedure SetRecordCount(const Value: Integer); procedure SetAutoEdit(const Value: Boolean); procedure SetAutoPost(const Value: Boolean); function GetAutoEdit: Boolean; function GetAutoPost: Boolean; protected function GetInternalAdapter: TBindSourceAdapter; override; public constructor Create(AOwner: TComponent); override; [Default(true)] property AutoEdit: Boolean read GetAutoEdit write SetAutoEdit default true; property AutoPost: Boolean read GetAutoPost write SetAutoPost; property FieldDefs: TGeneratorFieldDefs read GetFieldDefs write SetFieldDefs; [Default(-1)] property RecordCount: Integer read GetRecordCount write SetRecordCount default -1; property DataGenerator: TCustomDataGeneratorAdapter read FDataGenerator; end; /// <summary>Bind source for creating sample data</summary> TPrototypeBindSource = class(TCustomPrototypeBindSource) published property AutoActivate; property AutoEdit; property AutoPost; property RecordCount; property FieldDefs; property ScopeMappings; property OnCreateAdapter; end; { TBindFieldDef } TBindFieldDef = class(TCollectionItem) private FName: string; protected function GetDisplayName: string; override; procedure SetDisplayName(const Value: string); reintroduce;// overload; class function MakeKey(const AName: string): string; static; property Name: string read FName write SetDisplayName; function HasChildDefs: Boolean; virtual; public destructor Destroy; override; end; TBindFieldDefClass = class of TBindFieldDef; TBindFieldDefs = class; TDefUpdateMethod = procedure of object; TBindFieldDefs = class(TOwnedCollection) private FDictionary: TDictionary<string, TBindFieldDef>; [weak] FDataSource: TComponent; FUpdated: Boolean; FInternalUpdateCount: Integer; FParentDef: TBindFieldDef; function SafeCast<T: TBindFieldDef>(AValue: TObject): T; protected procedure DoRenamingFieldDef(AFieldDef: TBindFieldDef; const CurName, NewName: string); virtual; procedure DoRenameFieldDef(AFieldDef: TBindFieldDef; const CurName, PrevName: string); virtual; procedure DataSourceFieldDefChanged(Sender: TObject); virtual; abstract; procedure DataSourceInitFieldDefs; virtual; abstract; function GetDataSourceFieldDefs: TBindFieldDefs; virtual; abstract; procedure DoUpdate(Sender: TObject); procedure SetItemName(AItem: TCollectionItem); override; procedure Update(AItem: TCollectionItem); overload; override; procedure UpdateDefs(AMethod: TDefUpdateMethod); function GetParentDef<T: TBindFieldDef>: T; function GetFieldDef<T: TBindFieldDef>(Index: Integer): T; procedure SetFieldDef(Index: Integer; Value: TBindFieldDef); procedure FieldDefUpdate(Sender: TObject); procedure ChildDefUpdate(Sender: TObject); function GetFieldDefClass: TBindFieldDefClass; virtual; abstract; function AddFieldDef<T: TBindFieldDef>: T; function Find<T: TBindFieldDef>(const Name: string): T; procedure Update; reintroduce; overload; public constructor Create(AOwner: TPersistent); virtual; destructor Destroy; override; procedure GetItemNames(List: TStrings); overload; function IndexOf(const AName: string): Integer; property DataSource: TComponent read FDataSource; property Updated: Boolean read FUpdated write FUpdated; end; TBindFieldDefsClass = class of TBindFieldDefs; TBindFieldDefWithChildren = class(TBindFieldDef) private FChildDefs: TBindFieldDefs; protected function GetChildDefs<T: TBindFieldDefs>: T; function GetParentDef<T: TBindFieldDef>: T; procedure SetChildDefs(Value: TBindFieldDefs); function GetChildDefsClass: TBindFieldDefsClass; virtual; abstract; function AddChild<T: TBindFieldDef>: T; function HasChildDefs: Boolean; override; public destructor Destroy; override; end; TGeneratorBindFieldDefsClass = class of TGeneratorFieldDefs; TGeneratorFieldType = (ftString, ftInteger, ftSingle, ftBoolean, ftBitmap, ftUInteger, ftCurrency, ftDateTime, ftTStrings, ftDate, ftTime, ftChar); TGeneratorFieldTypes = set of TGeneratorFieldType; TGeneratorOption = (optShuffle, optRepeat); TGeneratorOptions = set of TGeneratorOption; TGeneratorFieldDef = class(TBindFieldDefWithChildren) private FFieldNo: Integer; FFieldType: TGeneratorFieldType; FGenerator: string; FReadOnly: Boolean; FOptions: TGeneratorOptions; FCustomFormat: string; function GetChildDefs: TGeneratorFieldDefs; function GetFieldNo: Integer; function GetParentDef: TGeneratorFieldDef; procedure SetChildDefs(Value: TGeneratorFieldDefs); procedure SetFieldType(Value: TGeneratorFieldType); procedure SetGenerator(const Value: string); function GetTypeInfo: PTypeInfo; function GetMemberType: TScopeMemberType; procedure SetReadOnly(const Value: Boolean); procedure SetOptions(const Value: TGeneratorOptions); procedure SetCustomFormat(const Value: string); protected function GetChildDefsClass: TBindFieldDefsClass; override;//override; //virtual; reintroduce; public constructor Create(Collection: TCollection); overload; override; constructor Create(Owner: TBindFieldDefs; const Name: string; FieldNo: Integer); reintroduce; overload; virtual; function AddChild: TGeneratorFieldDef; procedure Assign(Source: TPersistent); override; property FieldNo: Integer read GetFieldNo write FFieldNo stored False; property ParentDef: TGeneratorFieldDef read GetParentDef; property TypeInfo: PTypeInfo read GetTypeInfo; property MemberType: TScopeMemberType read GetMemberType; property ChildDefs: TGeneratorFieldDefs read GetChildDefs write SetChildDefs stored HasChildDefs; published property Name; property FieldType: TGeneratorFieldType read FFieldType write SetFieldType default ftString; property Generator: string read FGenerator write SetGenerator; property Options: TGeneratorOptions read FOptions write SetOptions default [optShuffle, optRepeat]; property ReadOnly: Boolean read FReadOnly write SetReadOnly; property CustomFormat: string read FCustomFormat write SetCustomFormat; end; TGeneratorFieldDefs = class(TBindFieldDefs) type TEnumerator = TCollectionEnumerator<TGeneratorFieldDef>; protected function GetAttr(Index: Integer): string; override; function GetAttrCount: Integer; override; function GetItemAttr(Index, ItemIndex: Integer): string; override; procedure DoRenamingFieldDef(AFieldDef: TBindFieldDef; const CurName, NewName: string); override; procedure DoRenameFieldDef(AFieldDef: TBindFieldDef; const CurName, PrevName: string); override; procedure DataSourceFieldDefChanged(Sender: TObject); override; procedure DataSourceInitFieldDefs; override; function GetDataSourceFieldDefs: TBindFieldDefs; override; function GetFieldDefClass: TBindFieldDefClass; override; function GetParentDef: TGeneratorFieldDef; function GetFieldDef(Index: Integer): TGeneratorFieldDef; procedure SetFieldDef(Index: Integer; Value: TGeneratorFieldDef); public function GetEnumerator: TEnumerator; function AddFieldDef: TGeneratorFieldDef; function Find(const Name: string): TGeneratorFieldDef; property Items[Index: Integer]: TGeneratorFieldDef read GetFieldDef write SetFieldDef; default; property ParentDef: TGeneratorFieldDef read GetParentDef; end; TBindSourceAdapterLink = class private [weak] FAdapter: TBindSourceAdapter; FUpdating: Boolean; FActive: Boolean; FEditing: Boolean; FReadOnly: Boolean; procedure SetAdapter(const Value: TBindSourceAdapter); procedure UpdateState; procedure SetActive(Value: Boolean); procedure SetEditing(Value: Boolean); protected procedure UpdateRecord; procedure RecordChanged(Field: TBindSourceAdapterField); virtual; procedure DataSetChanged; virtual; procedure DataSetScrolled(ADistance: Integer); virtual; procedure LayoutChanged; virtual; procedure ActiveChanged; virtual; procedure EditingChanged; virtual; procedure UpdateData; virtual; function Edit: Boolean; virtual; property Active: Boolean read FActive; property Adapter: TBindSourceAdapter read FAdapter write SetAdapter; property Editing: Boolean read FEditing; public constructor Create; end; /// <summary>State of a scope adapter</summary> TBindSourceAdapterState = (seInactive, seBrowse, seEdit, seInsert); /// <summary>Interface for retrieving the underlying object exposed an adapter field</summary> IGetMemberObject = interface function GetMemberObject: TObject; end; /// <summary>Type information about an adapter field</summary> TBindSourceAdapterFieldType = record private FTypeKind: TTypeKind; FTypeName: string; public constructor Create(const ATypeName: string; ATypeKind: TTypeKind); property TypeKind: TTypeKind read FTypeKind; property TypeName: string read FTypeName; end; IBindSourceAdapter = interface; IBindSourceAdapter = interface ['{6F63422E-B03D-4308-A536-12F3C5A22931}'] procedure Next; procedure Prior; procedure First; procedure Last; procedure Insert; procedure Append; procedure Delete; procedure Cancel; procedure Post; procedure Edit(AForce: Boolean=False); procedure ApplyUpdates; procedure CancelUpdates; function GetEmpty: Boolean; function GetCurrent: TObject; function GetCount: Integer; function GetItemIndex: Integer; function GetCurrentIndex: Integer; function GetCanDelete: Boolean; function GetCanInsert: Boolean; function GetActive: Boolean; function GetCanModify: Boolean; function GetCanApplyUpdates: Boolean; function GetCanCancelUpdates: Boolean; function GetBOF: Boolean; function GetEOF: Boolean; procedure GetMemberNames(AList: TStrings); procedure GetLookupMemberNames(AList: TStrings); procedure SetItemIndex(AValue: Integer); procedure SetItemIndexOffset(AValue: Integer); function GetItemIndexOffset: Integer; procedure SetActive(AValue: Boolean); property Current: TObject read GetCurrent; function GetCurrentRecord(const AMemberName: string): IScope; property ItemIndex: Integer read GetItemIndex write SetItemIndex; property CurrentIndex: Integer read GetCurrentIndex; property ItemCount: Integer read GetCount; property ItemIndexOffset: Integer read GetItemIndexOffset write SetItemIndexOffset; property CanModify: Boolean read GetCanModify; property CanInsert: Boolean read GetCanInsert; property CanDelete: Boolean read GetCanDelete; property Active: Boolean read GetActive write SetActive; property BOF: Boolean read GetBOF; property Eof: Boolean read GetEOF; property Empty: Boolean read GetEmpty; end; TAdapterErrorAction = (aaFail, aaAbort, aaRetry); TAdapterNotifyEvent = procedure(Adapter: TBindSourceAdapter) of object; TAdapterHasUpdatesEvent = procedure(Adapter: TBindSourceAdapter; var AHasUpdates: Boolean) of object; TAdapterErrorEvent = procedure(Adapter: TBindSourceAdapter; E: EBindCompError; var Action: TAdapterErrorAction) of object; /// <summary>Adapter base class for providing data to a TAdapterBindScope</summary> TBindSourceAdapter = class(TComponent, IBindSourceAdapter) private type // Disambiguate methods when linked statically with C++ TDummy<T> = class protected FDummy: T; end; private FEnteringEditState: Boolean; FUpdatingRecords: Integer; FScopes: TList<TBaseObjectBindSource>; FModified: Boolean; FFields: TList<TBindSourceAdapterField>; FLinks: TList<TBindSourceAdapterLink>; FItemIndex: Integer; FState: TBindSourceAdapterState; { Events } FBeforeOpen: TAdapterNotifyEvent; FAfterOpen: TAdapterNotifyEvent; FBeforeClose: TAdapterNotifyEvent; FAfterClose: TAdapterNotifyEvent; FBeforeInsert: TAdapterNotifyEvent; FAfterInsert: TAdapterNotifyEvent; FBeforeEdit: TAdapterNotifyEvent; FAfterEdit: TAdapterNotifyEvent; FBeforePost: TAdapterNotifyEvent; FAfterPost: TAdapterNotifyEvent; FBeforeCancel: TAdapterNotifyEvent; FAfterCancel: TAdapterNotifyEvent; FBeforeDelete: TAdapterNotifyEvent; FAfterDelete: TAdapterNotifyEvent; FBeforeRefresh: TAdapterNotifyEvent; FAfterRefresh: TAdapterNotifyEvent; FBeforeScroll: TAdapterNotifyEvent; FAfterScroll: TAdapterNotifyEvent; FBeforeApplyUpdates: TAdapterNotifyEvent; FAfterApplyUpdates: TAdapterNotifyEvent; FBeforeCancelUpdates: TAdapterNotifyEvent; FAfterCancelUpdates: TAdapterNotifyEvent; FOnPostError: TAdapterErrorEvent; FOnDeleteError: TAdapterErrorEvent; FOnInsertError: TAdapterErrorEvent; FItemIndexOffset: Integer; FOnCancelUpdates: TAdapterNotifyEvent; FOnApplyUpdates: TAdapterNotifyEvent; FOnApplyUpdatesError: TAdapterErrorEvent; FOnEditError: TAdapterErrorEvent; FOnCancelUpdatesError: TAdapterErrorEvent; FOnHasUpdates: TAdapterHasUpdatesEvent; FAutoEdit: Boolean; FResetNeeded: Boolean; FAutoPost: Boolean; function GetScopes: TEnumerable<TBaseObjectBindSource>; procedure CheckBrowseMode; procedure CheckActive; procedure CheckCanModify; procedure CheckOperation(AOperation: TProc; ErrorEvent: TAdapterErrorEvent); procedure DoAfterApplyUpdates; procedure DoAfterCancelUpdates; procedure DoBeforeApplyUpdates; procedure DoBeforeCancelUpdates; procedure AutoEditField(AField: TBindSourceAdapterField); procedure AutoPostField(AField: TBindSourceAdapterField); protected procedure PostFields(AFields: TArray<TBindSourceAdapterField>); procedure DataSetChanged; procedure RecordChanged(AField: TBindSourceAdapterField); procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetItemIndexOffset: Integer; procedure SetItemIndexOffset(Value: Integer); function SupportsNestedFields: Boolean; virtual; function GetCanActivate: Boolean; virtual; procedure AddScope(Value: TBaseObjectBindSource); virtual; function HasScope(Value: TBaseObjectBindSource): Boolean; procedure RemoveScope(Value: TBaseObjectBindSource); virtual; procedure SetItemIndex(Value: Integer); procedure ClearFields; procedure AddLink(DataLink: TBindSourceAdapterLink); procedure RemoveLink(DataLink: TBindSourceAdapterLink); procedure SetState(Value: TBindSourceAdapterState); function GetMemberGetter(const AMemberName: string; var AGetter: string): Boolean; virtual; function GetMemberSetter(const AMemberName: string; var ASetter: string): Boolean; virtual; function GetMemberType(const AMemberName: string; var AType: TScopeMemberType): Boolean; virtual; function IsValidChar(const AMemberName: string; const AChar: Char): Boolean; virtual; procedure UpdateRecord; function GetEmpty: Boolean; function GetCurrent: TObject; virtual; function GetCount: Integer; virtual; function GetItemIndex: Integer; function GetCurrentIndex: Integer; function GetCanDelete: Boolean; virtual; function GetCanInsert: Boolean; virtual; function GetActive: Boolean; virtual; function GetCanModify: Boolean; virtual; function GetCanRefresh: Boolean; virtual; function GetBOF: Boolean; virtual; function GetEOF: Boolean; virtual; procedure GetLookupMemberNames(AList: TStrings); virtual; function DeleteAt(AIndex: Integer): Boolean; virtual; procedure SetActive(Value: Boolean); virtual; function AppendAt: Integer; virtual; procedure InternalEdit; virtual; procedure InternalRefresh; virtual; procedure InternalCancelUpdates; virtual; procedure InternalApplyUpdates; virtual; procedure InternalPost; virtual; function InsertAt(AIndex: Integer): Integer; virtual; function GetCanApplyUpdates: Boolean; virtual; function GetCanCancelUpdates: Boolean; virtual; class procedure AddFieldsToList(AType: TRttiType; ABindSourceAdapter: TBindSourceAdapter; AFieldsList: TList<TBindSourceAdapterField>; const AGetMemberObject: IGetMemberObject); class function CreateRttiPropertyField<T>(AProperty: TRttiProperty; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; AMemberType: TScopeMemberType; LDummy: TDummy<T> = nil): TBindSourceAdapterField; class function CreateRttiObjectPropertyField<T: class>(AProperty: TRttiProperty; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; AMemberType: TScopeMemberType; LDummy: TDummy<T> = nil): TBindSourceAdapterField; class function CreateRttiFieldField<T>(AProperty: TRttiField; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; AMemberType: TScopeMemberType; LDummy: TDummy<T> = nil): TBindSourceAdapterField; class function CreateRttiObjectFieldField<T: class>(AProperty: TRttiField; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; AMemberType: TScopeMemberType; LDummy: TDummy<T> = nil): TBindSourceAdapterField; class procedure AddPropertiesToList(AType: TRttiType; ABindSourceAdapter: TBindSourceAdapter; AFieldsList: TList<TBindSourceAdapterField>; const AGetMemberObject: IGetMemberObject); procedure DoAfterCancel; virtual; procedure DoAfterClose; virtual; procedure DoAfterDelete; virtual; procedure DoAfterEdit; virtual; procedure DoAfterInsert; virtual; procedure DoAfterOpen; virtual; procedure DoAfterPost; virtual; procedure DoAfterRefresh; virtual; procedure DoAfterScroll; virtual; procedure DoBeforeCancel; virtual; procedure DoBeforeClose; virtual; procedure DoBeforeDelete; virtual; procedure DoBeforeEdit; virtual; procedure DoBeforeInsert; virtual; procedure DoBeforeOpen; virtual; procedure DoBeforePost; virtual; procedure DoBeforePostFields(AFields: TArray<TBindSourceAdapterField>); virtual; procedure DoAfterPostFields(AFields: TArray<TBindSourceAdapterField>); virtual; procedure DoBeforeRefresh; virtual; procedure DoBeforeScroll; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function FindField(const AMemberName: string): TBindSourceAdapterField; function GetEnumerator(const AMemberName: string; AGetScope: TFunc<IScope>; AGetMemberScope: TFunc<string, IScope>): IScopeRecordEnumerator; function GetValue: TObject; function GetMember(const AMemberName: string): TObject; procedure Refresh; virtual; procedure Next; virtual; procedure Prior; virtual; procedure First; virtual; procedure Last; virtual; procedure Insert; virtual; procedure Append; virtual; procedure Delete; virtual; procedure Cancel; virtual; procedure Post; virtual; procedure PosChanging; virtual; procedure Edit(AForce: Boolean = False); overload; virtual; procedure CancelUpdates; virtual; procedure ApplyUpdates; virtual; procedure GetMemberNames(AList: TStrings); virtual; // Cause linked grid controls to reset on next data change procedure ResetNeeded; property Current: TObject read GetCurrent; function GetCurrentRecord(const AMemberName: string): IScope; property ItemIndex: Integer read GetItemIndex write SetItemIndex; property CurrentIndex: Integer read GetCurrentIndex; property ItemCount: Integer read GetCount; property ItemIndexOffset: Integer read GetItemIndexOffset write SetItemIndexOffset; property CanModify: Boolean read GetCanModify; property CanInsert: Boolean read GetCanInsert; property CanDelete: Boolean read GetCanDelete; property CanRefresh: Boolean read GetCanRefresh; property Active: Boolean read GetActive write SetActive; [Default(True)] property AutoEdit: Boolean read FAutoEdit write FAutoEdit default True; property AutoPost: Boolean read FAutoPost write FAutoPost; property BOF: Boolean read GetBOF; property Eof: Boolean read GetEOF; property Modified: Boolean read FModified; property Empty: Boolean read GetEmpty; property State: TBindSourceAdapterState read FState; property Fields: TList<TBindSourceAdapterField> read FFields; property CanActivate: Boolean read GetCanActivate; property CanApplyUpdates: Boolean read GetCanApplyUpdates; property CanCancelUpdates: Boolean read GetCanCancelUpdates; property Scopes: TEnumerable<TBaseObjectBindSource> read GetScopes; property BeforeOpen: TAdapterNotifyEvent read FBeforeOpen write FBeforeOpen; property AfterOpen: TAdapterNotifyEvent read FAfterOpen write FAfterOpen; property BeforeClose: TAdapterNotifyEvent read FBeforeClose write FBeforeClose; property AfterClose: TAdapterNotifyEvent read FAfterClose write FAfterClose; property BeforeInsert: TAdapterNotifyEvent read FBeforeInsert write FBeforeInsert; property AfterInsert: TAdapterNotifyEvent read FAfterInsert write FAfterInsert; property BeforeEdit: TAdapterNotifyEvent read FBeforeEdit write FBeforeEdit; property AfterEdit: TAdapterNotifyEvent read FAfterEdit write FAfterEdit; property BeforePost: TAdapterNotifyEvent read FBeforePost write FBeforePost; property AfterPost: TAdapterNotifyEvent read FAfterPost write FAfterPost; property BeforeCancel: TAdapterNotifyEvent read FBeforeCancel write FBeforeCancel; property AfterCancel: TAdapterNotifyEvent read FAfterCancel write FAfterCancel; property BeforeDelete: TAdapterNotifyEvent read FBeforeDelete write FBeforeDelete; property AfterDelete: TAdapterNotifyEvent read FAfterDelete write FAfterDelete; property BeforeScroll: TAdapterNotifyEvent read FBeforeScroll write FBeforeScroll; property AfterScroll: TAdapterNotifyEvent read FAfterScroll write FAfterScroll; property BeforeRefresh: TAdapterNotifyEvent read FBeforeRefresh write FBeforeRefresh; property AfterRefresh: TAdapterNotifyEvent read FAfterRefresh write FAfterRefresh; property BeforeApplyUpdates: TAdapterNotifyEvent read FBeforeApplyUpdates write FBeforeApplyUpdates; property AfterApplyUpdates: TAdapterNotifyEvent read FAfterApplyUpdates write FAfterApplyUpdates; property BeforeCancelUpdates: TAdapterNotifyEvent read FBeforeCancelUpdates write FBeforeCancelUpdates; property AfterCancelUpdates: TAdapterNotifyEvent read FAfterCancelUpdates write FAfterCancelUpdates; property OnDeleteError: TAdapterErrorEvent read FOnDeleteError write FOnDeleteError; property OnInsertError: TAdapterErrorEvent read FOnInsertError write FOnINsertError; property OnEditError: TAdapterErrorEvent read FOnEditError write FOnEditError; property OnPostError: TAdapterErrorEvent read FOnPostError write FOnPostError; property OnApplyUpdatesError: TAdapterErrorEvent read FOnApplyUpdatesError write FOnApplyUpdatesError; property OnCancelUpdatesError: TAdapterErrorEvent read FOnCancelUpdatesError write FOnCancelUpdatesError; property OnApplyUpdates: TAdapterNotifyEvent read FOnApplyUpdates write FOnApplyUpdates; property OnCancelUpdates: TAdapterNotifyEvent read FOnCancelUpdates write FOnCancelUpdates; property OnHasUpdates: TAdapterHasUpdatesEvent read FOnHasUpdates write FOnHasUpdates; end; TObjectAdapterOption = (optAllowModify, optAllowApplyUpdates, optAllowCancelUpdates); TObjectAdapterOptions = set of TObjectAdapterOption; TBaseObjectBindSourceAdapter = class(TBindSourceAdapter) private FOptions: TObjectAdapterOptions; protected function GetObjectType: TRttiType; virtual; public constructor Create(AOwner: TComponent); override; property Options: TObjectAdapterOptions read FOptions write FOptions; end; TBindSourceAdapterInstanceFactory = class private FType: TRttiType; FFindConstructor: Boolean; FConstructor: TRttiMethod; function FindConstructor: TRttiMethod; public constructor Create(AType: TRttiType); function CheckConstructor(out AType: TRttiType; out AMethod: TRttiMethod): Boolean; overload; function CheckConstructor: Boolean; overload; function CanConstructInstance: Boolean; function ConstructInstance: TObject; end; TListAdapterOption = (loptAllowInsert, loptAllowDelete, loptAllowModify, loptAllowApplyUpdates, loptAllowCancelUpdates); TListAdapterOptions = set of TListAdapterOption; TListInsertEvent = procedure(Sender: TBindSourceAdapter; AIndex: Integer; var AHandled: Boolean; var ANewIndex: Integer) of object; TListAppendEvent = procedure(Sender: TBindSourceAdapter; var AHandled: Boolean; var Appended: Boolean) of object; TListDeleteEvent = procedure(Sender: TBindSourceAdapter; AIndex: Integer; var AHandled: Boolean; var ADeleted: Boolean) of object; TCreateItemInstanceEvent = procedure(Sender: TBindSourceAdapter; var AHandled: Boolean; var AInstance: TObject) of object; TInitItemInstanceEvent = procedure(Sender: TBindSourceAdapter; AInstance: TObject) of object; TSetObjectEvent = procedure(Sender: TBindSourceAdapter; AObject: TObject) of object; TBaseListBindSourceAdapter = class(TBaseObjectBindSourceAdapter) private FOnListAppend: TListAppendEvent; FOnListInsert: TListInsertEvent; FOnListDelete: TListDeleteEvent; FOnCreateItemInstance: TCreateItemInstanceEvent; FOnInitItemInstance: TInitItemInstanceEvent; FOptions: TListAdapterOptions; protected procedure DoListDelete(AIndex: Integer; out AHandled: Boolean; out ARemoved: Boolean); virtual; procedure DoListInsert(AIndex: Integer; out AHandled: Boolean; out ANewIndex: Integer); virtual; procedure DoListAppend(out AHandled: Boolean; out AAppended: Boolean); virtual; procedure DoCreateInstance(out AHandled: Boolean; out AInstance: TObject); virtual; procedure DoInitItemInstance(AInstance: TObject); virtual; public constructor Create(AOwner: TComponent); override; property OnListAppend: TListAppendEvent read FOnListAppend write FOnListAppend; property OnListDelete: TListDeleteEvent read FOnListDelete write FOnListDelete; property OnListInsert: TListInsertEvent read FOnListInsert write FOnListInsert; property OnCreateItemInstance: TCreateItemInstanceEvent read FOnCreateItemInstance write FOnCreateItemInstance; property OnInitItemInstance: TInitItemInstanceEvent read FOnInitItemInstance write FOnInitItemInstance; property Options: TListAdapterOptions read FOptions write FOptions; end; /// <summary>Adapter to provide a generic TList to TAdapterBindSource</summary> TListBindSourceAdapter<T: class> = class(TBaseListBindSourceAdapter) private FList: TList<T>; FInstanceFactory: TBindSourceAdapterInstanceFactory; FOwnsList: Boolean; FOnBeforeSetList: TSetObjectEvent; FOnAfterSetList: TAdapterNotifyEvent; function GetItemInstanceFactory: TBindSourceAdapterInstanceFactory; protected procedure CheckList; function GetObjectType: TRttiType; override; function CreateItemInstance: T; virtual; procedure InitItemInstance(AInstance: T); virtual; function GetCurrent: TObject; override; function GetCount: Integer; override; function DeleteAt(AIndex: Integer): Boolean; override; function AppendAt: Integer; override; function InsertAt(AIndex: Integer): Integer; override; function GetCanActivate: Boolean; override; function SupportsNestedFields: Boolean; override; function GetCanDelete: Boolean; override; function GetCanInsert: Boolean; override; function GetCanModify: Boolean; override; function GetCanApplyUpdates: Boolean; override; function GetCanCancelUpdates: Boolean; override; procedure AddFields; virtual; procedure InternalCancelUpdates; override; procedure InternalApplyUpdates; override; procedure DoOnBeforeSetList(AList: TList<T>); virtual; procedure DoOnAfterSetList; virtual; public constructor Create(AOwner: TComponent; AList: TList<T>; AOwnsObject: Boolean = True); reintroduce; overload; virtual; destructor Destroy; override; procedure SetList(AList: TList<T>; AOwnsObject: Boolean = True); property List: TList<T> read FList; property OnBeforeSetList: TSetObjectEvent read FOnBeforeSetList write FOnBeforeSetList; property OnAfterSetList: TAdapterNotifyEvent read FOnAfterSetList write FOnAfterSetList; end; TListBindSourceAdapter = class(TListBindSourceAdapter<TObject>) private FClass: TClass; protected function GetObjectType: TRttiType; override; public constructor Create(AOwner: TComponent; AList: TList<TObject>; AClass: TClass; AOwnsObject: Boolean = True); reintroduce; overload; virtual; end; /// <summary>Adapter to provide an arbitrary object to TAdapterBindSource</summary> TObjectBindSourceAdapter<T: class> = class(TBaseObjectBindSourceAdapter) private FDataObject: T; FOwnsObject: Boolean; FOnBeforeSetDataObject: TSetObjectEvent; FOnAfterSetDataObject: TAdapterNotifyEvent; protected function GetObjectType: TRttiType; override; function GetCanActivate: Boolean; override; function GetCurrent: TObject; override; function GetCount: Integer; override; function DeleteAt(AIndex: Integer): Boolean; override; function AppendAt: Integer; override; function InsertAt(AIndex: Integer): Integer; override; function SupportsNestedFields: Boolean; override; function GetCanModify: Boolean; override; function GetCanApplyUpdates: Boolean; override; function GetCanCancelUpdates: Boolean; override; procedure AddFields; virtual; procedure InternalApplyUpdates; override; procedure InternalCancelUpdates; override; procedure DoOnBeforeSetDataObject(ADataObject: T); virtual; procedure DoOnAfterSetDataObject; virtual; public constructor Create(AOwner: TComponent; AObject: T; AOwnsObject: Boolean = True); reintroduce; overload; virtual; destructor Destroy; override; procedure SetDataObject(ADataObject: T; AOwnsObject: Boolean = True); property DataObject: T read FDataObject; property OnBeforeSetDataObject: TSetObjectEvent read FOnBeforeSetDataObject write FOnBeforeSetDataObject; property OnAfterSetDataObject: TAdapterNotifyEvent read FOnAfterSetDataObject write FOnAfterSetDataObject; end; TObjectBindSourceAdapter = class(TObjectBindSourceAdapter<TObject>) private FClass: TClass; protected function GetObjectType: TRttiType; override; public constructor Create(AOwner: TComponent; AObject: TObject; AClass: TClass; AOwnsObject: Boolean = True); reintroduce; overload; virtual; end; /// <summary>Base class for an adapter field</summary> TBindSourceAdapterField = class(TPersistent) private class var FValidChars: TDictionary<char, TScopeMemberTypes>; private var FMemberName: string; [weak] FOwner: TBindSourceAdapter; FGetMemberObject: IGetMemberObject; function GetMemberObject: TObject; function SupportsStreamPersist(const Persistent: TObject; var StreamPersist: IStreamPersist): Boolean; procedure SaveToStreamPersist(StreamPersist: IStreamPersist); procedure SaveToStrings(Strings: TStrings); function CreateValueBlobStream(AValue: TObject): TStream; function GetAutoPost: Boolean; virtual; procedure SetAutoPost(const Value: Boolean); virtual; protected procedure AutoPostField; procedure AutoEditField; function CreateBlobStream: TStream; virtual; function AssignValue(Dest: TPersistent): Boolean; procedure Post; virtual; function IsBuffered: Boolean; virtual; procedure Cancel; virtual; function GetIsObject: Boolean; virtual; function GetIsReadable: Boolean; virtual; function GetIsWritable: Boolean; virtual; function GetGetter(var AGetter: string): Boolean; virtual; function GetSetter(var AGetter: string): Boolean; virtual; function GetMemberType(var AType: TScopeMemberType): Boolean; virtual; function IsValidChar(AChar: Char): Boolean; procedure RecordChanged; public constructor Create(AOwner: TBindSourceAdapter; const AMemberName: string; const AGetMemberObject: IGetMemberObject); virtual; class destructor Destroy; // Non generic access function GetTValue: TValue; virtual; procedure SetTValue(const AValue: TValue); virtual; function FindField(const AMemberName: string): TBindSourceAdapterField; virtual; property Owner: TBindSourceAdapter read FOwner; property MemberName: string read FMemberName; property IsObject: Boolean read GetIsObject; property IsReadable: Boolean read GetIsReadable; property IsWritable: Boolean read GetIsWritable; property AutoPost: Boolean read GetAutoPost write SetAutoPost; property MemberObject: TObject read GetMemberObject; property GetMemberObjectIntf: IGetMemberObject read FGetMemberObject write FGetMemberObject; end; /// <summary>Base class to get a value using RTTI</summary> TValueAccessor = class protected FField: TBindSourceAdapterField; end; /// <summary>Base class to get a value of a particular type using RTTI</summary> TValueReader<T> = class(TValueAccessor) public function GetValue: T; virtual; abstract; end; /// <summary>Use RTTI to read the value of a field</summary> TFieldValueReader<T> = class(TValueReader<T>) public function GetValue: T; override; end; TBindFieldDefValueReader<T> = class(TValueReader<T>) public function GetValue: T; override; end; TBindFieldDefObjectValueReader<T: class> = class(TBindFieldDefValueReader<T>) public function GetValue: T; override; end; /// <summary>Use RTTI to read the value of a property</summary> TPropertyValueReader<T> = class(TValueReader<T>) public function GetValue: T; override; end; /// <summary>Base class to set a value using RTTI</summary> TValueWriter<T> = class(TValueAccessor) public procedure SetValue(const AValue: T); virtual; abstract; end; /// <summary>Use RTTI to set the value of a field</summary> TFieldValueWriter<T> = class(TValueWriter<T>) public procedure SetValue(const AValue: T); override; end; TBindFieldDefValueWriter<T> = class(TValueWriter<T>) public procedure SetValue(const AValue: T); override; end; TBindFieldDefObjectValueWriter<T: class> = class(TBindFieldDefValueWriter<T>) public procedure SetValue(const AValue: T); override; end; /// <summary>Use RTTI to set the value of a property</summary> TPropertyValueWriter<T> = class(TValueWriter<T>) public procedure SetValue(const AValue: T); override; end; /// <summary>Adapter field which supports reading</summary> TBindSourceAdapterReadField<T> = class(TBindSourceAdapterField) protected const sMemberName = 'Value'; strict private var FValueReader: TValueReader<T>; FRttiType: TBindSourceAdapterFieldType; FMemberType: TScopeMemberType; protected function GetValue: T; virtual; function GetMemberType(var AType: TScopeMemberType): Boolean; override; function GetGetter(var AGetter: string): Boolean; override; public constructor Create(AOwner: TBindSourceAdapter; const AMemberName: string; AType: TBindSourceAdapterFieldType; const AGetMemberObject: IGetMemberObject; const AReader: TValueReader<T>; AMemberType: TScopeMemberType); reintroduce; destructor Destroy; override; function GetTValue: TValue; override; property Value: T read GetValue; end; TBindSourceAdapterReadObjectField<T: class> = class(TBindSourceAdapterReadField<T>) protected function CreateBlobStream: TStream; override; procedure AssignTo(Dest: TPersistent); override; end; /// <summary>Adapter field which supports reading and writing</summary> TBindSourceAdapterReadWriteField<T> = class(TBindSourceAdapterReadField<T>) strict private FAutoPost: Boolean; FBuffered: Boolean; FValueWriter: TValueWriter<T>; private FBuffer: T; protected function IsBuffered: Boolean; override; procedure Post; override; procedure Cancel; override; function GetValue: T; override; procedure SetValue(const Value: T); virtual; function GetSetter(var AGetter: string): Boolean; override; procedure ClearBuffer; virtual; function GetAutoPost: Boolean; override; procedure SetAutoPost(const Value: Boolean); override; public constructor Create(AOwner: TBindSourceAdapter; const AMemberName: string; AType: TBindSourceAdapterFieldType; const AGetMemberObject: IGetMemberObject; const AReader: TValueReader<T>; const AWriter: TValueWriter<T>; AMemberType: TScopeMemberType); reintroduce; procedure SetTValue(const AValue: TValue); override; destructor Destroy; override; property Value: T read GetValue write SetValue; end; TBindSourceAdapterReadWriteObjectField<T: class> = class(TBindSourceAdapterReadWriteField<T>) protected function CreateBlobStream: TStream; override; procedure AssignTo(Dest: TPersistent); override; procedure ClearBuffer; override; end; /// <summary>Adapter field which supports an object property</summary> /// <remarks>The members of the object are also exposed as fields</remarks> TBindSourceAdapterReadObjectField = class(TBindSourceAdapterReadObjectField<TObject>) private var FHaveFields: Boolean; FFields: TList<TBindSourceAdapterField>; procedure CheckAddFields; protected function GetIsObject: Boolean; override; public destructor Destroy; override; constructor Create(AOwner: TBindSourceAdapter; const AMemberName: string; AType: TBindSourceAdapterFieldType; const AGetMemberObject: IGetMemberObject; const AReader: TValueReader<TObject>; AMemberType: TScopeMemberType); function FindField(const AMemberName: string): TBindSourceAdapterField; override; property Fields: TList<TBindSourceAdapterField> read FFields; end; /// <summary>Custom scope to allow the expression engine to access field names as if they are members of the /// wrapped TBindSourceAdapter</summary> TBindSourceAdapterCustomScope = class(TCustomScope) protected function DoLookup(const Name: String): IInterface; override; end; /// <summary>Custom scope to allow the expression engine to access field names as if they are members of the /// wrapped field</summary> TBindSourceAdapterObjectFieldCustomScope = class(TCustomScope) protected function DoLookup(const Name: String): IInterface; override; end; /// <summary>Implementation of IGetMemberObject to get the object associated with an adapter</summary> TBindSourceAdapterGetMemberObject = class(TInterfacedObject, IGetMemberObject) private FBindSourceAdapter: TBindSourceAdapter; public constructor Create(ACollectionEditor: TBindSourceAdapter); function GetMemberObject: TObject; end; /// <summary>Implementation of IGetMemberObject to get the object associated with object field</summary> TBindSourceAdapteObjectFieldGetMemberObject = class(TInterfacedObject, IGetMemberObject) private FObject: TObject; public constructor Create(AObject: TObject); function GetMemberObject: TObject; end; TGeneratorRecord = class(TObject) private FDictionary: TDictionary<string, TValue>; FFreeObjects: TList<TObject>; public constructor Create; destructor Destroy; override; end; TValueGenerator = class; TCustomFormatObject = class; /// <summary>Adapter to provide a generic TList to TAdaptiveBindScope</summary> TCustomDataGeneratorAdapter = class(TListBindSourceAdapter<TGeneratorRecord>) private type // Disambiguate methods when linked statically with C++ TDummy<T> = class protected FDummy: T; end; private FFieldDefs: TGeneratorFieldDefs; FRecordCount: Integer; class procedure AddFieldsToList(AFieldDefs: TGeneratorFieldDefs; ABindSourceAdapter: TBindSourceAdapter; AFieldsList: TList<TBindSourceAdapterField>; const AGetMemberObject: IGetMemberObject); static; class function CreateField<T>(AFieldDef: TGeneratorFieldDef; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; LDummy: TDummy<T> = nil): TBindSourceAdapterField; static; class function CreateObjectField<T: class>(AFieldDef: TGeneratorFieldDef; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; LDummy: TDummy<T> = nil): TBindSourceAdapterField; static; procedure GenerateExistingRecords(AList: TList<TGeneratorRecord>); procedure SetFieldDefs(Value: TGeneratorFieldDefs); function GetFieldDefsClass: TGeneratorBindFieldDefsClass; procedure InitFieldDefs; procedure SetRecordCount(const Value: Integer); procedure CreateCustomFormatExpression<T>(const ACustomFormat: string; out AExpression: TBindingExpression; out ACustomFormatObject: TCustomFormatObject);// function GenerateValue<T>(const AGenerator: TValueGenerator; protected function SupportsNestedFields: Boolean; override; procedure SetActive(Value: Boolean); override; function CreateItemInstance: TGeneratorRecord; override; procedure InitItemInstance(ARecord: TGeneratorRecord); override; procedure FieldDefChanged(Sender: TObject); virtual; function GetCanActivate: Boolean; override; function GetCanInsert: Boolean; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure GetMemberNames(AList: TStrings); override; procedure AddFields; override; property FieldDefs: TGeneratorFieldDefs read FFieldDefs write SetFieldDefs; [Default(-1)] property RecordCount: Integer read FRecordCount write SetRecordCount default -1; end; TDataGeneratorAdapter = class(TCustomDataGeneratorAdapter) published property FieldDefs; property Active; property AutoEdit; property AutoPost; property RecordCount; property BeforeOpen; property AfterOpen; property BeforeClose; property AfterClose; property BeforeInsert; property AfterInsert; property BeforeEdit; property AfterEdit; property BeforePost; property AfterPost; property BeforeCancel; property AfterCancel; property BeforeDelete; property AfterDelete; property BeforeScroll; property AfterScroll; property BeforeRefresh; property AfterRefresh; property OnDeleteError; property OnInsertError; property OnEditError; property OnPostError; property OnApplyUpdates; property OnCancelUpdates; property Options; end; TValueGenerator = class private FGeneratorName: string; FFieldType: TGeneratorFieldType; FOptions: TGeneratorOptions; FCustomFormat: string; protected function GetRecordCount: Integer; virtual; public constructor Create(AFieldDef: TGeneratorFieldDef); virtual; procedure FirstRecord; virtual; procedure NextRecord; virtual; function GetValue(var AFree: Boolean): TValue; virtual; property FieldType: TGeneratorFieldType read FFieldType; property Options: TGeneratorOptions read FOptions; property GeneratorName: string read FGeneratorName; property CustomFormat: string read FCustomFormat; property RecordCount: Integer read GetRecordCount; end; TValueGeneratorDelegate = class public function GetValue(var AFree: Boolean): TValue; virtual; abstract; procedure NextRecord; virtual; abstract; procedure FirstRecord; virtual; abstract; function GetRecordCount: Integer; virtual; end; TValueGeneratorOnGetValue = reference to function(AKey: TValue; var AFreeObject: Boolean): TValue; TValueGeneratorDelegateWithEvents = class(TValueGeneratorDelegate) private FGetValue: TValueGeneratorOnGetValue; // TFunc<TValue, TValue>; public property OnGetValue: TValueGeneratorOnGetValue read FGetValue write FGetValue; end; TInternalTypedListValueGeneratorDelegate = class(TValueGeneratorDelegateWithEvents) strict protected function PRNGenerator(const ARange: Integer; var Seed: Integer): Integer; end; TTypedListValueGeneratorDelegate<T> = class(TInternalTypedListValueGeneratorDelegate) private FValueCounter: Integer; FValuesList: TList<T>; public constructor Create(AOptions: TGeneratorOptions; AValuesList: TArray<T>); destructor Destroy; override; function GetRecordCount: Integer; override; function GetValue(var AFree: Boolean): TValue; override; procedure NextRecord; override; procedure FirstRecord; override; end; TTypedListValueGeneratorDelegate2<T, T1> = class(TTypedListValueGeneratorDelegate<T>) private function ConvertArray(AArray: TArray<T1>): TArray<T>; public constructor Create(AOptions: TGeneratorOptions; AValuesList: TArray<T1>); end; TDelegateValueGenerator = class(TValueGenerator) private FDelegate: TValueGeneratorDelegate; protected function GetRecordCount: Integer; override; function CreateDelegate: TValueGeneratorDelegate; virtual; abstract; public constructor Create(AFieldDef: TGeneratorFieldDef); override; procedure FirstRecord; override; procedure NextRecord; override; function GetValue(var AFree: Boolean): TValue; override; destructor Destroy; override; end; TValueGeneratorClass = class of TValueGenerator; TValueGeneratorDescription = record strict private FClassType: TValueGeneratorClass; FFormatFieldName: string; FUnitName: string; public constructor Create(AClassType: TValueGeneratorClass; const AFormatFieldName: string = ''; const AUnitName: string = ''); property ClassType: TValueGeneratorClass read FClassType; // String used to Format a field name (e.g.; 'StringField%d') property FormatFieldName: string read FFormatFieldName; // Used at design time to add to uses list property UnitName: string read FUnitName; end; TCustomFormatObject = class protected function GetTValue: TValue; virtual; abstract; procedure SetTValue(const AValue: TValue); virtual; abstract; end; TTypedCustomFormatObject<T> = class(TCustomFormatObject) private FValue: T; //constructor Create(const AValue: TValue); overload; constructor Create; overload; function GetValue: T; procedure SetValue(AValue: T); protected function GetTValue: TValue; override; procedure SetTValue(const AValue: TValue); override; public property V: T read GetValue write SetValue; end; TValueReaderFunc<T> = class(TValueReader<T>) private FGetValue: TFunc<string, T>; FName: string; public constructor Create(const AName: string; AGetValue: TFunc<string, T>); function GetValue: T; override; end; // Writer with an anonymous method TValueWriterProc<T> = class(TValueWriter<T>) private FSetValue: TProc<string,T>; FName: string; public constructor Create(const AName: string; ASetValue: TProc<string, T>); procedure SetValue(const AValue: T); override; end; TNameValueGeneratorDescriptionPair = TPair<string, TValueGeneratorDescription>; procedure RegisterValueGenerator(const AName: string; AFieldTypes: TGeneratorFieldTypes; const ADescription: TValueGeneratorDescription; const AFrameWorkExt: string = ''); overload; procedure RegisterValueGenerator(const AName: string; AFieldTypes: TGeneratorFieldTypes; AClass: TValueGeneratorClass; const AFrameworkExt: string = ''); overload; procedure UnRegisterValueGenerator(const AName: string; AFieldTypes: TGeneratorFieldTypes; const AFrameWorkExt: string); function GetRegisteredValueGenerators(AFieldType: TGeneratorFieldType): TArray<string>; function FindRegisteredValueGenerator(const AName: string; AFieldType: TGeneratorFieldType; var ADescription: TValueGeneratorDescription): Boolean; function FindRegisteredValueGenerators(const AName: string; AFieldType: TGeneratorFieldType): TArray<TNameValueGeneratorDescriptionPair>; procedure BindSourceAdapterError(const Message: string; Component: TComponent = nil); const /// <summary>Modes which allow editing</summary> seEditModes = [seEdit, seInsert]; implementation uses System.Math, Data.Bind.Consts, System.Bindings.CustomWrapper, System.Bindings.Factories, System.Bindings.Outputs, System.Bindings.Helper, System.Types, System.Bindings.ObjEval; var // Lookup by framework, then name, then fieldtype GValueGenerators: TDictionary<string, TDictionary<string, TDictionary<TGeneratorFieldType, TValueGeneratorDescription>>>; procedure RegisterValueGenerator(const AName: string; AFieldTypes: TGeneratorFieldTypes; AClass: TValueGeneratorClass; const AFrameWorkExt: string); begin RegisterValueGenerator(AName, AFieldTypes, TValueGeneratorDescription.Create(AClass), AFrameworkExt); end; procedure RegisterValueGenerator(const AName: string; AFieldTypes: TGeneratorFieldTypes; const ADescription: TValueGeneratorDescription; const AFrameWorkExt: string); var LNameDictionary: TDictionary<string, TDictionary<TGeneratorFieldType, TValueGeneratorDescription>>; LFieldTypeDictionary: TDictionary<TGeneratorFieldType, TValueGeneratorDescription>; LFieldType: TGeneratorFieldType; begin if GValueGenerators = nil then GValueGenerators := TObjectDictionary<string, TDictionary<string, TDictionary<TGeneratorFieldType, TValueGeneratorDescription>>>.Create([doOwnsValues]); if not GValueGenerators.TryGetValue(AFrameWorkExt, LNameDictionary) then begin LNameDictionary := TObjectDictionary<string, TDictionary<TGeneratorFieldType, TValueGeneratorDescription>>.Create([doOwnsValues]); GValueGenerators.Add(AFrameWorkExt, LNameDictionary); end; if not LNameDictionary.TryGetValue(AName, LFieldTypeDictionary) then begin LFieldTypeDictionary := TDictionary<TGeneratorFieldType, TValueGeneratorDescription>.Create; LNameDictionary.Add(AName, LFieldTypeDictionary); end; for LFieldType in AFieldTypes do begin if not LFieldTypeDictionary.ContainsKey(LFieldType) then LFieldTypeDictionary.Add(LFieldType, ADescription) else Assert(False); // Duplicates end; end; procedure UnRegisterValueGenerator(const AName: string; AFieldTypes: TGeneratorFieldTypes; const AFrameWorkExt: string); var LNameDictionary: TDictionary<string, TDictionary<TGeneratorFieldType, TValueGeneratorDescription>>; LFieldTypeDictionary: TDictionary<TGeneratorFieldType, TValueGeneratorDescription>; LFieldType: TGeneratorFieldType; begin if GValueGenerators <> nil then if GValueGenerators.TryGetValue(AFrameWorkExt, LNameDictionary) then if LNameDictionary.TryGetValue(AName, LFieldTypeDictionary) then for LFieldType in AFieldTypes do if LFieldTypeDictionary.ContainsKey(LFieldType) then LFieldTypeDictionary.Remove(LFieldType); end; function GetRegisteredValueGenerators(AFieldType: TGeneratorFieldType): TArray<string>; var LList: TList<string>; LFrameworkPair: TPair<string, TDictionary<string, TDictionary<TGeneratorFieldType, TValueGeneratorDescription>>>; LNamePair: TPair<string, TDictionary<TGeneratorFieldType, TValueGeneratorDescription>>; begin LList := TList<string>.Create; try if GValueGenerators <> nil then for LFrameworkPair in GValueGenerators do begin for LNamePair in LFrameworkPair.Value do begin if LNamePair.Value.ContainsKey(AFieldType) then begin // May be duplicates for fmx and vcl frameworks if not LList.Contains(LNamePair.Key) then LList.Add(LNamePair.Key); end; end; end; Result := LList.ToArray; finally LList.Free; end; end; function FindRegisteredValueGenerator(const AName: string; AFieldType: TGeneratorFieldType; var ADescription: TValueGeneratorDescription): Boolean; var LDescriptions: TArray<TPair<string, TValueGeneratorDescription>>; begin Result := False; LDescriptions := FindRegisteredValueGenerators(AName, AFieldType); if Length(LDescriptions) > 0 then begin ADescription := LDescriptions[0].Value; Result := True; end; // if duplicates for multiple frameworks, just pick first found // Data generated by different frameworks must be cross-framework compatible. // However, framework specific generators will be implemented using framework specific rtl. end; function FindRegisteredValueGenerators(const AName: string; AFieldType: TGeneratorFieldType): TArray<TPair<string, TValueGeneratorDescription>>; var LList: TList<TPair<string, TValueGeneratorDescription>>; LFrameworkPair: TPair<string, TDictionary<string, TDictionary<TGeneratorFieldType, TValueGeneratorDescription>>>; LNameDictionary: TDictionary<string, TDictionary<TGeneratorFieldType, TValueGeneratorDescription>>; LFieldTypeDictionary: TDictionary<TGeneratorFieldType, TValueGeneratorDescription>; LDescription: TValueGeneratorDescription; begin LList := TList<TPair<string, TValueGeneratorDescription>>.Create; try if GValueGenerators <> nil then for LFrameworkPair in GValueGenerators do begin LNameDictionary := LFrameworkPair.Value; if LNameDictionary.TryGetValue(AName, LFieldTypeDictionary) then if LFieldTypeDictionary.TryGetValue(AFieldType, LDescription) then LList.Add(TPair<string, TValueGeneratorDescription>.Create(LFrameworkPair.Key, LDescription)); end; Result := LList.ToArray; finally LList.Free; end; end; { TCustomBindScopeStrings } procedure TBaseObjectBindSource.AddActiveChanged(LNotify: TNotifyEvent); begin FActiveChanged.Add(LNotify); end; procedure TBaseObjectBindSource.AddDataSetChanged(LNotify: TNotifyEvent); begin FDataSetChanged.Add(LNotify); end; procedure TBaseObjectBindSource.AddDataSetScrolled(LNotify: TNotifyDistanceEvent); begin FDataSetScrolled.Add(LNotify); end; procedure TBaseObjectBindSource.AddEditingChanged(LNotify: TNotifyEvent); begin FEditingChanged.Add(LNotify); end; type TBindSourceAdapterLinkImpl = class(TBindSourceAdapterLink) private FDeferEvaluate: Boolean; FField: TBindSourceAdapterField; FEditing: Boolean; FBindLink: IBindLink; FBindPosition: IBindPosition; FBindListUpdate: IBindListUpdate; FModified: Boolean; FRefreshNeeded: Boolean; function GetCanModify: Boolean; procedure DoDataChange(AField: TBindSourceAdapterField); function GetField: TBindSourceAdapterField; function GetFieldName: string; procedure UpdateField; procedure SetField(Value: TBindSourceAdapterField); procedure SetEditing(Value: Boolean); protected procedure RecordChanged(Field: TBindSourceAdapterField); override; procedure DataSetChanged; override; procedure DataSetScrolled(ADistance: Integer); override; procedure LayoutChanged; override; procedure ActiveChanged; override; procedure EditingChanged; override; procedure UpdateData; override; function Edit: Boolean; override; public constructor Create(ABindLink: IBindLink); overload; constructor Create(ABindPosition: IBindPosition); overload; constructor Create(ABindListUpdate: IBindListUpdate); overload; procedure SetModified; function GetIsModified: Boolean; procedure Reset; procedure RefreshNeeded; property CanModify: Boolean read GetCanModify; property Editing: Boolean read FEditing; property Field: TBindSourceAdapterField read GetField; end; procedure TBaseObjectBindSource.AddExpression(AExpression: TBasicBindComponent); var LBindLinkDataLink: TBindSourceAdapterLinkImpl; LBindLink: IBindLink; LBindPosition: IBindPosition; begin inherited; if Supports(AExpression, IBindLink, LBindLink) then begin LBindLinkDataLink := TBindSourceAdapterLinkImpl.Create(LBindLink); FAdapterLinks.AddOrSetValue(AExpression, LBindLinkDataLink); LBindLinkDataLink.Adapter := Self.GetInternalAdapter; end else if Supports(AExpression, IBindPosition, LBindPosition) then begin LBindLinkDataLink := TBindSourceAdapterLinkImpl.Create(LBindPosition); FAdapterLinks.AddOrSetValue(AExpression, LBindLinkDataLink); LBindLinkDataLink.Adapter := Self.GetInternalAdapter; end; end; procedure TBaseObjectBindSource.ApplyUpdates; begin if CheckAdapter then GetInternalAdapter.ApplyUpdates; end; constructor TBaseObjectBindSource.Create(AOwner: TComponent); var LDataLink: TBindSourceAdapterLink; begin inherited; FCheckRuntimeAdapter := True; LDataLink := TBindSourceAdapterLink.Create; FDataLink := LDataLink; FAdapterLinks := TObjectDictionary<TBasicBindComponent, TBindSourceAdapterLink>.Create([doOwnsValues]); FActiveChanged := TBindEventList.Create; FDataSetChanged := TBindEventList.Create; FEditingChanged := TBindEventList.Create; FDataSetScrolled := TBindEventList1<Integer>.Create; FAutoActivate := True; FAutoEdit := True; end; function TBaseObjectBindSource.CheckAdapter: Boolean; var LAdapter: TBindSourceAdapter; begin LAdapter := GetInternalAdapter; Result := (LAdapter <> nil) and LAdapter.CanActivate; end; procedure TBaseObjectBindSource.OnAdapterEdit(Sender: TObject; var Allow: Boolean); begin Assert(False); end; procedure TBaseObjectBindSource.OnAdapterEditingChanged( Sender: TObject); begin FEditingChanged.Send(Self); end; procedure TBaseObjectBindSource.OnAdapterDataSetChanged(Sender: TObject); var ALink: TBindSourceAdapterLink; begin FDataSetChanged.Send(Self); for ALink in FAdapterLinks.Values do ALink.DataSetChanged; end; procedure TBaseObjectBindSource.OnAdapterUpdateState(Sender: TObject); var ALink: TBindSourceAdapterLink; begin FActiveChanged.Send(Self); ActivateExpressions(Active); for ALink in FAdapterLinks.Values do ALink.UpdateState; end; procedure TBaseObjectBindSource.OnAdapterLayoutChanged(Sender: TObject); begin Assert(False); end; procedure TBaseObjectBindSource.OnAdapterUpdateRecord(Sender: TObject); var ALink: TBindSourceAdapterLink; begin for ALink in FAdapterLinks.Values do ALink.UpdateRecord; end; procedure TBaseObjectBindSource.OnAdapterDataSetScrolled(Sender: TObject; ADistance: Integer); var ALink: TBindSourceAdapterLink; begin FDataSetScrolled.Send(Self,ADistance); for ALink in FAdapterLinks.Values do ALink.DataSetScrolled(ADistance); end; procedure TBaseObjectBindSource.OnAdapterRecordChanged(Sender: TObject; AField: TBindSourceAdapterField); var ALink: TBindSourceAdapterLink; begin for ALink in FAdapterLinks.Values do ALink.RecordChanged(AField); end; procedure TBaseObjectBindSource.Delete; begin if CheckAdapter then GetInternalAdapter.Delete; end; destructor TBaseObjectBindSource.Destroy; begin FDataLink.Free; // Free and clear in case we are called back during destruction FreeAndNil(FAdapterLinks); FreeAndNil(FActiveChanged); FreeAndNil(FDataSetChanged); FreeAndNil(FEditingChanged); FreeAndNil(FDataSetScrolled); FreeAndNil(FRuntimeAdapter); inherited; end; procedure TBaseObjectBindSource.DoCreateAdapter( var ADataObject: TBindSourceAdapter); begin ADataObject := nil; if Assigned(FOnCreateAdapter) then FOnCreateAdapter(Self, ADataObject) end; procedure TBaseObjectBindSource.DoMemberRenamed(const CurName, PrevName: string); var LBindComponent: TBasicBindComponent; LBindMemberChange: IBindMemberChange; begin for LBindComponent in Expressions do if Supports(LBindComponent, IBindMemberChange, LBindMemberChange) then begin LBindMemberChange.MemberRenamed(Self, CurName, PrevName); end; end; procedure TBaseObjectBindSource.ConnectAdapter(AAdapter: TBindSourceAdapter); var LCollectionEditorLink: TBindSourceAdapterLink; begin Assert(AAdapter <> nil); if FConnectedAdapter = AAdapter then Exit; Assert(FConnectedAdapter = nil); if csDestroying in AAdapter.ComponentState then Exit; if csDestroying in ComponentState then Exit; if csLoading in ComponentState then Exit; if not AAdapter.HasScope(Self) then begin FConnectedAdapter := AAdapter; AAdapter.AddScope(Self); for LCollectionEditorLink in FAdapterLinks.Values do LCollectionEditorLink.Adapter := AAdapter; if AutoActivate then if (csDesigning in ComponentState) then if AAdapter.CanActivate then Active := True; end; end; procedure TBaseObjectBindSource.DisconnectAdapter(AAdapter: TBindSourceAdapter); var LCollectionEditorLink: TBindSourceAdapterLink; begin Assert(AAdapter <> nil); Assert((csDestroying in Self.ComponentState) or (csDestroying in AAdapter.ComponentState) or AAdapter.HasScope(Self)); if Active then begin FConnectedAdapter := nil; OnAdapterUpdateState(Self); end else FConnectedAdapter := nil; Assert(Active = False); if (not (csDestroying in ComponentState)) and (not (csDestroying in AAdapter.ComponentState)) then // Already removed AAdapter.RemoveScope(Self); for LCollectionEditorLink in FAdapterLinks.Values do if LCollectionEditorLink.Adapter = AAdapter then LCollectionEditorLink.Adapter := nil; end; procedure TBaseObjectBindSource.DoMemberRenaming(const CurName, NewName: string); var LBindComponent: TBasicBindComponent; LBindMemberChange: IBindMemberChange; begin for LBindComponent in Expressions do if Supports(LBindComponent, IBindMemberChange, LBindMemberChange) then begin LBindMemberChange.MemberRenaming(Self, CurName, NewName); end; end; procedure TBaseObjectBindSource.Edit; begin if CheckAdapter then GetInternalAdapter.Edit(True); // Force end; function TBaseObjectBindSource.Edit(ABindComp: TBasicBindComponent): Boolean; var LDataLink: TBindSourceAdapterLink; begin if FAdapterLinks.TryGetValue(ABindComp, LDataLink) then begin Assert(LDataLink <> nil); Result := LDataLink.Edit end else Result := False; end; procedure TBaseObjectBindSource.First; begin if CheckAdapter then GetInternalAdapter.First; end; procedure TBaseObjectBindSource.UpdateRecord(ABindComp: TBasicBindComponent); var LDataLink: TBindSourceAdapterLink; begin if FAdapterLinks.TryGetValue(ABindComp, LDataLink) then begin Assert(LDataLink <> nil); LDataLink.UpdateRecord; end end; procedure TBaseObjectBindSource.Reset(ABindComp: TBasicBindComponent); var LDataLink: TBindSourceAdapterLink; begin if FAdapterLinks.TryGetValue(ABindComp, LDataLink) then begin Assert(LDataLink <> nil); if LDataLink is TBindSourceAdapterLinkImpl then TBindSourceAdapterLinkImpl(LDataLink).Reset end end; procedure TBaseObjectBindSource.SetActive(const Value: Boolean); begin if csLoading in ComponentState then FDeferActivate := Value else if Value <> Active then begin if Value then begin if CheckAdapter then GetInternalAdapter.Active := True; end else if GetInternalAdapter <> nil then GetInternalAdapter.Active := False; OnAdapterUpdateState(Self); if not Active then if not (csDestroying in ComponentState) then FCheckRuntimeAdapter := True; // Recheck later end; end; procedure TBaseObjectBindSource.UpdateAdapterChanged; begin end; procedure TBaseObjectBindSource.UpdateAdapterChanging; begin end; procedure TBaseObjectBindSource.SetAutoActivate(const Value: Boolean); begin if FAutoActivate <> Value then begin FAutoActivate := Value; if not (csLoading in ComponentState) then if (csDesigning in ComponentState) then // While designing, active when enable Active := FAutoActivate; end; end; procedure TBaseObjectBindSource.SetField(ABindComp: TBasicBindComponent; const FieldName: string); begin // end; procedure TBaseObjectBindSource.SetItemIndex(const Value: Integer); begin if CheckAdapter then GetInternalAdapter.ItemIndex := Value; end; procedure TBaseObjectBindSource.SetModified(ABindComp: TBasicBindComponent); var LDataLink: TBindSourceAdapterLink; begin if FAdapterLinks.TryGetValue(ABindComp, LDataLink) then begin Assert(LDataLink <> nil); if LDataLink is TBindSourceAdapterLinkImpl then TBindSourceAdapterLinkImpl(LDataLink).SetModified end end; procedure TBaseObjectBindSource.SetReadOnly(ABindComp: TBasicBindComponent; const Value: Boolean); var LDataLink: TBindSourceAdapterLink; begin if FAdapterLinks.TryGetValue(ABindComp, LDataLink) then begin Assert(LDataLink <> nil); if LDataLink is TBindSourceAdapterLinkImpl then TBindSourceAdapterLinkImpl(LDataLink).FReadOnly := Value; end end; function TBaseObjectBindSource.GetIsModified(ABindComp: TBasicBindComponent): Boolean; var LDataLink: TBindSourceAdapterLink; begin Result := False; if FAdapterLinks.TryGetValue(ABindComp, LDataLink) then begin Assert(LDataLink <> nil); if LDataLink is TBindSourceAdapterLinkImpl then Result := TBindSourceAdapterLinkImpl(LDataLink).GetIsModified end end; function TBaseObjectBindSource.GetIsEditing(ABindComp: TBasicBindComponent): Boolean; var LDataLink: TBindSourceAdapterLink; begin Result := False; if FAdapterLinks.TryGetValue(ABindComp, LDataLink) then begin Assert(LDataLink <> nil); if LDataLink is TBindSourceAdapterLinkImpl then Result := TBindSourceAdapterLinkImpl(LDataLink).Editing; end end; function TBaseObjectBindSource.GetCanApplyUpdates: Boolean; begin if CheckAdapter then Result := GetInternalAdapter.CanApplyUpdates else Result := False; end; function TBaseObjectBindSource.GetCanCancelUpdates: Boolean; begin if CheckAdapter then Result := GetInternalAdapter.CanCancelUpdates else Result := False; end; procedure TBaseObjectBindSource.Cancel; begin if CheckAdapter then GetInternalAdapter.Cancel; end; procedure TBaseObjectBindSource.CancelUpdates; begin if CheckAdapter then GetInternalAdapter.CancelUpdates; end; procedure TBaseObjectBindSource.ClearModified(ABindComp: TBasicBindComponent); var LDataLink: TBindSourceAdapterLink; begin if (FAdapterLinks <> nil) and FAdapterLinks.TryGetValue(ABindComp, LDataLink) then begin Assert(LDataLink <> nil); if LDataLink is TBindSourceAdapterLinkImpl then TBindSourceAdapterLinkImpl(LDataLink).FModified := False; end end; function TBaseObjectBindSource.GetCanModify(ABindComp: TBasicBindComponent): Boolean; var LDataLink: TBindSourceAdapterLink; begin Result := False; if FAdapterLinks.TryGetValue(ABindComp, LDataLink) then begin Assert(LDataLink <> nil); if LDataLink is TBindSourceAdapterLinkImpl then Result := TBindSourceAdapterLinkImpl(LDataLink).CanModify end end; function TBaseObjectBindSource.GetActive: Boolean; begin Result := (FConnectedAdapter <> nil) and (FConnectedAdapter.Active) end; function TBaseObjectBindSource.GetInternalAdapter: TBindSourceAdapter; begin Result := nil; end; procedure TBaseObjectBindSource.SetRuntimeAdapter(AAdapter: TBindSourceAdapter); begin SetInternalAdapter(AAdapter, procedure(AScope: TBindSourceAdapter) begin if FRuntimeAdapter <> nil then begin if not (csDestroying in FRuntimeAdapter.ComponentState) then FreeAndNil(FRuntimeAdapter); if (AAdapter = nil) and not (csDestroying in ComponentState) then // Recheck FCheckRuntimeAdapter := True; end; FRuntimeAdapter := AAdapter; if FRuntimeAdapter <> nil then begin FRuntimeAdapter.FreeNotification(Self); end; end); end; function TBaseObjectBindSource.CheckRuntimeAdapter: Boolean; var LAdapter: TBindSourceAdapter; begin if FCheckRuntimeAdapter and (FRuntimeAdapter = nil) and not (csDestroying in ComponentState) then begin FCheckRuntimeAdapter := False; Self.DoCreateAdapter(LAdapter); if LAdapter <> nil then SetRuntimeAdapter(LAdapter); end; Result := FRuntimeAdapter <> nil; end; function TBaseObjectBindSource.GetBOF: Boolean; begin if CheckAdapter then Result := GetInternalAdapter.BOF else Result := False; end; function TBaseObjectBindSource.GetCanModify: Boolean; begin if CheckAdapter then Result := GetInternalAdapter.CanModify else Result := False; end; function TBaseObjectBindSource.GetCanDelete: Boolean; begin if CheckAdapter then Result := GetInternalAdapter.CanDelete else Result := False; end; function TBaseObjectBindSource.GetCanInsert: Boolean; begin if CheckAdapter then Result := GetInternalAdapter.CanInsert else Result := False; end; function TBaseObjectBindSource.GetCanRefresh: Boolean; begin if CheckAdapter then Result := GetInternalAdapter.CanRefresh else Result := False; end; function TBaseObjectBindSource.GetCurrentRecord(const AMemberName: string): IScope; begin if AMemberName <> '' then Result := GetMemberScope(AMemberName) else Result := GetScope; end; function TBaseObjectBindSource.GetEditing: Boolean; begin if CheckAdapter then Result := GetInternalAdapter.State in seEditModes else Result := False end; function TBaseObjectBindSource.GetEnumerator( const AMemberName: string; ABufferCount: Integer): IScopeRecordEnumerator; begin if not CheckAdapter then Result := nil; Result := GetInternalAdapter.GetEnumerator(AMemberName, function: IScope begin Result := GetScope; end, function(AMemberName: string): IScope begin Result := GetMemberScope(AMemberName); end); end; function TBaseObjectBindSource.GetEOF: Boolean; begin if CheckAdapter then Result := GetInternalAdapter.Eof else Result := True; end; function TBaseObjectBindSource.GetSelected: Boolean; begin if CheckAdapter then Result := GetInternalAdapter.ItemIndex <> -1 else Result := True; end; function TBaseObjectBindSource.GetItemIndex: Integer; begin if CheckAdapter then Result := GetInternalAdapter.ItemIndex else Result := -1; end; procedure TBaseObjectBindSource.GetLookupMemberNames(AList: TStrings); begin if CheckAdapter then GetInternalAdapter.GetLookupMemberNames(AList); end; function TBaseObjectBindSource.GetMember(const AMemberName: string): TObject; begin if CheckAdapter then Result := GetInternalAdapter.GetMember(AMemberName) else raise TBindCompException.Create(sNoBindSourceAdapter); end; function TBaseObjectBindSource.GetMemberGetter(const AMemberName: string; var AGetter: string): Boolean; begin Result := False; if CheckAdapter then Result := GetInternalAdapter.GetMemberGetter(AMemberName, AGetter) else if (csDesigning in ComponentState) then begin AGetter := 'Value'; // do not localize Result := True; end; end; procedure TBaseObjectBindSource.GetMemberNames(AList: TStrings); begin if CheckAdapter then GetInternalAdapter.GetMemberNames(AList) end; function TBaseObjectBindSource.GetMemberSetter(const AMemberName: string; var ASetter: string): Boolean; begin Result := False; if CheckAdapter then Result := GetInternalAdapter.GetMemberSetter(AMemberName, ASetter) else begin if (csDesigning in ComponentState) then begin ASetter := 'Value'; // do not localize Result := True; end; end; end; function TBaseObjectBindSource.GetMemberType(const AMemberName: string; var AType: TScopeMemberType): Boolean; begin AType := mtUnknown; Result := False; if CheckAdapter then Result := GetInternalAdapter.GetMemberType(AMemberName, AType) else begin if (csDesigning in ComponentState) then begin AType := mtText; Result := True; end; end; end; function TBaseObjectBindSource.GetPositionGetter( var AGetter: string; var ABase: Integer): Boolean; begin AGetter := 'ItemIndex'; // Do not localize ABase := 0; Exit(True); end; function TBaseObjectBindSource.GetPositionSetter( var ASetter: string; var ABase: Integer): Boolean; begin ASetter := 'ItemIndex'; // Do not localize ABase := 0; Exit(True); end; procedure TBaseObjectBindSource.GetRecord(ARow: Integer; const AMemberName: string; ACallback: TProc<IScope>); begin GetRowMember(ARow, AMemberName, procedure(AObject: TObject) begin if AObject = nil then ACallback(nil) else ACallback(WrapObject(AObject)); end); end; procedure TBaseObjectBindSource.GetRowMember(ARow: Integer; const AMemberName: string; ACallback: TProc<TObject>); var LObject: TObject; LBindSourceAdapter: TBindSourceAdapter; LItemIndexOffset: Integer; begin if CheckAdapter then begin LBindSourceAdapter := GetInternalAdapter; if AMemberName <> '' then LObject := LBindSourceAdapter.GetMember(AMemberName) else LObject := nil; LItemIndexOffset := LBindSourceAdapter.ItemIndexOffset; LBindSourceAdapter.ItemIndexOffset := ARow - LBindSourceAdapter.ItemIndex; try ACallBack(LObject); finally LBindSourceAdapter.ItemIndexOffset := LItemIndexOffset; end; end; end; function TBaseObjectBindSource.GetRuntimeAdapter: TBindSourceAdapter; begin Result := FRuntimeAdapter; end; function TBaseObjectBindSource.GetValue: TObject; begin if CheckAdapter then Result := GetInternalAdapter.GetValue else raise TBindCompException.Create(sNoBindSourceAdapter); end; procedure TBaseObjectBindSource.Loaded; begin try inherited; if FDeferActivate or FAutoActivate then Active := True; except // Do not raise exception while loading end; end; function TBaseObjectBindSource.Lookup(const KeyFields: string; const KeyValues: TValue; const ResultFields: string): TValue; begin if CheckAdapter then Result := AdapterLookup(KeyFields, KeyValues, ResultFields); end; function TBaseObjectBindSource.Locate(const KeyFields: string; const KeyValues: TValue): Boolean; begin Result := False; if CheckAdapter then Result := AdapterLocate(KeyFields, KeyValues); end; function TBaseObjectBindSource.AdapterLocate(const KeyFields: string; const KeyValues: TValue): Boolean; var LEnumerator: IScopeRecordEnumerator; LIndex: Integer; begin Result := False; LIndex := -1; LEnumerator := GetEnumerator('', -1); // Need auto buffer count if LEnumerator = nil then Exit; LEnumerator.First; Result := AdapterFindValues(LEnumerator, KeyFields, KeyValues, procedure(AIndex: Integer; AValue: TValue) begin LIndex := AIndex; end); LEnumerator := nil; if Result then begin Assert(LIndex >= 0); Assert(LIndex < GetInternalAdapter.GetCount); GetInternalAdapter.ItemIndex := LIndex; end; end; function TBaseObjectBindSource.AdapterLookup(const KeyFields: string; const KeyValues: TValue; const ResultFields: string): TValue; var LEnumerator: IScopeRecordEnumerator; LValueMemberName: string; LResult: TValue; LValueExpression: TBindingExpression; LIValueValue: IValue; LValueScope: IScope; begin LResult := TValue.Empty; if not GetMemberGetter(ResultFields, LValueMemberName) then Exit; LEnumerator := GetEnumerator('', -1); // Need auto buffer count if LEnumerator = nil then Exit; LEnumerator.First; AdapterFindValues(LEnumerator, KeyFields, KeyValues, procedure(AIndex: Integer; AValue: TValue) begin LValueScope := LEnumerator.GetMemberCurrent(ResultFields); LValueExpression := TBindings.CreateExpression( LValueScope, LValueMemberName, TBindingEventRec.Create(TBindingEvalErrorEvent(nil) (*DoOnEvalError*))); try LIValueValue := LValueExpression.Evaluate; LResult := LIValueValue.GetValue; finally LValueExpression.Free; end; end); LEnumerator := nil; Result := LResult; end; function TBaseObjectBindSource.AdapterFindValues(LEnumerator: IScopeRecordEnumerator; const KeyFields: string; const KeyValues: TValue; AProc: TProc<Integer, TValue>): Boolean; function SameValue(const AValue1, AValue2: TValue): Boolean; begin Result := False; try if AValue1.IsEmpty or AValue2.IsEmpty then Result := AValue1.IsEmpty and AValue2.IsEmpty else if (AValue1.TypeInfo.Kind = tkInteger) and (AValue2.TypeInfo.Kind = tkInteger) then begin if AValue1.IsType<uint64> or AValue2.IsType<uint64> then Result := AValue1.AsType<uint64> = AValue2.AsType<uint64> else Result := AValue1.AsType<int64> = AValue2.AsType<int64>; end else Result := AValue1.ToString = AValue2.ToString except end; end; var LKeyMemberName: string; LKeyExpression: TBindingExpression; LIKeyValue: IValue; LKeyScope: IScope; LIndex: Integer; LKeyValue: TValue; begin Result := False; if LEnumerator = nil then Exit; if not GetMemberGetter(KeyFields, LKeyMemberName) then Exit; LKeyScope := LEnumerator.GetMemberCurrent(KeyFields); LKeyExpression := TBindings.CreateExpression( LKeyScope, LKeyMemberName, TBindingEventRec.Create(TBindingEvalErrorEvent(nil) (*DoOnEvalError*))); try LIndex := 0; while LEnumerator.MoveNext do begin LIKeyValue := LKeyExpression.Evaluate; LKeyValue := LIKeyValue.GetValue; if SameValue(LKeyValue, KeyValues) then begin Result := True; AProc(LIndex, LKeyValue); break; end; Inc(LIndex); end; finally LKeyExpression.Free; end; end; procedure TBaseObjectBindSource.Insert; begin if CheckAdapter then GetInternalAdapter.Insert; end; function TBaseObjectBindSource.IsRequired(const AFieldName: string): Boolean; begin Result := True; // null scaler types not supported end; function TBaseObjectBindSource.IsValidChar(const AFieldName: string; const AChar: Char): Boolean; begin Result := False; if CheckAdapter then Result := GetInternalAdapter.IsValidChar(AFieldName, AChar); end; procedure TBaseObjectBindSource.Last; begin if CheckAdapter then GetInternalAdapter.Last; end; procedure TBaseObjectBindSource.Next; begin if CheckAdapter then GetInternalAdapter.Next; end; procedure TBaseObjectBindSource.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = TOperation.opRemove then begin if AComponent = FRuntimeAdapter then SetRuntimeAdapter(nil); if AComponent = FConnectedAdapter then FConnectedAdapter := nil; if AComponent is TBasicBindComponent then if FAdapterLinks.ContainsKey(TBasicBindComponent(AComponent)) then FAdapterLinks.Remove(TBasicBindComponent(AComponent)); end; end; procedure TBaseObjectBindSource.PosChanging(ABindComp: TBasicBindComponent); begin if CheckAdapter then GetInternalAdapter.PosChanging; end; procedure TBaseObjectBindSource.Post; begin if CheckAdapter then GetInternalAdapter.Post; end; procedure TBaseObjectBindSource.Prior; begin if CheckAdapter then GetInternalAdapter.Prior; end; procedure TBaseObjectBindSource.Refresh; begin if CheckAdapter then GetInternalAdapter.Refresh; end; procedure TBaseObjectBindSource.RemoveActiveChanged(LNotify: TNotifyEvent); begin if Assigned(FActiveChanged) then FActiveChanged.Remove(LNotify); end; procedure TBaseObjectBindSource.RemoveDataSetChanged(LNotify: TNotifyEvent); begin if Assigned(FDataSetChanged) then FDataSetChanged.Remove(LNotify); end; procedure TBaseObjectBindSource.RemoveDataSetScrolled(LNotify: TNotifyDistanceEvent); begin if Assigned(FDataSetScrolled) then FDataSetScrolled.Remove(LNotify); end; procedure TBaseObjectBindSource.RemoveEditingChanged(LNotify: TNotifyEvent); begin if Assigned(FEditingChanged) then FEditingChanged.Remove(LNotify); end; procedure TBaseObjectBindSource.RemoveExpression(AExpression: TBasicBindComponent); begin inherited; if not (csDestroying in ComponentState) then if Assigned(FAdapterLinks) then FAdapterLinks.Remove(AExpression); end; procedure TBaseObjectBindSource.SetInternalAdapter(const Value: TBindSourceAdapter; AAssignProc: TProc<TBindSourceAdapter>); begin Assert(Assigned(AAssignProc)); if InternalAdapter <> Value then begin if FConnectedAdapter <> nil then begin DisconnectAdapter(FConnectedAdapter) end; try UpdateAdapterChanging; finally AAssignProc(Value); end; UpdateAdapterChanged; end; end; { TCustomAdapterBindSource } destructor TCustomAdapterBindSource.Destroy; begin Adapter := nil; inherited; end; function TCustomAdapterBindSource.GetInternalAdapter: TBindSourceAdapter; begin if CheckRuntimeAdapter then Result := GetRuntimeAdapter else Result := FAdapter; if Result <> nil then ConnectAdapter(Result); end; procedure TCustomAdapterBindSource.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = TOperation.opRemove then begin if AComponent = FAdapter then begin if GetInternalAdapter = FAdapter then SetAdapter(nil) else FAdapter := nil; end; end; end; procedure TCustomAdapterBindSource.SetAdapter(Value: TBindSourceAdapter); begin if Value <> nil then Value.RemoveFreeNotification(Self); SetInternalAdapter(Value, procedure(AScope: TBindSourceAdapter) begin FAdapter := Value; if FAdapter <> nil then FAdapter.FreeNotification(Self); if InternalAdapter <> nil then begin ConnectAdapter(InternalAdapter); end; end); end; { TCustomPrototypeBindSource } function TCustomPrototypeBindSource.GetAutoEdit: Boolean; begin Result := FDataGenerator.AutoEdit; end; function TCustomPrototypeBindSource.GetAutoPost: Boolean; begin Result := FDataGenerator.AutoPost; end; function TCustomPrototypeBindSource.GetFieldDefs: TGeneratorFieldDefs; begin Result := FDataGenerator.FieldDefs; end; function TCustomPrototypeBindSource.GetInternalAdapter: TBindSourceAdapter; begin if CheckRuntimeAdapter then Result := GetRuntimeAdapter else if FAdapter <> nil then Result := FAdapter else Result := FDataGenerator; if (Result <> nil) and (not (csDestroying in Result.ComponentState)) then begin ConnectAdapter(Result); end; end; function TCustomPrototypeBindSource.GetRecordCount: Integer; begin Result := FDataGenerator.RecordCount; end; procedure TCustomPrototypeBindSource.SetAutoEdit(const Value: Boolean); begin FDataGenerator.AutoEdit := Value; end; procedure TCustomPrototypeBindSource.SetAutoPost(const Value: Boolean); begin FDataGenerator.AutoPost := Value; end; procedure TCustomPrototypeBindSource.SetFieldDefs( const Value: TGeneratorFieldDefs); begin FDataGenerator.FieldDefs := Value; end; procedure TCustomPrototypeBindSource.SetRecordCount(const Value: Integer); begin FDataGenerator.RecordCount := Value; end; constructor TCustomPrototypeBindSource.Create(AOwner: TComponent); begin inherited; FAutoEdit := True; FDataGenerator := TCustomDataGeneratorAdapter.Create(Self); // No free needed, Owned by Self end; { TBindSourceAdapter } procedure TBindSourceAdapter.Cancel; var LField: TBindSourceAdapterField; LLink: TBindSourceAdapterLink; begin case State of seEdit, seInsert: begin DoBeforeCancel; for LLink in FLinks do if LLink is TBindSourceAdapterLinkImpl then TBindSourceAdapterLinkImpl(LLink).FDeferEvaluate := True; try for LField in FFields do begin LField.Cancel; end; finally for LLink in FLinks do if LLink is TBindSourceAdapterLinkImpl then TBindSourceAdapterLinkImpl(LLink).FDeferEvaluate := False; end; SetState(seBrowse); DataSetChanged; DoAfterCancel; end; end; end; procedure TBindSourceAdapter.Refresh; var LLink: TBindSourceAdapterLink; begin CheckBrowseMode; DoBeforeRefresh; ResetNeeded; // Refresh grids for LLink in FLinks do if LLink is TBindSourceAdapterLinkImpl then TBindSourceAdapterLinkImpl(LLink).FDeferEvaluate := True; try InternalRefresh; finally for LLink in FLinks do if LLink is TBindSourceAdapterLinkImpl then TBindSourceAdapterLinkImpl(LLink).FDeferEvaluate := False; end; DataSetChanged; DoAfterRefresh; end; procedure TBindSourceAdapter.CancelUpdates; begin CheckBrowseMode; DoBeforeCancelUpdates; CheckOperation(InternalCancelUpdates, FOnCancelUpdatesError); DataSetChanged; DoAfterCancelUpdates; end; procedure TBindSourceAdapter.ClearFields; begin FFields.Clear; end; constructor TBindSourceAdapter.Create(AOwner: TComponent); begin inherited; FAutoEdit := True; FScopes := TList<TBaseObjectBindSource>.Create; FFields := TObjectList<TBindSourceAdapterField>.Create; // Owned FLinks := TObjectList<TBindSourceAdapterLink>.Create(False); // not Owned FItemIndex := 0; FItemIndexOffset := 0; end; procedure TBindSourceAdapter.Delete; var LItemIndex: Integer; LDeleted: Boolean; begin if ItemIndex <> -1 then begin DoBeforeDelete; LItemIndex := ItemIndex; CheckOperation( procedure begin LDeleted := Self.DeleteAt(ItemIndex) end, FOnDeleteError); if LDeleted then begin if LItemIndex >= Self.GetCount then begin LItemIndex := Self.GetCount - 1; ItemIndex := Max(0, LItemIndex); end; DataSetChanged; end; DoAfterDelete; end; end; function TBindSourceAdapter.DeleteAt(AIndex: Integer): Boolean; begin Assert(False); Result := False; end; destructor TBindSourceAdapter.Destroy; begin FFields.Free; FLinks.Free; FScopes.Free; inherited; end; procedure BindSourceAdapterError(const Message: string; Component: TComponent = nil); begin if Assigned(Component) and (Component.Name <> '') then begin if (csSubComponent in Component.ComponentStyle) and (Component.Owner <> nil) and (Component.Owner.Name <> '') then raise EBindCompError.Create(Format('%s.%s: %s', [Component.Owner.Name, Component.Name, Message])) else raise EBindCompError.Create(Format('%s: %s', [Component.Name, Message])) end else raise EBindCompError.Create(Message); end; procedure TBindSourceAdapter.CheckCanModify; begin if not CanModify then BindSourceAdapterError(SDataSourceReadOnly, Self); end; procedure TBindSourceAdapter.CheckActive; begin if State = seInactive then BindSourceAdapterError(SDataSourceClosed, Self); end; procedure TBindSourceAdapter.CheckBrowseMode; begin CheckActive; case State of seEdit, seInsert: begin UpdateRecord; if Modified then Post else Cancel; end; end; end; procedure TBindSourceAdapter.Edit(AForce: Boolean); begin if (ItemIndex >= 0) and ((AForce or AutoEdit) and not(State in [seEdit, seInsert])) then // and not Inserting then begin if GetCount = 0 then Insert else begin CheckBrowseMode; CheckCanModify; DoBeforeEdit; CheckOperation(InternalEdit, FOnEditError); SetState(seEdit); DoAfterEdit; end; end; end; procedure TBindSourceAdapter.InternalApplyUpdates; begin end; procedure TBindSourceAdapter.InternalCancelUpdates; begin end; procedure TBindSourceAdapter.InternalEdit; begin end; procedure TBindSourceAdapter.InternalRefresh; begin end; procedure TBindSourceAdapter.AddScope(Value: TBaseObjectBindSource); begin FScopes.Add(Value); end; procedure TBindSourceAdapter.RemoveScope(Value: TBaseObjectBindSource); begin FScopes.Remove(Value); end; procedure TBindSourceAdapter.ResetNeeded; var LLink: TBindSourceAdapterLink; begin for LLink in FLinks do if LLink is TBindSourceAdapterLinkImpl then TBindSourceAdapterLinkImpl(LLink).RefreshNeeded; end; function TBindSourceAdapter.HasScope(Value: TBaseObjectBindSource): Boolean; begin Result := FScopes.Contains(Value); end; procedure TBindSourceAdapter.SetState(Value: TBindSourceAdapterState); var LScope: TBaseObjectBindSource; begin if FState <> Value then begin FState := Value; FModified := False; for LScope in FScopes do begin LScope.OnAdapterUpdateState(Self); end; end; end; function TBindSourceAdapter.SupportsNestedFields: Boolean; begin Result := False; end; procedure TBindSourceAdapter.First; var LNewIndex: Integer; begin LNewIndex := GetItemIndex; if GetCount >= 1 then LNewIndex := 0; if GetItemIndex <> LNewIndex then begin ItemIndex := LNewIndex; end; end; function TBindSourceAdapter.GetBOF: Boolean; begin Result := ItemIndex <= 0; end; function TBindSourceAdapter.GetCanModify: Boolean; begin Result := False; end; function TBindSourceAdapter.GetCanRefresh: Boolean; begin Result := True; end; function TBindSourceAdapter.GetCanInsert: Boolean; begin Result := False; end; function TBindSourceAdapter.GetCanActivate: Boolean; begin Result := True; end; function TBindSourceAdapter.GetCanApplyUpdates: Boolean; begin Result := False; end; function TBindSourceAdapter.GetCanCancelUpdates: Boolean; begin Result := False; end; function TBindSourceAdapter.GetCanDelete: Boolean; begin Result := False; end; function TBindSourceAdapter.GetCount: Integer; begin Assert(False); // Should be implemented by descendent Result := 1; end; function TBindSourceAdapter.GetItemIndex: Integer; begin Result := FItemIndex; end; procedure TBindSourceAdapter.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = TOperation.opRemove then begin if AComponent is TBaseObjectBindSource then if FScopes.Contains(TBaseObjectBindSource(AComponent)) then FScopes.Remove(TBaseObjectBindSource(AComponent)); end; end; procedure TBindSourceAdapter.AutoEditField(AField: TBindSourceAdapterField); begin Edit(True); end; procedure TBindSourceAdapter.AutoPostField(AField: TBindSourceAdapterField); begin Inc(FUpdatingRecords); try PostFields(TArray<TBindSourceAdapterField>.Create(AField)); finally Dec(FUpdatingRecords); end; end; procedure TBindSourceAdapter.PostFields(AFields: TArray<TBindSourceAdapterField>); var LBuffered: Boolean; LField: TBindSourceAdapterField; begin UpdateRecord; case State of seEdit, seInsert: begin DoBeforePostFields(AFields); CheckOperation( procedure var LField: TBindSourceAdapterField; begin for LField in AFields do begin LField.Post; end; end, FOnPostError); // FOnPostFieldError); LBuffered := False; for LField in Fields do if LField.IsBuffered then begin LBuffered := True; break; end; if not LBuffered then begin // Not pending changes SetState(seBrowse); DataSetChanged; end else if Length(AFields) = 1 then RecordChanged(AFields[0]) else RecordChanged(nil); DoAfterPostFields(AFields); end; end; end; function TBindSourceAdapter.GetItemIndexOffset: Integer; begin Result := FItemIndexOffset; end; function TBindSourceAdapter.GetCurrent: TObject; begin Result := Self; end; function TBindSourceAdapter.GetCurrentIndex: Integer; begin Result := ItemIndex + ItemIndexOffset; end; function TBindSourceAdapter.GetCurrentRecord(const AMemberName: string): IScope; begin Assert(False); Result := nil; end; type TBindSourceAdapterEnumerator = class(TInterfacedObject, IScopeRecordEnumerator, IScopeRecordEnumeratorCount, IScopeRecordEnumeratorStatus, IScopeRecordEnumeratorEvalShortcut) private FBindSourceAdapter: TBindSourceAdapter; FMemberName: string; FNextRecord: Integer; FGetScope: TFunc<IScope>; FGetMemberScope: TFunc<string, IScope>; FMultiRecordChange: Boolean; { IScopeRecordEnumeratorEvalShortcut } procedure GetMemberValue(const AMemberName: string; const AType: TScopeMemberType; const ACallback: TValueCallback); overload; function GetMemberValue(const AMemberName: string; const ATypes: array of TScopeMemberType; out AValue: TValue): Boolean; overload; function CanGetMemberValue(const AMemberName: string; AType: TScopeMemberType): Boolean; // function GetSupportedTypes(AType: TScopeMemberType): TScopeMemberTypes; public constructor Create(ABindScope: TBindSourceAdapter; const AMemberName: string; AGetScope: TFunc<IScope>; AGetMemberScope: TFunc<string, IScope>); destructor Destroy; override; procedure First; function GetCurrent: IScope; function GetRecordCount: Integer; function GetMemberCurrent(const AMemberName: string): IScope; function GetMultiRecordChange: Boolean; function MoveNext: Boolean; property Current: IScope read GetCurrent; end; constructor TBindSourceAdapterEnumerator.Create(ABindScope: TBindSourceAdapter; const AMemberName: string; AGetScope: TFunc<IScope>; AGetMemberScope: TFunc<string, IScope>); begin Assert(ABindScope <> nil); FBindSourceAdapter := ABindScope; FMemberName := AMemberName; Assert(FBindSourceAdapter.ItemIndexOffset = 0); // FNextRecord := FBindSourceAdapter.ItemIndex; FBindSourceAdapter.ItemIndexOffset := FNextRecord - FBindSourceAdapter.ItemIndex; FGetScope := AGetScope; FGetMemberScope := AGetMemberScope; end; destructor TBindSourceAdapterEnumerator.Destroy; begin FBindSourceAdapter.ItemIndexOffset := 0; inherited; end; procedure TBindSourceAdapterEnumerator.First; begin FNextRecord := 0; FBindSourceAdapter.ItemIndexOffset := FNextRecord - FBindSourceAdapter.ItemIndex; end; function TBindSourceAdapterEnumerator.GetCurrent: IScope; begin if FMemberName <> '' then Result := FGetMemberScope(FMemberName) else Result := FGetScope; end; function TBindSourceAdapterEnumerator.GetMemberCurrent(const AMemberName: string): IScope; begin if AMemberName <> '' then Result := FGetMemberScope(AMemberName) else Result := GetCurrent; end; type TConvertFunc = function(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; function ConvNone(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin AResult := ASource; Result := True; end; function ConvFail(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin Result := False; end; function ConvToText(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin AResult := ASource.ToString; Result := True; end; function ConvTextToInteger(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin case AType of mtInteger: TConverterUtils.StringToInteger(ASource, TypeInfo(Int64), AResult); mtUInteger: TConverterUtils.StringToInteger(ASource, TypeInfo(UInt64), AResult); else Assert(False); end; Result := True; end; function ConvTextToFloat(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin case AType of mtFloat: TConverterUtils.StringToFloat(ASource, TypeInfo(Extended), AResult); mtCurrency: TConverterUtils.StringToFloat(ASource, TypeInfo(Currency), AResult); else Assert(False); end; Result := True; end; function ConvTextToBoolean(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin TConverterUtils.StringToBool(ASource, AResult); Result := True; end; function ConvTextToDateTime(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin TConverterUtils.StringToDateTime(ASource, AResult); Result := True; end; function ConvTextToTime(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin TConverterUtils.StringToTime(ASource, AResult); Result := True; end; function ConvTextToDate(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin TConverterUtils.StringToDate(ASource, AResult); Result := True; end; function ConvTextToChar(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin TConverterUtils.StringToChar(ASource, AResult); Result := True; end; // Handle Integer, UInteger function ConvFloatToInteger(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin case AType of mtInteger: TConverterUtils.FloatToInteger(ASource, TypeInfo(Int64), AResult); mtUInteger: TConverterUtils.FloatToInteger(ASource, TypeInfo(UInt64), AResult); else Assert(False); end; Result := True; end; function ConvBitmapToText(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin TConverterUtils.PersistentToString(ASource, AResult); Result := True; end; function ConvBitmapToObject(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin TConverterUtils.PersistentToPersistent(ASource, AResult); Result := True; end; function ConvMemoToText(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin TConverterUtils.StringsToString(ASource, AResult); Result := True; end; function ConvBooleanToText(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin TConverterUtils.BoolToString(ASource, AResult); Result := True; end; function ConvObjectToText(const ASource: TValue; AType: TScopeMemberType; out AResult: TValue): Boolean; begin TConverterUtils.PersistentToString(ASource, AResult); Result := True; end; const Conversions: array[TScopeMemberType,TScopeMemberType] of TConvertFunc = ( // [source, target] // mtUnknown ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvNone, ConvFail, ConvFail, ConvFail, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvFail ), // mtText ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvNone, ConvTextToInteger, ConvTextToFloat, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvTextToBoolean, ConvFail, ConvFail, ConvTextToDateTime, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvTextToFloat, ConvFail, ConvFail, ConvTextToDate, ConvTextToTime, // mtChar, mtTValue ConvTextToChar, ConvNone ), // mtInteger ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvToText, ConvNone, ConvNone, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvNone ), // mtFloat ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvToText, ConvFloatToInteger, ConvNone, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvNone ), // mtBitmap ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvBitmapToText, ConvFail, ConvFail, ConvNone, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvBitmapToObject, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvNone ), // mtMemo ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvMemoToText, ConvFail, ConvFail, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvNone, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvNone ), // mtBoolean ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvBooleanToText, ConvFail, ConvFail, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvNone, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvNone ), // mtBCD ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvToText, ConvTextToInteger, ConvTextToFloat, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvNone, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvToText ), // mtUInteger ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvToText, ConvNone, ConvNone, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvNone, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvNone ), // mtDateTime ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvToText, ConvFail, ConvFail, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvNone, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvNone, ConvNone, // mtChar, mtTValue ConvFail, ConvNone ), // mtCurrency ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvToText, ConvFloatToInteger, ConvNone, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvNone ), // mtObject ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvObjectToText, ConvFail, ConvFail, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvNone, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvNone ), // mtVariant ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvToText, ConvFail, ConvFail, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvFail, ConvNone ), // mtDate ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvToText, ConvFail, ConvFail, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvNone, ConvNone, // mtChar, mtTValue ConvFail, ConvNone ), // mtTime ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvToText, ConvFail, ConvFail, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvNone, ConvNone, // mtChar, mtTValue ConvFail, ConvNone ), // mtChar ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvToText, ConvFail, ConvFail, ConvFail, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvFail, ConvFail, // mtChar, mtTValue ConvNone, ConvNone ), // mtTValue ( // mtUnknown, mtText, mtInteger, mtFloat, mtBitmap, ConvFail, ConvNone, ConvNone, ConvNone, ConvNone, // mtMemo, mtBoolean, mtBCD, mtUInteger, mtDateTime, ConvFail, ConvNone, ConvFail, ConvFail, ConvNone, // mtCurrency, mtObject, mtVariant, mtDate, mtTime, ConvFail, ConvFail, ConvFail, ConvNone, ConvNone, // mtChar, mtTValue ConvFail, ConvNone ) ); procedure TBindSourceAdapterEnumerator.GetMemberValue(const AMemberName: string; const AType: TScopeMemberType; const ACallback: TValueCallback); const LObjectTypes: TScopeMemberTypes = [TScopeMemberType.mtObject, TScopeMemberType.mtBitmap]; var LMember: TObject; LMemberType: TScopeMemberType; LValue: TValue; LConverter: TConvertFunc; LResult: TValue; begin LMember := FBindSourceAdapter.GetMember(AMemberName); if (LMember is TBindSourceAdapterField) and TBindSourceAdapterField(LMember).GetMemberType(LMemberType) then begin LConverter := Conversions[LMemberType, AType]; LValue := TBindSourceAdapterField(LMember).GetTValue; Assert(@LConverter <> @ConvFail); if @LConverter <> @ConvNone then begin if LConverter(LValue, AType, LResult) then ACallback(LResult, AType) else Assert(False); end else ACallback(LValue, AType) end; end; function TBindSourceAdapterEnumerator.GetMemberValue(const AMemberName: string; const ATypes: array of TScopeMemberType; out AValue: TValue): Boolean; const FloatTypes: TScopeMemberTypes = [TScopeMemberType.mtFloat, TScopeMemberType.mtCurrency, TScopeMemberType.mtBCD]; IntegerTypes: TScopeMemberTypes = [TScopeMemberType.mtInteger, TScopeMemberType.mtUInteger]; var LMember: TObject; LType: TScopeMemberType; LValue: TValue; LMemberType: TScopeMemberType; begin LType := TScopeMemberType.mtUnknown; LMember := FBindSourceAdapter.GetMember(AMemberName); Result := (LMember is TBindSourceAdapterField) and TBindSourceAdapterField(LMember).GetMemberType(LMemberType); if Result then begin for LType in ATypes do begin Result := (LType = LMemberType); if not Result then Result := (@Conversions[LMemberType, LType] = @ConvNone) and not ((LType in FloatTypes) and (LType in IntegerTypes)); if Result then break; end; if not Result then for LType in ATypes do begin Result := @Conversions[LMemberType, LType] = @ConvNone; if Result then break; end; if not Result then for LType in ATypes do begin Result := LType = mtText; if Result then break; end; if Result then begin GetMemberValue(AMemberName, LType, procedure(const AValue: TValue; AType: TScopeMemberType) begin LValue := AValue; end); AValue := LValue; end; end; end; function TBindSourceAdapterEnumerator.CanGetMemberValue(const AMemberName: string; AType: TScopeMemberType): Boolean; var LMember: TObject; LMemberType: TScopeMemberType; LConvertFunc: TConvertFunc; begin LMember := FBindSourceAdapter.GetMember(AMemberName); Result := (LMember is TBindSourceAdapterField) and TBindSourceAdapterField(LMember).GetMemberType(LMemberType); if Result then begin LConvertFunc := Conversions[LMemberType, AType]; Result := @LConvertFunc <> @ConvFail; end; end; function TBindSourceAdapterEnumerator.GetMultiRecordChange: Boolean; begin Result := FMultiRecordChange; end; function TBindSourceAdapterEnumerator.GetRecordCount: Integer; begin Result := FBindSourceAdapter.GetCount; end; function TBindSourceAdapterEnumerator.MoveNext: Boolean; begin if (FBindSourceAdapter.GetCount > 0) and (FNextRecord < FBindSourceAdapter.GetCount) then begin FBindSourceAdapter.ItemIndexOffset := FNextRecord - FBindSourceAdapter.ItemIndex; FNextRecord := FNextRecord + 1; Result := True; end else Result := False; end; procedure TBindSourceAdapter.AddLink(DataLink: TBindSourceAdapterLink); begin FLinks.Add(DataLink); DataLink.FAdapter := Self; DataLink.UpdateState; end; procedure TBindSourceAdapter.RemoveLink(DataLink: TBindSourceAdapterLink); begin DataLink.FAdapter := nil; FLinks.Remove(DataLink); DataLink.UpdateState; end; function TBindSourceAdapter.GetEmpty: Boolean; begin Result := GetCount = 0; end; function TBindSourceAdapter.GetEnumerator( const AMemberName: string; AGetScope: TFunc<IScope>; AGetMemberScope: TFunc<string, IScope>): IScopeRecordEnumerator; var LEnumerator: TBindSourceAdapterEnumerator; begin LEnumerator := TBindSourceAdapterEnumerator.Create(Self, AMemberName, AGetScope, AGetMemberScope); LEnumerator.FMultiRecordChange := FResetNeeded; FResetNeeded := False; Result := LEnumerator; end; function TBindSourceAdapter.GetEOF: Boolean; begin Result := (GetCount = 0) or (ItemIndex + 1 = GetCount); end; function TBindSourceAdapter.FindField(const AMemberName: string): TBindSourceAdapterField; var LField: TBindSourceAdapterField; LFieldName, LPath: string; LPos: Integer; begin if SupportsNestedFields then begin LPath := AMemberName; LPos := LPath.IndexOf('.') + 1; if LPos > 0 then begin LFieldName := LPath.Substring(0, LPos-1); LPath := LPath.Remove(0, LPos); end else begin LFieldName := LPath; LPath := ''; end; end else LFieldName := AMemberName; for LField in FFields do begin if SameText(LField.MemberName, LFieldName) then begin if LPath <> '' then Exit(LField.FindField(LPath)); Exit(LField); end; end; Result := nil; end; function TBindSourceAdapter.GetMember(const AMemberName: string): TObject; begin Result := FindField(AMemberName); end; function TBindSourceAdapter.GetMemberGetter(const AMemberName: string; var AGetter: string): Boolean; var LField: TBindSourceAdapterField; begin LField := FindField(AMemberName); if LField <> nil then Result := LField.GetGetter(AGetter) else Result := False; end; procedure TBindSourceAdapter.GetMemberNames(AList: TStrings); var LField: TBindSourceAdapterField; begin AList.Clear; for LField in FFields do AList.Add(LField.MemberName); end; procedure TBindSourceAdapter.GetLookupMemberNames(AList: TStrings); var LField: TBindSourceAdapterField; begin AList.Clear; for LField in FFields do if not LField.IsObject then AList.Add(LField.MemberName); end; function TBindSourceAdapter.GetMemberSetter(const AMemberName: string; var ASetter: string): Boolean; var LField: TBindSourceAdapterField; begin LField := FindField(AMemberName); if LField <> nil then Result := LField.GetSetter(ASetter) else Result := False; end; function TBindSourceAdapter.IsValidChar(const AMemberName: string; const AChar: Char): Boolean; var LField: TBindSourceAdapterField; begin LField := FindField(AMemberName); if LField <> nil then Result := LField.IsValidChar(AChar) else Result := False; end; function TBindSourceAdapter.GetMemberType(const AMemberName: string; var AType: TScopeMemberType): Boolean; var LField: TBindSourceAdapterField; begin LField := FindField(AMemberName); if LField <> nil then Result := LField.GetMemberType(AType) else Result := False; end; function TBindSourceAdapter.GetScopes: TEnumerable<TBaseObjectBindSource>; begin Result := FScopes; end; function TBindSourceAdapter.GetValue: TObject; begin Result := Self; end; procedure TBindSourceAdapter.Insert; var LIndex: Integer; begin if (ItemCount > 0) and (FItemIndex <> -1) then begin CheckBrowseMode; DoBeforeInsert; DoBeforeScroll; CheckOperation( procedure begin LIndex := InsertAt(FItemIndex + FItemIndexOffset) end, FOnInsertError); if LIndex >= 0 then begin SetState(seInsert); FEnteringEditState := True; try ItemIndex := LIndex; DataSetChanged; finally FEnteringEditState := False; end; end; DoAfterInsert; DoAfterScroll; end else begin Append; end; end; function TBindSourceAdapter.InsertAt(AIndex: Integer): Integer; begin Assert(False); Result := -1; end; procedure TBindSourceAdapter.Append; var LIndex: Integer; begin CheckBrowseMode; DoBeforeInsert; DoBeforeScroll; CheckOperation( procedure begin LIndex := AppendAt end, FOnInsertError); if LIndex >= 0 then begin SetState(seInsert); FEnteringEditState := True; try DataSetChanged; ItemIndex := LIndex; finally FEnteringEditState := False; end; end; DoAfterInsert; DoAfterScroll; end; function TBindSourceAdapter.AppendAt: Integer; begin Assert(False); Result := -1; end; procedure TBindSourceAdapter.DataSetChanged; var LScope: TBaseObjectBindSource; begin for LScope in Scopes do begin LScope.OnAdapterDataSetChanged(Self); end; end; procedure TBindSourceAdapter.RecordChanged(AField: TBindSourceAdapterField); var LScope: TBaseObjectBindSource; begin for LScope in Scopes do begin LScope.OnAdapterRecordChanged(Self, AField); end; end; procedure TBindSourceAdapter.ApplyUpdates; begin CheckBrowseMode; DoBeforeApplyUpdates; CheckOperation(InternalApplyUpdates, FOnApplyUpdatesError); DataSetChanged; DoAfterApplyUpdates; end; procedure TBindSourceAdapter.Last; var LNewIndex: Integer; begin LNewIndex := ItemIndex; if GetCount >= 1 then begin LNewIndex := GetCount - 1; end; if GetItemIndex <> LNewIndex then begin ItemIndex := LNewIndex; end; end; procedure TBindSourceAdapter.Next; var LNewIndex: Integer; begin LNewIndex := ItemIndex; if LNewIndex = -1 then begin if GetCount > 0 then LNewIndex := 0; end else if LNewIndex + 1 < GetCount then Inc(LNewIndex); if ItemIndex <> LNewIndex then begin ItemIndex := LNewIndex; end; end; procedure TBindSourceAdapter.UpdateRecord; var LScope: TBaseObjectBindSource; begin if not (State in seEditModes) then BindSourceAdapterError(SNotEditing, Self); if FUpdatingRecords = 0 then for LScope in FScopes do begin LScope.OnAdapterUpdateRecord(Self); end; end; procedure TBindSourceAdapter.PosChanging; begin if (State in seEditModes) then Post; end; procedure TBindSourceAdapter.Post; begin UpdateRecord; case State of seEdit, seInsert: begin DoBeforePost; CheckOperation( procedure begin InternalPost; end, FOnPostError); SetState(seBrowse); DataSetChanged; DoAfterPost; end; end; end; procedure TBindSourceAdapter.InternalPost; var LField: TBindSourceAdapterField; begin for LField in FFields do begin LField.Post; end; end; procedure TBindSourceAdapter.Prior; var LNewIndex: Integer; begin LNewIndex := ItemIndex; if LNewIndex - 1 >= 0 then Dec(LNewIndex); if ItemIndex <> LNewIndex then begin ItemIndex := LNewIndex; end; end; function TBindSourceAdapter.GetActive: Boolean; begin Result := not (State in [seInactive]); end; procedure TBindSourceAdapter.SetActive(Value: Boolean); begin if Active <> Value then begin if Value then begin DoBeforeOpen; SetState(seBrowse); DoAfterOpen; end else begin if not (csDestroying in ComponentState) then DoBeforeClose; SetState(seInactive); if not (csDestroying in ComponentState) then DoAfterClose; end; end; end; procedure TBindSourceAdapter.SetItemIndex(Value: Integer); var LDistance: Integer; LScope: TBaseObjectBindSource; begin Assert(FItemIndexOffset = 0); if (Value <> ItemIndex) and (Value < GetCount) then begin if Active then begin if (State in seEditModes) then if not FEnteringEditState then Post; DoBeforeScroll; LDistance := Value - ItemIndex; FItemIndex := Value; for LScope in Scopes do LScope.OnAdapterDataSetScrolled(Self, LDistance); DoAfterScroll; end else FItemIndex := Value; end; end; procedure TBindSourceAdapter.SetItemIndexOffset(Value: Integer); begin FItemIndexOffset := Value; end; { Event Handler Helpers } procedure TBindSourceAdapter.DoAfterCancel; begin if Assigned(FAfterCancel) then FAfterCancel(Self); end; procedure TBindSourceAdapter.DoAfterClose; begin if Assigned(FAfterClose) then FAfterClose(Self); end; procedure TBindSourceAdapter.DoAfterDelete; begin if Assigned(FAfterDelete) then FAfterDelete(Self); end; procedure TBindSourceAdapter.DoAfterEdit; begin if Assigned(FAfterEdit) then FAfterEdit(Self); end; procedure TBindSourceAdapter.DoAfterInsert; begin if Assigned(FAfterInsert) then FAfterInsert(Self); end; procedure TBindSourceAdapter.DoAfterOpen; begin if Assigned(FAfterOpen) then FAfterOpen(Self); if ItemCount <> 0 then DoAfterScroll; end; procedure TBindSourceAdapter.DoAfterPost; begin if Assigned(FAfterPost) then FAfterPost(Self); end; procedure TBindSourceAdapter.DoAfterRefresh; begin if Assigned(FAfterRefresh) then FAfterRefresh(Self); end; procedure TBindSourceAdapter.DoAfterScroll; begin if Assigned(FAfterScroll) then FAfterScroll(Self); end; procedure TBindSourceAdapter.DoBeforeCancel; begin if Assigned(FBeforeCancel) then FBeforeCancel(Self); end; procedure TBindSourceAdapter.DoBeforeClose; begin if Assigned(FBeforeClose) then FBeforeClose(Self); end; procedure TBindSourceAdapter.DoBeforeDelete; begin if Assigned(FBeforeDelete) then FBeforeDelete(Self); end; procedure TBindSourceAdapter.DoBeforeEdit; begin if Assigned(FBeforeEdit) then FBeforeEdit(Self); end; procedure TBindSourceAdapter.DoBeforeInsert; begin if Assigned(FBeforeInsert) then FBeforeInsert(Self); end; procedure TBindSourceAdapter.DoBeforeOpen; begin if Assigned(FBeforeOpen) then FBeforeOpen(Self); end; procedure TBindSourceAdapter.DoBeforePost; begin if Assigned(FBeforePost) then FBeforePost(Self); end; procedure TBindSourceAdapter.DoBeforePostFields( AFields: TArray<TBindSourceAdapterField>); begin // end; procedure TBindSourceAdapter.DoAfterPostFields( AFields: TArray<TBindSourceAdapterField>); begin // end; procedure TBindSourceAdapter.DoBeforeRefresh; begin if Assigned(FBeforeRefresh) then FBeforeRefresh(Self); end; procedure TBindSourceAdapter.DoBeforeScroll; begin if Assigned(FBeforeScroll) then FBeforeScroll(Self); end; procedure TBindSourceAdapter.DoBeforeCancelUpdates; begin if Assigned(FBeforeCancelUpdates) then FBeforeCancelUpdates(Self); end; procedure TBindSourceAdapter.DoBeforeApplyUpdates; begin if Assigned(FBeforeApplyUpdates) then FBeforeApplyUpdates(Self); end; procedure TBindSourceAdapter.DoAfterCancelUpdates; begin if Assigned(FAfterCancelUpdates) then FAfterCancelUpdates(Self); end; procedure TBindSourceAdapter.DoAfterApplyUpdates; begin if Assigned(FAfterApplyUpdates) then FAfterApplyUpdates(Self); end; procedure TBindSourceAdapter.CheckOperation(AOperation: TProc; ErrorEvent: TAdapterErrorEvent); var Done: Boolean; Action: TAdapterErrorAction; begin Done := False; repeat try AOperation(); Done := True; except on E: EBindCompError do begin Action := aaFail; if Assigned(ErrorEvent) then ErrorEvent(Self, E, Action); if Action = aaFail then raise; if Action = aaAbort then System.SysUtils.Abort; end; end; until Done; end; { TBindSourceAdapterField } function TBindSourceAdapterField.SupportsStreamPersist(const Persistent: TObject; var StreamPersist: IStreamPersist): Boolean; begin Result := (Persistent is TInterfacedPersistent) and (TInterfacedPersistent(Persistent).QueryInterface(IStreamPersist, StreamPersist) = S_OK); end; function TBindSourceAdapterField.AssignValue(Dest: TPersistent): Boolean; var StreamPersist: IStreamPersist; begin Result := False; if Dest is TStrings then begin SaveToStrings(TStrings(Dest)); Exit(True); end; if SupportsStreamPersist(Dest, StreamPersist) then begin SaveToStreamPersist(StreamPersist); Exit(True); end; end; function TBindSourceAdapterField.CreateValueBlobStream(AValue: TObject): TStream; var LStreamPersist: IStreamPersist; begin Result := TMemoryStream.Create; if SupportsStreamPersist(AValue, LStreamPersist) then begin LStreamPersist.SaveToStream(Result); end; end; class destructor TBindSourceAdapterField.Destroy; begin FValidChars.Free; end; function TBindSourceAdapterField.CreateBlobStream: TStream; begin Result := TMemoryStream.Create; end; procedure TBindSourceAdapterField.SaveToStrings(Strings: TStrings); var BlobStream: TStream; begin BlobStream := CreateBlobStream; try Strings.LoadFromStream(BlobStream); finally BlobStream.Free; end; end; procedure TBindSourceAdapterField.SetTValue(const AValue: TValue); begin BindSourceAdapterError(sNotImplemented, Self.Owner); end; procedure TBindSourceAdapterField.SetAutoPost(const Value: Boolean); begin // end; type TGraphicHeader = record Count: Word; { Fixed at 1 } HType: Word; { Fixed at $0100 } Size: Longint; { Size not including header } end; procedure TBindSourceAdapterField.SaveToStreamPersist(StreamPersist: IStreamPersist); var BlobStream: TStream; Size: Longint; Header: TGraphicHeader; begin BlobStream := CreateBlobStream; try Size := BlobStream.Size; if Size >= SizeOf(TGraphicHeader) then begin BlobStream.Read(Header, SizeOf(Header)); if (Header.Count <> 1) or (Header.HType <> $0100) or (Header.Size <> Size - SizeOf(Header)) then BlobStream.Position := 0; end; StreamPersist.LoadFromStream(BlobStream); finally BlobStream.Free; end; end; procedure TBindSourceAdapterField.AutoEditField; begin FOwner.AutoEditField(Self); end; procedure TBindSourceAdapterField.AutoPostField; begin FOwner.AutoPostField(Self); end; procedure TBindSourceAdapterField.Cancel; begin end; constructor TBindSourceAdapterField.Create(AOwner: TBindSourceAdapter; const AMemberName: string; const AGetMemberObject: IGetMemberObject); begin FOwner := AOwner; FMemberName := AMemberName; end; function TBindSourceAdapterField.FindField(const AMemberName: string): TBindSourceAdapterField; begin Result := nil; end; function TBindSourceAdapterField.GetGetter(var AGetter: string): Boolean; begin Result := False; end; function TBindSourceAdapterField.GetMemberType(var AType: TScopeMemberType): Boolean; begin Result := False; end; function TBindSourceAdapterField.GetIsObject: Boolean; begin Result := False; end; function TBindSourceAdapterField.GetIsReadable: Boolean; var LSetter: string; begin Result := GetGetter(LSetter); end; function TBindSourceAdapterField.GetIsWritable: Boolean; var LSetter: string; begin Result := GetSetter(LSetter); end; function TBindSourceAdapterField.GetMemberObject: TObject; begin if Assigned(FGetMemberObject) then Result := FGetMemberObject.GetMemberObject else Result := Self.FOwner.Current; end; function TBindSourceAdapterField.GetSetter(var AGetter: string): Boolean; begin Result := False; end; function TBindSourceAdapterField.GetTValue: TValue; begin Result := TValue.Empty; end; function TBindSourceAdapterField.GetAutoPost: Boolean; begin Result := False; end; function TBindSourceAdapterField.IsBuffered: Boolean; begin Result := False; end; function TBindSourceAdapterField.IsValidChar(AChar: Char): Boolean; var LMemberType: TScopeMemberType; C: Char; LMemberTypes: TScopeMemberTypes; begin if FValidChars = nil then begin FValidChars := TDictionary<char, TScopeMemberTypes>.Create; FValidChars.Add(#0, [mtUnknown, mtText, mtBitmap, mtMemo, mtBoolean, mtDateTime, mtTime, mtDate, mtChar]); for C := '0' to '9' do FValidChars.Add(C, [mtInteger, mtFloat, mtUInteger, mtBCD, mtCurrency]); FValidChars.Add(FormatSettings.DecimalSeparator, [mtInteger, mtFloat, mtUInteger, mtBCD, mtCurrency]); FValidChars.Add('+', [mtInteger, mtFloat, mtBCD, mtCurrency]); FValidChars.Add('-', [mtInteger, mtFloat, mtBCD, mtCurrency]); FValidChars.Add('e', [mtFloat]); FValidChars.Add('E', [mtFloat]); end; if AChar = #0 then // Special case to test if field is read only Result := GetIsWritable else begin Result := True; if GetMemberType(LMemberType) then begin if not (LMemberType in FValidChars[#0]) then if (not FValidChars.TryGetValue(AChar, LMemberTypes)) or (not (LMemberType in LMemberTypes)) then Result := False; end; end; end; procedure TBindSourceAdapterField.Post; begin end; procedure TBindSourceAdapterField.RecordChanged; var LScope: TBaseObjectBindSource; begin if Assigned(Self.FOwner) then for LScope in FOwner.Scopes do begin LScope.OnAdapterRecordChanged(Self, Self); end; end; { TCollectionEditorBindLink } constructor TBindSourceAdapterLinkImpl.Create(ABindLink: IBindLink); begin inherited Create; FBindLink := ABindLink; Supports(FBindLink, IBindPosition, FBindPosition); Supports(FBindLink, IBindListUpdate, FBindListUpdate); end; constructor TBindSourceAdapterLinkImpl.Create(ABindPosition: IBindPosition); begin inherited Create; FBindPosition := ABindPosition; Supports(FBindPosition, IBindLink, FBindLink); Supports(FBindPosition, IBindListUpdate, FBindListUpdate); end; constructor TBindSourceAdapterLinkImpl.Create(ABindListUpdate: IBindListUpdate); begin inherited Create; FBindListUpdate := ABindListUpdate; Supports(FBindListUpdate, IBindLink, FBindLink); Supports(FBindListUpdate, IBindPosition, FBindPosition); end; procedure TBindSourceAdapterLinkImpl.ActiveChanged; begin UpdateField; end; procedure TBindSourceAdapterLinkImpl.UpdateData; begin if FBindLink <> nil then if FModified then begin FBindLink.EvaluateParse(''); FModified := False; end; end; procedure TBindSourceAdapterLinkImpl.UpdateField; var LFieldName: string; begin LFieldName := GetFieldName; if (LFieldName = '') and (FField = nil) then begin // No field name RecordChanged(nil); end else begin if Active and (LFieldName <> '') then begin FField := nil; SetField(FAdapter.FindField(LFieldName)); end else SetField(nil); end; end; procedure TBindSourceAdapterLinkImpl.SetField(Value: TBindSourceAdapterField); begin if FField <> Value then begin FField := Value; EditingChanged; RecordChanged(nil); end; end; function TBindSourceAdapterLinkImpl.Edit: Boolean; begin if CanModify then inherited Edit; Result := FEditing; end; procedure TBindSourceAdapterLinkImpl.EditingChanged; begin SetEditing(inherited Editing and CanModify); end; procedure TBindSourceAdapterLinkImpl.SetEditing(Value: Boolean); begin if FEditing <> Value then begin FEditing := Value; FModified := False; end; end; procedure TBindSourceAdapterLinkImpl.RecordChanged(Field: TBindSourceAdapterField); begin if (Field = nil) or (Field = FField) then begin DoDataChange(Field); FModified := False; end else if FField = nil then begin DoDataChange(Field); FModified := False; end; end; function TBindSourceAdapterLinkImpl.GetFieldName: string; begin if FBindLink <> nil then Result := FBindLink.SourceMemberName else if FBindPosition <> nil then Result := FBindPosition.SourceMemberName else Result := ''; end; function TBindSourceAdapterLinkImpl.GetCanModify: Boolean; begin Result := FAdapter.CanModify and ((Field = nil) or Field.GetIsWritable); end; function TBindSourceAdapterLinkImpl.GetField: TBindSourceAdapterField; begin Result := FField; end; function TBindSourceAdapterLinkImpl.GetIsModified: Boolean; begin Result := FModified; end; procedure TBindSourceAdapterLinkImpl.LayoutChanged; begin UpdateField; end; procedure TBindSourceAdapterLinkImpl.SetModified; begin FModified := True; FAdapter.FModified := True; end; procedure TBindSourceAdapterLinkImpl.Reset; begin FModified := False; DoDataChange(FField); end; procedure TBindSourceAdapterLinkImpl.RefreshNeeded; begin FRefreshNeeded := True; end; procedure TBindSourceAdapterLinkImpl.DataSetChanged; var LBindListRefresh: IBindListRefresh; LRefreshed: Boolean; begin if (FBindListUpdate <> nil) and Active and FBindListUpdate.Active then begin LRefreshed := False; if Supports(FBindListUpdate, IBindListRefresh, LBindListRefresh) then if LBindListRefresh.RefreshNeeded or FRefreshNeeded then begin FRefreshNeeded := False; LBindListRefresh.RefreshList; LRefreshed := True; end; if not LRefreshed then begin if (FBindPosition <> nil) and FBindPosition.Active then begin FBindPosition.EvaluatePosControl; end; FBindListUpdate.UpdateList; if (FBindPosition <> nil) and FBindPosition.Active then begin // Make sure new row is selected if seInsert = Self.Adapter.State then FBindPosition.EvaluatePosControl; end; end; end else if (FBindPosition <> nil) and Active and FBindPosition.Active then begin FBindPosition.EvaluatePosControl; end; RecordChanged(nil); end; procedure TBindSourceAdapterLinkImpl.DataSetScrolled(ADistance: Integer); begin if Active then if (FBindLink <> nil) and (FBindLink.Active) then begin if (FBindPosition <> nil) and (FBindPosition.Active) then begin // Must position grid to current record FBindPosition.EvaluatePosControl; end else RecordChanged(nil); end else if (FBindPosition <> nil) and (FBindPosition.Active) then if Active then FBindPosition.EvaluatePosControl; end; procedure TBindSourceAdapterLinkImpl.DoDataChange(AField: TBindSourceAdapterField); var LMemberName: string; begin if AField <> nil then LMemberName := AField.MemberName; if not FDeferEvaluate then if (FBindLink <> nil) and (FBindLink.Active) then begin if Active and (Adapter.ItemCount > 0) then FBindLink.EvaluateFormat(LMemberName) else FBindLink.EvaluateClear(LMemberName) end end; { TBindSourceAdapterLink } procedure TBindSourceAdapterLink.ActiveChanged; begin end; procedure TBindSourceAdapterLink.EditingChanged; begin end; constructor TBindSourceAdapterLink.Create; begin FReadOnly := False; end; procedure TBindSourceAdapterLink.DataSetChanged; begin end; procedure TBindSourceAdapterLink.DataSetScrolled(ADistance: Integer); begin end; procedure TBindSourceAdapterLink.LayoutChanged; begin end; procedure TBindSourceAdapterLink.RecordChanged(Field: TBindSourceAdapterField); begin end; function TBindSourceAdapterLink.Edit: Boolean; begin if not FReadOnly and (FAdapter <> nil) then FAdapter.Edit; Result := FEditing; end; procedure TBindSourceAdapterLink.SetAdapter(const Value: TBindSourceAdapter); begin if FAdapter <> Value then begin if (FAdapter <> nil) and (not (csDestroying in FAdapter.ComponentState)) then FAdapter.RemoveLink(Self); FAdapter := Value; if Value <> nil then Value.AddLink(Self); end; end; procedure TBindSourceAdapterLink.UpdateData; begin end; procedure TBindSourceAdapterLink.UpdateRecord; begin FUpdating := True; try UpdateData; finally FUpdating := False; end; end; procedure TBindSourceAdapterLink.UpdateState; begin SetActive((FAdapter <> nil) and (not (csDestroying in FAdapter.ComponentState)) and (FAdapter.State <> seInactive)); SetEditing((FAdapter <> nil) and (not (csDestroying in FAdapter.ComponentState)) and (FAdapter.State in seEditModes) and not FReadOnly); end; procedure TBindSourceAdapterLink.SetActive(Value: Boolean); begin if FActive <> Value then begin FActive := Value; ActiveChanged; end; end; procedure TBindSourceAdapterLink.SetEditing(Value: Boolean); begin if FEditing <> Value then begin FEditing := Value; EditingChanged; end; end; { TBindSourceAdapterCustomScope } function TBindSourceAdapterCustomScope.DoLookup(const Name: String): IInterface; var LScope: TBindSourceAdapter; begin Result := nil; if MappedObject is TBindSourceAdapter then begin LScope := TBindSourceAdapter(MappedObject); if LScope.FindField(Name) <> nil then Result := TCustomWrapper.Create(LScope, LScope.ClassType, Name, cwtProperty, function (ParentObject: TObject; const MemberName: String; Args: TArray<TValue>): TValue begin Result := TBindSourceAdapter(ParentObject).FindField(MemberName); end); end; end; { TBaseObjectBindSourceAdapter } constructor TBaseObjectBindSourceAdapter.Create(AOwner: TComponent); begin inherited; FOptions := [optAllowModify]; end; function TBaseObjectBindSourceAdapter.GetObjectType: TRttiType; begin Result := nil; end; { TBindSourceAdapterInstanceFactory } function TBindSourceAdapterInstanceFactory.FindConstructor: TRttiMethod; var LMethod: TRTTIMethod; LParameters: TArray<TRttiParameter>; begin if FType <> nil then for LMethod in FType.GetMethods do begin if LMethod.HasExtendedInfo and LMethod.IsConstructor then begin LParameters := LMethod.GetParameters; if Length(LParameters) = 0 then begin Exit(LMethod); end; end; end; exit(nil); end; function TBindSourceAdapterInstanceFactory.ConstructInstance: TObject; var LClass: TClass; LInstance: TObject; begin Result := nil; if FConstructor <> nil then begin LClass := FType.AsInstance.MetaclassType; LInstance := FConstructor.Invoke(LClass, []).AsObject; try Result := LInstance; if not (LInstance.InheritsFrom(LClass)) then BindSourceAdapterError(Format(sInvalidInstance, [LInstance.ClassName, LClass.ClassName])); except LInstance.Free; raise; end; end; end; function TBindSourceAdapterInstanceFactory.CanConstructInstance: Boolean; begin Result := CheckConstructor; end; function TBindSourceAdapterInstanceFactory.CheckConstructor: Boolean; var LMethod: TRttiMethod; LType: TRttiType; begin Result := CheckConstructor(LType, LMethod); end; function TBindSourceAdapterInstanceFactory.CheckConstructor(out AType: TRttiType; out AMethod: TRttiMethod): Boolean; begin if (FType <> nil) and FFindConstructor then begin FFindConstructor := False; if FType <> nil then FConstructor := FindConstructor end; AMethod := FConstructor; AType := FType; Result := AMethod <> nil; end; constructor TBindSourceAdapterInstanceFactory.Create(AType: TRttiType); begin FFindConstructor := True; Assert(AType <> nil); FType := AType; end; { TBaseListBindSourceAdapter } procedure TBaseListBindSourceAdapter.DoInitItemInstance(AInstance: TObject); begin if Assigned(FOnInitItemInstance) then FOnInitItemInstance(Self, AInstance); end; procedure TBaseListBindSourceAdapter.DoListInsert(AIndex: Integer; out AHandled: Boolean; out ANewIndex: Integer); begin AHandled := False; ANewIndex := AIndex; if Assigned(FOnListInsert) then FOnListInsert(Self, AIndex, AHandled, ANewIndex); end; constructor TBaseListBindSourceAdapter.Create(AOwner: TComponent); begin inherited; FOptions := [loptAllowInsert, loptAllowModify, loptAllowDelete]; end; procedure TBaseListBindSourceAdapter.DoCreateInstance(out AHandled: Boolean; out AInstance: TObject); begin AHandled := False; AInstance := nil; if Assigned(FOnCreateItemInstance) then FOnCreateItemInstance(Self, AHandled, AInstance); end; procedure TBaseListBindSourceAdapter.DoListAppend(out AHandled: Boolean; out AAppended: Boolean); begin AHandled := False; AAppended := True; if Assigned(FOnListAppend) then FOnListAppend(Self, AHandled, AAppended); end; procedure TBaseListBindSourceAdapter.DoListDelete(AIndex: Integer; out AHandled: Boolean; out ARemoved: Boolean); begin AHandled := False; ARemoved := True; if Assigned(FOnListDelete) then FOnListDelete(Self, AIndex, AHandled, ARemoved); end; { TListBindSourceAdapter<T> } function TListBindSourceAdapter<T>.GetObjectType: TRttiType; var LType: TRttiType; LCtxt: TRttiContext; begin LType := LCtxt.GetType(TypeInfo(T)); Result := LType; end; function TListBindSourceAdapter<T>.GetItemInstanceFactory: TBindSourceAdapterInstanceFactory; begin if FInstanceFactory = nil then FInstanceFactory := TBindSourceAdapterInstanceFactory.Create(GetObjectType); Result := FInstanceFactory; end; procedure TListBindSourceAdapter<T>.CheckList; begin if FList = nil then BindSourceAdapterError(sNilList); end; function TListBindSourceAdapter<T>.CreateItemInstance: T; var LObject: TObject; LHandled: Boolean; begin CheckList; Result := nil; DoCreateInstance(LHandled, LObject); if not LHandled then begin Assert(GetItemInstanceFactory.CanConstructInstance); if GetItemInstanceFactory.CanConstructInstance then LObject := GetItemInstanceFactory.ConstructInstance; end; try if not (LObject is T) then BindSourceAdapterError(Format(sInvalidInstance, [LObject.ClassName, T.ClassName])); Result := LObject as T; except LObject.Free; raise; end; end; function TListBindSourceAdapter<T>.AppendAt: Integer; var ANewItem: T; LIndex: Integer; LHandled: Boolean; LAppended: Boolean; begin DoListAppend(LHandled, LAppended); if LHandled then if LAppended then begin CheckList; Exit(FList.Count - 1) end else Exit(-1); Result := -1; ANewItem := CreateItemInstance; if ANewItem <> nil then begin InitItemInstance(ANewItem); FList.Add(ANewItem); Result := FList.Count - 1; end; end; function TListBindSourceAdapter<T>.GetCanInsert: Boolean; begin Result := (loptAllowInsert in Options); if Result then begin Result := Assigned(FOnCreateItemInstance) or GetItemInstanceFactory.CheckConstructor; end; end; function TListBindSourceAdapter<T>.GetCanModify: Boolean; begin Result := (loptAllowModify in Options); end; constructor TListBindSourceAdapter<T>.Create(AOwner: TComponent; AList: TList<T>; AOwnsObject: Boolean = True); begin Create(AOwner); SetList(AList, AOwnsObject); end; procedure TListBindSourceAdapter<T>.SetList(AList: TList<T>; AOwnsObject: Boolean); begin DoOnBeforeSetList(AList); Active := False; if FList <> nil then begin ClearFields; if FOwnsList then FreeAndNil(FList); end; FOwnsList := AOwnsObject; FList := AList; if FList <> nil then begin AddFields; end; DoOnAfterSetList; end; function TListBindSourceAdapter<T>.SupportsNestedFields: Boolean; begin Result := True; end; function TListBindSourceAdapter<T>.DeleteAt(AIndex: Integer): Boolean; var LHandled: Boolean; LRemoved: Boolean; begin DoListDelete(AIndex, LHandled, LRemoved); if LHandled then Exit(LRemoved); if (AIndex >= 0) and (AIndex < FList.Count) then begin CheckList; FList.Delete(AIndex); Result := True; end else Result := False; end; function TListBindSourceAdapter<T>.GetCanApplyUpdates: Boolean; var LHasUpdates: Boolean; begin Result := loptAllowApplyUpdates in Options; if Result then begin Result := Assigned(FOnApplyUpdates); if Result then if Assigned(FOnHasUpdates) then begin LHasUpdates := False; FOnHasUpdates(Self, LHasUpdates); Result := LHasUpdates; end; end; end; function TListBindSourceAdapter<T>.GetCanCancelUpdates: Boolean; var LHasUpdates: Boolean; begin Result := loptAllowCancelUpdates in Options; if Result then begin Result := Assigned(FOnCancelUpdates); if Result then if Assigned(FOnHasUpdates) then begin LHasUpdates := False; FOnHasUpdates(Self, LHasUpdates); Result := LHasUpdates; end; end; end; function TListBindSourceAdapter<T>.GetCanDelete: Boolean; begin Result := loptAllowDelete in Options; end; destructor TListBindSourceAdapter<T>.Destroy; begin if FOwnsList then FreeAndNil(FList); FInstanceFactory.Free; inherited; end; procedure TListBindSourceAdapter<T>.DoOnAfterSetList; begin if Assigned(FOnAfterSetList) then FOnAfterSetList(Self); end; procedure TListBindSourceAdapter<T>.DoOnBeforeSetList(AList: TList<T>); begin if Assigned(FOnBeforeSetList) then FOnBeforeSetList(Self, AList); end; function TListBindSourceAdapter<T>.GetCanActivate: Boolean; begin Result := FList <> nil; end; function TListBindSourceAdapter<T>.GetCount: Integer; begin if FList <> nil then Result := FList.Count else Result := 0; end; function TListBindSourceAdapter<T>.GetCurrent: TObject; var LIndex: Integer; begin LIndex := ItemIndex + FItemIndexOffset; if (FList <> nil) and (LIndex >= 0) and (LIndex < FList.Count) then Result := FList.Items[ItemIndex + FItemIndexOffset] else Result := nil; end; procedure TListBindSourceAdapter<T>.InitItemInstance(AInstance: T); begin DoInitItemInstance(AInstance); end; function TListBindSourceAdapter<T>.InsertAt(AIndex: Integer): Integer; var ANewItem: T; AHandled: Boolean; begin DoListInsert(AIndex, AHandled, Result); if AHandled then Exit; Result := -1; ANewItem := CreateItemInstance; if ANewItem <> nil then begin InitItemInstance(ANewItem); FList.Insert(AIndex, ANewItem); Result := AIndex; end; end; procedure TListBindSourceAdapter<T>.InternalApplyUpdates; begin if Assigned(FOnApplyUpdates) then FOnApplyUpdates(Self); end; procedure TListBindSourceAdapter<T>.InternalCancelUpdates; begin if Assigned(FOnCancelUpdates) then FOnCancelUpdates(Self); end; { TObjectBindSourceAdapter<T> } function TObjectBindSourceAdapter<T>.GetObjectType: TRttiType; var LType: TRttiType; LCtxt: TRttiContext; begin LType := LCtxt.GetType(TypeInfo(T)); Result := LType; end; procedure TObjectBindSourceAdapter<T>.AddFields; var LType: TRttiType; LIntf: IGetMemberObject; begin LType := GetObjectType; LIntf := TBindSourceAdapterGetMemberObject.Create(Self); AddFieldsToList(LType, Self, Self.Fields, LIntf); AddPropertiesToList(LType, Self, Self.Fields, LIntf); end; function TObjectBindSourceAdapter<T>.AppendAt: Integer; var ANewItem: T; begin Assert(False); end; constructor TObjectBindSourceAdapter<T>.Create(AOwner: TComponent; AObject: T; AOwnsObject: Boolean); begin inherited Create(AOwner); SetDataObject(AObject, AOwnsObject); end; function TObjectBindSourceAdapter<T>.DeleteAt(AIndex: Integer): Boolean; begin Assert(False); end; destructor TObjectBindSourceAdapter<T>.Destroy; begin if FOwnsObject then FreeAndNil(FDataObject); inherited; end; procedure TObjectBindSourceAdapter<T>.DoOnBeforeSetDataObject(ADataObject: T); begin if Assigned(FOnBeforeSetDataObject) then FOnBeforeSetDataObject(Self, ADataObject); end; procedure TObjectBindSourceAdapter<T>.DoOnAfterSetDataObject; begin if Assigned(FOnAfterSetDataObject) then FOnAfterSetDataObject(Self); end; function TObjectBindSourceAdapter<T>.GetCanActivate: Boolean; begin Result := FDataObject <> nil; end; function TObjectBindSourceAdapter<T>.GetCanModify: Boolean; begin Result := optAllowModify in Options; end; function TObjectBindSourceAdapter<T>.GetCanApplyUpdates: Boolean; begin Result := optAllowApplyUpdates in Options; if Result then Result := Assigned(FOnApplyUpdates) end; function TObjectBindSourceAdapter<T>.GetCanCancelUpdates: Boolean; begin Result := optAllowCancelUpdates in Options; if Result then Result := Assigned(FOnCancelUpdates); end; procedure TObjectBindSourceAdapter<T>.InternalApplyUpdates; begin if Assigned(FOnApplyUpdates) then FOnApplyUpdates(Self); end; procedure TObjectBindSourceAdapter<T>.InternalCancelUpdates; begin if Assigned(FOnCancelUpdates) then FOnCancelUpdates(Self); end; function TObjectBindSourceAdapter<T>.GetCount: Integer; begin if Assigned(FDataObject) then Result := 1 else Result := 0; end; function TObjectBindSourceAdapter<T>.GetCurrent: TObject; begin Result := FDataObject; end; function TObjectBindSourceAdapter<T>.InsertAt(AIndex: Integer): Integer; var ANewItem: T; begin Assert(False); end; procedure TObjectBindSourceAdapter<T>.SetDataObject(ADataObject: T; AOwnsObject: Boolean); begin DoOnBeforeSetDataObject(ADataObject); Active := False; if FDataObject <> nil then begin ClearFields; if FOwnsObject then FreeAndNil(FDataObject); end; FOwnsObject := AOwnsObject; FDataObject := ADataObject; if FDataObject <> nil then begin AddFields; end; DoOnAfterSetDataObject; end; function TObjectBindSourceAdapter<T>.SupportsNestedFields: Boolean; begin Result := True; end; { TCustomDataGeneratorAdapter } class function TCustomDataGeneratorAdapter.CreateField<T>(AFieldDef: TGeneratorFieldDef; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; LDummy: TDummy<T>): TBindSourceAdapterField; var LTypeInfo: PTypeInfo; begin LTypeInfo := AFieldDef.TypeInfo; Assert(LTypeInfo <> nil); if AFieldDef.ReadOnly then Result := TBindSourceAdapterReadField<T>.Create(ABindSourceAdapter, AFieldDef.Name, TBindSourceAdapterFieldType.Create(LTypeInfo.NameFld.ToString, LTypeInfo.Kind), AGetMemberObject, TBindFieldDefValueReader<T>.Create, AFieldDef.MemberType) else Result := TBindSourceAdapterReadWriteField<T>.Create(ABindSourceAdapter, AFieldDef.Name, TBindSourceAdapterFieldType.Create(LTypeInfo.NameFld.ToString, LTypeInfo.Kind), AGetMemberObject, TBindFieldDefValueReader<T>.Create, TBindFieldDefValueWriter<T>.Create, AFieldDef.MemberType) end; class function TCustomDataGeneratorAdapter.CreateObjectField<T>(AFieldDef: TGeneratorFieldDef; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; LDummy: TDummy<T>): TBindSourceAdapterField; var LTypeInfo: PTypeInfo; begin LTypeInfo := AFieldDef.TypeInfo; Assert(LTypeInfo <> nil); if AFieldDef.ReadOnly then Result := TBindSourceAdapterReadObjectField<T>.Create(ABindSourceAdapter, AFieldDef.Name, TBindSourceAdapterFieldType.Create(LTypeInfo.NameFld.ToString, LTypeInfo.Kind), AGetMemberObject, TBindFieldDefValueReader<T>.Create, AFieldDef.MemberType) else Result := TBindSourceAdapterReadWriteObjectField<T>.Create(ABindSourceAdapter, AFieldDef.Name, TBindSourceAdapterFieldType.Create(LTypeInfo.NameFld.ToString, LTypeInfo.Kind), AGetMemberObject, TBindFieldDefObjectValueReader<T>.Create, TBindFieldDefObjectValueWriter<T>.Create, AFieldDef.MemberType) end; class procedure TCustomDataGeneratorAdapter.AddFieldsToList(AFieldDefs: TGeneratorFieldDefs; ABindSourceAdapter: TBindSourceAdapter; AFieldsList: TList<TBindSourceAdapterField>; const AGetMemberObject: IGetMemberObject); var LFieldDef: TGeneratorFieldDef; LCollectionEditorField: TBindSourceAdapterField; LTypeInfo: PTypeInfo; I: Integer; begin AFieldsList.Clear; for I := 0 to AFieldDefs.Count - 1 do begin LFieldDef := AFieldDefs.GetFieldDef(I); LCollectionEditorField := nil; LTypeInfo := LFieldDef.TypeInfo; if LTypeInfo = nil then continue; case LTypeInfo.Kind of tkClass: case LFieldDef.FieldType of ftTStrings: LCollectionEditorField := CreateObjectField<TStrings>(LFieldDef, ABindSourceAdapter, AGetMemberObject); else LCollectionEditorField := CreateObjectField<TPersistent>(LFieldDef, ABindSourceAdapter, AGetMemberObject); end; tkEnumeration: if LFieldDef.FieldType = ftBoolean then LCollectionEditorField := CreateField<Boolean>(LFieldDef, ABindSourceAdapter, AGetMemberObject); tkWChar: LCollectionEditorField := CreateField<char>(LFieldDef, ABindSourceAdapter, AGetMemberObject); tkUString: LCollectionEditorField := CreateField<string>(LFieldDef, ABindSourceAdapter, AGetMemberObject); {$IFNDEF NEXTGEN} tkChar: LCollectionEditorField := CreateField<ansichar>(LFieldDef, ABindSourceAdapter, AGetMemberObject); tkLString: LCollectionEditorField := CreateField<AnsiString>(LFieldDef, ABindSourceAdapter, AGetMemberObject); tkString: LCollectionEditorField := CreateField<ShortString>(LFieldDef, ABindSourceAdapter, AGetMemberObject); {$ENDIF} tkInteger: case System.TypInfo.GetTypeData(LTypeInfo).OrdType of otSByte: // Int8 LCollectionEditorField := CreateField<int8>(LFieldDef, ABindSourceAdapter, AGetMemberObject); otSWord: // Int16 LCollectionEditorField := CreateField<int16>(LFieldDef, ABindSourceAdapter, AGetMemberObject); otSLong: // Int32 LCollectionEditorField := CreateField<int32>(LFieldDef, ABindSourceAdapter, AGetMemberObject); otUByte: // UInt8 LCollectionEditorField := CreateField<uint8>(LFieldDef, ABindSourceAdapter, AGetMemberObject); otUWord: // UInt16 LCollectionEditorField := CreateField<uint16>(LFieldDef, ABindSourceAdapter, AGetMemberObject); otULong: //UInt32 LCollectionEditorField := CreateField<uint32>(LFieldDef, ABindSourceAdapter, AGetMemberObject); else LCollectionEditorField := CreateField<integer>(LFieldDef, ABindSourceAdapter, AGetMemberObject); end; tkInt64: if LTypeInfo.TypeData.MinInt64Value > LTypeInfo.TypeData.MaxInt64Value then LCollectionEditorField := CreateField<Uint64>(LFieldDef, ABindSourceAdapter, AGetMemberObject) else LCollectionEditorField := CreateField<int64>(LFieldDef, ABindSourceAdapter, AGetMemberObject); tkFloat: case LFieldDef.FieldType of ftSingle: LCollectionEditorField := CreateField<single>(LFieldDef, ABindSourceAdapter, AGetMemberObject); ftCurrency: LCollectionEditorField := CreateField<currency>(LFieldDef, ABindSourceAdapter, AGetMemberObject); ftDateTime: LCollectionEditorField := CreateField<TDatetime>(LFieldDef, ABindSourceAdapter, AGetMemberObject); ftDate: LCollectionEditorField := CreateField<TDate>(LFieldDef, ABindSourceAdapter, AGetMemberObject); ftTime: LCollectionEditorField := CreateField<TTime>(LFieldDef, ABindSourceAdapter, AGetMemberObject); else Assert(False); LCollectionEditorField := CreateField<single>(LFieldDef, ABindSourceAdapter, AGetMemberObject); end; end; if LCollectionEditorField <> nil then begin LCollectionEditorField.FGetMemberObject := AGetMemberObject; AFieldsList.Add(LCollectionEditorField); end; end; end; function TCustomDataGeneratorAdapter.CreateItemInstance: TGeneratorRecord; begin Result := TGeneratorRecord.Create; end; procedure TCustomDataGeneratorAdapter.InitItemInstance(ARecord: TGeneratorRecord); var I: Integer; LFieldDef: TGeneratorFieldDef; begin for I := 0 to FieldDefs.Count - 1 do begin LFieldDef := FieldDefs[I]; case LFieldDef.FieldType of ftString: ARecord.FDictionary.Add(LFieldDef.Name, ''); ftInteger, ftUInteger: ARecord.FDictionary.Add(LFieldDef.Name, 0); ftSingle: ARecord.FDictionary.Add(LFieldDef.Name, 0); ftBoolean: ARecord.FDictionary.Add(LFieldDef.Name, False); ftTStrings: ARecord.FDictionary.Add(LFieldDef.Name, TStringList.Create); ftBitmap: ARecord.FDictionary.Add(LFieldDef.Name, nil); ftCurrency: ARecord.FDictionary.Add(LFieldDef.Name, TValue.Empty.AsType<Currency>); ftDateTime: ARecord.FDictionary.Add(LFieldDef.Name, TValue.Empty.AsType<TDateTime>); ftTime: ARecord.FDictionary.Add(LFieldDef.Name, TValue.Empty.AsType<TTime>); ftDate: ARecord.FDictionary.Add(LFieldDef.Name, TValue.Empty.AsType<TDate>); else Assert(False); end; end; end; procedure TCustomDataGeneratorAdapter.AddFields; var LGetMemberObject: IGetMemberObject; begin LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(Self); AddFieldsToList(Self.FieldDefs, Self, Self.Fields, LGetMemberObject); end; function TCustomDataGeneratorAdapter.GetCanActivate: Boolean; begin Result := True; end; function TCustomDataGeneratorAdapter.GetCanInsert: Boolean; begin Result := (loptAllowInsert in Options); end; constructor TCustomDataGeneratorAdapter.Create(AOwner: TComponent); begin inherited Create(AOwner); FFieldDefs := GetFieldDefsClass.Create(Self); FRecordCount := -1; end; destructor TCustomDataGeneratorAdapter.Destroy; begin FreeAndNil(FFieldDefs); inherited; end; procedure TCustomDataGeneratorAdapter.FieldDefChanged(Sender: TObject); var LActive: Boolean; begin LActive := Active; if LActive then Active := False; Self.AddFields; if Self.List <> nil then Self.GenerateExistingRecords(Self.List); Active := LActive; end; function TCustomDataGeneratorAdapter.SupportsNestedFields: Boolean; begin Result := False; end; procedure TCustomDataGeneratorAdapter.SetActive(Value: Boolean); begin if Value and (List = nil) then begin SetList(TObjectList<TGeneratorRecord>.Create); // Owns records GenerateExistingRecords(List); end; inherited; end; procedure TCustomDataGeneratorAdapter.SetFieldDefs(Value: TGeneratorFieldDefs); begin FFieldDefs.Assign(Value); end; procedure TCustomDataGeneratorAdapter.SetRecordCount(const Value: Integer); var LActive: Boolean; begin if Value <> FRecordCount then begin FRecordCount := Value; LActive := Active; if LActive then Active := False; if FRecordCount > 0 then if ItemIndex >= 0 then ItemIndex := Min(FRecordCount - 1, ItemIndex) else ItemIndex := 0 else ItemIndex := 0; if Self.List <> nil then GenerateExistingRecords(Self.List); Active := LActive; end; end; function TCustomDataGeneratorAdapter.GetFieldDefsClass: TGeneratorBindFieldDefsClass; begin Result := TGeneratorFieldDefs; end; procedure TCustomDataGeneratorAdapter.GetMemberNames(AList: TStrings); var LFieldDef: TGeneratorFieldDef; begin for LFieldDef in FFieldDefs do AList.AddObject(LFieldDef.Name, LFieldDef); end; procedure TCustomDataGeneratorAdapter.InitFieldDefs; begin end; constructor TTypedCustomFormatObject<T>.Create; begin end; procedure TCustomDataGeneratorAdapter.CreateCustomFormatExpression<T>(const ACustomFormat: string; out AExpression: TBindingExpression; out ACustomFormatObject: TCustomFormatObject); const sGenerator = '_G'; sGeneratorValue = '_G.V'; var LExpression: TBindingExpression; LScope: IScope; LCustomFormatObject: TTypedCustomFormatObject<T>; begin LExpression := nil; LCustomFormatObject := TTypedCustomFormatObject<T>.Create; try LScope := TBindings.CreateAssociationScope( TArray<TBindingAssociation>.Create( TBindingAssociation.Create(LCustomFormatObject, sGenerator))); LExpression := TBindings.CreateExpression( LScope, Format(ACustomFormat, [sGeneratorValue]), TBindingEventRec.Create(TBindingEvalErrorEvent(nil) (*DoOnEvalError*))); except LExpression.Free; LExpression := nil; LCustomFormatObject.Free; LCustomFormatObject := nil; // Ignore and don't provide an expression end; AExpression := LExpression; ACustomFormatObject := LCustomFormatObject; end; procedure TCustomDataGeneratorAdapter.GenerateExistingRecords(AList: TList<TGeneratorRecord>); procedure InitExistingRecord(ARecord: TGeneratorRecord; AGenerators: TList<TValueGenerator>; AExpressions: TList<TBindingExpression>; AExpressionObjects: TList<TCustomFormatObject>; AGetDefaultValue: TFunc<Integer, TValue>); var I: Integer; LFieldDef: TGeneratorFieldDef; LGenerator: TValueGenerator; LValue: TValue; LExpression: TBindingExpression; LObject: TCustomFormatObject; LIValue: IValue; LFree: Boolean; begin for I := 0 to FieldDefs.Count - 1 do begin LFree := False; LFieldDef := FieldDefs[I]; LGenerator := AGenerators[I]; LExpression := AExpressions[I]; LObject := AExpressionObjects[I]; LValue := TValue.Empty; if LGenerator <> nil then begin LValue := LGenerator.GetValue(LFree); if LFree then Assert(LValue.IsObject); end else begin // LValue := ADefaultValues[I]; LValue := AGetDefaultValue(I); LFree := LValue.IsObject and (LValue.AsObject <> nil); end; if LExpression <> nil then begin Assert(LObject <> nil); LObject.SetTValue(LValue); LIValue := LExpression.Evaluate; LValue := LIValue.GetValue; end; ARecord.FDictionary.Add(LFieldDef.Name, LValue); if LFree and LValue.IsObject then ARecord.FFreeObjects.Add(LValue.AsObject); end; end; function Validate(AExpression: TBindingExpression; AObject: TCustomFormatObject; AValue: TValue): Boolean; begin Result := True; try Assert(AObject <> nil); AObject.SetTValue(AValue); AExpression.Evaluate; except Result := False; end; end; var I: Integer; LRecordCount: integer; LRecord: TGeneratorRecord; LFieldDef: TGeneratorFieldDef; LGenerators: TList<TValueGenerator>; LGenerator: TValueGenerator; LGeneratorRecord: TValueGeneratorDescription; LCustomFormatExpressions: TList<TBindingExpression>; LCustomFormatExpression: TBindingExpression; LExpressionObjects: TList<TCustomFormatObject>; LExpressionObject: TCustomFormatObject; LDefaultValues: TList<TValue>; LDefaultValue: TValue; LMinNoRepeat: Integer; begin LExpressionObjects := nil; LCustomFormatExpressions := nil; LDefaultValues := nil; try AList.Clear; LRecordCount := RecordCount; if LRecordCount <> 0 then begin LGenerators := TObjectList<TValueGenerator>.Create; // Owns objects LExpressionObjects := TObjectList<TCustomFormatObject>.Create; LCustomFormatExpressions := TObjectList<TBindingExpression>.Create; LDefaultValues := TList<TValue>.Create; try for I := 0 to FieldDefs.Count - 1 do begin LFieldDef := FieldDefs[I]; LGenerator := nil; LCustomFormatExpression := nil; LExpressionObject := nil; if LFieldDef.Generator <> '' then if FindRegisteredValueGenerator(LFieldDef.Generator, LFieldDef.FFieldType, LGeneratorRecord) then LGenerator := LGeneratorRecord.ClassType.Create(LFieldDef); // LGenerator may be nil LGenerators.Add(LGenerator); case LFieldDef.FieldType of ftString: begin if LFieldDef.CustomFormat <> '' then Self.CreateCustomFormatExpression<string>(LFieldDef.CustomFormat, LCustomFormatExpression, LExpressionObject); LDefaultValue := TValue.Empty.AsType<string>; end; ftInteger: begin if LFieldDef.CustomFormat <> '' then Self.CreateCustomFormatExpression<integer>(LFieldDef.CustomFormat, LCustomFormatExpression, LExpressionObject); LDefaultValue := TValue.Empty.AsType<integer>; end; ftSingle: begin if LFieldDef.CustomFormat <> '' then Self.CreateCustomFormatExpression<single>(LFieldDef.CustomFormat, LCustomFormatExpression, LExpressionObject); LDefaultValue := TValue.Empty.AsType<single>; end; ftBoolean: begin if LFieldDef.CustomFormat <> '' then Self.CreateCustomFormatExpression<Boolean>(LFieldDef.CustomFormat, LCustomFormatExpression, LExpressionObject); LDefaultValue := TValue.Empty.AsType<Boolean>; end; ftBitmap, ftTStrings: begin if LFieldDef.CustomFormat <> '' then Self.CreateCustomFormatExpression<TObject>(LFieldDef.CustomFormat, LCustomFormatExpression, LExpressionObject); LDefaultValue := TValue.Empty.AsType<TObject>; end; ftUInteger: begin if LFieldDef.CustomFormat <> '' then Self.CreateCustomFormatExpression<uint32>(LFieldDef.CustomFormat, LCustomFormatExpression, LExpressionObject); LDefaultValue := TValue.Empty.AsType<uint32>; end; ftCurrency: begin if LFieldDef.CustomFormat <> '' then Self.CreateCustomFormatExpression<currency>(LFieldDef.CustomFormat, LCustomFormatExpression, LExpressionObject); LDefaultValue := TValue.Empty.AsType<currency>; end; ftDateTime: begin if LFieldDef.CustomFormat <> '' then Self.CreateCustomFormatExpression<TDateTime>(LFieldDef.CustomFormat, LCustomFormatExpression, LExpressionObject); LDefaultValue := TValue.Empty.AsType<TDateTime>; end; ftTime: begin if LFieldDef.CustomFormat <> '' then Self.CreateCustomFormatExpression<TTime>(LFieldDef.CustomFormat, LCustomFormatExpression, LExpressionObject); LDefaultValue := TValue.Empty.AsType<TDate>; end; ftDate: begin if LFieldDef.CustomFormat <> '' then Self.CreateCustomFormatExpression<TDate>(LFieldDef.CustomFormat, LCustomFormatExpression, LExpressionObject); LDefaultValue := TValue.Empty.AsType<TTime>; end; else LDefaultValue := TValue.Empty; Assert(False); end; if LCustomFormatExpression <> nil then if not Validate(LCustomFormatExpression, LExpressionObject, LDefaultValue) then FreeAndNil(LCustomFormatExpression); LCustomFormatExpressions.Add(LCustomFormatExpression); LExpressionObjects.Add(LExpressionObject); LDefaultValues.Add(LDefaultValue); end; if LRecordCount < 0 then begin LMinNoRepeat := MaxInt; for LGenerator in LGenerators do begin if LGenerator <> nil then if not (TGeneratorOption.optRepeat in LGenerator.Options) then LMinNoRepeat := Min(LMinNoRepeat, LGenerator.RecordCount); end; // If any can't repeat then constrain record count to number of unique records if LMinNoRepeat <> MaxInt then LRecordCount := LMinNoRepeat; end; if LRecordCount < 0 then LRecordCount := 200; if csDesigning in ComponentState then // Make sure we don't lock up the ide displaying a large number of records LRecordCount := Min(1000, LRecordCount); for I := 0 to LRecordCount - 1 do begin LRecord := TGeneratorRecord.Create; try for LGenerator in LGenerators do if LGenerator <> nil then if I = 0 then LGenerator.FirstRecord else LGenerator.NextRecord; InitExistingRecord(LRecord, LGenerators, LCustomFormatExpressions, LExpressionObjects, function(I: Integer): TValue begin case FieldDefs[I].FFieldType of ftBitmap: Result := LDefaultValues[I]; ftTStrings: Result := TStringList.Create; else Result := LDefaultValues[I]; end; end); AList.Add(LRecord); except LRecord.Free; end; end; finally LGenerators.Free; end; end; finally LCustomFormatExpressions.Free; LExpressionObjects.Free; LDefaultValues.Free; end; end; class function TBindSourceAdapter.CreateRttiFieldField<T>(AProperty: TRttiField; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; AMemberType: TScopeMemberType; LDummy: TDummy<T>): TBindSourceAdapterField; begin Result := TBindSourceAdapterReadWriteField<T>.Create(ABindSourceAdapter, AProperty.Name, TBindSourceAdapterFieldType.Create(AProperty.FieldType.Name, AProperty.FieldType.TypeKind), AGetMemberObject, TFieldValueReader<T>.Create, TFieldValueWriter<T>.Create, AMemberType) end; class function TBindSourceAdapter.CreateRttiObjectFieldField<T>(AProperty: TRttiField; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; AMemberType: TScopeMemberType; LDummy: TDummy<T>): TBindSourceAdapterField; begin Result := TBindSourceAdapterReadWriteObjectField<T>.Create(ABindSourceAdapter, AProperty.Name, TBindSourceAdapterFieldType.Create(AProperty.FieldType.Name, AProperty.FieldType.TypeKind), AGetMemberObject, TFieldValueReader<T>.Create, TFieldValueWriter<T>.Create, AMemberType) end; class procedure TBindSourceAdapter.AddFieldsToList(AType: TRttiType; ABindSourceAdapter: TBindSourceAdapter; AFieldsList: TList<TBindSourceAdapterField>; const AGetMemberObject: IGetMemberObject); const sTStrings = 'TStrings'; sTPersistent = 'TPersistent'; var LType: TRttiType; LFields: TArray<TRttiField>; LField: TRttiField; LCollectionEditorField: TBindSourceAdapterField; LTypeName: string; LTypeInfo: PTypeInfo; LInstance: TRttiInstanceType; LAncestor: string; begin LType := AType; LFields := LType.GetFields; for LField in LFields do begin if LField.FieldType = nil then continue; LCollectionEditorField := nil; case LField.Visibility of TMemberVisibility.mvPublic, TMemberVisibility.mvPublished: begin LTypeName := LField.FieldType.Name; LTypeInfo := LField.FieldType.Handle; case LField.FieldType.TypeKind of tkEnumeration: if SameText(LTypeName, 'boolean') or SameText(LTypeName, 'bool') then // 'bool' for C++ LCollectionEditorField := CreateRttiFieldField<Boolean>(LField, ABindSourceAdapter, AGetMemberObject, mtBoolean); tkInteger: case System.TypInfo.GetTypeData(LField.FieldType.Handle).OrdType of otSByte: // Int8 LCollectionEditorField := CreateRttiFieldField<Int8>(LField, ABindSourceAdapter, AGetMemberObject, mtInteger); otSWord: // Int16 LCollectionEditorField := CreateRttiFieldField<Int16>(LField, ABindSourceAdapter, AGetMemberObject, mtInteger); otSLong: // Int32 LCollectionEditorField := CreateRttiFieldField<Int32>(LField, ABindSourceAdapter, AGetMemberObject, mtInteger); otUByte: // UInt8 LCollectionEditorField := CreateRttiFieldField<UInt8>(LField, ABindSourceAdapter, AGetMemberObject, mtUInteger); otUWord: // UInt16 LCollectionEditorField := CreateRttiFieldField<UInt16>(LField, ABindSourceAdapter, AGetMemberObject, mtUInteger); otULong: // UInt32 LCollectionEditorField := CreateRttiFieldField<UInt32>(LField, ABindSourceAdapter, AGetMemberObject, mtUInteger); else LCollectionEditorField := CreateRttiFieldField<Integer>(LField, ABindSourceAdapter, AGetMemberObject, mtInteger); end; tkWChar: LCollectionEditorField := CreateRttiFieldField<char>(LField, ABindSourceAdapter, AGetMemberObject, mtChar); tkUString: LCollectionEditorField := CreateRttiFieldField<string>(LField, ABindSourceAdapter, AGetMemberObject, mtText); {$IFNDEF NEXTGEN} tkChar: LCollectionEditorField := CreateRttiFieldField<ansichar>(LField, ABindSourceAdapter, AGetMemberObject, mtChar); tkString: LCollectionEditorField := CreateRttiFieldField<ShortString>(LField, ABindSourceAdapter, AGetMemberObject, mtText); tkLString: LCollectionEditorField := CreateRttiFieldField<AnsiString>(LField, ABindSourceAdapter, AGetMemberObject, mtText); {$ENDIF} tkFloat: begin case LTypeInfo.TypeData^.FloatType of System.TypInfo.ftSingle: LCollectionEditorField := CreateRttiFieldField<single>(LField, ABindSourceAdapter, AGetMemberObject, mtFloat); System.TypInfo.ftDouble: begin if LTypeinfo = System.TypeInfo(TDate) then LCollectionEditorField := CreateRttiFieldField<TDate>(LField, ABindSourceAdapter, AGetMemberObject, mtDate) else if LTypeinfo = System.TypeInfo(TTime) then LCollectionEditorField := CreateRttiFieldField<TTime>(LField, ABindSourceAdapter, AGetMemberObject, mtTime) else if LTypeinfo = System.TypeInfo(TDateTime) then LCollectionEditorField := CreateRttiFieldField<TDateTime>(LField, ABindSourceAdapter, AGetMemberObject, mtDateTime) else LCollectionEditorField := CreateRttiFieldField<double>(LField, ABindSourceAdapter, AGetMemberObject, mtFloat); end; ftExtended: LCollectionEditorField := CreateRttiFieldField<Extended>(LField, ABindSourceAdapter, AGetMemberObject, mtFloat); ftCurr: LCollectionEditorField := CreateRttiFieldField<currency>(LField, ABindSourceAdapter, AGetMemberObject, mtCurrency); // ftComp: // Not supported else Assert(False); LCollectionEditorField := CreateRttiFieldField<Extended>(LField, ABindSourceAdapter, AGetMemberObject, mtFloat); end; end; tkInt64: if LTypeInfo.TypeData.MinInt64Value > LTypeInfo.TypeData.MaxInt64Value then LCollectionEditorField := CreateRttiFieldField<UInt64>(LField, ABindSourceAdapter, AGetMemberObject, mtUInteger) else LCollectionEditorField := CreateRttiFieldField<Int64>(LField, ABindSourceAdapter, AGetMemberObject, mtInteger); tkClass: begin if LField.FieldType.IsInstance then begin LInstance := LField.FieldType.AsInstance; while LInstance <> nil do begin LAncestor := LInstance.Name; if LAncestor = sTStrings then break; if LAncestor = sTPersistent then break; LInstance := LInstance.BaseType; end; end; if LAncestor = sTStrings then LCollectionEditorField := CreateRttiObjectFieldField<TObject>(LField, ABindSourceAdapter, AGetMemberObject, mtMemo) else if LAncestor = sTPersistent then LCollectionEditorField := CreateRttiObjectFieldField<TObject>(LField, ABindSourceAdapter, AGetMemberObject, mtBitmap) else LCollectionEditorField := CreateRttiObjectFieldField<TObject>(LField, ABindSourceAdapter, AGetMemberObject, mtObject) end; end; if LCollectionEditorField <> nil then begin LCollectionEditorField.FGetMemberObject := AGetMemberObject; AFieldsList.Add(LCollectionEditorField); end; end; end; end; end; class function TBindSourceAdapter.CreateRttiPropertyField<T>(AProperty: TRttiProperty; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; AMemberType: TScopeMemberType; LDummy: TDummy<T>): TBindSourceAdapterField; begin Result := nil; if AProperty.IsReadable then if AProperty.IsWritable then Result := TBindSourceAdapterReadWriteField<T>.Create(ABindSourceAdapter, AProperty.Name, TBindSourceAdapterFieldType.Create(AProperty.PropertyType.Name, AProperty.PropertyType.TypeKind), AGetMemberObject, TPropertyValueReader<T>.Create, TPropertyValueWriter<T>.Create, AMemberType) else Result := TBindSourceAdapterReadField<T>.Create(ABindSourceAdapter, AProperty.Name, TBindSourceAdapterFieldType.Create(AProperty.PropertyType.Name, AProperty.PropertyType.TypeKind), AGetMemberObject, TPropertyValueReader<T>.Create, AMemberType); end; class function TBindSourceAdapter.CreateRttiObjectPropertyField<T>(AProperty: TRttiProperty; ABindSourceAdapter: TBindSourceAdapter; const AGetMemberObject: IGetMemberObject; AMemberType: TScopeMemberType; LDummy: TDummy<T>): TBindSourceAdapterField; begin Result := nil; if AProperty.IsReadable then if AProperty.IsWritable then Result := TBindSourceAdapterReadWriteObjectField<T>.Create(ABindSourceAdapter, AProperty.Name, TBindSourceAdapterFieldType.Create(AProperty.PropertyType.Name, AProperty.PropertyType.TypeKind), AGetMemberObject, TPropertyValueReader<T>.Create, TPropertyValueWriter<T>.Create, AMemberType) else Result := TBindSourceAdapterReadObjectField<T>.Create(ABindSourceAdapter, AProperty.Name, TBindSourceAdapterFieldType.Create(AProperty.PropertyType.Name, AProperty.PropertyType.TypeKind), AGetMemberObject, TPropertyValueReader<T>.Create, AMemberType); end; class procedure TBindSourceAdapter.AddPropertiesToList(AType: TRttiType; ABindSourceAdapter: TBindSourceAdapter; AFieldsList: TList<TBindSourceAdapterField>; const AGetMemberObject: IGetMemberObject); const sTStrings = 'TStrings'; sTPersistent = 'TPersistent'; var LType: TRttiType; LProperties: TArray<TRttiProperty>; LProperty: TRttiProperty; LCollectionEditorField: TBindSourceAdapterField; LTypeInfo: PTypeInfo; LTypeName: string; LTypeData: PTypeData; LInstance: TRttiInstanceType; LAncestor: string; begin LType := AType; LProperties := LType.GetProperties; for LProperty in LProperties do begin LCollectionEditorField := nil; LTypeInfo := LProperty.PropertyType.Handle; if LTypeInfo = nil then continue; LTypeName := LProperty.PropertyType.Name; LTypeData := System.TypInfo.GetTypeData(LTypeInfo); case LProperty.Visibility of TMemberVisibility.mvPublic, TMemberVisibility.mvPublished: begin {$IFDEF NEXTGEN} if (LProperty.Name = 'Disposed') or (LProperty.Name = 'RefCount') then continue; {$ENDIF} case LProperty.PropertyType.TypeKind of tkEnumeration: if SameText(LTypeName, 'boolean') or SameText(LTypeName, 'bool') then // 'bool' for C++ LCollectionEditorField := CreateRttiPropertyField<Boolean>(LProperty, ABindSourceAdapter, AGetMemberObject, mtBoolean); tkInteger: begin case LTypeData.OrdType of otSByte: // Int8 LCollectionEditorField := CreateRttiPropertyField<Int8>(LProperty, ABindSourceAdapter, AGetMemberObject, mtInteger); otSWord: // Int16 LCollectionEditorField := CreateRttiPropertyField<Int16>(LProperty, ABindSourceAdapter, AGetMemberObject, mtInteger); otSLong: // Int32 LCollectionEditorField := CreateRttiPropertyField<Int32>(LProperty, ABindSourceAdapter, AGetMemberObject, mtInteger); otUByte: // UInt8 LCollectionEditorField := CreateRttiPropertyField<UInt8>(LProperty, ABindSourceAdapter, AGetMemberObject, mtUInteger); otUWord: // UInt16 LCollectionEditorField := CreateRttiPropertyField<UInt16>(LProperty, ABindSourceAdapter, AGetMemberObject, mtUInteger); otULong: // UInt32 LCollectionEditorField := CreateRttiPropertyField<UInt32>(LProperty, ABindSourceAdapter, AGetMemberObject, mtUInteger); else LCollectionEditorField := CreateRttiPropertyField<Integer>(LProperty, ABindSourceAdapter, AGetMemberObject, mtInteger); end end; tkWChar: LCollectionEditorField := CreateRttiPropertyField<Char>(LProperty, ABindSourceAdapter, AGetMemberObject, mtChar); tkUString: LCollectionEditorField := CreateRttiPropertyField<string>(LProperty, ABindSourceAdapter, AGetMemberObject, mtText); {$IFNDEF NEXTGEN} tkChar: LCollectionEditorField := CreateRttiPropertyField<AnsiChar>(LProperty, ABindSourceAdapter, AGetMemberObject, mtChar); tkString: LCollectionEditorField := CreateRttiPropertyField<ShortString>(LProperty, ABindSourceAdapter, AGetMemberObject, mtText); tkLString: LCollectionEditorField := CreateRttiPropertyField<AnsiString>(LProperty, ABindSourceAdapter, AGetMemberObject, mtText); {$ENDIF} tkFloat: case LTypeData^.FloatType of System.TypInfo.ftSingle: LCollectionEditorField := CreateRttiPropertyField<single>(LProperty, ABindSourceAdapter, AGetMemberObject, mtFloat); System.TypInfo.ftDouble: begin if LTypeinfo = System.TypeInfo(TDate) then LCollectionEditorField := CreateRttiPropertyField<TDate>(LProperty, ABindSourceAdapter, AGetMemberObject, mtDate) else if LTypeinfo = System.TypeInfo(TTime) then LCollectionEditorField := CreateRttiPropertyField<TTime>(LProperty, ABindSourceAdapter, AGetMemberObject, mtTime) else if LTypeinfo = System.TypeInfo(TDateTime) then LCollectionEditorField := CreateRttiPropertyField<TDateTime>(LProperty, ABindSourceAdapter, AGetMemberObject, mtDateTime) else LCollectionEditorField := CreateRttiPropertyField<double>(LProperty, ABindSourceAdapter, AGetMemberObject, mtFloat); end; ftExtended: LCollectionEditorField := CreateRttiPropertyField<Extended>(LProperty, ABindSourceAdapter, AGetMemberObject, mtFloat); ftCurr: LCollectionEditorField := CreateRttiPropertyField<currency>(LProperty, ABindSourceAdapter, AGetMemberObject, mtCurrency); // ftComp: // Not supported else Assert(False); LCollectionEditorField := CreateRttiPropertyField<Extended>(LProperty, ABindSourceAdapter, AGetMemberObject, mtFloat); end; tkInt64: if LTypeData.MinInt64Value > LTypeData.MaxInt64Value then LCollectionEditorField := CreateRttiPropertyField<UInt64>(LProperty, ABindSourceAdapter, AGetMemberObject, mtUInteger) else LCollectionEditorField := CreateRttiPropertyField<Int64>(LProperty, ABindSourceAdapter, AGetMemberObject, mtInteger); tkClass: begin if LProperty.PropertyType.IsInstance then begin LInstance := LProperty.PropertyType.AsInstance; while LInstance <> nil do begin LAncestor := LInstance.Name; if LAncestor = sTStrings then break; if LAncestor = sTPersistent then break; LInstance := LInstance.BaseType; end; end; if LAncestor = sTStrings then LCollectionEditorField := CreateRttiObjectPropertyField<TObject>(LProperty, ABindSourceAdapter, AGetMemberObject, mtMemo) else if LAncestor = sTPersistent then LCollectionEditorField := CreateRttiObjectPropertyField<TObject>(LProperty, ABindSourceAdapter, AGetMemberObject, mtBitmap) else LCollectionEditorField := CreateRttiObjectPropertyField<TObject>(LProperty, ABindSourceAdapter, AGetMemberObject, mtObject) end; end; if LCollectionEditorField <> nil then begin LCollectionEditorField.FGetMemberObject := AGetMemberObject; AFieldsList.Add(LCollectionEditorField); end; end; end; end; end; procedure TListBindSourceAdapter<T>.AddFields; var LType: TRttiType; LGetMemberObject: IGetMemberObject; begin LType := GetObjectType; LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(Self); AddFieldsToList(LType, Self, Self.Fields, LGetMemberObject); AddPropertiesToList(LType, Self, Self.Fields, LGetMemberObject); end; { TBindSourceAdapterReadWriteField<T> } procedure TBindSourceAdapterReadWriteField<T>.ClearBuffer; begin // end; constructor TBindSourceAdapterReadWriteField<T>.Create(AOwner: TBindSourceAdapter; const AMemberName: string; AType: TBindSourceAdapterFieldType; const AGetMemberObject: IGetMemberObject; const AReader: TValueReader<T>; const AWriter: TValueWriter<T>; AMemberType: TScopeMemberType); begin inherited Create(AOwner, AMemberName, AType, AGetMemberObject, AReader, AMemberType); FValueWriter := AWriter; AWriter.FField := Self; end; destructor TBindSourceAdapterReadWriteField<T>.Destroy; begin FValueWriter.Free; inherited; end; function TBindSourceAdapterReadWriteField<T>.GetSetter(var AGetter: string): Boolean; begin AGetter := sMemberName; Result := True; end; function TBindSourceAdapterReadWriteField<T>.GetAutoPost: Boolean; begin Result := FAutoPost; end; function TBindSourceAdapterReadWriteField<T>.GetValue: T; begin if FBuffered and (Owner.FItemIndexOffset = 0) then Result := FBuffer else Result := inherited; end; function TBindSourceAdapterReadWriteField<T>.IsBuffered: Boolean; begin Result := FBuffered = True; end; procedure TBindSourceAdapterReadWriteField<T>.SetTValue(const AValue: TValue); begin Value := AValue.AsType<T>; end; procedure TBindSourceAdapterReadWriteField<T>.SetAutoPost( const Value: Boolean); begin FAutoPost := Value; end; procedure TBindSourceAdapterReadWriteField<T>.SetValue(const Value: T); begin if (Owner <> nil) and not (Owner.State in seEditModes) then if Owner.AutoEdit then AutoEditField else BindSourceAdapterError(SNotEditing, Self.Owner); FBuffer := Value; FBuffered := True; if FAutoPost or Owner.AutoPost then AutoPostField else RecordChanged; end; procedure TBindSourceAdapterReadWriteField<T>.Post; begin if FBuffered then begin FBuffered := False; try FValueWriter.SetValue(FBuffer); finally ClearBuffer; end; end; end; procedure TBindSourceAdapterReadWriteField<T>.Cancel; begin FBuffered := False; RecordChanged; end; { TScopeAdapteObjectField } constructor TBindSourceAdapterReadObjectField.Create(AOwner: TBindSourceAdapter; const AMemberName: string; AType: TBindSourceAdapterFieldType; const AGetMemberObject: IGetMemberObject; const AReader: TValueReader<TObject>; AMemberType: TScopeMemberType); begin inherited; FFields := TObjectList<TBindSourceAdapterField>.Create; // Owned end; destructor TBindSourceAdapterReadObjectField.Destroy; begin FFields.Free; inherited; end; function TBindSourceAdapterReadObjectField.FindField(const AMemberName: string): TBindSourceAdapterField; var LField: TBindSourceAdapterField; LFieldName, LPath: string; LPos: Integer; begin CheckAddFields; LPath := AMemberName; LPos := LPath.IndexOf('.') + 1; if LPos > 0 then begin LFieldName := LPath.Substring(0, LPos-1); LPath := LPath.Remove(0, LPos); end else begin LFieldName := LPath; LPath := ''; end; for LField in FFields do begin if SameText(LField.MemberName, LFieldName) then begin if LPath <> '' then Exit(LField.FindField(LPath)); Exit(LField); end; end; Result := nil; end; function TBindSourceAdapterReadObjectField.GetIsObject: Boolean; begin Result := True; end; procedure TBindSourceAdapterReadObjectField.CheckAddFields; var LCtxt: TRttiContext; LType: TRttiType; LObject: TObject; begin LObject := GetValue; if (LObject <> nil) and (not FHaveFields) then begin FHaveFields := True; LType := LCtxt.GetType(LObject.ClassType); TBindSourceAdapter.AddFieldsToList(LType, FOwner, FFields, TBindSourceAdapteObjectFieldGetMemberObject.Create(Self)); TBindSourceAdapter.AddPropertiesToList(LType, FOwner, FFields, TBindSourceAdapteObjectFieldGetMemberObject.Create(Self)); end; end; { TBindSourceAdapterObjectFieldCustomScope } function TBindSourceAdapterObjectFieldCustomScope.DoLookup( const Name: String): IInterface; var LScope: TBindSourceAdapterReadObjectField; begin Result := nil; if MappedObject is TBindSourceAdapterReadObjectField then begin LScope := TBindSourceAdapterReadObjectField(MappedObject); if LScope.FindField(Name) <> nil then Result := TCustomWrapper.Create(LScope, LScope.ClassType, Name, cwtProperty, function (ParentObject: TObject; const MemberName: String; Args: TArray<TValue>): TValue begin Result := TBindSourceAdapterReadObjectField(ParentObject).FindField(MemberName); end); end; end; { TBindSourceAdapterGetMemberObject } constructor TBindSourceAdapterGetMemberObject.Create( ACollectionEditor: TBindSourceAdapter); begin FBindSourceAdapter := ACollectionEditor; end; function TBindSourceAdapterGetMemberObject.GetMemberObject: TObject; begin Result := FBindSourceAdapter.Current; end; { TScopeAdapteObjectFieldGetMemberObject } constructor TBindSourceAdapteObjectFieldGetMemberObject.Create( AObject: TObject); begin FObject := AObject; end; function TBindSourceAdapteObjectFieldGetMemberObject.GetMemberObject: TObject; begin Result := nil; if FObject is TBindSourceAdapterReadObjectField then begin Result := TBindSourceAdapterReadObjectField(FObject).GetValue; end else Assert(False); end; { TFieldValueReader<T> } function TFieldValueReader<T>.GetValue: T; var LObject: TObject; LCtxt: TRttiContext; LRttiType: TRttiType; LRttiField: TRttiField; begin LObject := FField.GetMemberObject; if LObject <> nil then begin LRttiType := LCtxt.GetType(LObject.ClassType); LRttiField := LRttiType.GetField(FField.MemberName); if LRttiField <> nil then begin Result := LRttiField.GetValue(LObject).AsType<T>; end else Result := TValue.Empty.AsType<T>; end else Result := TValue.Empty.AsType<T>; end; { TBindFieldDefValueReader<T> } function TBindFieldDefValueReader<T>.GetValue: T; var LObject: TObject; LDictionary: TDictionary<string, TValue>; LValue: TValue; S: string; begin LObject := FField.GetMemberObject; if LObject <> nil then begin LDictionary := (LObject as TGeneratorRecord).FDictionary; if LDictionary.TryGetValue(FField.MemberName, LValue) then begin //if not LValue.IsEmpty then try Result := LValue.AsType<T>() except on E: Exception do begin S := E.Message; raise; end; end; end else begin Assert(False); Result := TValue.Empty.AsType<T>; end; end else Result := TValue.Empty.AsType<T>; end; { TBindFieldDefObjectValueReader<T> } function TBindFieldDefObjectValueReader<T>.GetValue: T; begin Result := inherited GetValue; end; { TFieldValueWriter } procedure TFieldValueWriter<T>.SetValue(const AValue: T); var LObject: TObject; LCtxt: TRttiContext; LRttiType: TRttiType; LRttiField: TRttiField; begin LObject := FField.GetMemberObject; if LObject <> nil then begin LRttiType := LCtxt.GetType(LObject.ClassType); LRttiField := LRttiType.GetField(FField.MemberName); if LRttiField <> nil then begin LRttiField.SetValue(LObject, TValue.From<T>(AValue)); end; end; end; { TPropertyValueReader<T> } function TPropertyValueReader<T>.GetValue: T; var LObject: TObject; LCtxt: TRttiContext; LRttiType: TRttiType; LRttiField: TRttiProperty; begin LObject := FField.GetMemberObject; if LObject <> nil then begin LRttiType := LCtxt.GetType(LObject.ClassType); LRttiField := LRttiType.GetProperty(FField.MemberName); if LRttiField <> nil then begin Result := LRttiField.GetValue(LObject).AsType<T>; end else Result := TValue.Empty.AsType<T>; end else Result := TValue.Empty.AsType<T>; end; { TPropertyValueWriter } procedure TPropertyValueWriter<T>.SetValue(const AValue: T); var LObject: TObject; LCtxt: TRttiContext; LRttiType: TRttiType; LRttiField: TRttiProperty; begin LObject := FField.GetMemberObject; if LObject <> nil then begin LRttiType := LCtxt.GetType(LObject.ClassType); LRttiField := LRttiType.GetProperty(FField.MemberName); if LRttiField <> nil then begin LRttiField.SetValue(LObject, TValue.From<T>(AValue)); //RecordChanged; end; end; end; { TBindSourceAdapterReadField<T> } constructor TBindSourceAdapterReadField<T>.Create(AOwner: TBindSourceAdapter; const AMemberName: string; AType: TBindSourceAdapterFieldType; const AGetMemberObject: IGetMemberObject; const AReader: TValueReader<T>; AMemberType: TScopeMemberType); begin inherited Create(AOwner, AMemberName, AGetMemberObject); FRttiType := AType; FValueReader := AReader; AReader.FField := Self; FMemberType := AMemberType; end; destructor TBindSourceAdapterReadField<T>.Destroy; begin FValueReader.Free; inherited; end; function TBindSourceAdapterReadField<T>.GetGetter(var AGetter: string): Boolean; begin AGetter := sMemberName; Result := True; end; function TBindSourceAdapterReadField<T>.GetMemberType(var AType: TScopeMemberType): Boolean; begin Result := True; AType := FMemberType; end; function TBindSourceAdapterReadField<T>.GetTValue: TValue; begin Result := TValue.From<T>(Value); end; function TBindSourceAdapterReadField<T>.GetValue: T; begin Result := FValueReader.GetValue; end; { TBindSourceAdapterFieldType } constructor TBindSourceAdapterFieldType.Create(const ATypeName: string; ATypeKind: TTypeKind); begin FTypeName := ATypeName; FTypeKind := ATypeKind; end; { TBindFieldDef } destructor TBindFieldDef.Destroy; var LCollection: TBindFieldDefs; begin if Collection is TBindFieldDefs then begin LCollection := TBindFieldDefs(Collection); if (LCollection.FDictionary <> nil) and LCollection.FDictionary.ContainsKey(MakeKey(FName)) then LCollection.FDictionary.Remove(MakeKey(FName)); end; inherited; end; function TBindFieldDef.GetDisplayName: string; begin Result := FName; end; procedure TBindFieldDef.SetDisplayName(const Value: string); var LCollection: TBindFieldDefs; begin LCollection := nil; if (Value <> '') and (AnsiCompareText(Value, FName) <> 0) and (Collection is TBindFieldDefs) and (TBindFieldDefs(Collection).IndexOf(Value) >= 0) then raise TBindCompException.CreateFmt(SDuplicateName, [Value, Collection.ClassName]); if Collection is TBindFieldDefs then begin LCollection := TBindFieldDefs(Collection); LCollection.DoRenamingFieldDef(Self, FName, Value); if FName <> '' then LCollection.FDictionary.Remove(MakeKey(FName)); if Value <> '' then LCollection.FDictionary.Add(MakeKey(Value), Self); end; FName := Value; //FNameHashValue := TBindFieldDef.HashName(FName); inherited SetDisplayName(Value); if LCollection <> nil then begin LCollection.DoRenameFieldDef(Self, FName, Value); end; end; { TBindFieldDefsWithChildren } destructor TBindFieldDefWithChildren.Destroy; begin inherited Destroy; FChildDefs.Free; end; function TBindFieldDefWithChildren.GetChildDefs<T>: T; begin if FChildDefs = nil then FChildDefs := GetChildDefsClass.Create(Self); Result := FChildDefs as T; end; procedure TBindFieldDefWithChildren.SetChildDefs(Value: TBindFieldDefs); begin FChildDefs.Assign(Value); end; function TBindFieldDefWithChildren.HasChildDefs: Boolean; begin Result := (FChildDefs <> nil) and (FChildDefs.Count > 0); end; function TBindFieldDefWithChildren.AddChild<T>: T; begin Result := FChildDefs.AddFieldDef<T>; end; function TBindFieldDefWithChildren.GetParentDef<T>: T; begin Result := TBindFieldDefs(Collection).GetParentDef<T>; end; { TGeneratorBindFieldDef } constructor TGeneratorFieldDef.Create(Collection: TCollection); begin inherited; FOptions := [optRepeat, optShuffle]; // Default FFieldType := ftString; // Default end; constructor TGeneratorFieldDef.Create(Owner: TBindFieldDefs; const Name: string; FieldNo: Integer); begin FName := Name; Create(Owner); FFieldNo := FieldNo; end; function TGeneratorFieldDef.GetFieldNo: Integer; begin if FFieldNo > 0 then Result := FFieldNo else Result := Index + 1; end; function TGeneratorFieldDef.GetMemberType: TScopeMemberType; begin case FFieldType of ftString: Result := mtText; ftInteger: Result := mtInteger; ftUInteger: Result := mtUInteger; ftSingle: Result := mtFloat; ftBoolean: Result := mtBoolean; ftBitmap: Result := mtBitmap; ftTStrings: Result := mtMemo; ftCurrency: Result := mtCurrency; ftDateTime: Result := mtDateTime; ftTime: Result := mtTime; ftDate: Result := mtDate; ftChar: Result := mtChar; else Assert(False); Result := mtUnknown; end; end; procedure TGeneratorFieldDef.SetFieldType(Value: TGeneratorFieldType); var LRecord: TValueGeneratorDescription; begin FFieldType := Value; if Generator <> '' then if (Collection <> nil) and (Collection.Owner is TComponent) then if csDesigning in TComponent(Collection.Owner).ComponentState then if (not FindRegisteredValueGenerator(Generator, FFieldType, LRecord)) then Generator := ''; Changed(False); end; procedure TGeneratorFieldDef.SetGenerator(const Value: string); begin FGenerator := Value; Changed(False); end; procedure TGeneratorFieldDef.SetCustomFormat(const Value: string); begin FCustomFormat := Value; Changed(False); end; procedure TGeneratorFieldDef.SetOptions( const Value: TGeneratorOptions); begin FOptions := Value; Changed(False); end; procedure TGeneratorFieldDef.SetReadOnly(const Value: Boolean); begin FReadOnly := Value; Changed(False); // No need to regenerate end; function TGeneratorFieldDef.GetChildDefs: TGeneratorFieldDefs; begin Result := inherited GetChildDefs<TGeneratorFieldDefs>; end; procedure TGeneratorFieldDef.SetChildDefs(Value: TGeneratorFieldDefs); begin ChildDefs.Assign(Value); end; function TGeneratorFieldDef.AddChild: TGeneratorFieldDef; begin Result := inherited AddChild<TGeneratorFieldDef>; end; function TGeneratorFieldDef.GetParentDef: TGeneratorFieldDef; begin Result := inherited GetParentDef<TGeneratorFieldDef>; end; function TGeneratorFieldDef.GetTypeInfo: PTypeInfo; begin case FFieldType of ftString: Result := System.TypeInfo(string); ftInteger: Result := System.TypeInfo(Integer); ftUInteger: Result := System.TypeInfo(UInt32); ftSingle: Result := System.TypeInfo(Single); ftBoolean: Result := System.TypeInfo(Boolean); ftBitmap: Result := System.TypeInfo(TPersistent); ftTStrings: Result := System.TypeInfo(TStrings); ftCurrency: Result := System.TypeInfo(Currency); ftDateTime: Result := System.TypeInfo(TDateTime); ftTime: Result := System.TypeInfo(TTime); ftDate: Result := System.TypeInfo(TDate); else Result := System.TypeInfo(string); Assert(False); end; end; procedure TGeneratorFieldDef.Assign(Source: TPersistent); var I: Integer; S, LBindFieldDef: TGeneratorFieldDef; begin if Source is TGeneratorFieldDef then begin if Collection <> nil then Collection.BeginUpdate; try S := TGeneratorFieldDef(Source); Name := S.Name; FieldType := S.FieldType; Generator := S.Generator; Options := S.Options; ReadOnly := S.ReadOnly; CustomFormat := S.CustomFormat; if HasChildDefs then ChildDefs.Clear; if S.HasChildDefs then for I := 0 to S.ChildDefs.Count - 1 do begin LBindFieldDef := AddChild; LBindFieldDef.Assign(S.ChildDefs[I]); end; finally if Collection <> nil then Collection.EndUpdate; end; end else inherited; end; function TGeneratorFieldDef.GetChildDefsClass: TBindFieldDefsClass; begin Result := TGeneratorFieldDefs; end; { TBindFieldDefs } procedure TBindFieldDefs.Update(AItem: TCollectionItem); begin if Assigned(FDataSource) and not (csLoading in FDataSource.ComponentState) then DoUpdate(AItem); end; destructor TBindFieldDefs.Destroy; begin FreeAndNil(FDictionary); inherited; end; procedure TBindFieldDefs.DoRenameFieldDef(AFieldDef: TBindFieldDef; const CurName, PrevName: string); begin // end; procedure TBindFieldDefs.DoRenamingFieldDef(AFieldDef: TBindFieldDef; const CurName, NewName: string); begin // end; procedure TBindFieldDefs.DoUpdate(Sender: TObject); begin if (FInternalUpdateCount = 0) then begin Updated := False; DataSourceFieldDefChanged(Self); end; end; procedure TBindFieldDefs.UpdateDefs(AMethod: TDefUpdateMethod); begin if not Updated then begin Inc(FInternalUpdateCount); BeginUpdate; try AMethod; finally EndUpdate; Dec(FInternalUpdateCount); end; Updated := True; { Defs are now a mirror of data source } end; end; function TBindFieldDefs.IndexOf(const AName: string): Integer; var LFieldDef: TBindFieldDef; begin if Count > 0 then begin if FDictionary.TryGetValue(TBindFieldDef.MakeKey(AName), LFieldDef) then begin Exit(LFieldDef.Index); end; end; Result := -1; end; procedure TBindFieldDefs.GetItemNames(List: TStrings); var I: Integer; begin List.BeginUpdate; try List.Clear; for I := 0 to Count - 1 do if TBindFieldDef(Items[I]).Name <> '' then List.Add(TBindFieldDef(Items[I]).Name); finally List.EndUpdate; end; end; constructor TBindFieldDefs.Create(AOwner: TPersistent); var LDataSource: TComponent; begin inherited Create(AOwner, GetFieldDefClass); FDictionary := TDictionary<string, TBindFieldDef>.Create; if AOwner is TBindFieldDef then begin FParentDef := TBindFieldDef(AOwner); LDataSource := TBindFieldDefs(FParentDef.Collection).DataSource end else LDataSource := AOwner as TComponent; FDataSource := LDataSource; end; procedure TBindFieldDefs.SetItemName(AItem: TCollectionItem); const sField = 'Field'; var LID: Integer; LName: string; begin if TBindFieldDef(AItem).Name = '' then begin LID := TBindFieldDef(AItem).ID; while TBindFieldDef(AItem).Name = '' do begin if (GetOwner = nil) or (not (Self.GetOwner is TBindFieldDef)) then begin LName := sField + IntToStr(LID+1); end else LName := TBindFieldDef(Self.GetOwner).Name + sField + IntToStr(LID+1); if IndexOf(LName) = -1 then TBindFieldDef(AItem).Name := LName; Inc(LID); end; end; end; function TBindFieldDefs.AddFieldDef<T>: T; begin Result := SafeCast<T>(inherited Add); end; function TBindFieldDefs.Find<T>(const Name: string): T; var I: Integer; LResult: TBindFieldDef; begin I := IndexOf(Name); if I < 0 then LResult := nil else LResult := TBindFieldDef(Items[I]); Result := SafeCast<T>(LResult); if Result = nil then raise TBindCompException.CreateFmt(SFieldNotFound, [Name]); end; function TBindFieldDefs.GetFieldDef<T>(Index: Integer): T; begin Result := T(inherited Items[Index]); end; function TBindFieldDefs.SafeCast<T>(AValue: TObject): T; begin if AValue <> nil then Result := T(AValue) else Result := nil; end; procedure TBindFieldDefs.SetFieldDef(Index: Integer; Value: TBindFieldDef); begin inherited Items[Index] := Value; end; procedure TBindFieldDefs.Update; begin UpdateDefs(DataSourceInitFieldDefs); end; procedure TBindFieldDefs.ChildDefUpdate(Sender: TObject); begin { Need to update based on the UpdateCount of the DataSet's FieldDefs } if (GetDataSourceFieldDefs.UpdateCount = 0) and (GetDataSourceFieldDefs.FInternalUpdateCount = 0) then DoUpdate(Sender); end; procedure TBindFieldDefs.FieldDefUpdate(Sender: TObject); begin DoUpdate(Sender); end; function TBindFieldDefs.GetParentDef<T>: T; begin Result := SafeCast<T>(FParentDef); end; { TGeneratorRecord } constructor TGeneratorRecord.Create; begin FDictionary := TDictionary<string, TValue>.Create(); FFreeObjects := TObjectList<TObject>.Create; end; destructor TGeneratorRecord.Destroy; begin FDictionary.Free; FFreeObjects.Free; inherited; end; { TBindFieldDefValueWriter<T> } procedure TBindFieldDefValueWriter<T>.SetValue(const AValue: T); var LObject: TObject; LDictionary: TDictionary<string, TValue>; LValue: TValue; begin LObject := FField.GetMemberObject; if LObject <> nil then begin LDictionary := (LObject as TGeneratorRecord).FDictionary; if LDictionary.TryGetValue(FField.MemberName, LValue) then begin Assert( not LValue.IsEmpty); LValue := TValue.From<T>(AValue); LDictionary[FField.MemberName] := LValue; end else Assert(False); end; end; { TGeneratorBindFieldDefs } function TGeneratorFieldDefs.GetAttrCount: Integer; begin Result := 3; end; function TGeneratorFieldDefs.GetAttr(Index: Integer): string; begin case Index of 0: Result := sNameAttr; 1: Result := sTypeAttr; 2: Result := sGeneratorAttr; else Result := ''; { do not localize } end; end; function TGeneratorFieldDefs.GetItemAttr(Index, ItemIndex: Integer): string; begin case Index of 0: begin Result := Items[ItemIndex].Name; if Result = '' then Result := IntToStr(ItemIndex); end; 1: begin Result := GetEnumName(TypeInfo(TGeneratorFieldType), Integer(Items[ItemIndex].FieldType)); end; 2: begin Result := Items[ItemIndex].Generator; end; else Result := ''; end; end; procedure TGeneratorFieldDefs.DataSourceFieldDefChanged(Sender: TObject); begin if FDataSource <> nil then (FDataSource as TCustomDataGeneratorAdapter).FieldDefChanged(Sender); end; procedure TGeneratorFieldDefs.DoRenamingFieldDef(AFieldDef: TBindFieldDef; const CurName, NewName: string); var LScope: TBaseObjectBindSource; begin if (FDataSource <> nil) and (not (csLoading in FDataSource.ComponentState)) then for LScope in (FDataSource as TCustomDataGeneratorAdapter).Scopes do LScope.DoMemberRenaming(CurName, NewName); end; procedure TGeneratorFieldDefs.DoRenameFieldDef(AFieldDef: TBindFieldDef; const CurName, PrevName: string); var LScope: TBaseObjectBindSource; begin if (FDataSource <> nil) and (not (csLoading in FDataSource.ComponentState)) then for LScope in (FDataSource as TCustomDataGeneratorAdapter).Scopes do LScope.DoMemberRenamed(CurName, PrevName); end; procedure TGeneratorFieldDefs.DataSourceInitFieldDefs; begin (FDataSource as TCustomDataGeneratorAdapter).InitFieldDefs; end; function TGeneratorFieldDefs.GetDataSourceFieldDefs: TBindFieldDefs; begin Result := (FDataSource as TCustomDataGeneratorAdapter).FieldDefs; end; function TGeneratorFieldDefs.AddFieldDef: TGeneratorFieldDef; begin Result := inherited AddFieldDef<TGeneratorFieldDef>; end; function TGeneratorFieldDefs.Find(const Name: string): TGeneratorFieldDef; begin Result := inherited Find<TGeneratorFieldDef>(Name); end; function TGeneratorFieldDefs.GetFieldDef(Index: Integer): TGeneratorFieldDef; begin Result := inherited GetFieldDef<TGeneratorFieldDef>(Index); end; function TGeneratorFieldDefs.GetFieldDefClass: TBindFieldDefClass; begin Result := TGeneratorFieldDef; end; function TGeneratorFieldDefs.GetParentDef: TGeneratorFieldDef; begin Result := inherited GetParentDef<TGeneratorFieldDef>; end; procedure TGeneratorFieldDefs.SetFieldDef(Index: Integer; Value: TGeneratorFieldDef); begin inherited SetFieldDef(Index, Value); end; function TGeneratorFieldDefs.GetEnumerator: TEnumerator; begin Result := TEnumerator.Create(Self); end; { TBindFieldDef } function TBindFieldDef.HasChildDefs: Boolean; begin Result := False; end; class function TBindFieldDef.MakeKey(const AName: string): string; begin Assert(AName <> ''); Result := UpperCase(AName); end; { TValueGenerator } constructor TValueGenerator.Create(AFieldDef: TGeneratorFieldDef); begin FGeneratorName := AFieldDef.Generator; FFieldType := AFieldDef.FieldType; FOptions := AFieldDef.Options; FCustomFormat := AFieldDef.CustomFormat; end; function TValueGenerator.GetRecordCount: Integer; begin Result := -1; end; procedure TValueGenerator.FirstRecord; begin end; procedure TValueGenerator.NextRecord; begin end; function TValueGenerator.GetValue(var AFree: Boolean): TValue; begin Result := TValue.Empty; end; { TDelegateValueGenerator } constructor TDelegateValueGenerator.Create(AFieldDef: TGeneratorFieldDef); begin inherited; FDelegate := CreateDelegate; end; destructor TDelegateValueGenerator.Destroy; begin FDelegate.Free; inherited; end; procedure TDelegateValueGenerator.FirstRecord; begin inherited; if FDelegate <> nil then FDelegate.FirstRecord; end; function TDelegateValueGenerator.GetRecordCount: Integer; begin if FDelegate <> nil then Result := FDelegate.GetRecordCount else Result := inherited; end; procedure TDelegateValueGenerator.NextRecord; begin inherited; if FDelegate <> nil then FDelegate.NextRecord; end; function TDelegateValueGenerator.GetValue(var AFree: Boolean): TValue; begin if FDelegate <> nil then Exit(FDelegate.GetValue(AFree)) else begin Assert(False); Result := TValue.Empty; end; end; { TValueGeneratorRecord } constructor TValueGeneratorDescription.Create( AClassType: TValueGeneratorClass; const AFormatFieldName: string; const AUnitName: string); begin FClassType := AClassType; FFormatFieldName := AFormatFieldName; FUnitName := AUnitName; end; { TBindSourceAdapterReadWriteObjectField<T> } type TPersistentCracker = class(TPersistent) end; procedure TBindSourceAdapterReadWriteObjectField<T>.AssignTo(Dest: TPersistent); begin if (Value is TPersistent) or (Value = nil) then begin if AssignValue(Dest) then begin // Assign OK end else inherited end else inherited; end; procedure TBindSourceAdapterReadWriteObjectField<T>.ClearBuffer; begin FBuffer := nil; end; function TBindSourceAdapterReadWriteObjectField<T>.CreateBlobStream: TStream; begin Result := CreateValueBlobStream(Value); end; { TBindSourceAdapterReadObjectField<T> } procedure TBindSourceAdapterReadObjectField<T>.AssignTo(Dest: TPersistent); begin if Value is TPersistent then begin if AssignValue(Dest) then begin // Assign OK end else inherited; end else inherited; end; function TBindSourceAdapterReadObjectField<T>.CreateBlobStream: TStream; begin Result := CreateValueBlobStream(Value); end; { TInternalTypedListValueGeneratorDelegate } // Copy from System.Random function TInternalTypedListValueGeneratorDelegate.PRNGenerator(const ARange: Integer; var Seed: Integer): Integer; var Temp: Integer; begin Temp := Seed * $08088405 + 1; Seed := Temp; Result := (UInt64(Cardinal(ARange)) * UInt64(Cardinal(Temp))) shr 32; end; { TTypedListValueGeneratorDelegate2<T> } constructor TTypedListValueGeneratorDelegate2<T, T1>.Create(AOptions: TGeneratorOptions; AValuesList: TArray<T1>); begin inherited Create(AOptions, ConvertArray(AValuesList)); end; function TTypedListValueGeneratorDelegate2<T, T1>.ConvertArray( AArray: TArray<T1>): TArray<T>; var LList: TList<T>; LT1: T1; LT: T; LValue: TValue; begin LList := TList<T>.Create; try for LT1 in AArray do begin LValue := TValue.From<T1>(LT1); if LValue.TryAsType<T>(LT) then LList.Add(LT) else begin LValue := LValue.ToString; if LValue.TryAsType<T>(LT) then LList.Add(LT) else begin LValue := TValue.Empty; // Debugging end; end; end; Result := LList.ToArray; finally LList.Free; end; end; { TTypedListValueGeneratorDelegate<T> } constructor TTypedListValueGeneratorDelegate<T>.Create(AOptions: TGeneratorOptions; AValuesList: TArray<T>); var I: Integer; Seed: Integer; begin FValuesList := TList<T>.Create; FValuesList.AddRange(AValuesList); if optShuffle in AOptions then begin if (FValuesList.Count > 0) and (optRepeat in AOptions) then while FValuesList.Count < 20 do // Add more if a list of booleans, for example FValuesList.AddRange(AValuesList); Seed := 123456789; // Shuffle always results in same order, so that generated and names match corresponding generated values for I := 0 to FValuesList.Count - 1 do FValuesList.Exchange(I, PRNGenerator(FValuesList.Count, Seed)); end; end; destructor TTypedListValueGeneratorDelegate<T>.Destroy; begin FValuesList.Free; inherited; end; procedure TTypedListValueGeneratorDelegate<T>.FirstRecord; begin FValueCounter := 0; end; function TTypedListValueGeneratorDelegate<T>.GetRecordCount: Integer; begin Result := FValuesList.Count; end; procedure TTypedListValueGeneratorDelegate<T>.NextRecord; begin Inc(FValueCounter); end; function TTypedListValueGeneratorDelegate<T>.GetValue(var AFree: Boolean): TValue; var LValue: T; begin if (FValuesList <> nil) and (FValuesList.Count > 0) then Result := TValue.From<T>(FValuesList[FValueCounter mod FValuesList.Count]) else begin // Create default value LValue := TValue.Empty.AsType<T>; Result := TValue.From<T>(LValue); end; // Allow owner to override return value if Assigned(FGetValue) then begin Assert(not AFree); Result := FGetValue(Result, AFree); if AFree then begin Assert(Result.IsObject); end; end; end; { TValueGeneratorDelegate } function TValueGeneratorDelegate.GetRecordCount: Integer; begin Result := -1; end; { TBindFieldDefObjectValueWriter<T> } procedure TBindFieldDefObjectValueWriter<T>.SetValue(const AValue: T); var LObject: TObject; LDictionary: TDictionary<string, TValue>; LValue: TValue; LDictionaryValue: TValue; begin LObject := FField.GetMemberObject; if LObject <> nil then begin LDictionary := (LObject as TGeneratorRecord).FDictionary; if LDictionary.TryGetValue(FField.MemberName, LValue) then begin Assert( not LValue.IsEmpty); LValue := TValue.From<T>(AValue); LDictionaryValue := LDictionary[FField.MemberName]; if LDictionaryValue.IsObject and (LDictionaryValue.AsObject is TPersistent) then if (LValue.IsObject) and (LValue.AsObject is TPersistent) then TPersistent(LDictionaryValue.AsObject).Assign(TPersistent(LValue.AsObject)) else TPersistent(LDictionaryValue.AsObject).Assign(nil) // Clear else Assert(False); // Unexpected value end else Assert(False); end; end; function TTypedCustomFormatObject<T>.GetTValue: TValue; begin Result := TValue.From<T>(FValue); end; function TTypedCustomFormatObject<T>.GetValue: T; begin Result := FValue; end; procedure TTypedCustomFormatObject<T>.SetTValue(const AValue: TValue); begin FValue := AValue.AsType<T>(); end; procedure TTypedCustomFormatObject<T>.SetValue(AValue: T); begin FValue := AValue; end; { TListBindSourceAdapter } constructor TListBindSourceAdapter.Create(AOwner: TComponent; AList: TList<TObject>; AClass: TClass; AOwnsObject: Boolean); begin FClass := AClass; inherited Create(AOwner, AList, AOwnsObject); end; function TListBindSourceAdapter.GetObjectType: TRttiType; var LType: TRttiType; LCtxt: TRttiContext; begin if FClass <> nil then LType := LCtxt.GetType(FClass) else LType := LCtxt.GetType(TObject); Result := LType; end; { TObjectBindSourceAdapter } constructor TObjectBindSourceAdapter.Create(AOwner: TComponent; AObject: TObject; AClass: TClass; AOwnsObject: Boolean); begin FClass := AClass; inherited Create(AOwner, AObject, AOwnsObject); end; function TObjectBindSourceAdapter.GetObjectType: TRttiType; var LType: TRttiType; LCtxt: TRttiContext; begin if FClass <> nil then LType := LCtxt.GetType(FClass) else LType := LCtxt.GetType(TObject); Result := LType; end; { TBaseObjectBindSourceDelegate } procedure TBaseObjectBindSourceDelegate.AddActiveChanged(LNotify: TNotifyEvent); begin FBindSource.AddActiveChanged(LNotify); end; procedure TBaseObjectBindSourceDelegate.AddDataSetChanged( LNotify: TNotifyEvent); begin FBindSource.AddDataSetChanged(LNotify); end; procedure TBaseObjectBindSourceDelegate.AddDataSetScrolled( LNotify: TNotifyDistanceEvent); begin FBindSource.AddDataSetScrolled(LNotify); end; procedure TBaseObjectBindSourceDelegate.AddEditingChanged( LNotify: TNotifyEvent); begin FBindSource.AddEditingChanged(LNotify); end; procedure TBaseObjectBindSourceDelegate.AddExpression( AExpression: TBasicBindComponent); begin FBindSource.AddExpression(AExpression); end; procedure TBaseObjectBindSourceDelegate.ApplyUpdates; begin FBindSource.ApplyUpdates; end; procedure TBaseObjectBindSourceDelegate.Cancel; begin FBindSource.Cancel; end; procedure TBaseObjectBindSourceDelegate.CancelUpdates; begin FBindSource.CancelUpdates; end; procedure TBaseObjectBindSourceDelegate.ClearModified( ABindComp: TBasicBindComponent); begin FBindSource.ClearModified(ABindComp); end; constructor TBaseObjectBindSourceDelegate.Create(AOwner: TComponent); begin FBindSource := CreateBindSource; inherited; end; procedure TBaseObjectBindSourceDelegate.Delete; begin FBindSource.Delete; end; function TBaseObjectBindSourceDelegate.Edit( ABindComp: TBasicBindComponent): Boolean; begin Result := FBindSource.Edit(ABindComp); end; procedure TBaseObjectBindSourceDelegate.Edit; begin FBindSource.Edit; end; procedure TBaseObjectBindSourceDelegate.First; begin FBindSource.First; end; function TBaseObjectBindSourceDelegate.GetActive: Boolean; begin Result := FBindSource.GetActive; end; function TBaseObjectBindSourceDelegate.GetBOF: Boolean; begin Result := FBindSource.GetBOF; end; function TBaseObjectBindSourceDelegate.GetCanApplyUpdates: Boolean; begin Result := FBindSource.GetCanApplyUpdates; end; function TBaseObjectBindSourceDelegate.GetCanCancelUpdates: Boolean; begin Result := FBindSource.GetCanCancelUpdates; end; function TBaseObjectBindSourceDelegate.GetCanDelete: Boolean; begin Result := FBindSource.GetCanDelete; end; function TBaseObjectBindSourceDelegate.GetCanInsert: Boolean; begin Result := FBindSource.GetCanInsert; end; function TBaseObjectBindSourceDelegate.GetCanModify: Boolean; begin Result := FBindSource.GetCanModify; end; function TBaseObjectBindSourceDelegate.GetCanModify( ABindComp: TBasicBindComponent): Boolean; begin Result := FBindSource.GetCanModify(ABindComp); end; function TBaseObjectBindSourceDelegate.GetCanRefresh: Boolean; begin Result := FBindSource.GetCanRefresh; end; function TBaseObjectBindSourceDelegate.GetCurrentRecord( const AMemberName: string): IScope; begin Result := FBindSource.GetCurrentRecord(AMemberName); end; function TBaseObjectBindSourceDelegate.GetEditing: Boolean; begin Result := FBindSource.GetEditing; end; function TBaseObjectBindSourceDelegate.GetEnumerator(const AMemberName: string; ABufferCount: Integer): IScopeRecordEnumerator; begin Result := FBindSource.GetEnumerator(AMemberName, ABufferCount); end; function TBaseObjectBindSourceDelegate.GetEOF: Boolean; begin Result := FBindSource.GetEOF; end; function TBaseObjectBindSourceDelegate.GetIsEditing( ABindComp: TBasicBindComponent): Boolean; begin Result := FBindSource.GetIsEditing(ABindComp); end; function TBaseObjectBindSourceDelegate.GetIsModified( ABindComp: TBasicBindComponent): Boolean; begin Result := FBindSource.GetIsModified(ABindComp); end; procedure TBaseObjectBindSourceDelegate.GetLookupMemberNames(AList: TStrings); begin FBindSource.GetLookupMemberNames(AList); end; function TBaseObjectBindSourceDelegate.GetMember( const AMemberName: string): TObject; begin Result := FBindSource.GetMember(AMemberName) end; function TBaseObjectBindSourceDelegate.GetMemberGetter( const AMemberName: string; var AGetter: string): Boolean; begin Result := FBindSource.GetMemberGetter(AMemberName, AGetter); end; procedure TBaseObjectBindSourceDelegate.GetMemberNames(AList: TStrings); begin FBindSource.GetMemberNames(AList); end; function TBaseObjectBindSourceDelegate.GetMemberSetter( const AMemberName: string; var ASetter: string): Boolean; begin Result := FBindSource.GetMemberSetter(AMemberName, ASetter); end; function TBaseObjectBindSourceDelegate.GetMemberType(const AMemberName: string; var AType: TScopeMemberType): Boolean; begin Result := FBindSource.GetMemberType(AMemberName, AType); end; function TBaseObjectBindSourceDelegate.GetPositionGetter(var AGetter: string; var ABase: Integer): Boolean; begin Result := FBindSource.GetPositionGetter(AGetter, ABase); end; function TBaseObjectBindSourceDelegate.GetPositionSetter(var ASetter: string; var ABase: Integer): Boolean; begin Result := FBindSource.GetPositionSetter(ASetter, ABase); end; procedure TBaseObjectBindSourceDelegate.GetRecord(ARow: Integer; const AMemberName: string; ACallback: TProc<IScope>); begin FBindSource.GetRecord(ARow, AMemberName, ACallback); end; function TBaseObjectBindSourceDelegate.GetSelected: Boolean; begin Result := FBindSource.GetSelected; end; function TBaseObjectBindSourceDelegate.GetValue: TObject; begin Result := FBindSource.GetValue; end; procedure TBaseObjectBindSourceDelegate.Insert; begin FBindSource.Insert; end; function TBaseObjectBindSourceDelegate.IsRequired( const AFieldName: string): Boolean; begin Result := FBindSource.IsRequired(AFieldName); end; function TBaseObjectBindSourceDelegate.IsValidChar(const AFieldName: string; const AChar: Char): Boolean; begin Result := FBindSource.IsValidChar(AFieldName, AChar); end; procedure TBaseObjectBindSourceDelegate.Last; begin FBindSource.Last; end; function TBaseObjectBindSourceDelegate.Locate(const KeyFields: string; const KeyValues: TValue): Boolean; begin Result := FBindSource.Locate(KeyFields, KeyValues); end; function TBaseObjectBindSourceDelegate.Lookup(const KeyFields: string; const KeyValues: TValue; const ResultFields: string): TValue; begin Result := FBindSource.Lookup(KeyFields, KeyValues, ResultFields); end; procedure TBaseObjectBindSourceDelegate.Next; begin FBindSource.Next; end; procedure TBaseObjectBindSourceDelegate.PosChanging( ABindComp: TBasicBindComponent); begin FBindSource.PosChanging(ABindComp); end; procedure TBaseObjectBindSourceDelegate.Post; begin FBindSource.Post; end; procedure TBaseObjectBindSourceDelegate.Prior; begin FBindSource.Prior; end; procedure TBaseObjectBindSourceDelegate.Refresh; begin FBindSource.Refresh; end; procedure TBaseObjectBindSourceDelegate.RemoveActiveChanged( LNotify: TNotifyEvent); begin FBindSource.RemoveActiveChanged(LNotify); end; procedure TBaseObjectBindSourceDelegate.RemoveDataSetChanged( LNotify: TNotifyEvent); begin FBindSource.RemoveDataSetChanged(LNotify); end; procedure TBaseObjectBindSourceDelegate.RemoveDataSetScrolled( LNotify: TNotifyDistanceEvent); begin FBindSource.RemoveDataSetScrolled(LNotify); end; procedure TBaseObjectBindSourceDelegate.RemoveEditingChanged( LNotify: TNotifyEvent); begin FBindSource.RemoveEditingChanged(LNotify); end; procedure TBaseObjectBindSourceDelegate.RemoveExpression( AExpression: TBasicBindComponent); begin FBindSource.RemoveExpression(AExpression); end; procedure TBaseObjectBindSourceDelegate.Reset(ABindComp: TBasicBindComponent); begin FBindSource.Reset(ABindComp); end; procedure TBaseObjectBindSourceDelegate.SetField(ABindComp: TBasicBindComponent; const FieldName: string); begin FBindSource.SetField(ABindComp, FieldName); end; procedure TBaseObjectBindSourceDelegate.SetModified( ABindComp: TBasicBindComponent); begin FBindSource.SetModified(ABindComp); end; procedure TBaseObjectBindSourceDelegate.SetReadOnly( ABindComp: TBasicBindComponent; const Value: Boolean); begin FBindSource.SetReadOnly(ABindComp, Value); end; procedure TBaseObjectBindSourceDelegate.UpdateRecord( ABindComp: TBasicBindComponent); begin FBindSource.UpdateRecord(ABindComp); end; { TValueReaderFunc<T> } constructor TValueReaderFunc<T>.Create(const AName: string; AGetValue: TFunc<string, T>); begin FGetValue := AGetValue; FName := AName; end; function TValueReaderFunc<T>.GetValue: T; begin Result := FGetValue(FName); end; { TValueWriteProc<T> } constructor TValueWriterProc<T>.Create(const AName: string; ASetValue: TProc<string, T>); begin FSetValue := ASetValue; FName := AName; end; procedure TValueWriterProc<T>.SetValue(const AValue: T); begin FSetValue(FName, AValue); end; initialization TBindingScopeFactory.RegisterScope(TBindSourceAdapter, TBindSourceAdapterCustomScope); TBindingScopeFactory.RegisterScope(TBindSourceAdapterReadObjectField, TBindSourceAdapterObjectFieldCustomScope); finalization TBindingScopeFactory.UnregisterScope(TBindSourceAdapterCustomScope); TBindingScopeFactory.UnregisterScope(TBindSourceAdapterObjectFieldCustomScope); GValueGenerators.Free; end.
unit uDAO.Pessoa; interface uses System.SysUtils, System.Classes, FireDAC.Comp.Client, Data.DB, uDAO.Interfaces, uDB, uModel.Interfaces, uDAO.PessoaContato; type TPessoaDAO = class(TInterfacedObject, iPessoaDAO) private FQry: TFDQuery; function IsExist(pId: Integer): Boolean; procedure Bind(pDataSet: TDataSet; pModel: iPessoaModel); public constructor Create; destructor Destroy; override; class function New: iPessoaDAO; function Get(pId: Integer): TDataSet; overload; function Get(pId: Integer; pModel: iPessoaModel): iPessoaDAO; overload; function Delete(pId: Integer): Boolean; function Save(pModel: iPessoaModel): Boolean; end; implementation { TPessoaDAO } constructor TPessoaDAO.Create; begin FQry := TFDQuery.Create(nil); FQry.Connection := TDB.getInstance.Conexao; end; destructor TPessoaDAO.Destroy; begin FQry.Close; FreeAndNil(FQry); inherited; end; class function TPessoaDAO.New: iPessoaDAO; begin Result := Self.Create; end; function TPessoaDAO.Delete(pId: Integer): Boolean; var Qry: TFDQuery; begin if (pId = 0) then begin Result := False; raise Exception.Create('Nenhum ID foi passado como parametro'); end; Result := True; Qry := TFDQuery.Create(nil); try Qry.Connection := TDB.getInstance.Conexao; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add('delete from PESSOA'); Qry.SQL.Add('where ID = :ID'); Qry.ParamByName('ID').AsInteger := pId; try Qry.ExecSQL; except on E: Exception do begin Result := False; raise Exception.Create(E.Message); end; end; finally FreeAndNil(Qry); end; end; function TPessoaDAO.Get(pId: Integer): TDataSet; begin FQry.Connection := TDB.getInstance.Conexao; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('select * from PESSOA'); FQry.SQL.Add('where 1 = 1'); if pId > 0 then begin FQry.SQL.Add('and ID = :ID'); FQry.ParamByName('ID').AsInteger := pId; end; try FQry.Open; Result := FQry; except on E: Exception do raise Exception.Create(E.Message); end; end; function TPessoaDAO.Get(pId: Integer; pModel: iPessoaModel): iPessoaDAO; var Qry: TFDQuery; begin Result := Self; if (pId = 0) then begin raise Exception.Create('Nenhum ID foi passado como parametro'); end; Qry := TFDQuery.Create(nil); try Qry.Connection := TDB.getInstance.Conexao; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add('select * from PESSOA'); Qry.SQL.Add('where ID = :ID'); Qry.ParamByName('ID').AsInteger := pId; try Qry.Open; Bind(Qry, pModel); except on E: Exception do begin raise Exception.Create(E.Message); end; end; finally Qry.Close; FreeAndNil(Qry); end; end; procedure TPessoaDAO.Bind(pDataSet: TDataSet; pModel: iPessoaModel); begin if not pDataSet.IsEmpty then begin pModel.Id(pDataSet.FieldByName('ID').AsInteger); pModel.Nome(pDataSet.FieldByName('NOME').AsString); pModel.Endereco.Logradouro(pDataSet.FieldByName('LOGRADOURO').AsString); pModel.Endereco.Numero(pDataSet.FieldByName('NUMERO').AsString); pModel.Endereco.Bairro(pDataSet.FieldByName('BAIRRO').AsString); pModel.Endereco.Cep(pDataSet.FieldByName('CEP').AsString); pModel.Endereco.Cidade(pDataSet.FieldByName('CIDADE').AsString); pModel.Endereco.UF(pDataSet.FieldByName('UF').AsString); TPessoaContatoDAO.New.Get(pModel.Id, pModel.Contatos); end; end; function TPessoaDAO.IsExist(pId: Integer): Boolean; var Qry: TFDQuery; begin Qry := TFDQuery.Create(nil); try Qry.Connection := TDB.getInstance.Conexao; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add('select 1 from PESSOA'); Qry.SQL.Add('where ID = :ID'); Qry.ParamByName('ID').AsInteger := pId; try Qry.Open; Result := not Qry.IsEmpty; except on E: Exception do raise Exception.Create(E.Message); end; finally FreeAndNil(Qry); end; end; function TPessoaDAO.Save(pModel: iPessoaModel): Boolean; var Qry: TFDQuery; IsInsert: Boolean; I: Integer; ItemContato: iPessoaContatoModel; begin if (pModel = nil) then begin Result := False; raise Exception.Create('Nenhum contato foi passado como parametro'); end; Result := True; IsInsert := Self.IsExist(pModel.Id); Qry := TFDQuery.Create(nil); try Qry.Connection := TDB.getInstance.Conexao; Qry.Close; Qry.SQL.Clear; if not IsInsert then begin Qry.SQL.Add('insert into PESSOA ('); Qry.SQL.Add(' NOME, LOGRADOURO, NUMERO, BAIRRO, CEP, CIDADE, UF) values ('); Qry.SQL.Add(' :NOME, :LOGRADOURO, :NUMERO, :BAIRRO, :CEP, :CIDADE, :UF)'); Qry.SQL.Add('returns ID'); end else begin Qry.SQL.Add('update PESSOA set'); Qry.SQL.Add(' NOME =:NOME, LOGRADOURO =:LOGRADOURO, NUMERO =:NUMERO,'); Qry.SQL.Add(' BAIRRO =:BAIRRO, CEP =:CEP, CIDADE =:CIDADE, UF =:UF'); Qry.SQL.Add('where ID =:ID'); Qry.ParamByName('ID').AsInteger := pModel.Id; end; Qry.ParamByName('NOME').AsString := pModel.Nome; Qry.ParamByName('LOGRADOURO').AsString := pModel.Endereco.Logradouro; Qry.ParamByName('NUMERO').AsString := pModel.Endereco.Numero; Qry.ParamByName('BAIRRO').AsString := pModel.Endereco.Bairro; Qry.ParamByName('CEP').AsString := pModel.Endereco.Cep; Qry.ParamByName('CIDADE').AsString := pModel.Endereco.Cidade; Qry.ParamByName('UF').AsString := pModel.Endereco.UF; try if IsInsert then begin Qry.Open; pModel.Id(Qry.ParamByName('ID').AsInteger); end else Qry.ExecSQL; if pModel.Contatos.Count > 0 then begin for I := 0 to pModel.Contatos.Count-1 do begin ItemContato := pModel.Contatos.Get(I); ItemContato.IdPessoa(pModel.Id); TPessoaContatoDAO.New.Save(ItemContato); end; end; except on E: Exception do begin Result := False; raise Exception.Create(E.Message); end; end; finally FreeAndNil(Qry); end; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit DSAzDlgBlockProps; interface uses Vcl.Buttons, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, Vcl.Graphics, Vcl.StdCtrls; type TAzBlockProps = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; lbeCache: TLabeledEdit; lbeType: TLabeledEdit; lbeMD5: TLabeledEdit; lbeEncoding: TLabeledEdit; lbeLanguage: TLabeledEdit; procedure lbeCacheChange(Sender: TObject); private { Private declarations } function GetCache: string; procedure SetCache(const Data: string); function GetType: string; procedure SetType(const Data: string); function GetMD5: string; procedure SetMD5(const Data: string); function GetEncoding: string; procedure SetEncoding(const Data: string); function GetLanguage: string; procedure SetLanguage(const Data: string); public { Public declarations } procedure SetBaseline; property Cache: string read GetCache write SetCache; property ContentType: string read GetType write SetType; property MD5: string read GetMD5 write SetMD5; property Encoding: string read GetEncoding write SetEncoding; property Language: string read GetLanguage write SetLanguage; end; implementation {$R *.dfm} function TAzBlockProps.GetCache: string; begin Result := lbeCache.Text; end; function TAzBlockProps.GetEncoding: string; begin Result := lbeEncoding.Text; end; function TAzBlockProps.GetLanguage: string; begin Result := lbeLanguage.Text; end; function TAzBlockProps.GetMD5: string; begin Result := lbeMD5.Text; end; function TAzBlockProps.GetType: string; begin Result := lbeType.Text; end; procedure TAzBlockProps.lbeCacheChange(Sender: TObject); begin OKBtn.Enabled := true; end; procedure TAzBlockProps.SetBaseline; begin OKBtn.Enabled := false; end; procedure TAzBlockProps.SetCache(const Data: string); begin lbeCache.Text := Data; end; procedure TAzBlockProps.SetEncoding(const Data: string); begin lbeEncoding.Text := Data; end; procedure TAzBlockProps.SetLanguage(const Data: string); begin lbeLanguage.Text := Data; end; procedure TAzBlockProps.SetMD5(const Data: string); begin lbeMD5.Text := Data; end; procedure TAzBlockProps.SetType(const Data: string); begin lbeType.Text := Data; end; end.
unit UserController; interface uses System.SysUtils, System.Classes, superobject, View, BaseController; type TUserController = class(TBaseController) public procedure Index; procedure getData; procedure Add; procedure Edit; procedure Del; procedure Save; end; implementation uses UsersService, RoleService, UsersInterface, RoleInterface; { TUserController } procedure TUserController.Add; var role: ISuperObject; role_service: IRoleInterface; begin with view do begin role_service := TRoleService.Create(Db); role := role_service.getAlldata(); setAttrJSON('role', role); ShowHTML('add'); end; end; procedure TUserController.Del; var id: string; user_service: IUsersInterface; begin user_service := TUsersService.Create(view.Db); with view do begin id := Input('id'); if id <> '' then begin if user_service.delById(id) then Success(0, '删除成功') else Fail(-1, '删除失败'); end; end; end; procedure TUserController.Edit; var role: ISuperObject; role_service: IRoleInterface; begin with view do begin role_service := TRoleService.Create(Db); role := role_service.getAlldata(); setAttrJSON('role', role); ShowHTML('edit'); end; end; procedure TUserController.getData; var con: Integer; ret: ISuperObject; map: ISuperObject; user_service: IUsersInterface; begin user_service := TUsersService.Create(View.Db); with View do begin map := SO(); map.I['page'] := InputInt('page'); map.I['limit'] := InputInt('limit'); map.S['roleid'] := Input('roleid'); ret := user_service.getdata(con, map); ShowPage(con, ret); end; end; procedure TUserController.Index; var role: ISuperObject; role_service: IRoleInterface; begin with view do begin role_service := TRoleService.Create(Db); role := role_service.getAlldata(); setAttrJSON('role', role); ShowHTML('index'); end; end; procedure TUserController.Save; var map: ISuperObject; user_service: IUsersInterface; begin user_service := TUsersService.Create(View.Db); with view do begin map := SO(); map.S['username'] := Input('username'); map.S['roleid'] := Input('roleid'); map.S['realname'] := Input('realname'); map.S['pwd'] := Input('pwd'); map.S['id'] := Input('id'); if user_service.save(map) then begin Success(0, '保存成功'); end else begin Fail(-1, '保存失败'); end; end; end; end.
unit uOptions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, ORFn; type TSurrogate = class private FIEN: Int64; FName: string; FStart: TFMDateTime; FStop: TFMDateTime; public property IEN: Int64 read FIEN write FIEN; property Name: string read FName write FName; property Start: TFMDateTime read FStart write FStart; property Stop: TFMDateTime read FStop write FStop; end; function RelativeDate(entry: string): integer; procedure DateLimits(const limit: integer; var value: integer); procedure ShowDisplay(editbox: TEdit); procedure TextExit(editbox: TEdit; var entrycheck: boolean; limitcheck: integer); procedure LabelSurrogate(surrogateinfo: string; alabel: TStaticText); procedure DisplayPtInfo(PtID: string); const INVALID_DAYS = -99999; DAYS_LIMIT = 999; SELECTION_LIMIT = 999; implementation uses rCore, fRptBox, VAUtils; function RelativeDate(entry: string): integer; // return the number of days for the entry (e.g. -3 for T - 3) function OKToday(value: string): boolean; // check if value is used as the current date begin Result := false; if value = 'T' then Result := true else if value = 'TODAY' then Result := true else if value = 'N' then Result := true else if value = 'NOW' then Result := true; end; procedure GetMultiplier(var entry: string; var multiplier: integer); // check if entry has a multiplier on today's date (days, weeks, months, years) var lastchar: char; begin if (entry = 'NOW') or (entry = 'TODAY') then begin multiplier := 1; exit; end; lastchar := entry[length(entry)]; case lastchar of 'D': multiplier := 1; 'W': multiplier := 7; 'M': multiplier := 30; 'Y': multiplier := 365; else multiplier := 0; end; if multiplier > 0 then entry := copy(entry, 0, length(entry) - 1) else multiplier := 1; end; var firstpart, operator: string; lenfirstpart, multiplier: integer; begin // begin function RelativeDate Result := INVALID_DAYS; entry := Uppercase(entry); GetMultiplier(entry, multiplier); if strtointdef(entry, INVALID_DAYS) <> INVALID_DAYS then begin Result := strtointdef(entry, INVALID_DAYS); if Result <> INVALID_DAYS then Result := Result * multiplier; exit; end; if OKToday(entry) then // process today only begin Result := 0; exit; end; firstpart := Piece(entry, ' ', 1); lenfirstpart := length(firstpart); if OKToday(firstpart) then // process space begin operator := Copy(entry, lenfirstpart + 2, 1); if (operator = '+') or (operator = '-') then begin if Copy(entry, lenfirstpart + 3, 1) = ' ' then Result := strtointdef(Copy(entry, lenfirstpart + 4, length(entry)), INVALID_DAYS) else Result := strtointdef(Copy(entry, lenfirstpart + 3, length(entry)), INVALID_DAYS); if Result <> INVALID_DAYS then if Result < 0 then Result := INVALID_DAYS else if operator = '-' then Result := -Result; end; if Result <> INVALID_DAYS then Result := Result * multiplier; end else begin firstpart := Piece(entry, '+', 1); lenfirstpart := length(firstpart); if OKToday(firstpart) then // process + begin if Copy(entry, lenfirstpart + 2, 1) = ' ' then Result := strtointdef(Copy(entry, lenfirstpart + 3, length(entry)), INVALID_DAYS) else Result := strtointdef(Copy(entry, lenfirstpart + 2, length(entry)), INVALID_DAYS); if Result <> INVALID_DAYS then if Result < 0 then Result := INVALID_DAYS end else begin firstpart := Piece(entry, '-', 1); lenfirstpart := length(firstpart); if OKToday(firstpart) then // process - begin if Copy(entry, lenfirstpart + 2, 1) = ' ' then Result := strtointdef(Copy(entry, lenfirstpart + 3, length(entry)), INVALID_DAYS) else Result := strtointdef(Copy(entry, lenfirstpart + 2, length(entry)), INVALID_DAYS); if Result <> INVALID_DAYS then Result := -Result; end; end; if Result <> INVALID_DAYS then Result := Result * multiplier; end; end; procedure DateLimits(const limit: integer; var value: integer); // check if date is within valid limit begin if value > limit then begin beep; InfoBox('Date cannot be greater than Today + ' + inttostr(limit), 'Warning', MB_OK or MB_ICONWARNING); value := INVALID_DAYS; end else if value < -limit then begin beep; InfoBox('Date cannot be less than Today - ' + inttostr(limit), 'Warning', MB_OK or MB_ICONWARNING); value := INVALID_DAYS; end; end; procedure ShowDisplay(editbox: TEdit); // displays the relative date (uses tag of editbox to hold # of days begin with editbox do begin if Tag > 0 then Text := 'Today + ' + inttostr(Tag) else if Tag < 0 then Text := 'Today - ' + inttostr(-Tag) else Text := 'Today'; Hint := Text; end; end; procedure TextExit(editbox: TEdit; var entrycheck: boolean; limitcheck: integer); // checks entry in editbx if date is valid var tagnum: integer; begin with editbox do begin if entrycheck then begin tagnum := RelativeDate(Hint); if tagnum = INVALID_DAYS then begin beep; InfoBox('Date entry was invalid', 'Warning', MB_OK or MB_ICONWARNING); SetFocus; end else begin DateLimits(limitcheck, tagnum); if tagnum = INVALID_DAYS then SetFocus else Tag := tagnum; end; ShowDisplay(editbox); if Focused then SelectAll; end; entrycheck := false; end; end; procedure LabelSurrogate(surrogateinfo: string; alabel: TStaticText); // surrogateinfo = surrogateIEN^surrogate name^surrogate start date/time^surrogate stop date/time var surrogatename, surrogatestart, surrogatestop: string; surrogateien: Int64; begin surrogateien := strtoint64def(Piece(surrogateinfo, '^', 1), -1); if surrogateien > 1 then begin surrogatename := Piece(surrogateinfo, '^', 2); surrogatestart := Piece(surrogateinfo, '^', 3); if surrogatestart = '-1' then surrogatestart := '0'; if surrogatestart = '' then surrogatestart := '0'; surrogatestop := Piece(surrogateinfo, '^', 4); if surrogatestop = '-1' then surrogatestop := '0'; if surrogatestop = '' then surrogatestop := '0'; alabel.Caption := surrogatename; if (surrogatestart <> '0') and (surrogatestop <> '0') then alabel.Caption := surrogatename + ' (from ' + FormatFMDateTimeStr('mmm d,yyyy@hh:nn', surrogatestart) + ' until ' + FormatFMDateTimeStr('mmm d,yyyy@hh:nn', surrogatestop) + ')' else if surrogatestart <> '0' then alabel.Caption := surrogatename + ' (from ' + FormatFMDateTimeStr('mmm d,yyyy@hh:nn', surrogatestart) + ')' else if surrogatestop <> '0' then alabel.Caption := surrogatename + ' (until ' + FormatFMDateTimeStr('mmm d,yyyy@hh:nn', surrogatestop) + ')' else alabel.Caption := surrogatename; end else alabel.Caption := '<no surrogate designated>'; end; procedure DisplayPtInfo(PtID: string); var PtRec: TPtIDInfo; rpttext: TStringList; begin if strtointdef(PtID, -1) < 0 then exit; PtRec := GetPtIDInfo(PtID); rpttext := TStringList.Create; try with PtRec do begin rpttext.Add(' ' + Name); rpttext.Add('SSN: ' + SSN); rpttext.Add('DOB: ' + DOB); rpttext.Add(''); rpttext.Add(Sex); rpttext.Add(SCSts); rpttext.Add(Vet); rpttext.Add(''); if length(Location) > 0 then rpttext.Add('Location: ' + Location); if length(RoomBed) > 0 then rpttext.Add('Room/Bed: ' + RoomBed); end; ReportBox(rpttext, 'Patient ID', false); finally rpttext.free end; end; end.
unit cPagamentoComCheque; interface uses cPagamento; type PagamentoComCheque = class (Pagamento) protected numCheq : integer; contaCheq : integer; agenciaCheq : integer; bancoCheq : string; public Constructor Create(codPag : integer; valPag : real; statusPag : string; dataPag : TDateTime; tipoPag : string; numCheq : integer; contaCheq : integer; agenciaCheq : integer; bancoCheq : string); Procedure setnumCheq(numCheq:integer); Function getnumCheq:integer; Procedure setcontaCheq(contaCheq:integer); Function getcontaCheq:integer; Procedure setagenciaCheq(agenciaCheq:integer); Function getagenciaCheq:integer; Procedure setbancoCheq(bancoCheq:string); Function getbancoCheq:string; end; implementation Constructor PagamentoComCheque.Create(codPag : integer; valPag : real; statusPag : string; dataPag : TDateTime; tipoPag : string; numCheq : integer; contaCheq : integer; agenciaCheq : integer; bancoCheq : string); begin inherited Create (codPag,valPag,statusPag,dataPag, tipoPag); self.numCheq := numCheq; self.contaCheq := contaCheq; self.agenciaCheq := agenciaCheq; self.bancoCheq := bancoCheq; end; Procedure PagamentoComCheque.setnumCheq(numCheq:integer); begin self.numCheq := numCheq; end; Function PagamentoComCheque.getnumCheq:integer; begin result := numCheq; end; Procedure PagamentoComCheque.setcontaCheq(contaCheq:integer); begin self.contaCheq := contaCheq; end; Function PagamentoComCheque.getcontaCheq:integer; begin result := contaCheq; end; Procedure PagamentoComCheque.setagenciaCheq(agenciaCheq:integer); begin self.agenciaCheq := agenciaCheq; end; Function PagamentoComCheque.getagenciaCheq:integer; begin result := agenciaCheq; end; Procedure PagamentoComCheque.setbancoCheq(bancoCheq:string); begin self.bancoCheq := bancoCheq; end; Function PagamentoComCheque.getbancoCheq:string; begin result := bancoCheq; end; end.
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium Software E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com CAPTCHA component with several properties to customize (kind, set of characters, length, font, background etc) } unit smcaptcha; interface {$I SMVersion.inc} uses Windows, Classes, Controls, Graphics; type TSMCaptchaKind = (ckDefault{TODO:, ckMathEquition}); {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TSMCaptcha = class(TGraphicControl) private { Private declarations } FAvailableCharacters: string; FCaseSensetive: Boolean; FLength: Integer; FKind: TSMCaptchaKind; protected { Protected declarations } FGeneratedImage: TBitmap; FCaptchaValue: string; procedure DoDrawText(FAngle: Integer; Rect: TRect; AText: string); procedure Paint; override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Initialize; function ValidateValue(const AValue: string): Boolean; published { Published declarations } property AvailableCharacters: string read FAvailableCharacters write FAvailableCharacters; property Length: Integer read FLength write FLength default 5; property Kind: TSMCaptchaKind read FKind write FKind default ckDefault; property CaseSensetive: Boolean read FCaseSensetive write FCaseSensetive default False; property Align; {$IFDEF SMForDelphi4} property Anchors; {$ENDIF} property Color; property DragCursor; property DragMode; property Enabled; property Font; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation uses SysUtils; procedure Register; begin RegisterComponents('SMComponents', [TSMCaptcha]); end; { TSMCaptcha } constructor TSMCaptcha.Create(AOwner: TComponent); var i: Integer; begin inherited Create(AOwner); FGeneratedImage := TBitmap.Create; FAvailableCharacters := ''; for i := Ord('A') to Ord('Z') do FAvailableCharacters := FAvailableCharacters + Chr(i); for i := Ord('a') to Ord('z') do FAvailableCharacters := FAvailableCharacters + Chr(i); FAvailableCharacters := FAvailableCharacters + '0123456789'; FLength := 5; FKind := ckDefault; FCaseSensetive := False; Font.Name := 'Arial'; Font.Size := 14; Width := 100; Height := 50; Initialize; end; destructor TSMCaptcha.Destroy; begin FGeneratedImage.Free; FGeneratedImage := nil; inherited; end; procedure TSMCaptcha.Initialize; var i, intLen, Angle: Integer; r: TRect; begin {generate string} FCaptchaValue := ''; if (AvailableCharacters <> '') then begin intLen := System.Length(AvailableCharacters); for i := 0 to Length-1 do FCaptchaValue := FCaptchaValue + AvailableCharacters[Random(intLen-1)+1]; end; {generate the image} FGeneratedImage.Width := ClientRect.Right-ClientRect.Left; FGeneratedImage.Height := ClientRect.Bottom-ClientRect.Top; FGeneratedImage.Canvas.Brush.Color := clWhite; FGeneratedImage.Canvas.FillRect(FGeneratedImage.Canvas.ClipRect); {1. draw the random lines with random colors} for i := 0 to Length do begin FGeneratedImage.Canvas.Pen.Color := Random($02FFFFFF); FGeneratedImage.Canvas.MoveTo(Random(5), Random(FGeneratedImage.Height)-Random(5)); FGeneratedImage.Canvas.LineTo(FGeneratedImage.Width-Random(5), Random(FGeneratedImage.Height)-Random(5)); end; {2. draw the characters with random colors} for i := 1 to System.Length(FCaptchaValue) do begin r := ClientRect; r.Left := r.Left + (Width div Length)*(i-1); r.Right := r.Left + (Width div Length); r.Top := r.Top + Random(Height-ABS(Font.Height)); if (i mod 2 = 0) then Angle := Random(20) else Angle := 360-Random(20); DoDrawText(Angle, r, FCaptchaValue[i]); end; Invalidate; end; procedure TSMCaptcha.DoDrawText(FAngle: Integer; Rect: TRect; AText: string); var LogRec: TLogFont; OldFontHandle, NewFontHandle: hFont; fDegToRad, fCosAngle, fSinAngle: Double; H, W, X, Y: Integer; BRect: TRect; begin fDegToRad := PI / 180; fCosAngle := cos(FAngle * fDegToRad); fSinAngle := sin(FAngle * fDegToRad); with FGeneratedImage.Canvas do begin Font := Self.Font; Font.Color := Random($02FFFFFF); Brush.Style := bsClear; {-create a rotated font based on the font object Font} GetObject(Font.Handle, SizeOf(LogRec), Addr(LogRec)); LogRec.lfEscapement := FAngle*10; LogRec.lfOrientation := FAngle*10; LogRec.lfOutPrecision := OUT_DEFAULT_PRECIS; LogRec.lfClipPrecision := OUT_DEFAULT_PRECIS; NewFontHandle := CreateFontIndirect(LogRec); W := TextWidth(AText); H := TextHeight(AText); X := 0; case FAngle of 91..180: X := X - Trunc(W*fCosAngle); 181..270: X := X - Trunc(W*fCosAngle) - Trunc(H*fSinAngle); 271..359: X := X - Trunc(H*fSinAngle); end; if X > (Rect.Right-Rect.Left) then X := Rect.Right-Rect.Left; Y := 0; case FAngle of 0..90: Y := Y + Trunc(W*fSinAngle); 91..180: Y := Y + Trunc(W*fSinAngle) - Trunc(H*fCosAngle); 181..270: Y := Y - Trunc(H*fCosAngle); end; if Y > (Rect.Bottom-Rect.Top) then Y := Rect.Bottom-Rect.Top; OldFontHandle := SelectObject(Handle, NewFontHandle); with BRect do begin Left := Rect.Left + X; Top := Rect.Top + Y; Right := Rect.Right; Bottom := Rect.Bottom; end; FGeneratedImage.Canvas.TextOut(BRect.Left, BRect.Top, AText); NewFontHandle := SelectObject(FGeneratedImage.Canvas.Handle, OldFontHandle); DeleteObject(NewFontHandle); end; end; procedure TSMCaptcha.Paint; begin inherited; Canvas.StretchDraw(ClientRect, FGeneratedImage); end; function TSMCaptcha.ValidateValue(const AValue: string): Boolean; begin if CaseSensetive then Result := (CompareStr(AValue, FCaptchaValue) = 0) else Result := (CompareText(AValue, FCaptchaValue) = 0); end; end.
{$i deltics.inc} unit Test.WeakInterfaceReference; interface uses Deltics.Smoketest; type TWeakInterfaceReferenceTests = class(TTest) private fOnDestroyCallCount: Integer; procedure OnDestroyCallCounter(aSender: TObject); published procedure SetupMethod; procedure ReferencedObjectDestroyingDoesNotCrashIfWeakReferenceHasBeenDestroyed; procedure WeakInterfaceReferenceIsNILedWhenReferencedObjectIsDestroyed; procedure IsReferenceToIsTRUEWhenReferenceIsTheSameAndNotNIL; procedure IsReferenceToIsTRUEWhenReferencesAreNIL; procedure IsReferenceToIsFALSEWhenOneIsNIL; procedure IsReferenceToIsFALSEWhenReferencesAreDifferent; end; implementation uses Deltics.InterfacedObjects, Deltics.Multicast; { TInterfacedObjectTests } procedure TWeakInterfaceReferenceTests.OnDestroyCallCounter(aSender: TObject); begin Inc(fOnDestroyCallCount); end; procedure TWeakInterfaceReferenceTests.SetupMethod; begin fOnDestroyCallCount := 0; end; procedure TWeakInterfaceReferenceTests.ReferencedObjectDestroyingDoesNotCrashIfWeakReferenceHasBeenDestroyed; var foo: IUnknown; sut: TWeakInterfaceReference; iod: IOn_Destroy; begin Test('OnDestroyCallCount').Assert(fOnDestroyCallCount).Equals(0); foo := TComInterfacedObject.Create; iod := foo as IOn_Destroy; iod.Add(OnDestroyCallCounter); iod := NIL; Test('OnDestroyCallCount').Assert(fOnDestroyCallCount).Equals(0); // Create and immediately Destroy a weak reference to foo sut := TWeakInterfaceReference.Create(foo); sut.Free; Test('OnDestroyCallCount').Assert(fOnDestroyCallCount).Equals(0); // NIL'ing the ref to foo will destroy foo which will notify any listeners // via the On_Destroy foo := NIL; Test('OnDestroyCallCount').Assert(fOnDestroyCallCount).Equals(1); end; procedure TWeakInterfaceReferenceTests.WeakInterfaceReferenceIsNILedWhenReferencedObjectIsDestroyed; var foo: IUnknown; sut: TWeakInterfaceReference; iod: IOn_Destroy; begin foo := TComInterfacedObject.Create; iod := foo as IOn_Destroy; iod.Add(OnDestroyCallCounter); iod := NIL; Test('OnDestroyCallCount').Assert(fOnDestroyCallCount).Equals(0); sut := TWeakInterfaceReference.Create(foo); try // NIL'ing foo leaves the TWeakInterfaceReference as the only reference // to foo (it should not have been destroyed) foo := NIL; Test('OnDestroyCallCount').Assert(fOnDestroyCallCount).Equals(1); Test('WeakReference').Assert(NOT Assigned(sut as IUnknown)); finally sut.Free; end; end; procedure TWeakInterfaceReferenceTests.IsReferenceToIsFALSEWhenReferencesAreDifferent; var a, b: IUnknown; sut: TWeakInterfaceReference; begin a := TComInterfacedObject.Create; b := TComInterfacedObject.Create; sut := TWeakInterfaceReference.Create(a); try Test('IsReferenceTo').Assert(NOT sut.IsReferenceTo(b)); finally sut.Free; end; end; procedure TWeakInterfaceReferenceTests.IsReferenceToIsFALSEWhenOneIsNIL; var a, b: IUnknown; sut: TWeakInterfaceReference; begin a := TComInterfacedObject.Create; b := NIL; sut := TWeakInterfaceReference.Create(a); try Test('IsReferenceTo(NIL)').Assert(NOT sut.IsReferenceTo(b)); finally sut.Free; end; sut := TWeakInterfaceReference.Create(b); try Test('IsReferenceTo(<intf>)').Assert(NOT sut.IsReferenceTo(a)); finally sut.Free; end; end; procedure TWeakInterfaceReferenceTests.IsReferenceToIsTRUEWhenReferenceIsTheSameAndNotNIL; var a, b: IUnknown; sut: TWeakInterfaceReference; begin a := TComInterfacedObject.Create; b := a; sut := TWeakInterfaceReference.Create(a); try Test('IsReferenceTo').Assert(sut.IsReferenceTo(b)); finally sut.Free; end; end; procedure TWeakInterfaceReferenceTests.IsReferenceToIsTRUEWhenReferencesAreNIL; var sut: TWeakInterfaceReference; begin sut := TWeakInterfaceReference.Create(NIL); try Test('IsReferenceTo').Assert(sut.IsReferenceTo(NIL)); finally sut.Free; end; end; end.
{*******************************************************} { } { FMX UI 中国农历数据单元 } { } { 版权所有 (C) 2017 YangYxd } { } {*******************************************************} { 注意: 本单元数据部分由 Jea杨(JJonline@JJonline.Cn) JavaScript 翻译而来, 部分算法进行了优化和修改。 http://blog.jjonline.cn/userInterFace/173.html/comment-page-2 } unit UI.Calendar.Data; interface uses UI.Utils, Classes, SysUtils, Math, DateUtils; type /// <summary> /// 农历信息 /// </summary> TLunarData = record private iTerm: SmallInt; iUpdateGZM: Boolean; function GetAnimalStr: string; function GetAstro: string; function GetGanZhi: string; function GetGanZhiDay: string; function GetGanZhiMonth: string; function GetGanZhiYear: string; function GetIsTerm: Boolean; function GetTermStr: string; function GetCnDay: string; function GetCnMonth: string; function GetCnYear: string; public // 公历年月日 Y, M, D: Word; // 农历年,月,日,星期 Year, Month, Day: Word; // 是否闰月 IsLeap: Boolean; // 返回农历中文年月日字符串 function ToString(): string; // 生肖 property Animal: string read GetAnimalStr; // 节气与否 property IsTerm: Boolean read GetIsTerm; // 节气名称 property Term: string read GetTermStr; // 天干地支 property GanZhi: string read GetGanZhi; property GanZhiYear: string read GetGanZhiYear; property GanZhiMonth: string read GetGanZhiMonth; property GanZhiDay: string read GetGanZhiDay; // 星座 property Astro: string read GetAstro; property CnYear: string read GetCnYear; property CnMonth: string read GetCnMonth; property CnDay: string read GetCnDay; end; /// <summary> /// 传入公历年月日,获得详细的农历信息 /// </summary> function SolarToLunar(const Value: TDateTime = 0): TLunarData; overload; function SolarToLunar(Y, M, D: Word): TLunarData; overload; /// <summary> /// 传入农历年月日以及传入的月份是否闰月获得公历日期 /// <param name="IsLeapMonth">传入月份是否为润月</param> /// </summary> function LunarToSolar(const Y, M, D: Word; IsLeapMonth: Boolean = False): TDateTime; implementation const /// <summary> /// 农历 1900 - 2100 的润大小信息表 /// </summary> LunarInfo: array [0..200] of Integer = ( $04bd8, $04ae0, $0a570, $054d5, $0d260, $0d950, $16554, $056a0, $09ad0, $055d2, //1900-1909 $04ae0, $0a5b6, $0a4d0, $0d250, $1d255, $0b540, $0d6a0, $0ada2, $095b0, $14977, //1910-1919 $04970, $0a4b0, $0b4b5, $06a50, $06d40, $1ab54, $02b60, $09570, $052f2, $04970, //1920-1929 $06566, $0d4a0, $0ea50, $06e95, $05ad0, $02b60, $186e3, $092e0, $1c8d7, $0c950, //1930-1939 $0d4a0, $1d8a6, $0b550, $056a0, $1a5b4, $025d0, $092d0, $0d2b2, $0a950, $0b557, //1940-1949 $06ca0, $0b550, $15355, $04da0, $0a5b0, $14573, $052b0, $0a9a8, $0e950, $06aa0, //1950-1959 $0aea6, $0ab50, $04b60, $0aae4, $0a570, $05260, $0f263, $0d950, $05b57, $056a0, //1960-1969 $096d0, $04dd5, $04ad0, $0a4d0, $0d4d4, $0d250, $0d558, $0b540, $0b6a0, $195a6, //1970-1979 $095b0, $049b0, $0a974, $0a4b0, $0b27a, $06a50, $06d40, $0af46, $0ab60, $09570, //1980-1989 $04af5, $04970, $064b0, $074a3, $0ea50, $06b58, $055c0, $0ab60, $096d5, $092e0, //1990-1999 $0c960, $0d954, $0d4a0, $0da50, $07552, $056a0, $0abb7, $025d0, $092d0, $0cab5, //2000-2009 $0a950, $0b4a0, $0baa4, $0ad50, $055d9, $04ba0, $0a5b0, $15176, $052b0, $0a930, //2010-2019 $07954, $06aa0, $0ad50, $05b52, $04b60, $0a6e6, $0a4e0, $0d260, $0ea65, $0d530, //2020-2029 $05aa0, $076a3, $096d0, $04afb, $04ad0, $0a4d0, $1d0b6, $0d250, $0d520, $0dd45, //2030-2039 $0b5a0, $056d0, $055b2, $049b0, $0a577, $0a4b0, $0aa50, $1b255, $06d20, $0ada0, //2040-2049 // Add By JJonline@JJonline.Cn $14b63, $09370, $049f8, $04970, $064b0, $168a6, $0ea50, $06b20, $1a6c4, $0aae0, //2050-2059 $0a2e0, $0d2e3, $0c960, $0d557, $0d4a0, $0da50, $05d55, $056a0, $0a6d0, $055d4, //2060-2069 $052d0, $0a9b8, $0a950, $0b4a0, $0b6a6, $0ad50, $055a0, $0aba4, $0a5b0, $052b0, //2070-2079 $0b273, $06930, $07337, $06aa0, $0ad50, $14b55, $04b60, $0a570, $054e4, $0d160, //2080-2089 $0e968, $0d520, $0daa0, $16aa6, $056d0, $04ae0, $0a9d4, $0a2d0, $0d150, $0f252, //2090-2099 $0d520 ); /// <summary> /// 公历每个月份的天数普通表 /// </summary> SolarMonth: array [0..11] of Integer = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); /// <summary> /// 天干地支之天干速查表 /// </summary> Gan: array [0..9] of string = ( '甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸' ); /// <summary> /// 天干地支之地支速查表 /// </summary> Zhi: array [0..11] of string = ( '子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥' ); /// <summary> /// 天干地支之地支速查表 - 生肖 /// </summary> Animals: array [0..11] of string = ( '鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪' ); /// <summary> /// 24节气速查表 /// </summary> SolarTerms: array [0..23] of string = ( '小寒', '大寒', '立春', '雨水', '惊蛰', '春分', '清明', '谷雨', '立夏', '小满', '芒种', '夏至', '小暑', '大暑', '立秋', '处暑', '白露', '秋分', '寒露', '霜降', '立冬', '小雪', '大雪', '冬至' ); /// <summary> /// 1900-2100各年的24节气日期速查表 /// </summary> STermInfo: array [0..200] of string = ( '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa', '9778397bd19801ec9210c965cc920e', '97b6b97bd19801ec95f8c965cc920f', '97bd09801d98082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2', '9778397bd197c36c9210c9274c91aa', '97b6b97bd19801ec95f8c965cc920e', '97bd09801d98082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec95f8c965cc920e', '97bcf97c3598082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd097bd07f595b0b6fc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '9778397bd19801ec9210c9274c920e', '97b6b97bd19801ec95f8c965cc920f', '97bd07f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c920e', '97b6b97bd19801ec95f8c965cc920f', '97bd07f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bd07f1487f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c9274c920e', '97bcf7f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c91aa', '97b6b97bd197c36c9210c9274c920e', '97bcf7f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c920e', '97b6b7f0e47f531b0723b0b6fb0722', '7f0e37f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36b0b70c9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e37f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc9210c8dc2', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0787b0721', '7f0e27f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c91aa', '97b6b7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '977837f0e37f149b0723b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f5307f595b0b0bc920fb0722', '7f0e397bd097c35b0b6fc9210c8dc2', '977837f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e37f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc9210c8dc2', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0723b06bd', '7f07e7f0e37f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f1487f595b0b0bb0b6fb0722', '7f0e37f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e37f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f149b0723b0787b0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0723b06bd', '7f07e7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', '7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0723b06bd', '7f07e7f0e37f14998083b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', '7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14898082b0723b02d5', '7f07e7f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e36665b66aa89801e9808297c35', '665f67f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e36665b66a449801e9808297c35', '665f67f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e36665b66a449801e9808297c35', '665f67f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e26665b66a449801e9808297c35', '665f67f0e37f1489801eb072297c35', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722' ); /// <summary> /// 数字转中文速查表 /// </summary> nStr1: array [0 .. 11] of string = ( '日', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '〇' ); /// <summary> /// 日期转农历称呼速查表 /// </summary> nStr2: array [0 .. 3] of string = ( '初', '十', '廿', '卅' ); /// <summary> /// 月份转农历称呼速查表 /// </summary> nStr3: array [0 .. 11] of string = ( '正','二','三','四','五','六','七','八','九','十','冬','腊' ); nStr4: array [0 .. 3] of string = ( '年', '月', '日', '座' ); const UTC19001031 = -2206396800000; var LYearDaysCacle: array of Integer; const UnixDateDelta: Extended = 25569; SecsPerDay: Int64 = 86400000; // 计算指定年月日UTC时间 (与JavaScript一致) function UTC(const Y, M, D: Word): Int64; var LDate: TDateTime; begin if TryEncodeDate(Y, M, D, LDate) then begin Result := Round((LDate - UnixDateDelta) * SecsPerDay); // - 28800000; end else Result := 0; end; function UTCToDateTime(const V: Int64): TDateTime; begin Result := V / SecsPerDay + UnixDateDelta; end; // 返回农历y年闰月是哪个月;若y年没有闰月 则返回0 function LeapMonth(const Y: Word): Integer; inline; begin Result := LunarInfo[Y - 1900] and $F; end; // 返回农历y年闰月的天数 若该年没有闰月则返回0 function LeapDays(const Y: Word): Integer; begin if LeapMonth(Y) <> 0 then begin if LunarInfo[Y-1900] and $10000 <> 0 then Result := 30 else Result := 29; end else Result := 0; end; // 返回农历y年一整年的总天数 function InnerGetYearDays(const Y: Word): Integer; var I, Sum: Integer; begin Sum := 348; I := $8000; while I > $8 do begin if (LunarInfo[Y - 1900] and I) <> 0 then Inc(Sum); I := I shr 1; end; Result := Sum + LeapDays(Y); end; function GetYearDays(const Y: Word): Integer; inline; begin Result := LYearDaysCacle[Y - 1900]; end; // 返回农历y年m月(非闰月)的总天数,计算m为闰月时的天数请使用leapDays方法 function GetMonthDays(const Y, M: Word): Integer; begin if (M > 12) or (M < 1) then Result := -1 else begin if LunarInfo[Y-1900] and ($10000 shr M) <> 0 then Result := 30 else Result := 29; end; end; procedure InitYearDaysCacle(); var I: Integer; begin SetLength(LYearDaysCacle, 201); for I := 1900 to 2100 do LYearDaysCacle[I - 1900] := InnerGetYearDays(I); end; function SolarToLunar(const Value: TDateTime): TLunarData; var Y, M, D: Word; begin if Value = 0 then Result := SolarToLunar(0, 0, 0) else begin DecodeDate(Value, Y, M, D); Result := SolarToLunar(Y, M, D); end; end; // 农历年份转换为干支纪年 function ToGanZhiYear(const Year: Word): string; var ganKey, zhiKey: Integer; begin ganKey := (Year - 3) mod 10; zhiKey := (Year - 3) mod 12; if (ganKey = 0) then ganKey := 10; //如果余数为0则为最后一个天干 if (zhiKey = 0) then zhiKey := 12; //如果余数为0则为最后一个地支 Result := Gan[ganKey - 1] + Zhi[zhiKey - 1]; end; /// <summary> /// 传入offset偏移量返回干支 /// <param name="Offset">相对甲子的偏移量</param> /// </summary> function ToGanZhi(const Offset: Integer): string; begin Result := Gan[offset mod 10] + Zhi[offset mod 12]; end; // 传入农历数字月份返回汉语通俗表示法 function ToChinaMonth(const M: Word): string; begin if (M > 12) or (M < 1) then Result := '' else Result := nStr3[M - 1] + nStr4[1]; end; // 传入农历日期数字返回汉字表示法 function ToChinaDay(const D: Word): string; begin case D of 10: Result := '初十'; 20: Result := '二十'; 30: Result := '三十'; else begin Result := nStr2[Floor(D div 10)] + nStr1[D mod 10]; end; end; end; /// <summary> /// 传入公历(!)y年获得该年第n个节气的公历日期 /// <param name="Y">公历年(1900-2100) </param> /// <param name="N">二十四节气中的第几个节气(1~24);从n=1(小寒)算起</param> /// </summary> function GetTerm(const Y, N: Integer): Integer; const CALDAY: array [0..23] of SmallInt = (0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4, 5,5,5,5); CALDAYL: array [0..23] of SmallInt = (0,1,3,4, 0,1,3,4, 0,1,3,4, 0,1,3,4, 0,1,3,4, 0,1,3,4); CALDAYE: array [0..23] of SmallInt = (1,2,1,2, 1,2,1,2, 1,2,1,2, 1,2,1,2, 1,2,1,2, 1,2,1,2); var LTable: string; P: PChar; I: Integer; begin Result := -1; if (Y < 1900) or (Y > 2100) then Exit; if (N < 1) or (N > 24) then Exit; LTable := STermInfo[Y - 1900]; P := PChar(LTable); I := CALDAY[N - 1]; LTable := IntToStr(PHexToIntDef(P + I * 5, 5)); P := PChar(LTable); I := N - 1; Result := PCharToIntDef(P+CALDAYL[I], CALDAYE[I]); end; function SolarToLunar(Y, M, D: Word): TLunarData; var offset, I, temp, Leap: Integer; firstNode, secondNode: Integer; begin FillChar(Result, SizeOf(Result), 0); // 未传参获得当天 if (Y = 0) and (M = 0) and (D = 0) then DecodeDate(Now, Y, M, D); Result.Y := Y; Result.M := M; Result.D := D; Result.iTerm := -1; Result.iUpdateGZM := False; //年份限定、上限 if (Y < 1900) or (Y > 2100) then Exit; //公历传参最下限 if (Y = 1900) and (M = 1) and (D < 31) then Exit; offset := (UTC(Y, M, D) - UTC19001031) div 86400000; temp := 0; I := 1900; while (I < 2101) and (offset > 0) do begin temp := GetYearDays(I); Dec(offset, temp); Inc(I); end; if offset < 0 then begin offset := offset + temp; Dec(I); end; // 农历年 Result.Year := I; Leap := LeapMonth(I); //闰哪个月 Result.IsLeap := False; //效验闰月 I := 1; while (I <= 12) and (offset > 0) do begin //闰月 if (Leap > 0) and (not Result.IsLeap) and (I = (Leap)+1) then begin Dec(i); Result.IsLeap := True; temp := LeapDays(Result.Year); //计算农历闰月天数 end else temp := GetMonthDays(Result.Year, I); //计算农历普通月天数 //解除闰月 if Result.IsLeap and (I = Leap+1) then Result.IsLeap := False; Dec(Offset, temp); Inc(I); end; // 闰月导致数组下标重叠取反 if (offset = 0) and (Leap > 0) and (I = Leap+1) then begin if Result.IsLeap then Result.IsLeap := False else begin Result.IsLeap := True; Dec(I); end; end; if (offset < 0) then begin offset := offset + temp; Dec(I); end; //农历月 Result.Month := I; //农历日 Result.Day := offset + 1; // 当月的两个节气 firstNode := GetTerm(Y, M * 2 - 1); //返回当月「节」为几日开始 secondNode := GetTerm(Y, M * 2); //返回当月「节」为几日开始 // 是否需要依据节气修正干支月 Result.iUpdateGZM := D >= firstNode; if firstNode = D then Result.iTerm := M * 2 - 2; if secondNode = D then Result.iTerm := M * 2 - 1; end; function LunarToSolar(const Y, M, D: Word; IsLeapMonth: Boolean): TDateTime; var I: Integer; leapMon, day, offset, leap: Integer; isAdd: Boolean; stmap: Int64; begin Result := 0; leapMon := LeapMonth(Y); if IsLeapMonth and (leapMon <> M) then IsLeapMonth := False; //传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同 if (Y = 2100) and (M = 12) and (D > 30) then Exit; if (Y = 1900) and (M = 1) and (D < 1) then Exit; day := GetMonthDays(Y, M); if IsLeapMonth then day := LeapDays(Y); if (Y < 1900) or (Y > 2100) or (D > day) then Exit; offset := 0; for I := 1900 to Y - 1 do offset := offset + GetYearDays(I); isAdd := False; leap := LeapMonth(Y); for I := 1 to M - 1 do begin if not isAdd then begin if (leap <= i) and (leap > 0) then begin //处理闰月 Inc(offset, LeapDays(Y)); isAdd := True; end; end; Inc(offset, GetMonthDays(Y, I)); end; //转换闰月农历 需补充该年闰月的前一个月的时差 if IsLeapMonth then Inc(offset, day); //stmap := UTC(1900, 1, 30); stmap := (Int64(offset + D - 31) * 86400 + -2203804800) * 1000; Result := UTCToDateTime(stmap); end; { TLunarData } function TLunarData.GetAnimalStr: string; begin Result := Animals[(Y - 4) mod 12]; end; function TLunarData.GetAstro: string; const CStr = '魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯'; ARR: array [0..11] of Integer = (20,19,21,21,21,22,23,23,23,23,22,22); function GetIndex(): Integer; begin Result := M * 2 + 1; if D < ARR[M - 1] then Dec(Result, 2); end; begin Result := Copy(CStr, GetIndex, 2) + nStr4[3]; end; function TLunarData.GetCnDay: string; begin Result := ToChinaDay(Day) end; function TLunarData.GetCnMonth: string; begin Result := ToChinaMonth(Month) end; function TLunarData.GetCnYear: string; function VV(const I: Integer): string; begin if I = 0 then Result := nStr1[11] else if (I >= 1) and (I <= 9) then Result := nStr1[I] else Result := ''; end; var L: string; I: Integer; begin L := IntToStr(Year); Result := ''; for I := 1 to Length(L) do Result := Result + VV(StrToIntDef(L[I], 0)); Result := Result + nStr4[0]; end; function TLunarData.GetGanZhi: string; begin Result := GanZhiYear + nStr4[0] + GanZhiMonth + GanZhiDay; end; function TLunarData.GetGanZhiDay: string; var dayCyclical: Integer; // 日柱 当月一日与 1900/1/1 相差天数 begin dayCyclical := UTC(Y, M, 1) div 86400000 + 25567 + 10; Result := ToGanZhi(dayCyclical + D - 1); end; function TLunarData.GetGanZhiMonth: string; begin if iUpdateGZM then Result := ToGanZhi((Y - 1900) * 12 + M + 12) // 依据12节气修正干支月 else Result := ToGanZhi((Y - 1900) * 12 + M + 11) end; function TLunarData.GetGanZhiYear: string; begin Result := ToGanZhiYear(Year); end; function TLunarData.GetIsTerm: Boolean; begin Result := iTerm >= 0; end; function TLunarData.GetTermStr: string; begin if iTerm < 0 then Result := '' else Result := SolarTerms[iTerm]; end; function TLunarData.ToString: string; begin Result := CnYear + CnMonth + CnDay; end; initialization InitYearDaysCacle(); end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormDestroy(Sender: TObject); private hrc: HGLRC; end; var frmGL: TfrmGL; implementation {$R *.DFM} {======================================================================= Перерисовка окна} procedure TfrmGL.FormPaint(Sender: TObject); var i : 0..6; begin wglMakeCurrent(Canvas.Handle, hrc); glViewPort (0, 0, ClientWidth, ClientHeight); glClearColor (0.75, 0.75, 0.75, 1.0); glClear (GL_COLOR_BUFFER_BIT); glColor3f (0.0, 0.0, 0.75); glTranslatef (0.4, 0.1, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glPointSize (10); glEnable (GL_POINT_SMOOTH); For i := 0 to 5 do begin glBegin (GL_POINTS); glVertex2f (0.0, 0.0); glEnd; glTranslatef (-0.3, 0.3, 0.0); glRotatef (60, 0, 0, 1); glBegin (GL_POLYGON); glVertex2f (-0.125, -0.125); glVertex2f (-0.125, 0.125); glVertex2f (0.125, 0.125); glVertex2f (0.125, -0.125); glEnd; end; glTranslatef (-0.4, -0.1, 0.0); SwapBuffers(Canvas.Handle); // содержимое буфера - на экран wglMakeCurrent(0, 0); end; {======================================================================= Формат пикселя} procedure SetDCPixelFormat (hdc : HDC); var pfd : TPixelFormatDescriptor; nPixelFormat : Integer; begin FillChar (pfd, SizeOf (pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat (hdc, @pfd); SetPixelFormat (hdc, nPixelFormat, @pfd); end; {======================================================================= Создание формы} procedure TfrmGL.FormCreate(Sender: TObject); begin SetDCPixelFormat(Canvas.Handle); hrc := wglCreateContext(Canvas.Handle); end; {======================================================================= Конец работы приложения} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglDeleteContext(hrc); end; end.
{*****************************************************************************} { } { XML Data Binding } { } { Generated on: 25.02.2006 11:51:20 } { Generated from: Q:\RegExpr\Test\Tests\RegularExpressionsXMLBind.xml } { Settings stored in: Q:\RegExpr\Test\Tests\RegularExpressionsXMLBind.xdb } { } {*****************************************************************************} unit RegularExpressionsXMLBind; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLRegularExpressionsType = interface; IXMLRegularExpressionType = interface; IXMLTestCaseType = interface; IXMLTestCaseTypeList = interface; IXMLSubjectType = interface; IXMLSubstringType = interface; IXMLMatchType = interface; IXMLMatchTypeList = interface; IXMLSubstitutionType = interface; IXMLSubstitutionTypeList = interface; IXMLReplaceType = interface; IXMLReplaceTypeList = interface; IXMLString_List = interface; { IXMLRegularExpressionsType } IXMLRegularExpressionsType = interface(IXMLNodeCollection) ['{A7D5B1B3-C40D-4D63-8270-146EE0667E7F}'] { Property Accessors } function Get_RegularExpression(Index: Integer): IXMLRegularExpressionType; { Methods & Properties } function Add: IXMLRegularExpressionType; function Insert(const Index: Integer): IXMLRegularExpressionType; property RegularExpression[Index: Integer]: IXMLRegularExpressionType read Get_RegularExpression; default; end; { IXMLRegularExpressionType } IXMLRegularExpressionType = interface(IXMLNode) ['{6CD4EDE6-B46D-4764-BD0E-61660204612A}'] { Property Accessors } function Get_Id: Integer; function Get_Name: WideString; function Get_Description: WideString; function Get_Comment: WideString; function Get_Expression: WideString; function Get_Category: IXMLString_List; function Get_TestCase: IXMLTestCaseTypeList; procedure Set_Id(Value: Integer); procedure Set_Name(Value: WideString); procedure Set_Description(Value: WideString); procedure Set_Comment(Value: WideString); procedure Set_Expression(Value: WideString); { Methods & Properties } property Id: Integer read Get_Id write Set_Id; property Name: WideString read Get_Name write Set_Name; property Description: WideString read Get_Description write Set_Description; property Comment: WideString read Get_Comment write Set_Comment; property Expression: WideString read Get_Expression write Set_Expression; property Category: IXMLString_List read Get_Category; property TestCase: IXMLTestCaseTypeList read Get_TestCase; end; { IXMLTestCaseType } IXMLTestCaseType = interface(IXMLNode) ['{A087D83F-28E1-486A-AE80-CA8AE4CFE8A8}'] { Property Accessors } function Get_Modifiers: WideString; function Get_Subject: IXMLSubjectType; function Get_Match: IXMLMatchTypeList; function Get_Substitution: IXMLSubstitutionTypeList; function Get_Replace: IXMLReplaceTypeList; procedure Set_Modifiers(Value: WideString); { Methods & Properties } property Modifiers: WideString read Get_Modifiers write Set_Modifiers; property Subject: IXMLSubjectType read Get_Subject; property Match: IXMLMatchTypeList read Get_Match; property Substitution: IXMLSubstitutionTypeList read Get_Substitution; property Replace: IXMLReplaceTypeList read Get_Replace; end; { IXMLTestCaseTypeList } IXMLTestCaseTypeList = interface(IXMLNodeCollection) ['{FFE9C8E6-06FA-42E8-B469-CF4B75B9CAFE}'] { Methods & Properties } function Add: IXMLTestCaseType; function Insert(const Index: Integer): IXMLTestCaseType; function Get_Item(Index: Integer): IXMLTestCaseType; property Items[Index: Integer]: IXMLTestCaseType read Get_Item; default; end; { IXMLSubjectType } IXMLSubjectType = interface(IXMLNodeCollection) ['{B8582A18-07B0-4A22-8916-FDCC7CB7137A}'] { Property Accessors } function Get_Substring(Index: Integer): IXMLSubstringType; { Methods & Properties } function Add: IXMLSubstringType; function Insert(const Index: Integer): IXMLSubstringType; property Substring[Index: Integer]: IXMLSubstringType read Get_Substring; default; end; { IXMLSubstringType } IXMLSubstringType = interface(IXMLNode) ['{F263D564-1EC6-4FCA-BEBB-4390B9E50734}'] { Property Accessors } function Get_RepeatCount: Integer; function Get_FileName: WideString; procedure Set_RepeatCount(Value: Integer); procedure Set_FileName(Value: WideString); { Methods & Properties } property RepeatCount: Integer read Get_RepeatCount write Set_RepeatCount; property FileName: WideString read Get_FileName write Set_FileName; end; { IXMLMatchType } IXMLMatchType = interface(IXMLNodeCollection) ['{C484715D-A39C-49AF-85B5-C97E16022397}'] { Property Accessors } function Get_Position: Integer; function Get_Length: Integer; function Get_CapturedSubstring(Index: Integer): WideString; procedure Set_Position(Value: Integer); procedure Set_Length(Value: Integer); { Methods & Properties } function Add(const CapturedSubstring: WideString): IXMLNode; function Insert(const Index: Integer; const CapturedSubstring: WideString): IXMLNode; property Position: Integer read Get_Position write Set_Position; property Length: Integer read Get_Length write Set_Length; property CapturedSubstring[Index: Integer]: WideString read Get_CapturedSubstring; default; end; { IXMLMatchTypeList } IXMLMatchTypeList = interface(IXMLNodeCollection) ['{9699FB75-7D5C-4906-9218-7CA89995B208}'] { Methods & Properties } function Add: IXMLMatchType; function Insert(const Index: Integer): IXMLMatchType; function Get_Item(Index: Integer): IXMLMatchType; property Items[Index: Integer]: IXMLMatchType read Get_Item; default; end; { IXMLSubstitutionType } IXMLSubstitutionType = interface(IXMLNode) ['{B0E59E06-3FDB-48D7-857A-169599156F93}'] { Property Accessors } function Get_Template: WideString; function Get_Result: WideString; procedure Set_Template(Value: WideString); procedure Set_Result(Value: WideString); { Methods & Properties } property Template: WideString read Get_Template write Set_Template; property Result: WideString read Get_Result write Set_Result; end; { IXMLSubstitutionTypeList } IXMLSubstitutionTypeList = interface(IXMLNodeCollection) ['{4389D23C-1983-42D4-B37A-2DAD2CD8E05E}'] { Methods & Properties } function Add: IXMLSubstitutionType; function Insert(const Index: Integer): IXMLSubstitutionType; function Get_Item(Index: Integer): IXMLSubstitutionType; property Items[Index: Integer]: IXMLSubstitutionType read Get_Item; default; end; { IXMLReplaceType } IXMLReplaceType = interface(IXMLNode) ['{20CBB304-7D53-40B9-87D2-5CB502AFE298}'] { Property Accessors } function Get_Template: WideString; function Get_Result: WideString; procedure Set_Template(Value: WideString); procedure Set_Result(Value: WideString); { Methods & Properties } property Template: WideString read Get_Template write Set_Template; property Result: WideString read Get_Result write Set_Result; end; { IXMLReplaceTypeList } IXMLReplaceTypeList = interface(IXMLNodeCollection) ['{845B6020-3A75-42D3-8BC4-EF7F9E6A34FF}'] { Methods & Properties } function Add: IXMLReplaceType; function Insert(const Index: Integer): IXMLReplaceType; function Get_Item(Index: Integer): IXMLReplaceType; property Items[Index: Integer]: IXMLReplaceType read Get_Item; default; end; { IXMLString_List } IXMLString_List = interface(IXMLNodeCollection) ['{174F014A-A1B9-4FDC-BF2B-1D21F3D6E41A}'] { Methods & Properties } function Add(const Value: WideString): IXMLNode; function Insert(const Index: Integer; const Value: WideString): IXMLNode; function Get_Item(Index: Integer): WideString; property Items[Index: Integer]: WideString read Get_Item; default; end; { Forward Decls } TXMLRegularExpressionsType = class; TXMLRegularExpressionType = class; TXMLTestCaseType = class; TXMLTestCaseTypeList = class; TXMLSubjectType = class; TXMLSubstringType = class; TXMLMatchType = class; TXMLMatchTypeList = class; TXMLSubstitutionType = class; TXMLSubstitutionTypeList = class; TXMLReplaceType = class; TXMLReplaceTypeList = class; TXMLString_List = class; { TXMLRegularExpressionsType } TXMLRegularExpressionsType = class(TXMLNodeCollection, IXMLRegularExpressionsType) protected { IXMLRegularExpressionsType } function Get_RegularExpression(Index: Integer): IXMLRegularExpressionType; function Add: IXMLRegularExpressionType; function Insert(const Index: Integer): IXMLRegularExpressionType; public procedure AfterConstruction; override; end; { TXMLRegularExpressionType } TXMLRegularExpressionType = class(TXMLNode, IXMLRegularExpressionType) private FCategory: IXMLString_List; FTestCase: IXMLTestCaseTypeList; protected { IXMLRegularExpressionType } function Get_Id: Integer; function Get_Name: WideString; function Get_Description: WideString; function Get_Comment: WideString; function Get_Expression: WideString; function Get_Category: IXMLString_List; function Get_TestCase: IXMLTestCaseTypeList; procedure Set_Id(Value: Integer); procedure Set_Name(Value: WideString); procedure Set_Description(Value: WideString); procedure Set_Comment(Value: WideString); procedure Set_Expression(Value: WideString); public procedure AfterConstruction; override; end; { TXMLTestCaseType } TXMLTestCaseType = class(TXMLNode, IXMLTestCaseType) private FMatch: IXMLMatchTypeList; FSubstitution: IXMLSubstitutionTypeList; FReplace: IXMLReplaceTypeList; protected { IXMLTestCaseType } function Get_Modifiers: WideString; function Get_Subject: IXMLSubjectType; function Get_Match: IXMLMatchTypeList; function Get_Substitution: IXMLSubstitutionTypeList; function Get_Replace: IXMLReplaceTypeList; procedure Set_Modifiers(Value: WideString); public procedure AfterConstruction; override; end; { TXMLTestCaseTypeList } TXMLTestCaseTypeList = class(TXMLNodeCollection, IXMLTestCaseTypeList) protected { IXMLTestCaseTypeList } function Add: IXMLTestCaseType; function Insert(const Index: Integer): IXMLTestCaseType; function Get_Item(Index: Integer): IXMLTestCaseType; end; { TXMLSubjectType } TXMLSubjectType = class(TXMLNodeCollection, IXMLSubjectType) protected { IXMLSubjectType } function Get_Substring(Index: Integer): IXMLSubstringType; function Add: IXMLSubstringType; function Insert(const Index: Integer): IXMLSubstringType; public procedure AfterConstruction; override; end; { TXMLSubstringType } TXMLSubstringType = class(TXMLNode, IXMLSubstringType) protected { IXMLSubstringType } function Get_RepeatCount: Integer; function Get_FileName: WideString; procedure Set_RepeatCount(Value: Integer); procedure Set_FileName(Value: WideString); end; { TXMLMatchType } TXMLMatchType = class(TXMLNodeCollection, IXMLMatchType) protected { IXMLMatchType } function Get_Position: Integer; function Get_Length: Integer; function Get_CapturedSubstring(Index: Integer): WideString; procedure Set_Position(Value: Integer); procedure Set_Length(Value: Integer); function Add(const CapturedSubstring: WideString): IXMLNode; function Insert(const Index: Integer; const CapturedSubstring: WideString): IXMLNode; public procedure AfterConstruction; override; end; { TXMLMatchTypeList } TXMLMatchTypeList = class(TXMLNodeCollection, IXMLMatchTypeList) protected { IXMLMatchTypeList } function Add: IXMLMatchType; function Insert(const Index: Integer): IXMLMatchType; function Get_Item(Index: Integer): IXMLMatchType; end; { TXMLSubstitutionType } TXMLSubstitutionType = class(TXMLNode, IXMLSubstitutionType) protected { IXMLSubstitutionType } function Get_Template: WideString; function Get_Result: WideString; procedure Set_Template(Value: WideString); procedure Set_Result(Value: WideString); end; { TXMLSubstitutionTypeList } TXMLSubstitutionTypeList = class(TXMLNodeCollection, IXMLSubstitutionTypeList) protected { IXMLSubstitutionTypeList } function Add: IXMLSubstitutionType; function Insert(const Index: Integer): IXMLSubstitutionType; function Get_Item(Index: Integer): IXMLSubstitutionType; end; { TXMLReplaceType } TXMLReplaceType = class(TXMLNode, IXMLReplaceType) protected { IXMLReplaceType } function Get_Template: WideString; function Get_Result: WideString; procedure Set_Template(Value: WideString); procedure Set_Result(Value: WideString); end; { TXMLReplaceTypeList } TXMLReplaceTypeList = class(TXMLNodeCollection, IXMLReplaceTypeList) protected { IXMLReplaceTypeList } function Add: IXMLReplaceType; function Insert(const Index: Integer): IXMLReplaceType; function Get_Item(Index: Integer): IXMLReplaceType; end; { TXMLString_List } TXMLString_List = class(TXMLNodeCollection, IXMLString_List) protected { IXMLString_List } function Add(const Value: WideString): IXMLNode; function Insert(const Index: Integer; const Value: WideString): IXMLNode; function Get_Item(Index: Integer): WideString; end; { Global Functions } function GetregularExpressions(Doc: IXMLDocument): IXMLRegularExpressionsType; function LoadregularExpressions(const FileName: WideString): IXMLRegularExpressionsType; function NewregularExpressions: IXMLRegularExpressionsType; const TargetNamespace = ''; implementation { Global Functions } function GetregularExpressions(Doc: IXMLDocument): IXMLRegularExpressionsType; begin Result := Doc.GetDocBinding('regularExpressions', TXMLRegularExpressionsType, TargetNamespace) as IXMLRegularExpressionsType; end; function LoadregularExpressions(const FileName: WideString): IXMLRegularExpressionsType; begin Result := LoadXMLDocument(FileName).GetDocBinding('regularExpressions', TXMLRegularExpressionsType, TargetNamespace) as IXMLRegularExpressionsType; end; function NewregularExpressions: IXMLRegularExpressionsType; begin Result := NewXMLDocument.GetDocBinding('regularExpressions', TXMLRegularExpressionsType, TargetNamespace) as IXMLRegularExpressionsType; end; { TXMLRegularExpressionsType } procedure TXMLRegularExpressionsType.AfterConstruction; begin RegisterChildNode('regularExpression', TXMLRegularExpressionType); ItemTag := 'regularExpression'; ItemInterface := IXMLRegularExpressionType; inherited; end; function TXMLRegularExpressionsType.Get_RegularExpression(Index: Integer): IXMLRegularExpressionType; begin Result := List[Index] as IXMLRegularExpressionType; end; function TXMLRegularExpressionsType.Add: IXMLRegularExpressionType; begin Result := AddItem(-1) as IXMLRegularExpressionType; end; function TXMLRegularExpressionsType.Insert(const Index: Integer): IXMLRegularExpressionType; begin Result := AddItem(Index) as IXMLRegularExpressionType; end; { TXMLRegularExpressionType } procedure TXMLRegularExpressionType.AfterConstruction; begin RegisterChildNode('testCase', TXMLTestCaseType); FCategory := CreateCollection(TXMLString_List, IXMLNode, 'category') as IXMLString_List; FTestCase := CreateCollection(TXMLTestCaseTypeList, IXMLTestCaseType, 'testCase') as IXMLTestCaseTypeList; inherited; end; function TXMLRegularExpressionType.Get_Id: Integer; begin Result := AttributeNodes['id'].NodeValue; end; procedure TXMLRegularExpressionType.Set_Id(Value: Integer); begin SetAttribute('id', Value); end; function TXMLRegularExpressionType.Get_Name: WideString; begin Result := AttributeNodes['name'].Text; end; procedure TXMLRegularExpressionType.Set_Name(Value: WideString); begin SetAttribute('name', Value); end; function TXMLRegularExpressionType.Get_Description: WideString; begin Result := ChildNodes['description'].Text; end; procedure TXMLRegularExpressionType.Set_Description(Value: WideString); begin ChildNodes['description'].NodeValue := Value; end; function TXMLRegularExpressionType.Get_Comment: WideString; begin Result := ChildNodes['comment'].Text; end; procedure TXMLRegularExpressionType.Set_Comment(Value: WideString); begin ChildNodes['comment'].NodeValue := Value; end; function TXMLRegularExpressionType.Get_Expression: WideString; begin Result := ChildNodes['expression'].Text; end; procedure TXMLRegularExpressionType.Set_Expression(Value: WideString); begin ChildNodes['expression'].NodeValue := Value; end; function TXMLRegularExpressionType.Get_Category: IXMLString_List; begin Result := FCategory; end; function TXMLRegularExpressionType.Get_TestCase: IXMLTestCaseTypeList; begin Result := FTestCase; end; { TXMLTestCaseType } procedure TXMLTestCaseType.AfterConstruction; begin RegisterChildNode('subject', TXMLSubjectType); RegisterChildNode('match', TXMLMatchType); RegisterChildNode('substitution', TXMLSubstitutionType); RegisterChildNode('replace', TXMLReplaceType); FMatch := CreateCollection(TXMLMatchTypeList, IXMLMatchType, 'match') as IXMLMatchTypeList; FSubstitution := CreateCollection(TXMLSubstitutionTypeList, IXMLSubstitutionType, 'substitution') as IXMLSubstitutionTypeList; FReplace := CreateCollection(TXMLReplaceTypeList, IXMLReplaceType, 'replace') as IXMLReplaceTypeList; inherited; end; function TXMLTestCaseType.Get_Modifiers: WideString; begin Result := AttributeNodes['Modifiers'].Text; end; procedure TXMLTestCaseType.Set_Modifiers(Value: WideString); begin SetAttribute('Modifiers', Value); end; function TXMLTestCaseType.Get_Subject: IXMLSubjectType; begin Result := ChildNodes['subject'] as IXMLSubjectType; end; function TXMLTestCaseType.Get_Match: IXMLMatchTypeList; begin Result := FMatch; end; function TXMLTestCaseType.Get_Substitution: IXMLSubstitutionTypeList; begin Result := FSubstitution; end; function TXMLTestCaseType.Get_Replace: IXMLReplaceTypeList; begin Result := FReplace; end; { TXMLTestCaseTypeList } function TXMLTestCaseTypeList.Add: IXMLTestCaseType; begin Result := AddItem(-1) as IXMLTestCaseType; end; function TXMLTestCaseTypeList.Insert(const Index: Integer): IXMLTestCaseType; begin Result := AddItem(Index) as IXMLTestCaseType; end; function TXMLTestCaseTypeList.Get_Item(Index: Integer): IXMLTestCaseType; begin Result := List[Index] as IXMLTestCaseType; end; { TXMLSubjectType } procedure TXMLSubjectType.AfterConstruction; begin RegisterChildNode('substring', TXMLSubstringType); ItemTag := 'substring'; ItemInterface := IXMLSubstringType; inherited; end; function TXMLSubjectType.Get_Substring(Index: Integer): IXMLSubstringType; begin Result := List[Index] as IXMLSubstringType; end; function TXMLSubjectType.Add: IXMLSubstringType; begin Result := AddItem(-1) as IXMLSubstringType; end; function TXMLSubjectType.Insert(const Index: Integer): IXMLSubstringType; begin Result := AddItem(Index) as IXMLSubstringType; end; { TXMLSubstringType } function TXMLSubstringType.Get_RepeatCount: Integer; begin Result := AttributeNodes['repeatCount'].NodeValue; end; procedure TXMLSubstringType.Set_RepeatCount(Value: Integer); begin SetAttribute('repeatCount', Value); end; function TXMLSubstringType.Get_FileName: WideString; begin Result := AttributeNodes['fileName'].Text; end; procedure TXMLSubstringType.Set_FileName(Value: WideString); begin SetAttribute('fileName', Value); end; { TXMLMatchType } procedure TXMLMatchType.AfterConstruction; begin ItemTag := 'capturedSubstring'; ItemInterface := IXMLNode; inherited; end; function TXMLMatchType.Get_Position: Integer; begin Result := AttributeNodes['position'].NodeValue; end; procedure TXMLMatchType.Set_Position(Value: Integer); begin SetAttribute('position', Value); end; function TXMLMatchType.Get_Length: Integer; begin Result := AttributeNodes['length'].NodeValue; end; procedure TXMLMatchType.Set_Length(Value: Integer); begin SetAttribute('length', Value); end; function TXMLMatchType.Get_CapturedSubstring(Index: Integer): WideString; begin Result := List[Index].Text; end; function TXMLMatchType.Add(const CapturedSubstring: WideString): IXMLNode; begin Result := AddItem(-1); Result.NodeValue := CapturedSubstring; end; function TXMLMatchType.Insert(const Index: Integer; const CapturedSubstring: WideString): IXMLNode; begin Result := AddItem(Index); Result.NodeValue := CapturedSubstring; end; { TXMLMatchTypeList } function TXMLMatchTypeList.Add: IXMLMatchType; begin Result := AddItem(-1) as IXMLMatchType; end; function TXMLMatchTypeList.Insert(const Index: Integer): IXMLMatchType; begin Result := AddItem(Index) as IXMLMatchType; end; function TXMLMatchTypeList.Get_Item(Index: Integer): IXMLMatchType; begin Result := List[Index] as IXMLMatchType; end; { TXMLSubstitutionType } function TXMLSubstitutionType.Get_Template: WideString; begin Result := ChildNodes['template'].Text; end; procedure TXMLSubstitutionType.Set_Template(Value: WideString); begin ChildNodes['template'].NodeValue := Value; end; function TXMLSubstitutionType.Get_Result: WideString; begin Result := ChildNodes['result'].Text; end; procedure TXMLSubstitutionType.Set_Result(Value: WideString); begin ChildNodes['result'].NodeValue := Value; end; { TXMLSubstitutionTypeList } function TXMLSubstitutionTypeList.Add: IXMLSubstitutionType; begin Result := AddItem(-1) as IXMLSubstitutionType; end; function TXMLSubstitutionTypeList.Insert(const Index: Integer): IXMLSubstitutionType; begin Result := AddItem(Index) as IXMLSubstitutionType; end; function TXMLSubstitutionTypeList.Get_Item(Index: Integer): IXMLSubstitutionType; begin Result := List[Index] as IXMLSubstitutionType; end; { TXMLReplaceType } function TXMLReplaceType.Get_Template: WideString; begin Result := ChildNodes['template'].Text; end; procedure TXMLReplaceType.Set_Template(Value: WideString); begin ChildNodes['template'].NodeValue := Value; end; function TXMLReplaceType.Get_Result: WideString; begin Result := ChildNodes['result'].Text; end; procedure TXMLReplaceType.Set_Result(Value: WideString); begin ChildNodes['result'].NodeValue := Value; end; { TXMLReplaceTypeList } function TXMLReplaceTypeList.Add: IXMLReplaceType; begin Result := AddItem(-1) as IXMLReplaceType; end; function TXMLReplaceTypeList.Insert(const Index: Integer): IXMLReplaceType; begin Result := AddItem(Index) as IXMLReplaceType; end; function TXMLReplaceTypeList.Get_Item(Index: Integer): IXMLReplaceType; begin Result := List[Index] as IXMLReplaceType; end; { TXMLString_List } function TXMLString_List.Add(const Value: WideString): IXMLNode; begin Result := AddItem(-1); Result.NodeValue := Value; end; function TXMLString_List.Insert(const Index: Integer; const Value: WideString): IXMLNode; begin Result := AddItem(Index); Result.NodeValue := Value; end; function TXMLString_List.Get_Item(Index: Integer): WideString; begin Result := List[Index].NodeValue; end; end.
unit FileController; // Controls saving, loading, deleting files interface uses Main, Add, IOUtils, SysUtils, ClientModuleUnit, Data.FireDACJSONReflect, NetworkState, UITypes; var AddFilename: string; EditFilename: string; DeleteFilename: string; // If AVW folder doesn't exist, create it // Should be called before saving any file procedure EnsureDirExists; procedure GetFromFile; procedure RemoveFile(Str : string); procedure RefreshClients; implementation // If AVW folder doesn't exist, create it // Should be called before saving any file procedure EnsureDirExists; var DirName : String; begin DirName := IOUtils.TPath.Combine(IOUtils.TPath.GetDocumentsPath, 'AVW'); if not DirectoryExists(DirName) then begin CreateDir(DirName); end; end; procedure GetFromFile; begin // Set global file names AddFilename := IOUtils.TPath.Combine(IOUtils.TPath.GetDocumentsPath, IOUtils.TPath.Combine('AVW','ToAdd')); EditFilename:= IOUtils.TPath.Combine(IOUtils.TPath.GetDocumentsPath, IOUtils.TPath.Combine('AVW','ToEdit')); DeleteFileName := IOUtils.TPath.Combine(IOUtils.TPath.GetDocumentsPath, IOUtils.TPath.Combine('AVW','ToDelete')); // If there were records added while offline, add to MemTable if FileExists(AddFilename+'.FDS') then begin Main.HeaderFooterForm.FDMemTable_Add.LoadFromFile(AddFilename); SysUtils.DeleteFile(AddFilename+'.FDS'); end; // If there were records edited while offline, add to MemTable if FileExists(EditFilename+'.FDS') then begin Main.HeaderFooterForm.FDMemTable_Edit.LoadFromFile(EditFilename); SysUtils.DeleteFile(EditFilename+'.FDS'); end; // If there were records deleted while offline, add to MemTable if FileExists(DeleteFilename+'.FDS') then begin Main.HeaderFooterForm.FDMemTable_Delete.LoadFromFile(DeleteFilename); SysUtils.DeleteFile(DeleteFilename+'.FDS'); end; end; procedure RemoveFile(Str : string); begin if FileExists(Str+'.FDS') then begin DeleteFile(Str); end; end; procedure RefreshClients; var LDataSetList: TFDJSONDataSets; NS: TNetworkState; begin try try NS := TNetworkState.Create; if NS.IsConnected then begin // Empties the memory table of any existing data before adding the new context. Add.FormAdd.FDMemTable_Clients.Close; // Get dataset list containing Employee names LDataSetList := ClientModule.ServerMethods1Client.GetClients; // Add to MemTable Add.FormAdd.FDMemTable_Clients.AppendData(TFDJSONDataSetsReader.GetListValue(LDataSetList, 0)); Add.FormAdd.FDMemTable_Clients.Open; // Save to file to access when offline EnsureDirExists; Add.FormAdd.FDMemTable_Clients.SaveToFile(IOUtils.TPath.Combine(IOUtils.TPath.GetDocumentsPath, IOUtils.TPath.Combine('AVW','ClientList'))); end else begin Add.FormAdd.Print('You must be connected to the server to get the client list.'); end; except on E : Exception do begin Add.FormAdd.Print((E.ClassName+' error raised with message : '+E.Message)); end; end; finally NS.Free; end; end; end.
unit TinyDBReg; {$I TinyDB.inc} interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs, TinyDB; procedure Register; {$R TinyDB.dcr} implementation uses {$IFDEF COMPILER_6_UP} DesignIntf, DesignEditors; {$ELSE} DsgnIntf; {$ENDIF} type { Property Editor } TTinyStringsProperty = class(TStringProperty) protected procedure GetValueList(List: TStrings); virtual; public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; TTinyTableNameProperty = class(TTinyStringsProperty) protected procedure GetValueList(List: TStrings); override; end; TTinyIndexNameProperty = class(TTinyStringsProperty) protected procedure GetValueList(List: TStrings); override; end; TTinyDatabaseNameProperty = class(TStringProperty) private function GetMediumType: TTinyDBMediumType; public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; TTinyAboutProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; //procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); override; end; { TTinyStringsProperty } function TTinyStringsProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TTinyStringsProperty.GetValueList(List: TStrings); begin end; procedure TTinyStringsProperty.GetValues(Proc: TGetStrProc); var I: Integer; Values: TStringList; begin Values := TStringList.Create; try GetValueList(Values); for I := 0 to Values.Count - 1 do Proc(Values[I]); finally Values.Free; end; end; { TTinyTableNameProperty } procedure TTinyTableNameProperty.GetValueList(List: TStrings); var Table: TTinyTable; begin Table := GetComponent(0) as TTinyTable; Table.DBSession.GetTableNames(Table.DatabaseName, List); end; { TTinyIndexNameProperty } procedure TTinyIndexNameProperty.GetValueList(List: TStrings); var Table: TTinyTable; begin Table := GetComponent(0) as TTinyTable; Table.DBSession.GetIndexNames(Table.DatabaseName, Table.TableName, List); end; { TTinyDatabaseNameProperty } function TTinyDatabaseNameProperty.GetMediumType: TTinyDBMediumType; var AComponent: TComponent; begin AComponent := GetComponent(0) as TComponent; if AComponent is TTDEDataSet then Result := (AComponent as TTDEDataSet).MediumType else if AComponent is TTinyDatabase then Result := (AComponent as TTinyDatabase).MediumType else Result := mtDisk; end; function TTinyDatabaseNameProperty.GetAttributes: TPropertyAttributes; begin if GetMediumType = mtDisk then Result := [paDialog] else Result := []; end; procedure TTinyDatabaseNameProperty.Edit; var OpenDialog: TOpenDialog; begin if GetMediumType = mtDisk then begin OpenDialog := TOpenDialog.Create(Application); try with OpenDialog do begin Options := Options + [ofFileMustExist]; InitialDir := ExtractFilePath(GetValue); Filter := 'TinyDB Files(*' + tdbDBFileExt + ')|*' + tdbDBFileExt + '|All Files(*.*)|*.*'; DefaultExt := tdbDBFileExt; end; if OpenDialog.Execute then begin SetValue(OpenDialog.FileName); end; finally OpenDialog.Free; end; end; end; { TTinyAboutProperty } procedure TTinyAboutProperty.Edit; var Msg: string; begin Msg := 'TinyDB Database Engine' + #13 + 'Version ' + tdbSoftVer + #13 + 'Copyright(c) 2000-2006 DayDream Software' + #13 + 'URL: ' + tdbWebsite + #13 + 'Email: ' + tdbSupportEmail; MessageBox(Application.Handle, PChar(Msg), 'About TinyDB', MB_OK + MB_ICONINFORMATION); end; function TTinyAboutProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paReadOnly, paFullWidthName]; end; function TTinyAboutProperty.GetValue: string; begin Result := '(About)'; end; procedure Register; begin RegisterPropertyEditor(TypeInfo(TTinyAboutBox), nil, '', TTinyAboutProperty); RegisterPropertyEditor(TypeInfo(string), TTinyTable, 'TableName', TTinyTableNameProperty); RegisterPropertyEditor(TypeInfo(string), TTinyTable, 'IndexName', TTinyIndexNameProperty); RegisterPropertyEditor(TypeInfo(string), TTDBDataSet, 'DatabaseName', TTinyDatabaseNameProperty); RegisterPropertyEditor(TypeInfo(string), TTinyDatabase, 'DatabaseName', TTinyDatabaseNameProperty); RegisterPropertyEditor(TypeInfo(string), TTinyDatabase, 'FileName', TTinyDatabaseNameProperty); RegisterComponents('TinyDB', [TTinyTable]); //RegisterComponents('TinyDB', [TTinyQuery]); RegisterComponents('TinyDB', [TTinyDatabase]); RegisterComponents('TinyDB', [TTinySession]); end; end.
unit PlayerGPX; {$mode objfpc}{$H+} interface uses Classes, SysUtils, PlayerThreads, sqldb; type { TPlayerGPX } TPlayerGPX = class private FTripId: Integer; FFile: TextFile; FLines: TStringList; FThread: TPlayerThreadManager; FFileName: String; Query: TSQLQuery; procedure AddGpxPoint; procedure AppendLines; function FormatGpxTime(const AValue: String): String; function IsTerminated: Boolean; function ParseDuration(const AValue: Integer): String; public constructor Create(const ATripID: Integer; const AGpxFileName: String; AThread: TPlayerThreadManager = nil); destructor Destroy; override; procedure Convert; end; implementation uses dmxPlayer, PlayerLogger, PlayerSessionStorage, DateUtils, Forms, Math, StrUtils; { TPlayerGPX } procedure TPlayerGPX.AddGpxPoint; begin with Query do FLines.Add(Format(' <trkpt lat="%.6n" lon="%.6n"><time>%s</time><course>%n</course><speed>%n</speed></trkpt>', [ FieldByName('lat').AsFloat, FieldByName('lon').AsFloat, FormatGpxTime(FieldByName('time').AsString), FieldByName('course').AsFloat, FieldByName('speed').AsFloat ])); end; procedure TPlayerGPX.AppendLines; begin if FLines.Count = 0 then Exit; if IsTerminated then Exit; Write(FFile, FLines.Text); FLines.Clear; end; function TPlayerGPX.FormatGpxTime(const AValue: String): String; var dt: TDateTime; begin dt:=ScanDateTime(PLAYER_DATE_FORMAT, AValue); Result:=FormatDateTime(PLAYER_DATE_FORMAT, dt).Replace(' ', 'T') + 'Z'; end; function TPlayerGPX.IsTerminated: Boolean; begin Result:=(FThread <> nil) and FThread.Terminated; end; function TPlayerGPX.ParseDuration(const AValue: Integer): String; var Index, v: Integer; begin Result:=''; for Index:=3 downto 1 do begin v:=(AValue mod Trunc(Power(60, Index))) div Trunc(Power(60, Pred(Index))); if Result <> '' then Result:=Result + ':'; Result:=Result + AddChar('0', IntToStr(v), 2); end; end; constructor TPlayerGPX.Create(const ATripID: Integer; const AGpxFileName: String; AThread: TPlayerThreadManager); begin inherited Create; FFileName:=AGpxFileName; FThread:=AThread; FLines:=TStringList.Create; FTripID:=ATripID; Query:=TSQLQuery.Create(Application); Query.DataBase:=dmPlayer.Connection; Query.Transaction:=dmPlayer.Transaction; end; destructor TPlayerGPX.Destroy; begin FLines.Free; Query.Free; inherited; end; procedure TPlayerGPX.Convert; var Index: Integer; begin logger.Log('creating gpx for trip %d', [FTripId]); AssignFile(FFile, FFileName); Rewrite(FFile); try Query.SQL.Clear; Query.Clear; LoadTextFromResource(Query.SQL, 'GPX_INFO'); Query.ParamByName('trip_id').AsInteger:=FTripId; logger.Log('gpx info for trip %d', [FTripId]); Query.Open; try FLines.Add('<?xml version="1.0" encoding="UTF-8" ?>'); FLines.Add('<gpx version="1.0"'); FLines.Add(Format(' creator="%s"', [Application.Title])); FLines.Add(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'); FLines.Add(' xmlns="http://www.topografix.com/GPX/1/0"'); FLines.Add(' xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">'); FLines.Add(Format('<time>%s</time>', [FormatGpxTime(Query.FieldByName('started_at').AsString)])); FLines.Add(Format('<bounds minlat="%.6n" minlon="%.6n" maxlat="%.6n" maxlon="%.6n"/>', [ Query.FieldByName('minlat').AsFloat, Query.FieldByName('minlon').AsFloat, Query.FieldByName('maxlat').AsFloat, Query.FieldByName('maxlon').AsFloat ])); FLines.Add('<trk>'); FLines.Add(Format(' <name>Track %s</name>', [Query.FieldByName('started_at').AsString])); FLines.Add(Format(' <desc>Duration: %s. Length: %.2n km. AvgSpeed: %.2n km/h.</desc>', [ ParseDuration(Query.FieldByName('duration').AsInteger), Query.FieldByName('distance').AsFloat / 1000, Query.FieldByName('avg_speed').AsFloat ])); FLines.Add(Format(' <time>%s</time>', [FormatGpxTime(Query.FieldByName('started_at').AsString)])); FLines.Add(' <trkseg>'); AppendLines; finally Query.Close; end; if IsTerminated then Exit; Query.SQL.Clear; Query.Clear; LoadTextFromResource(Query.SQL, 'GPX'); Query.ParamByName('trip_id').AsInteger:=FTripId; Query.Open; try Index:=0; while not Query.EOF do begin if IsTerminated then Break; logger.Log('saving point %d, trip %d', [Query.FieldByName('id').AsInteger, FTripId]); AddGpxPoint; Inc(Index); if Index = 1000 then begin AppendLines; Index:=0; end; Query.Next; end; finally Query.Close; end; FLines.Add(' </trkseg>'); FLines.Add('</trk>'); FLines.Add('</gpx>'); AppendLines; finally CloseFile(FFile); end; end; end.
unit uLoadcellPressStatus; interface type TLoadcellPressStatus = class private FFirstOnTime : TDateTime; FPreviousOnTime : TDateTime; FCurrentOnTime : TDateTime; FFirstWeight : double; FCurrentWeight : double; FSumWeight : double; FPressOnCount : integer; FWeightCount : integer; FHuntingTime : integer; FIsHunting : boolean; FHuntingBeginTime : TDateTime; FHuntingEndTime : TDateTime; function GetStabilizationTime: Int64; function GetAverageWeight: double; function GetHuntingDurationTime: TDateTime; public procedure Initialize; procedure SetPressureOn; procedure SetWeight(aWeight : double); function IsHunting : boolean; function IsPressTimeOk(aMillisecond : integer) : boolean; class function IsPressBalanceOk(obj1 : TLoadcellPressStatus; obj2 : TLoadcellPressStatus; aBalanceMillisecond : integer) : boolean; property FirstOnTime : TDateTime read FFirstOnTime; property PreviousOnTime : TDateTime read FPreviousOnTime; property CurrentOnTime : TDateTime read FCurrentOnTime; property HuntingTime : integer read FHuntingTime write FHuntingTime; property StabilizationTime : Int64 read GetStabilizationTime; property FirstWeight : double read FFirstWeight; property CurrentWeight : double read FCurrentWeight; property SumWeight : double read FSumWeight; property PressOnCount : integer read FPressOnCount; property WeightCount : integer read FWeightCount; property AverageWeight : double read GetAverageWeight; property HuntingBeginTime : TDateTime read FHuntingBeginTime; property HuntingEndTime : TDateTime read FHuntingEndTime; property HuntingDurationTime : TDateTime read GetHuntingDurationTime; end; var FrontLoadcellPressStatus : TLoadcellPressStatus; RearLoadcellPressStatus : TLoadcellPressStatus; implementation uses SysUtils, DateUtils; { TLoadcellPressStatus } function TLoadcellPressStatus.GetAverageWeight: double; begin if SumWeight = 0 then result := 0 else if WeightCount = 0 then result := 0 else result := SumWeight / WeightCount; end; function TLoadcellPressStatus.GetHuntingDurationTime: TDateTime; begin result := FHuntingEndTime - FHuntingBeginTime; end; function TLoadcellPressStatus.GetStabilizationTime: Int64; begin result := MilliSecondsBetween(FCurrentOnTime, FFirstOnTime); end; procedure TLoadcellPressStatus.Initialize; begin FFirstOnTime := 0; FPreviousOnTime := 0; FCurrentOnTime := 0; FFirstWeight := 0; FCurrentWeight := 0; FSumWeight := 0; FPressOnCount := 0; FWeightCount := 0; FIsHunting := false; FHuntingBeginTime := 0; FHuntingEndTime := 0; end; function TLoadcellPressStatus.IsHunting: boolean; begin result := FIsHunting; end; class function TLoadcellPressStatus.IsPressBalanceOk(obj1, obj2: TLoadcellPressStatus; aBalanceMillisecond : integer): boolean; begin if MilliSecondsBetween(obj1.FirstOnTime, obj2.FirstOnTime) > aBalanceMillisecond then result := false else result := true; end; function TLoadcellPressStatus.IsPressTimeOk( aMillisecond: integer): boolean; begin if MilliSecondsBetween(FCurrentOnTime, FFirstOnTime) > aMillisecond then result := true else result := false; end; procedure TLoadcellPressStatus.SetPressureOn; begin FPreviousOnTime := FCurrentOnTime; FCurrentOnTime := Now; FPressOnCount := FPressOnCount + 1; if FPreviousOnTime <> 0 then begin if MilliSecondsBetween(FCurrentOnTime, FPreviousOnTime) > HuntingTime then begin FHuntingBeginTime := FPreviousOnTime; FHuntingEndTime := FCurrentOnTime; FIsHunting := true; end; end; if FFirstOnTime = 0 then begin FFirstOnTime := FCurrentOnTime; end; end; procedure TLoadcellPressStatus.SetWeight(aWeight: double); begin if FirstWeight = 0 then begin if aWeight = 0 then exit; FCurrentWeight := aWeight; FSumWeight := FSumWeight + FCurrentWeight; FWeightCount := FWeightCount + 1; FFirstWeight := aWeight; end else begin FCurrentWeight := aWeight; FSumWeight := FSumWeight + FCurrentWeight; FWeightCount := FWeightCount + 1; end; end; initialization FrontLoadcellPressStatus := TLoadcellPressStatus.Create; RearLoadcellPressStatus := TLoadcellPressStatus.Create; finalization FrontLoadcellPressStatus.Free; RearLoadcellPressStatus.Free; end.
program simplify; //Example program to simplify meshes // https://github.com/neurolabusc/Fast-Quadric-Mesh-Simplification-Pascal- //To compile // fpc -O3 -XX -Xs simplify.pas //On OSX to explicitly compile as 64-bit // ppcx64 -O3 -XX -Xs simplify.pas //With Delphi // >C:\PROGRA~2\BORLAND\DELPHI7\BIN\dcc32 -CC -B simplify.pas //To execute // ./simplify bunny.obj out.obj 0.2 {$IFDEF FPC}{$mode objfpc}{$H+}{$ENDIF} uses {$IFDEF FPC}{$IFNDEF DARWIN}DateUtils, {$ENDIF}{$ELSE} Windows, {$ENDIF} Classes, meshify_simplify_quadric, obj, sysutils; procedure ShowHelp; begin writeln('Usage: '+paramstr(0)+' <input> <output> <ratio> <agressiveness)'); writeln(' Input: name of existing OBJ format mesh'); writeln(' Output: name for decimated OBJ format mesh'); writeln(' Ratio: (default = 0.5) for example 0.2 will decimate 80% of triangles'); writeln(' Agressiveness: (default = 7.0) faster or better decimation'); writeln('Example :'); {$IFDEF UNIX} writeln(' '+paramstr(0)+' ~/dir/in.obj ~/dir/out.obj 0.2'); {$ELSE} writeln(' '+paramstr(0)+' c:\dir\in.obj c:\dir\out.obj 0.2'); {$ENDIF} end; procedure printf(s: string); //for GUI applications, this would call showmessage or memo1.lines.add begin writeln(s); end; procedure DecimateMesh(inname, outname: string; ratio, agress: single); var targetTri, startTri: integer; faces: TFaces; vertices: TVertices; {$IFDEF FPC} {$IFDEF DARWIN} msec: qWord;{$ELSE} msec: Int64; tic :TDateTime; {$ENDIF} {$ELSE} msec: dWord; {$ENDIF} begin LoadObj(inname, faces, vertices); startTri := length(faces); targetTri := round(length(faces) * ratio); if (targetTri < 0) or (length(faces) < 1) or (length(vertices) < 3) then begin printf('Unable to load the mesh'); exit; end; {$IFDEF FPC} {$IFDEF DARWIN} msec := GetTickCount64(); {$ELSE}tic := Now();{$ENDIF} {$ELSE} msec := GetTickCount();{$ENDIF} simplify_mesh(faces, vertices, targetTri, agress); {$IFDEF FPC} {$IFDEF DARWIN} msec := GetTickCount64()-msec; {$ELSE}msec := MilliSecondsBetween(Now(),tic);{$ENDIF} {$ELSE} msec := GetTickCount() - msec; {$ENDIF} printf(format(' number of triangles reduced from %d to %d (%.3f, %.2fsec)', [startTri, length(Faces), length(Faces)/startTri, msec*0.001 ])); if length(outname) > 0 then SaveObj(outname, faces, vertices); setlength(faces,0); setlength(vertices,0); end; procedure ParseCmds; var inname, outname: string; ratio, agress: single; begin printf('Mesh Simplification (C)2014 by Sven Forstmann, MIT License '+{$IFDEF CPU64}'64-bit'{$ELSE}'32-bit'{$ENDIF}); if ParamCount < 2 then begin ShowHelp; exit; end; inname := paramstr(1); outname := paramstr(2); ratio := 0.5; if ParamCount > 2 then ratio := StrToFloatDef(paramstr(3),0.5); if (ratio <= 0.0) or (ratio >= 1.0) then begin printf('Ratio must be more than zero and less than one.'); exit; end; agress := 7.0; if ParamCount > 2 then agress := StrToFloatDef(paramstr(4),7.0); DecimateMesh(inname, outname, ratio, agress); end; begin ParseCmds; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 2000-2001 Borland Software Corporation } { } {*******************************************************} unit SiteComp; interface uses Classes, WebComp, HTTPApp, WebContnrs, HTTPProd, WebCntxt; type IWebApplicationInfo = interface ['{B2E0A3B9-6FA7-11D4-A4B8-00C04F6BB853}'] function GetApplicationTitle: string; function GetApplicationAdapter: TComponent; property ApplicationTitle: string read GetApplicationTitle; property ApplicationAdapter: TComponent read GetApplicationAdapter; end; IDefaultPageFileName = interface ['{7F76F283-065E-11D4-A43E-00C04F6BB853}'] procedure SetDefaultPageFileName(const APageFile: string); end; IGetDefaultAction = interface ['{F8094BDD-3DBB-445C-805B-80D68624BAD4}'] function GetDefaultAction: TComponent; property DefaultAction: TComponent read GetDefaultAction; end; TDispatchPageFlag = (dpPublished); TDispatchPageFlags = set of TDispatchPageFlag; IPageDispatcher = interface(IWebRequestHandler) ['{C9FD165A-8F1C-11D4-A4E4-00C04F6BB853}'] function GetDefaultPageName: string; function DispatchPageName(const APageName: string; AResponse: TWebResponse; AFlags: TDispatchPageFlags): Boolean; function RedirectToPageName(const APageName: string; AParams: TStrings; AResponse: TWebResponse; AFlags: TDispatchPageFlags): Boolean; function PageNameOfRequest(ARequest: TWebRequest): string; function GetLoginRequired(const APageName: string): Boolean; function GetCanView(const APageName: string): Boolean; property DefaultPageName: string read GetDefaultPageName; end; TAdapterItemRequestParamOption = (roExcludeID); TAdapterItemRequestParamOptions = set of TAdapterItemRequestParamOption; IAdapterItemRequestParams = interface ['{AB707788-9328-45B7-B071-8A785610474F}'] procedure SetSuccessPage(const AValue: string); procedure SetFailurePage(const AValue: string); function GetSuccessPage: string; function GetFailurePage: string; function GetParamValues: TStrings; property SuccessPage: string read GetSuccessPage write SetSuccessPage; property FailurePage: string read GetFailurePage write SetFailurePage; property ParamValues: TStrings read GetParamValues; end; IAdapterDispatcher = interface(IWebRequestHandler) ['{C9FD1655-8F1C-11D4-A4E4-00C04F6BB853}'] function EncodeAdapterItemRequestAsHREF(AHandler: IUnknown; AOptions: TAdapterItemRequestParamOptions): string; function EncodeAdapterItemRequestAsFieldValue(AHandler: IUnknown; AOptions: TAdapterItemRequestParamOptions): string; procedure GetAdapterItemRequestParams(AHandler: IUnknown; AOptions: TAdapterItemRequestParamOptions; AParams: IAdapterItemRequestParams); end; IPageResult = interface ['{608D1F61-F223-4574-89F7-F29A73372FFC}'] function DispatchPage(const APageName: string; AWebResponse: TWebResponse): Boolean; function IncludePage(const APageName: string; var AOwned: Boolean): TStream; function RedirectToPage(const APageName: string; AParams: TStrings; AWebResponse: TWebResponse): Boolean; end; IAdapterDispatchParams = interface ['{87018D80-0450-4CAB-BE8C-58F54040BCEB}'] function GetRequestIdentifier: string; function GetObjectIdentifier: string; function GetParams: TStrings; function GetHandler: TObject; property RequestIdentifier: string read GetRequestIdentifier; property ObjectIdentifier: string read GetObjectIdentifier; property Params: TStrings read GetParams; property Handler: TObject read GetHandler; end; IAdapterRequestHandler = interface ['{48C27474-2E1F-4797-9E72-AFA6CE42F826}'] procedure CreateRequestContext(DispatchParams: IAdapterDispatchParams); function HandleRequest(DispatchParams: IAdapterDispatchParams): Boolean; end; IGetAdapterItemRequestParams = interface ['{14D978F5-D1E9-11D4-A532-00C04F6BB853}'] procedure GetAdapterItemRequestParams(var AIdentifier: string; AParams: IAdapterItemRequestParams); end; IGetAdapterRequestDefaultResponse = interface ['{14D978F4-D1E9-11D4-A532-00C04F6BB853}'] function GetSuccessPage: string; function GetFailurePage: string; property SuccessPage: string read GetSuccessPage; property FailurePage: string read GetFailurePage; end; IWebFormComponentContainer = interface ['{F7E1CF51-F759-11D3-ABDA-EFF689219731}'] function GetCount: Integer; function GetItem(I: Integer): TComponent; property Count: Integer read GetCount; property Items[I: Integer]: TComponent read GetItem; end; IWebUserList = interface ['{0877DEAF-AB5D-11D4-A503-00C04F6BB853}'] function ValidateUser(Strings: TStrings): Variant; function CheckAccessRights(UserID: Variant; Rights: string): Boolean; end; IGetWebAppComponents = interface ['{19CD2F0D-E68F-4A6F-92AA-4C7659E83708}'] function GetLocateFileService: ILocateFileService; function GetPageDispatcher: IPageDispatcher; function GetAdapterDispatcher: IAdapterDispatcher; function GetWebApplicationInfo: IWebApplicationInfo; function GetWebEndUser: IWebEndUser; function GetWebUserList: IWebUserList; property WebEndUser: IWebEndUser read GetWebEndUser; property WebApplicationInfo: IWebApplicationInfo read GetWebApplicationInfo; end; TAbstractDesigntimeWarnings = class public procedure AddString(AWarning: string); virtual; abstract; procedure AddObject(AObject: TObject); virtual; abstract; end; IGetDesigntimeWarnings = interface ['{20508BF7-A9CE-11D4-A501-00C04F6BB853}'] procedure GetDesigntimeWarnings(AWarnings: TAbstractDesigntimeWarnings); end; INotifyList = interface ['{0444FED2-835C-4DAD-9C79-49BDC62AFA8A}'] procedure AddNotify(ANotify: TObject); procedure RemoveNotify(ANotify: TObject); end; INotifyAdapterChange = interface ['{442FC843-4F85-4137-8564-FF6EEDBA1465}'] procedure NotifyAdapterChange(Sender: TComponent); end; IIteratorSupport = interface ['{BDFABA24-F5C3-11D3-ABD8-A00CB821173C}'] function StartIterator(var OwnerData: Pointer): Boolean; function NextIteration(var OwnerData: Pointer): Boolean; procedure EndIterator(OwnerData: Pointer); end; IIteratorIndex = interface ['{A6CBA53A-8326-4F7A-BFFE-02A2C6E41B67}'] function InIterator: Boolean; function GetIteratorIndex: Integer; property IteratorIndex: Integer read GetIteratorIndex; end; IIterateObjectSupport = interface(IIteratorSupport) ['{76159C52-A181-4F16-B27E-35F7979BE87F}'] function GetCurrentObject(OwnerData: Pointer): TObject; end; IIterateIntfSupport = interface(IIteratorSupport) ['{064EFCF2-B422-4720-B364-633D28CD3216}'] function GetCurrentIntf(OwnerData: Pointer): IUnknown; end; TScriptObject = class(TInterfacedObject); TScriptComponent = class(TScriptObject, IInterfaceComponentReference) private FObject: TComponent; protected { IInterfaceComponentReference } function GetComponent: TComponent; public constructor Create(AObject: TComponent); virtual; property Obj: TComponent read FObject; end; IGetScriptObject = interface ['{CAC16452-9BAD-11D4-A4F2-00C04F6BB853}'] function GetScriptObject: IInterface; deprecated; end; IGetScriptObjectClassKey = interface ['{2D98BC03-3595-424C-9F7B-6804F96EF444}'] function GetScriptObjectClassKey: TClass; deprecated; end; // Identify a subcomponent container IWebContainerSubComponent = interface end; TSessionID = type string; IWebSession = interface ['{D2727F50-2399-495C-B2C3-649A3512D087}'] procedure Terminate; end; IWebSessionValues = interface ['{26F78C60-0D62-42AE-B890-57EF475FB5D3}'] procedure GetItems(var AItems: TAbstractNamedVariants); function GetItemCount: Integer; procedure SetValue(const AName: string; const AValue: Variant); function GetValue(const AName: string): Variant; property Values[const AName: string]: Variant read GetValue write SetValue; end; IWebSessionID = interface ['{FF5D064E-FF1B-480E-BA9D-6B7F8AA4E477}'] function GetID: TSessionID; property ID: TSessionID read GetID; end; IWebSessionAttributes = interface ['{29D2BFB7-4336-4F14-B1FE-417AEC40A12F}'] function GetStartTime: TDateTime; property StartTime: TDateTime read GetStartTime; function GetTimeoutMinutes: Integer; procedure SetTimeoutMinutes(AValue: Integer); property TimeoutMinutes: Integer read GetTimeoutMinutes write SetTimeoutMinutes; function GetTouchTime: TDateTime; property TouchTime: TDateTime read GetTouchTime; function GetExpirationTime: TDateTime; property ExpirationTime: TDateTime read GetExpirationTime; function GetExpired: Boolean; property Expired: Boolean read GetExpired; function GetTerminated: Boolean; property Terminated: Boolean read GetTerminated; function GetIsActive: Boolean; property IsActive: Boolean read GetIsActive; end; ISessionsServiceConnectID = interface ['{FA0C1658-726C-47DF-9810-84A207EFCA65}'] function Connect(AID: TSessionID): IWebSession; function ConnectActive(AID: TSessionID): IWebSession; end; ISessionsServiceStoreID = interface ['{2BA89434-8F6B-4119-B700-1D1400E9CC87}'] function ReadSessionID(ARequest: TWebRequest; AResponse: TWebResponse; out AID: TSessionID): Boolean; procedure WriteSessionID(AResponse: TWebResponse; AID: TSessionID); end; IWebSessionIDs = interface ['{CC119E2C-6574-4A59-A3EE-952DB537F76B}'] function GetIDCount: Integer; function GetID(I: Integer): TSessionID; property IDCount: Integer read GetIDCount; property IDs[I: Integer]: TSessionID read GetID; end; IWebGetSessionIDs = interface ['{6D14F7B1-F503-4B53-B364-2BE7229D33EC}'] function GetSessionIDs: IWebSessionIDs; end; ISessionsService = interface ['{6EAAC21D-42CF-4486-A8E6-D9C8562BD681}'] function NewSession: IWebSession; procedure Clear; function CheckStatusChange: Boolean; procedure NotifyStatusChange; end; ISessionsServicePersist = interface ['{6FFA990F-183E-468E-8246-2E1093CEA13D}'] procedure LoadFromFile(const Filename: string); procedure SaveToFile(const Filename: string); procedure LoadFromStream(S: TStream); procedure SaveToStream(S: TStream); end; IFindIncludeFile = interface ['{93895ECC-E8BA-4F8E-80D0-785D28359932}'] function FindIncludeFile(AComponent: TComponent; const AFileName: string; var AResult: string): Boolean; end; TAbstractInetFileType = class(TObject) protected function GetTypeID: string; virtual; abstract; function GetExtCount: Integer; virtual; abstract; function GetFileExt(I: Integer): string; virtual; abstract; public property TypeID: string read GetTypeID; property FileExtCount: Integer read GetExtCount; property FileExt[I: Integer]: string read GetFileExt; end; IInternetFileTypes = interface ['{0257655C-F868-11D4-A55F-00C04F6BB853}'] function FindFileExt(const AFileExt: string): TAbstractInetFileType; end; IInternetScriptDebugger = interface ['{0257655B-F868-11D4-A55F-00C04F6BB853}'] procedure DebugScript(AContext: IUnknown); function CanDebugScript(AContext: IUnknown): Boolean; end; IInternetExecuteScript = interface ['{0257655E-F868-11D4-A55F-00C04F6BB853}'] procedure ExecuteScript(AContext: IUnknown); function CanExecuteScript(AContext: IUnknown): Boolean; end; IInternetEnvOptions = interface ['{F92A39B5-C7D1-4E10-A67C-AC775042DA0E}'] function GetDisableDebugging: Boolean; function GetHTMLExt: string; function GetSampleImageFile: string; function GetScriptTimeoutSecs: Integer; property DisableDebugger: Boolean read GetDisableDebugging; property HTMLExt: string read GetHTMLExt; property SampleImageFile: string read GetSampleImageFile; property ScriptTimeoutSecs: Integer read GetScriptTimeoutSecs; end; IIDEFileManager = interface ['{B61156EF-7265-43E9-9FAF-D6E1D2EA2075}'] function SearchFile(const AFileName: string): string; end; { Adapter interfaces } IAdapterError = interface ['{27A6D8A1-58E1-11D4-A493-00C04F6BB853}'] function GetErrorText: string; function GetID: integer; function GetField: TComponent; property ErrorText: string read GetErrorText; property ID: integer read GetID; property Field: TComponent read GetField; end; IAdapterHiddenField = interface ['{90E9C34B-D054-11D4-A530-00C04F6BB853}'] function GetName: string; function GetValue: string; property Name: string read GetName; property Value: string read GetValue; end; IAdapterAccess = interface ['{179232C0-CC77-11D4-A52B-00C04F6BB853}'] function HasViewAccess: Boolean; function HasModifyAccess: Boolean; function HasExecuteAccess: Boolean; end; IGetAdapterErrors = interface ['{27A6D89F-58E1-11D4-A493-00C04F6BB853}'] function GetAdapterErrors: TObject; end; IAdapterHiddenFields = interface ['{90E9C34C-D054-11D4-A530-00C04F6BB853}'] function GetFieldCount: Integer; function GetField(I: Integer): IAdapterHiddenField; property FieldCount: Integer read GetFieldCount; property Fields[I: Integer]: IAdapterHiddenField read GetField; end; IGetAdapterHiddenFields = interface ['{90E9C34D-D054-11D4-A530-00C04F6BB853}'] function GetAdapterHiddenFields: TObject; function GetAdapterHiddenRecordFields: TObject; end; IAdapterMode = interface ['{9E6E6A7C-574F-11D4-A491-00C04F6BB853}'] function GetAdapterMode: string; function GetNeedAdapterMode: Boolean; procedure SetAdapterMode(const AValue: string); procedure RestoreDefaultAdapterMode; property AdapterMode: string read GetAdapterMode write SetAdapterMode; property NeedAdapterMode: Boolean read GetNeedAdapterMode; end; IAdapterErrors = interface ['{27A6D8A0-58E1-11D4-A493-00C04F6BB853}'] procedure ClearErrors; function GetErrorCount: Integer; function GetError(I: Integer): IAdapterError; procedure DefineLabel(const AName, ALabel: string); property ErrorCount: Integer read GetErrorCount; property Errors[I: Integer]: IAdapterError read GetError; function HasObjectErrors(const AName: string): Boolean; function GetObjectErrors(const AName: string): TObject; end; IWebGetFieldValue = interface ['{9E6E6A7F-574F-11D4-A491-00C04F6BB853}'] function GetValue: Variant; property Value: Variant read GetValue; end; IAsFormatted = interface ['{18138862-52C0-11D4-A48D-00C04F6BB853}'] function AsFormatted: string; end; IWebGetDisplayWidth = interface ['{A23C86B6-672A-11D4-A4A7-00C04F6BB853}'] function GetDisplayWidth: Integer; end; IImageProducer = interface ['{1EFF2C50-B384-4089-BDA2-C49399BA1CE0}'] function GetAdapterImage(const AComponentName: string; const ACaption: WideString): TObject; end; IActionImageProducer = interface(IImageProducer) ['{58790FBB-D56F-4298-9B0C-C622A0D6DBAB}'] function GetDisplayStyle(Sender: TComponent): string; function GetAdapterEventImage(const AComponentName, AEvent, ACaption: WideString): TObject; end; IWebGetDisplayLabel = interface ['{A23C86B7-672A-11D4-A4A7-00C04F6BB853}'] function GetDisplayLabel: string; end; IWebGetMaxLength = interface ['{772D7639-8209-4744-9146-2B6D3A5F220F}'] function GetMaxLength: integer; end; IWebInputName = interface ['{CD1644C0-41E8-4C06-9AB8-CD6B05367E27}'] function GetInputName: string; property InputName: string read GetInputName; end; IValuesListAdapter = interface ['{CAC16451-9BAD-11D4-A4F2-00C04F6BB853}'] function GetListValue: Variant; function GetListName: string; function GetListNameOfValue(Value: Variant): string; function GetListImage: TComponent; function GetListImageOfValue(Value: Variant): TComponent; end; IGetAdapterImage = interface ['{E7F5D230-7AF9-46C8-9976-B954BD1152D8}'] function GetAdapterImage: TComponent; end; IGetHTMLStyle = interface ['{1C1557D1-CA79-4BEE-86E2-253BEC8925E2}'] function GetDisplayStyle(const AAdapterMode: string): string; function GetInputStyle(const AAdapterMode: string): string; function GetViewMode(const AAdapterMode: string): string; end; IAdapterFieldAccess = interface ['{98C3D564-3CE4-412C-A7FE-DA05A1A37953}'] function HasViewAccess: Boolean; function HasModifyAccess: Boolean; end; IGetFieldValuesAdapter = interface ['{87BDFE12-CA10-11D4-A528-00C04F6BB853}'] function GetFieldValuesAdapter: TComponent; end; IWebValueIsEqual = interface ['{495042FB-97CE-4CA1-921F-9A09DD3B65F2}'] function IsEqual(const Value: Variant): Boolean; end; IAdapterFieldAttributes = interface ['{179232BF-CC77-11D4-A52B-00C04F6BB853}'] function GetVisible: Boolean; function GetRequired: Boolean; property Visible: Boolean read GetVisible; property Required: Boolean read GetRequired; end; IIsAdapterActionList = interface ['{AFA05E90-DDAA-4B7F-B7A6-D3F9093D9427}'] function GetIsAdapterActionList: Boolean; property IsAdapterActionList: Boolean read GetIsAdapterActionList; end; IAdapterActionAccess = interface ['{55285C44-A3BE-4821-9994-0051647699A7}'] function HasExecuteAccess: Boolean; end; IGetAdapterValuesList = interface ['{59D7E94D-9BA9-11D4-A4F2-00C04F6BB853}'] function GetAdapterValuesList: IValuesListAdapter; end; IWebEnabled = interface ['{648F97D7-B299-444A-89CA-E60BD1FB9EA3}'] function WebEnabled: Boolean; end; IGetAdapterFields = interface ['{30B45B2F-B5B7-4BAE-A6FC-EC47E5B0C941}'] function GetAdapterFields: TComponent; end; IAdapterActionAttributes = interface ['{B86F48C3-BEEB-43A7-9BEF-1ABE1311E419}'] function GetVisible: Boolean; property Visible: Boolean read GetVisible; end; IGetAdapterActions = interface ['{0C2D1ECE-7BBA-43FE-A466-2D8BC70CC85D}'] function GetAdapterActions: TComponent; end; IWebImageHREF = interface ['{10E873A2-A6DD-4AE9-8AB5-4597142E4631}'] function WebImageHREF(var AHREF: string): Boolean; end; IFieldValuesAdapter = interface ['{87BDFE13-CA10-11D4-A528-00C04F6BB853}'] function GetField: TObject; function GetValueIndex: Integer; end; IWebGetFieldValues = interface ['{5DC0D607-1C9C-4E67-B3BA-35CE2A5872A0}'] function GetCurrentValue: Variant; function HasValue(const AValue: Variant): Boolean; function StartValueIterator(var OwnerData: Pointer): Boolean; function NextValueIteration(var OwnerData: Pointer): Boolean; procedure EndValueIterator(OwnerData: Pointer); end; IWebActionsList = interface ['{CB84BC93-4C65-11D4-A48B-00C04F6BB853}'] procedure GetActionsList(AList: TStrings); function FindAction(const AName: string): TComponent; function IsActionInUse(const AName: string): Boolean; function GetVisibleActions: TWebComponentList; property VisibleActions: TWebComponentList read GetVisibleActions; end; IWebDataFields = interface ['{D62DBBBD-2C40-11D4-A46E-00C04F6BB853}'] procedure GetFieldsList(AList: TStrings); function IsFieldInUse(const AName: string): Boolean; function FindField(const AName: string): TComponent; function GetVisibleFields: TWebComponentList; property VisibleFields: TWebComponentList read GetVisibleFields; end; IWebGetFieldName = interface ['{D62DBBC0-2C40-11D4-A46E-00C04F6BB853}'] function GetFieldName: string; property FieldName: string read GetFieldName; end; IWebSetFieldName = interface ['{CB84BC94-4C65-11D4-A48B-00C04F6BB853}'] procedure SetFieldName(const AFieldName: string); end; IWebGetActionName = interface ['{5DC620F7-C14A-4D49-868E-656041ADF017}'] function GetActionName: string; property ActionName: string read GetActionName; end; IWebSetActionName = interface ['{005FC2A6-92C1-4F7D-BC69-F4254672E6C0}'] procedure SetActionName(const AFieldName: string); end; TAdapterDisplayCharacteristic = (dcMultipleRecordView, dcCurrentRecordView, dcChangeCurrentRecordView); TAdapterDisplayCharacteristics = set of TAdapterDisplayCharacteristic; IGetAdapterDisplayCharacteristics = interface ['{CA500563-1298-400F-814D-DA836E08D8B4}'] function GetAdapterDisplayCharacteristics: TAdapterDisplayCharacteristics; end; TAdapterInputHTMLElementType = ( htmliNone, htmliTextInput, htmliPasswordInput, htmliSelect, htmliSelectMultiple, htmliRadio, htmliCheckBox, htmliTextArea, htmliFile); TAdapterDisplayHTMLElementType = ( htmldText, htmldImage, htmldList, htmldNone); TAdapterDisplayViewModeType = ( htmlvmInput, htmlvmDisplay, htmlvmToggleOnAccess, htmlvmNone); TAdapterActionHTMLElementType = (htmlaButton, htmlaImage, htmlaAnchor, htmlaEventImages); { Implement INotifyList } TNotifyList = class(TObject) private FList: TList; protected public constructor Create; destructor Destroy; override; function GetItem(Index: Integer): TObject; function GetCount: Integer; procedure AddNotify(ANotify: TObject); procedure RemoveNotify(ANotify: TObject); property Items[Index: Integer]: TObject read GetItem; default; property Count: Integer read GetCount; end; IWebIsDefaultField = interface ['{A22A7CE1-AC68-4DD5-BE09-18CBBAB57890}'] function IsDefaultField(ADisplay: TObject): Boolean; end; IWebIsDefaultAction = interface ['{E9FD2BD8-CD66-4C91-96FE-8B59C7CD048F}'] function IsDefaultAction(ADisplay: TObject): Boolean; end; IGetProducerComponent = interface ['{75E6B9BB-5AE1-45DB-BACA-314BBE845B4F}'] function GetProducerComponent: TComponent; end; TQualifyOption = (qaUseModulesVar, qaNoModulesVar, qaNoModuleName); const AdapterInputHTMLElementTypeNames: array[TAdapterInputHTMLElementType] of string = ('', 'TextInput', 'PasswordInput', 'Select', 'SelectMultiple', 'Radio', 'CheckBox', 'TextArea', 'File'); AdapterDisplayHTMLElementTypeNames: array[TAdapterDisplayHTMLElementType] of string = ('Text', 'Image', 'List', ''); AdapterActionHTMLElementTypeNames: array[TAdapterActionHTMLElementType] of string = ('Button', 'Image', 'Anchor', 'EventImages'); AdapterDisplayViewModeTypeNames: array[TAdapterDisplayViewModeType] of string = ('Input', 'Display', 'ToggleOnAccess', ''); var InetFileTypes: IInternetFileTypes = nil; ScriptDebugger: IInternetScriptDebugger = nil; InternetEnvOptions: IInternetEnvOptions = nil; ExecuteScript: IInternetExecuteScript = nil; IDEFileManager: IIDEFileManager = nil; GetHTMLSampleImage: function: string = nil; function FullyQualifiedFieldName(AComponent: TComponent): string; function FullyQualifiedName(AComponent: TComponent; AOption: TQualifyOption): string; implementation uses SysUtils; function FullyQualifiedName(AComponent: TComponent; AOption: TQualifyOption): string; var VariableName: IWebVariableName; Root: TComponent; ContainerName: IWebVariablesContainerName; begin Result := ''; Root := AComponent.Owner; while Assigned(AComponent) do begin if not Assigned(Root) then // Default components will not have an owner Root := AComponent.Owner; if Supports(IInterface(AComponent), IWebVariableName, VariableName) then begin if Result <> '' then begin if Supports(IInterface(AComponent), IWebVariablesContainerName, ContainerName) and (ContainerName.ContainerName <> '') then Result := ContainerName.ContainerName + '.' + Result; Result := '.' + Result; end; Result := VariableName.VariableName + Result; end; AComponent := AComponent.GetParentComponent; end; case AOption of qaUseModulesVar: if Assigned(Root) and (Result <> '') then Result := 'Modules.' + Root.Name + '.' + Result; qaNoModulesVar: if Assigned(Root) and (Result <> '') then Result := Root.Name + '.' + Result; qaNoModuleName: ; // No change end; end; function FullyQualifiedFieldName(AComponent: TComponent): string; begin Result := FullyQualifiedName(AComponent, qaUseModulesVar); end; { TScriptComponentObject } constructor TScriptComponent.Create(AObject: TComponent); begin FObject := AObject; inherited Create; end; { TNotifyList } procedure TNotifyList.AddNotify(ANotify: TObject); begin FList.Add(ANotify); end; constructor TNotifyList.Create; begin inherited; FList := TList.Create; end; destructor TNotifyList.Destroy; begin inherited; FList.Free; end; function TNotifyList.GetItem(Index: Integer): TObject; begin Result := FList[Index]; end; function TNotifyList.GetCount: Integer; begin Result := FList.Count; end; procedure TNotifyList.RemoveNotify(ANotify: TObject); begin FList.Remove(ANotify); end; function TScriptComponent.GetComponent: TComponent; begin Result := FObject; end; function GetWebEndUser: IWebEndUser; var GetIntf: IGetWebAppComponents; begin Result := nil; if WebContext <> nil then if Supports(IUnknown(WebContext.FindApplicationModule(nil)), IGetWebAppComponents, GetIntf) then Result := GetIntf.WebEndUser; end; initialization WebCntxt.GetWebEndUserProc := GetWebEndUser; end.