text
stringlengths
14
6.51M
unit Class_KeyValue; //主键检测. //kvctPALL:1.必须全部不为空. //kvctPONE:2.至少一项不为空. //过滤检测. //kvctFONE:1.有一项为空.则过滤. interface uses Classes,SysUtils,Uni,UniEngine; type TKeyValueCheckType=(kvctPALL,kvctPONE,kvctFONE); TKeyValue=class(TUniEngine) private FGKJGFLID: Integer; FKEYVALUE: string; protected procedure SetParameters;override; function GetStrInsert:string;override; function GetStrUpdate:string;override; function GetStrDelete:string;override; public function GetStrsIndex:string;override; public function GetNextIdex:Integer;overload; function GetNextIdex(AUniConnection:TUniConnection):Integer;overload; public function CheckExist(AUniConnection:TUniConnection):Boolean;override; public destructor Destroy; override; constructor Create; published property GKJGFLID: Integer read FGKJGFLID write FGKJGFLID; property KEYVALUE: string read FKEYVALUE write FKEYVALUE; public class function ReadDS(AUniQuery:TUniQuery):TUniEngine;override; class procedure ReadDS(AUniQuery:TUniQuery;var Result:TUniEngine);override; class function CopyIt(AKEYVALUE:TKeyValue):TKeyValue;overload; class procedure CopyIt(AKEYVALUE:TKeyValue;var Result:TKeyValue);overload; class function IsLicit(AList:TStringList;ACheckType:TKeyValueCheckType=kvctPALL):Boolean; end; implementation { TKeyValue } procedure TKeyValue.SetParameters; begin inherited; with FUniSQL.Params do begin case FOptTyp of otAddx: begin ParamByName('GKJGFLID').Value := GKJGFLID; ParamByName('KEYVALUE').Value := KEYVALUE; end; otEdit: begin ParamByName('GKJGFLID').Value := GKJGFLID; ParamByName('KEYVALUE').Value := KEYVALUE; end; otDelt: begin ParamByName('GKJGFLID').Value := GKJGFLID; ParamByName('KEYVALUE').Value := KEYVALUE; end; end; end; end; function TKeyValue.CheckExist(AUniConnection: TUniConnection): Boolean; begin Result:=CheckExist('TBL_KEYVALUE',['GKJGFLID',GKJGFLID,'KEYVALUE',KEYVALUE],AUniConnection); end; function TKeyValue.GetNextIdex: Integer; begin end; function TKeyValue.GetNextIdex(AUniConnection: TUniConnection): Integer; begin end; function TKeyValue.GetStrDelete: string; begin Result:='DELETE FROM TBL_KEYVALUE WHERE GKJGFLID=:GKJGFLID AND KEYVALUE=:KEYVALUE'; end; function TKeyValue.GetStrInsert: string; begin Result:='INSERT INTO TBL_KEYVALUE' +' ( GKJGFLID, KEYVALUE)' +' VALUES' +' (:GKJGFLID,:KEYVALUE)'; end; function TKeyValue.GetStrsIndex: string; begin Result:=Format('%D-%S',[GKJGFLID,KEYVALUE]); end; function TKeyValue.GetStrUpdate: string; begin raise Exception.Create('CAN NOT SUPPORT GETSTRUPDATE METHOD.CAUSE ALL THIS TABLE FILEDS ARE PRIMARY KEY.') end; constructor TKeyValue.Create; begin end; destructor TKeyValue.Destroy; begin inherited; end; class function TKeyValue.ReadDS(AUniQuery: TUniQuery): TUniEngine; begin Result:=TKeyValue.Create; with TKeyValue(Result) do begin GKJGFLID:=AUniQuery.FieldByName('GKJGFLID').AsInteger; KEYVALUE:=AUniQuery.FieldByName('KEYVALUE').AsString; end; end; class procedure TKeyValue.ReadDS(AUniQuery: TUniQuery; var Result: TUniEngine); begin if Result=nil then Exit; with TKeyValue(Result) do begin GKJGFLID:=AUniQuery.FieldByName('GKJGFLID').AsInteger; KEYVALUE:=AUniQuery.FieldByName('KEYVALUE').AsString; end; end; class function TKeyValue.CopyIt(AKEYVALUE: TKeyValue): TKeyValue; begin Result:=TKeyValue.Create; TKeyValue.CopyIt(AKEYVALUE,Result) end; class procedure TKeyValue.CopyIt(AKEYVALUE:TKeyValue;var Result:TKeyValue); begin if Result=nil then Exit; Result.GKJGFLID:=AKEYVALUE.GKJGFLID; Result.KEYVALUE:=AKEYVALUE.KEYVALUE; end; class function TKeyValue.IsLicit(AList: TStringList; ACheckType: TKeyValueCheckType): Boolean; var I:Integer; KeyValue:TKeyValue; begin Result:=False; case ACheckType of kvctPALL: begin if (AList=nil) or (AList.Count=0) then Exit;//if have no pk,exit. for I:=0 to AList.Count-1 do begin KeyValue:=TKeyValue(AList.Objects[I]); if KeyValue=nil then Continue; if Trim(KeyValue.FKEYVALUE)='' then Exit; end; Result:=True; end; kvctPONE: begin if (AList=nil) or (AList.Count=0) then Exit;//if have no pk,exit. if AList.Count=1 then begin for I:=0 to AList.Count-1 do begin KeyValue:=TKeyValue(AList.Objects[I]); if KeyValue=nil then Continue; if Trim(KeyValue.FKEYVALUE)='' then Exit; end; end else begin for I:=0 to AList.Count-1 do begin KeyValue:=TKeyValue(AList.Objects[I]); if KeyValue=nil then Continue; if Trim(KeyValue.FKEYVALUE)<>'' then begin Result:=True; Break; end; end; end; end; kvctFONE: begin if (AList=nil) or (AList.Count=0) then begin Result:=True; Exit; end; for I:=0 to AList.Count-1 do begin KeyValue:=TKeyValue(AList.Objects[I]); if KeyValue=nil then Continue; if Trim(KeyValue.FKEYVALUE)='' then Exit; end; Result:=True; end; end; end; end.
// // Generated by JavaToPas v1.5 20171018 - 171159 //////////////////////////////////////////////////////////////////////////////// unit java.util.Objects; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, java.util.function.Supplier; type JObjects = interface; JObjectsClass = interface(JObjectClass) ['{CAD59ACF-D97C-47C3-A4C6-8F73F79E74C0}'] function compare(a : JObject; b : JObject; c : JComparator) : Integer; cdecl;// (Ljava/lang/Object;Ljava/lang/Object;Ljava/util/Comparator;)I A: $9 function deepEquals(a : JObject; b : JObject) : boolean; cdecl; // (Ljava/lang/Object;Ljava/lang/Object;)Z A: $9 function equals(a : JObject; b : JObject) : boolean; cdecl; // (Ljava/lang/Object;Ljava/lang/Object;)Z A: $9 function hash(values : TJavaArray<JObject>) : Integer; cdecl; // ([Ljava/lang/Object;)I A: $89 function hashCode(o : JObject) : Integer; cdecl; // (Ljava/lang/Object;)I A: $9 function isNull(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $9 function nonNull(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $9 function requireNonNull(obj : JObject) : JObject; cdecl; overload; // (Ljava/lang/Object;)Ljava/lang/Object; A: $9 function requireNonNull(obj : JObject; &message : JString) : JObject; cdecl; overload;// (Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object; A: $9 function requireNonNull(obj : JObject; messageSupplier : JSupplier) : JObject; cdecl; overload;// (Ljava/lang/Object;Ljava/util/function/Supplier;)Ljava/lang/Object; A: $9 function toString(o : JObject) : JString; cdecl; overload; // (Ljava/lang/Object;)Ljava/lang/String; A: $9 function toString(o : JObject; nullDefault : JString) : JString; cdecl; overload;// (Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/String; A: $9 end; [JavaSignature('java/util/Objects')] JObjects = interface(JObject) ['{537B2CCB-AEE2-4193-854E-E747CB82F60F}'] end; TJObjects = class(TJavaGenericImport<JObjectsClass, JObjects>) end; implementation end.
{@author: Lara Carrión} program ppt; USES crt; TYPE tSeleccion = (Piedra, Papel, Tijeras); tResultado= (GanaMaquina, GanaHumano, Empate); rangoEnteros= 1..3; VAR cEmpate, cMaquina, cUser, contador: integer; resFinal: tResultado; terminado: boolean; {////////////////////// DECLARACIÓN DE SUBPROGRAMAS ////////////////////////} {===========================================================================} { Esta función se encarga de la elección aleatoria de la máquina. Para ello, se utiliza la función random, que genera un número aleatorio que luego ser  asignado al resultado, convirtiéndose en Piedra, Papel o Tijeras } FUNCTION eleccionMaquina: tSeleccion; VAR eMaq: integer; resMaq: tSeleccion; BEGIN randomize; eMaq:= random(3)+1; CASE eMaq OF 1: resMaq:= Piedra; 2: resMaq:= Papel; 3: resMaq:= Tijeras; end; eleccionmaquina:= resMaq; END; (* FUNCTION eleccionMaquina *) {===========================================================================} { Este procedimiento transforma el entero elegido por el usuario en un valor del tipo tSeleccion } PROCEDURE transformacion (euser: rangoEnteros; VAR resUser: tSeleccion); VAR eleccionUsuario: tSeleccion; BEGIN CASE euser OF 1: eleccionUsuario:= Piedra; 2: eleccionUsuario:= Papel; 3: eleccionUsuario:= Tijeras; END; resUser := eleccionUsuario; END; (* PROCEDURE transformacion *) {===========================================================================} { Este procedimiento hace el recuento de partidas jugadas y ganadas } PROCEDURE devuelveGanadas (resFinal: tResultado; VAR cEmpate, cMaquina, cUser,contador:integer); BEGIN IF (resFinal = Empate) THEN cEmpate:=cEmpate+1; IF (resFinal = ganaMaquina) THEN cMaquina:=cMaquina+1; IF (resFinal = ganaHumano) THEN cUser:= cUser+1; contador:=contador+1; END; (* PROCEDURE devuelveGanadas *) {===========================================================================} { Este procedimiento muestra por pantalla el número de partidas jugadas, las ganadas por la máquina, las ganadas por el usuario y las empatadas } PROCEDURE mostrarPuntuacionMaq (cEmpate, cMaquina, cUsuario, contador: integer); BEGIN writeln; writeln('###########################################'); writeln(' RESUMEN DE PARTIDAS '); writeln('###########################################'); writeln('+ Partidas jugadas: ',contador); writeln('+ Empates: ', cEmpate); writeln('+ Máquina: ', cMaquina); writeln('+ Usuario: ', cUsuario); writeln('###########################################'); END; (* PROCEDURE mostrarPuntuacion *) {===========================================================================} { Este procedimiento muestra por pantalla el número de partidas jugadas, las ganadas por el usuario 1, las ganadas por el usuario 2 y las empatadas } PROCEDURE mostrarPuntuacionUser (cEmpate, cUser1, cUser2, contador: integer); BEGIN writeln; writeln('###########################################'); writeln(' RESUMEN DE PARTIDAS '); writeln('###########################################'); writeln('+ Partidas jugadas: ',contador); writeln('+ Empates: ', cEmpate); writeln('+ Jugador1: ', cUser1); writeln('+ Jugador2: ', cUser2); writeln('###########################################'); END; (* PROCEDURE mostrarPuntuacion *) {===========================================================================} { Esta función acepta cada una de las elecciones y decide quién de los dos es el ganador de la partida o si se ha producido un empate } FUNCTION computar (resUser, eleccionMaquina: tSeleccion): tResultado; VAR resFinal: tResultado; BEGIN IF (resUser = eleccionMaquina) THEN BEGIN resFinal:= Empate; writeln('Se ha producido un EMPATE.'); writeln; END ELSE BEGIN IF ((resUser = piedra) AND (eleccionMaquina=papel)) or ((resUser=papel) and (eleccionMaquina=tijeras)) or ((resUser= tijeras) and (eleccionMaquina = piedra)) then begin resFinal:= ganaMaquina; writeln('Mala suerte. La MÁQUINA gana la partida.'); writeln; END; IF ((resUser = piedra) and (eleccionMaquina=tijeras)) or ((resUser=papel) and (eleccionMaquina=piedra)) or ((resUser=tijeras) and (eleccionMaquina=papel)) then begin resFinal:= ganaHumano; writeln('Enhorabuena. HAS ganado la partida.'); writeln; END; END; computar:= resFinal; devuelveganadas(resFinal, cEmpate, cMaquina, cUser,contador); END; (* FUNCTION computar *) {===========================================================================} { Este procedimiento muestra por pantalla la elección de la máquina y del jugador } PROCEDURE eleccionMaquina (resMaq: tSeleccion); BEGIN IF resMaq=Piedra THEN writeln('Piedra'); IF resMaq=papel THEN writeln('Papel'); IF resMaq=Tijeras THEN writeln('Tijeras'); end; PROCEDURE eleccionUsuario (resUser: tSeleccion); begin IF resUser=Piedra THEN writeln('Piedra'); IF resUser = Papel THEN writeln('Papel'); IF resUser = Tijeras THEN writeln('Tijeras'); END; (* PROCEDURE elecciones *) {===========================================================================} { Este procedimiento muestra las instrucciones contra la máquina } PROCEDURE instruccionescontramaquina; BEGIN clrscr; writeln('*****************************************'); writeln('Va a jugar una partida contra la m quina'); writeln('*****************************************'); writeln('Instrucciones'); writeln('*****************************************'); writeln('Pulse 1 si su elección es PIEDRA'); writeln('Pulse 2 si su elección es PAPEL'); writeln('Pulse 3 si su elección es TIJERAS'); writeln('*****************************************'); END; (* PROCEDURE instruccionescontramaquina *) {===========================================================================} { Este procedimiento muestra las instrucciones contra usuario } PROCEDURE instruccionesContraUsuario; BEGIN clrscr; writeln('*****************************************'); writeln('Va a jugar una partida contra otro usuario'); writeln('*****************************************'); writeln('Instrucciones'); writeln('*****************************************'); writeln('Pulse 1 si su elecci¢n es PIEDRA'); writeln('Pulse 2 si su elecci¢n es PAPEL'); writeln('Pulse 3 si su elecci¢n es TIJERAS'); writeln('*****************************************'); end; {===========================================================================} { Este procedimiento procesa una partida contra la máquina. } PROCEDURE jugarContraMaquina; VAR eUser:integer; resUser, resMaq: tSeleccion; resFinal: tResultado; BEGIN instruccionescontramaquina; resMaq:=eleccionMaquina; writeln('La máquina ya ha elegido. Es tu turno'); readln(euser); transformacion(euser,resUser); write ('La máquina eligió: '); eleccionMaquina(resMaq); write('El usuario eligió: '); eleccionUsuario(resUser); resFinal:=computar(resUser, resMaq); END; (* PROCEDURE jugarContraMaquina *) {===========================================================================} PROCEDURE jugarContraUsuario; VAR eUser1, euser2: integer; resUser1, resUser2: tSeleccion; resFinal: tResultado; BEGIN instruccionescontrausuario; clrscr; writeln('Turno del JUGADOR 1. Haga su elección: '); readln(euser1); transformacion(euser1, resuser1); clrscr; writeln('Turno del JUGADOR 2. Haga su elección: '); readln(euser2); transformacion(euser2, resuser2); write('Usuario 1 eligió: '); eleccionUsuario(resUser1); write('Usuario 2 eligió: '); eleccionUsuario(resUser2); resFinal:=computar(resUser1, resUser2); end; {===========================================================================} { Este procedimiento ejecuta la opción elegida por el usuario. Si pulsa 0, el juego termina } PROCEDURE menu (opcion: integer); BEGIN CASE opcion OF 1: jugarContraMaquina ; 2: jugarContraUsuario; END; END; (* PROCEDURE menu *) {===========================================================================} { Este procedimiento muestra un menú de opciones una vez que el usuario ha decidido comenzar una partida. El menú sigue apareciendo hasta que introduce una opción válida } PROCEDURE mostrarmenu; VAR elec: integer; BEGIN clrscr; REPEAT writeln('*********************************'); writeln(' Elige una opción'); writeln('********************************'); writeln('1. Jugar contra la máquina'); writeln('2. Jugar contra otro usuario'); writeln('0. Salir'); writeln('********************************'); readln(elec); UNTIL (elec=0) OR (elec=1) OR (elec = 2) ; IF elec<>0 THEN menu(elec); END; (* PROCEDURE mostrarmenu *) {===========================================================================} { Esta función pregunta si se desea jugar una nueva partida. En caso de que sea que no, devuelve un booleano con true, y si es que sí, con false } FUNCTION preguntaOtra: boolean; VAR op: char; terminado:boolean; BEGIN terminado:=false; REPEAT writeln('¿Desea jugar otra partida (S/N)?'); readln(op); CASE op OF 'S': mostrarmenu; 'N': BEGIN writeln('¡Hasta la próxima!'); terminado:=true; END; END; UNTIL (op='N') or (op='S'); preguntaOtra:=terminado; END; (*FUNCTION preguntaOtra*) {===========================================================================} { Este procedimiento muestra las reglas del juego. Pregunta al jugador si desea iniciar una nueva partida } PROCEDURE muestrareglas; VAR opc: char; BEGIN clrscr; writeln('************************************************'); writeln('____________________ REGLAS ____________________'); writeln('************************************************'); writeln; writeln('- Piedra gana a tijeras'); writeln('- Papel gana a piedra'); writeln('- Tijeras ganan a papel'); writeln('- Si ambos eligen lo mismo, se produce un empate'); writeln('************************************************'); REPEAT writeln('¿Desea jugar una partida(S/N)?'); readln(opc); CASE opc OF 'S': mostrarmenu; 'N': writeln('¿Demasiado difícil para ti? Mira las puntuaciones: '); END; UNTIL (opc='N') OR (opc='S'); END; (* PROCEDURE muestrareglas *) {===========================================================================} { Este procedimiento mustra una bienvenida al juego y pregunta al usuario si desea que se muestren las instrucciones } PROCEDURE bienvenida; VAR op: char; BEGIN writeln('******************************************'); writeln('****** JUEGO PIEDRA, PAPEL O TIJERAS *****'); writeln('******************************************'); writeln; writeln('Bienvenido al juego Piedra, Papel o Tijeras.'); REPEAT writeln('¿Desea que se muestren las instrucciones?(S/N)'); readln(op); CASE op OF 'S': muestrareglas; 'N': writeln('¿Estás seguro? Mira las estadísticas: '); END; UNTIL (op='N') OR (op='S'); END; (*PROCEDURE bienvenida*) {===========================================================================} {////////////////////////// PROGRAMA PRINCIPAL ////////////////////////////} BEGIN clrscr; cEmpate:=0; cMaquina:=0; cUser:=0; contador:=0; terminado:=false; bienvenida; REPEAT mostrarpuntuacion(cEmpate, cMaquina, cUser, contador); terminado:= preguntaOtra; UNTIL (terminado= true); END. (* PROGRAMA PRINCIPAL *)
{************************************************} {* *} {* AIMP Programming Interface *} {* v4.50 build 2000 *} {* *} {* Artem Izmaylov *} {* (C) 2006-2017 *} {* www.aimp.ru *} {* Mail: support@aimp.ru *} {* *} {************************************************} unit apiLyrics; {$I apiConfig.inc} interface uses Windows, // API apiObjects, apiFileManager, apiThreading; const SID_IAIMPServiceLyrics = '{41494D50-5372-764C-7972-697800000000}'; IID_IAIMPServiceLyrics: TGUID = SID_IAIMPServiceLyrics; SID_IAIMPExtensionLyricsProvider = '{41494D50-4578-744C-7972-697850727600}'; IID_IAIMPExtensionLyricsProvider: TGUID = SID_IAIMPExtensionLyricsProvider; SID_IAIMPLyrics = '{41494D50-4C79-7269-6373-46696C650000}'; IID_IAIMPLyrics: TGUID = SID_IAIMPLyrics; // PropertyID for the IAIMPLyrics AIMP_LYRICS_PROPID_TEXT = 1; AIMP_LYRICS_PROPID_TYPE = 2; AIMP_LYRICS_PROPID_LYRICIST = 3; AIMP_LYRICS_PROPID_OFFSET = 4; AIMP_LYRICS_PROPID_ALBUM = 5; AIMP_LYRICS_PROPID_TITLE = 6; AIMP_LYRICS_PROPID_CREATOR = 7; AIMP_LYRICS_PROPID_APP = 8; AIMP_LYRICS_PROPID_APPVER = 9; // Lyrics Type AIMP_LYRICS_TYPE_UNKNOWN = 0; AIMP_LYRICS_TYPE_UNSYNCED = 1; AIMP_LYRICS_TYPE_SYNCED = 2; // IAIMPLyrics's File Format AIMP_LYRICS_FORMAT_TXT = 0; AIMP_LYRICS_FORMAT_LRC = 1; AIMP_LYRICS_FORMAT_SRT = 2; // Flags for IAIMPServiceLyrics.Get AIMP_SERVICE_LYRICS_FLAGS_NOCACHE = 1; AIMP_SERVICE_LYRICS_FLAGS_WAITFOR = 4; // IAIMPExtensionLyricsProvider.GetCategory AIMP_LYRICS_PROVIDER_CATEGORY_FILE = 1; AIMP_LYRICS_PROVIDER_CATEGORY_INTERNET = 2; type { IAIMPLyrics } IAIMPLyrics = interface(IAIMPPropertyList) [SID_IAIMPLyrics] function Assign(Source: IAIMPLyrics): HRESULT; stdcall; function Clone(out Target: IAIMPLyrics): HRESULT; stdcall; // function Add(TimeStart, TimeFinish: Integer; Text: IAIMPString): HRESULT; stdcall; function Delete(Index: Integer): HRESULT; stdcall; function Find(Time: Integer; out Index: Integer; out Text: IAIMPString): HRESULT; stdcall; function Get(Index: Integer; out TimeStart, TimeFinish: Integer; out Text: IAIMPString): HRESULT; stdcall; function GetCount(out Value: Integer): HRESULT; stdcall; // I/O function LoadFromFile(FileURI: IAIMPString): HRESULT; stdcall; function LoadFromStream(Stream: IAIMPStream; Format: Integer): HRESULT; stdcall; function LoadFromString(&String: IAIMPString; Format: Integer): HRESULT; stdcall; function SaveToFile(FileURI: IAIMPString): HRESULT; stdcall; function SaveToStream(Stream: IAIMPStream; Format: Integer): HRESULT; stdcall; function SaveToString(out &String: IAIMPString; Format: Integer): HRESULT; stdcall; end; { IAIMPExtensionLyricsProvider } IAIMPExtensionLyricsProvider = interface [SID_IAIMPExtensionLyricsProvider] function Get(Owner: IAIMPTaskOwner; FileInfo: IAIMPFileInfo; Flags: DWORD; Lyrics: IAIMPLyrics): HRESULT; stdcall; function GetCategory: DWORD; stdcall; end; { IAIMPServiceLyrics } TAIMPServiceLyricsReceiveProc = procedure (Lyrics: IAIMPLyrics; UserData: Pointer); stdcall; IAIMPServiceLyrics = interface [SID_IAIMPServiceLyrics] function Get(FileInfo: IAIMPFileInfo; Flags: DWORD; CallbackProc: TAIMPServiceLyricsReceiveProc; UserData: Pointer; out TaskID: Pointer): HRESULT; stdcall; function Cancel(TaskID: Pointer; Flags: DWORD): HRESULT; stdcall; end; implementation end.
Program escultores; uses Windows; // AMBIENTE const numerosChar = ['0'..'9']; // del 0 al 9. a_dir = './escultores-secuencia.txt'; var a_sec : File of Char; v_sec : Char; continente, nombre, anioChar : ShortString; eleccion_usuario : Char; total_escultores, anioInt, total_incorrectos : Integer; porcentaje : Real; guardarEscultor : Boolean; // PROCEDIMIENTOS procedure reiniciarTemp; begin continente := ''; nombre := ''; anioChar := ''; guardarEscultor := False; end; procedure iniciarVariables; begin total_escultores := 0; total_incorrectos := 0; guardarEscultor := False; end; // FUNCIONES function devolverContinente(continente: ShortString): ShortString; var resp : ShortString; begin case continente of 'X' : resp := 'América'; 'E' : resp := 'Europa'; 'F' : resp := 'Africa'; 'A' : resp := 'Asia'; end; devolverContinente := resp; end; function hayQueInvertir(anio : Integer): Boolean; var resp : Boolean; dig1, dig2 : Integer; begin resp := False; dig1 := (anio DIV 1000); if (dig1 >= 3) or (dig1 = 0) then begin resp := True; end else begin dig2 := ((anio DIV 100) MOD 10); if (dig2 <> 0) and (dig2 <> 9) then begin resp := True; end; end; hayQueInvertir := resp; end; function invertir(anioIncorrecto : Integer): Integer; var n, m, i : Integer; begin total_incorrectos := total_incorrectos + 1; n := anioIncorrecto; m := 0; for i:=1 to 4 do begin m := (m * 10) + (n MOD 10); n := (n DIV 10); end; invertir := m; end; // ALGORITMO begin // Colocar consola en UTF8 (acentos, ñ, etc). SetConsoleOutputCP(CP_UTF8); Assign(a_sec, a_dir); // Manejo de errores. {$I-} Reset(a_sec); {$I+} if IOResult <> 0 then // Si el IOResult es 0 no hay error. begin WriteLn('ERROR: Por favor, cree un archivo .txt llamado "escultores-secuencia.txt"'); halt(2); // Detiene programa. end; // Iniciar variables. iniciarVariables; // Preguntar continente. WriteLn('¿Que continente desea consultar?'); WriteLn('X -> América | E -> Europa | F -> Africa | A -> Asia'); ReadLn(eleccion_usuario); // Análisis de secuencia. while not Eof(a_sec) do begin total_escultores := total_escultores + 1; // Reiniciar temporales. reiniciarTemp; Read(a_sec, v_sec); // CONTINENTE: continente := v_sec; if (continente = eleccion_usuario) then guardarEscultor := True; // devolverContinente(continente)); Read(a_sec, v_sec); // NOMBRE: while not (v_sec in numerosChar) do // Mientras no sea un numero, es decir año, hacer: begin nombre := nombre + v_sec; // Concatenar dos caracteres. Read(a_sec, v_sec); end; // AÑO: while (v_sec <> '|') do begin anioChar := anioChar + v_sec; Read(a_sec, v_sec); end; Val(anioChar, anioInt); if (hayQueInvertir(anioInt)) then begin anioInt := invertir(anioInt); end; if (guardarEscultor) then begin // Escribir secuencia de salida acá. Usando variables temporales guardadas anteriormente. end; // SIGUIENTE ESCULTOR... end; Close(a_sec); WriteLn('Análisis terminado.'); // Informar escultores antes del 2000. // Informar porcentaje incorrecto. porcentaje := (total_incorrectos * 100) / total_escultores; WriteLn('- Porcentaje de incorrectos sobre total de escultores: ', Round(porcentaje), '%'); end.
program SortingAlgo; uses wincrt; type TAB = array [0..50] of integer; {define the list} var T : TAB; n, i: integer; procedure fill(var T:TAB; n:integer); {procedure to fill the list} begin for i:=1 to n do begin write('T[',i,'] = '); readln(T[i]); end; end; Function Max(T:TAB; i,n:integer):integer; {function take 3 arg : T type TAB => the array to do the process on i var integer => the variable of where the no sorting part start n var integer => taille of the array } var {local variable => inside the function} {maximum var integer => the maximum value in the array (no sorting part)} {index var integer => the index of maximum element in the array (no sorting part)} {j var integer => the counter of for loop} maximum, index, j : integer; begin {the maximum variable take the first element in the array (no sorting part) and start to find the bigger element in this part} {for loop start from the var i => i is the index of first item in (no sorting part} maximum := T[i]; index := i; {here be carefull this statment is very important !} {if the index don't get the i as default value will get a bug in the program} {because there is a case when the next condition never come true.. that's the bug} for j:=i to n do if T[j] > maximum then begin maximum := T[j]; index := j; end; Max := index; {return the index of maximum item in the array (no sorting part)} end; procedure replace(var T:TAB; i, m:integer); {procedure to replace the value} var item : integer; begin item := T[i]; T[i] := T[m]; T[m] := item; end; procedure Sort(var T:TAB; n:integer); {procedure Sort => to change the item position in the array to sorted it in order} {item var integer => to put the variable change into - it's the one way to do that !} {m var integer => the return value from the Max function} var m : integer; begin for i:=1 to (n - 1) do begin m := Max(T, i, n); if m <> i then replace(T, i, m); end; end; procedure show(T:TAB; n:integer); {to show the sorted list} begin for i:=1 to n do write(T[i], ' | '); end; begin writeln('Hi From Sort Algorithm'); writeln(); write('First well will fill an array of integer, please input the length of the array : '); readln(n); writeln(); writeln('Fill the list with integer element'); fill(T, n); writeln('Let the processing work...'); Sort(T, n); writeln(); writeln('And now I will show you the sorting array'); show(T, n); writeln(); end.
unit UFrmNoteEditorConfig; interface uses Vcl.Forms, Vcl.Dialogs, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, System.Classes; type TFrmNoteEditorConfig = class(TForm) BtnOK: TButton; BtnCancel: TButton; FD: TFontDialog; RzLabel1: TLabel; AlteraFonte: TSpeedButton; BoxPreview: TPanel; EdBgColor: TColorBox; Label1: TLabel; Bevel1: TBevel; Lb: TLabel; procedure AlteraFonteClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure EdBgColorChange(Sender: TObject); private procedure FillCaptionFonte; end; implementation {$R *.dfm} uses System.SysUtils; procedure TFrmNoteEditorConfig.FormShow(Sender: TObject); begin FillCaptionFonte; EdBgColorChange(nil); end; procedure TFrmNoteEditorConfig.FillCaptionFonte; begin Lb.Caption := Format('%s, %d', [Lb.Font.Name, Lb.Font.Size]); end; procedure TFrmNoteEditorConfig.AlteraFonteClick(Sender: TObject); begin FD.Font.Assign(Lb.Font); if FD.Execute then begin Lb.Font.Assign(FD.Font); FillCaptionFonte; end; end; procedure TFrmNoteEditorConfig.EdBgColorChange(Sender: TObject); begin Lb.Color := EdBgColor.Selected; end; end.
{ ****************************************************************************** } { * Generic hash Library * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit GHashList; {$INCLUDE zDefine.inc} interface uses {$IFDEF FPC} FPCGenericStructlist, {$ENDIF FPC} DoStatusIO, CoreClasses, PascalStrings, UnicodeMixedLib, ListEngine; type {$IFDEF FPC} generic TGenericHashList<T_: TCoreClassObject> = class(TCoreClassObject) {$ELSE FPC} TGenericHashList<T_: class> = class(TCoreClassObject) {$ENDIF FPC} public type TRefClass_ = {$IFDEF FPC}specialize {$ENDIF FPC}TGenericHashList<T_>; TGebnericHashChangeEvent = procedure(Sender: TCoreClassObject; Name: SystemString; OLD_, New_: T_) of object; PGebnericHashListData = ^TGebnericHashListData; TGebnericHashListData = record Obj: T_; OnChnage: TGebnericHashChangeEvent; end; TGebnericHashListLoopCall = procedure(const Name_: PSystemString; Obj_: T_); TGebnericHashListLoopMethod = procedure(const Name_: PSystemString; Obj_: T_) of object; {$IFDEF FPC} TGebnericHashListLoopProc = procedure(const Name_: PSystemString; Obj_: T_) is nested; {$ELSE FPC} TGebnericHashListLoopProc = reference to procedure(const Name_: PSystemString; Obj_: T_); {$ENDIF FPC} private FAutoFreeObject: Boolean; FHashList: THashList; FIncremental: NativeInt; Default_Null_Value: T_; function GetCount: NativeInt; function GetIgnoreCase: Boolean; procedure SetIgnoreCase(const Value: Boolean); function GetKeyValue(const Name: SystemString): T_; procedure SetKeyValue(const Name: SystemString; const Value: T_); function GetOnChange(const Name: SystemString): TGebnericHashChangeEvent; procedure SetOnChange(const Name: SystemString; const AValue: TGebnericHashChangeEvent); function GetAccessOptimization: Boolean; procedure SetAccessOptimization(const Value: Boolean); procedure DefaultDataFreeProc(p: Pointer); protected public constructor Create(AutoFreeData_: Boolean; HashPoolSize_: Integer; Default_Null_Value_: T_); destructor Destroy; override; procedure Assign(sour: TRefClass_); procedure ProgressC(const OnProgress: TGebnericHashListLoopCall); procedure ProgressM(const OnProgress: TGebnericHashListLoopMethod); procedure ProgressP(const OnProgress: TGebnericHashListLoopProc); procedure Clear; procedure GetNameList(OutputList: TCoreClassStrings); overload; procedure GetNameList(OutputList: TListString); overload; procedure GetNameList(OutputList: TListPascalString); overload; procedure GetListData(OutputList: TCoreClassStrings); overload; procedure GetListData(OutputList: TListString); overload; procedure GetListData(OutputList: TListPascalString); overload; procedure GetAsList(OutputList: TCoreClassListForObj); function GetObjAsName(Obj: T_): SystemString; procedure Delete(const Name: SystemString); function Add(const Name: SystemString; Obj_: T_): T_; function FastAdd(const Name: SystemString; Obj_: T_): T_; function Find(const Name: SystemString): T_; function Exists(const Name: SystemString): Boolean; function ExistsObject(Obj: T_): Boolean; procedure CopyFrom(const Source: TRefClass_); function ReName(OLD_, New_: SystemString): Boolean; function MakeName: SystemString; function MakeRefName(RefrenceName: SystemString): SystemString; property AccessOptimization: Boolean read GetAccessOptimization write SetAccessOptimization; property IgnoreCase: Boolean read GetIgnoreCase write SetIgnoreCase; property AutoFreeObject: Boolean read FAutoFreeObject write FAutoFreeObject; property Count: NativeInt read GetCount; property KeyValue[const Name: SystemString]: T_ read GetKeyValue write SetKeyValue; default; property NameValue[const Name: SystemString]: T_ read GetKeyValue write SetKeyValue; property OnChange[const Name: SystemString]: TGebnericHashChangeEvent read GetOnChange write SetOnChange; property HashList: THashList read FHashList; end; procedure Test_GListEngine; implementation function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetCount: NativeInt; begin Result := FHashList.Count; end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetIgnoreCase: Boolean; begin Result := FHashList.IgnoreCase; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.SetIgnoreCase(const Value: Boolean); begin FHashList.IgnoreCase := Value; end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetKeyValue(const Name: SystemString): T_; var pObjData: PGebnericHashListData; begin pObjData := FHashList.NameValue[Name]; if pObjData <> nil then Result := pObjData^.Obj as T_ else Result := Default_Null_Value; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.SetKeyValue(const Name: SystemString; const Value: T_); begin Add(Name, Value); end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetOnChange(const Name: SystemString): TGebnericHashChangeEvent; var pObjData: PGebnericHashListData; begin pObjData := FHashList.NameValue[Name]; if pObjData <> nil then Result := pObjData^.OnChnage else Result := nil; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.SetOnChange(const Name: SystemString; const AValue: TGebnericHashChangeEvent); var pObjData: PGebnericHashListData; begin pObjData := FHashList.NameValue[Name]; if pObjData = nil then begin new(pObjData); pObjData^.OnChnage := AValue; pObjData^.Obj := Default_Null_Value; FHashList.Add(Name, pObjData, False); end else pObjData^.OnChnage := AValue; end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetAccessOptimization: Boolean; begin Result := FHashList.AccessOptimization; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.SetAccessOptimization(const Value: Boolean); begin FHashList.AccessOptimization := Value; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.DefaultDataFreeProc(p: Pointer); begin Dispose(PGebnericHashListData(p)); end; constructor TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.Create(AutoFreeData_: Boolean; HashPoolSize_: Integer; Default_Null_Value_: T_); begin inherited Create; FHashList := THashList.CustomCreate(HashPoolSize_); FHashList.AutoFreeData := True; FHashList.OnFreePtr := {$IFDEF FPC}@{$ENDIF FPC}DefaultDataFreeProc; FAutoFreeObject := AutoFreeData_; FIncremental := 0; Default_Null_Value := Default_Null_Value_; end; destructor TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.Destroy; begin Clear; DisposeObject(FHashList); inherited Destroy; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.Assign(sour: TRefClass_); var i: Integer; p: PHashListData; begin Clear; if sour.HashList.Count > 0 then begin i := 0; p := sour.HashList.FirstPtr; while i < sour.HashList.Count do begin FastAdd(p^.OriginName, PGebnericHashListData(p^.Data)^.Obj); inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.ProgressC(const OnProgress: TGebnericHashListLoopCall); var i: Integer; p: PHashListData; begin if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin try OnProgress(@p^.OriginName, PGebnericHashListData(p^.Data)^.Obj); except end; inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.ProgressM(const OnProgress: TGebnericHashListLoopMethod); var i: Integer; p: PHashListData; begin if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin try OnProgress(@p^.OriginName, PGebnericHashListData(p^.Data)^.Obj); except end; inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.ProgressP(const OnProgress: TGebnericHashListLoopProc); var i: Integer; p: PHashListData; begin if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin try OnProgress(@p^.OriginName, PGebnericHashListData(p^.Data)^.Obj); except end; inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.Clear; var lst: TCoreClassList; pObjData: PGebnericHashListData; i: Integer; begin if AutoFreeObject then begin lst := TCoreClassList.Create; FHashList.GetListData(lst); if lst.Count > 0 then for i := 0 to lst.Count - 1 do with PHashListData(lst[i])^ do begin pObjData := Data; if pObjData <> nil then if pObjData^.Obj <> Default_Null_Value then begin try DisposeObject(pObjData^.Obj); except end; end; end; DisposeObject(lst); end; FHashList.Clear; FIncremental := 0; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetNameList(OutputList: TCoreClassStrings); var i: Integer; p: PHashListData; begin OutputList.Clear; if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin OutputList.AddObject(p^.OriginName, PGebnericHashListData(p^.Data)^.Obj); inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetNameList(OutputList: TListString); var i: Integer; p: PHashListData; begin OutputList.Clear; if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin OutputList.Add(p^.OriginName, PGebnericHashListData(p^.Data)^.Obj); inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetNameList(OutputList: TListPascalString); var i: Integer; p: PHashListData; begin OutputList.Clear; if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin OutputList.Add(p^.OriginName, PGebnericHashListData(p^.Data)^.Obj); inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetListData(OutputList: TCoreClassStrings); var i: Integer; p: PHashListData; begin OutputList.Clear; if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin OutputList.AddObject(p^.OriginName, PGebnericHashListData(p^.Data)^.Obj); inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetListData(OutputList: TListString); var i: Integer; p: PHashListData; begin OutputList.Clear; if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin OutputList.Add(p^.OriginName, PGebnericHashListData(p^.Data)^.Obj); inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetListData(OutputList: TListPascalString); var i: Integer; p: PHashListData; begin OutputList.Clear; if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin OutputList.Add(p^.OriginName, PGebnericHashListData(p^.Data)^.Obj); inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetAsList(OutputList: TCoreClassListForObj); var i: Integer; p: PHashListData; begin OutputList.Clear; if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin OutputList.Add(PGebnericHashListData(p^.Data)^.Obj); inc(i); p := p^.Next; end; end; end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.GetObjAsName(Obj: T_): SystemString; var i: Integer; p: PHashListData; begin Result := ''; if HashList.Count > 0 then begin i := 0; p := HashList.FirstPtr; while i < HashList.Count do begin if PGebnericHashListData(p^.Data)^.Obj = Obj then begin Result := p^.OriginName; Exit; end; inc(i); p := p^.Next; end; end; end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.Delete(const Name: SystemString); var pObjData: PGebnericHashListData; begin if AutoFreeObject then begin pObjData := FHashList.NameValue[Name]; if pObjData <> nil then begin if pObjData^.Obj <> Default_Null_Value then begin try DisposeObject(pObjData^.Obj); pObjData^.Obj := Default_Null_Value; except end; end; end; end; FHashList.Delete(Name); end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.Add(const Name: SystemString; Obj_: T_): T_; var pObjData: PGebnericHashListData; begin pObjData := FHashList.NameValue[Name]; if pObjData <> nil then begin try if Assigned(pObjData^.OnChnage) then pObjData^.OnChnage(Self, Name, pObjData^.Obj, Obj_); except end; if (FAutoFreeObject) and (pObjData^.Obj <> Default_Null_Value) then begin try DisposeObject(pObjData^.Obj); pObjData^.Obj := Default_Null_Value; except end; end; end else begin new(pObjData); pObjData^.OnChnage := nil; FHashList.Add(Name, pObjData, False); end; pObjData^.Obj := Obj_; Result := Obj_; end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.FastAdd(const Name: SystemString; Obj_: T_): T_; var pObjData: PGebnericHashListData; begin new(pObjData); pObjData^.OnChnage := nil; FHashList.Add(Name, pObjData, False); pObjData^.Obj := Obj_; Result := Obj_; end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.Find(const Name: SystemString): T_; var pObjData: PGebnericHashListData; begin pObjData := FHashList.Find(Name); if pObjData <> nil then Result := pObjData^.Obj else Result := Default_Null_Value; end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.Exists(const Name: SystemString): Boolean; begin Result := FHashList.Exists(Name); end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.ExistsObject(Obj: T_): Boolean; var lst: TCoreClassList; i: Integer; begin Result := False; lst := TCoreClassList.Create; FHashList.GetListData(lst); if lst.Count > 0 then for i := 0 to lst.Count - 1 do begin with PHashListData(lst[i])^ do begin if PGebnericHashListData(Data)^.Obj = Obj then begin Result := True; Break; end; end; end; DisposeObject(lst); end; procedure TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.CopyFrom(const Source: TRefClass_); var lst: TCoreClassList; pObjData: PGebnericHashListData; i: Integer; begin lst := TCoreClassList.Create; Source.HashList.GetListData(lst); if lst.Count > 0 then for i := 0 to lst.Count - 1 do begin with PHashListData(lst[i])^ do if Data <> nil then begin pObjData := Data; NameValue[OriginName] := pObjData^.Obj; end; end; DisposeObject(lst); end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.ReName(OLD_, New_: SystemString): Boolean; var pObjData: PGebnericHashListData; begin pObjData := FHashList.NameValue[OLD_]; Result := (OLD_ <> New_) and (pObjData <> nil) and (FHashList.NameValue[New_] = nil); if Result then begin Add(New_, pObjData^.Obj); FHashList.Delete(OLD_); end; end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.MakeName: SystemString; begin repeat inc(FIncremental); Result := umlIntToStr(FIncremental); until not Exists(Result); end; function TGenericHashList{$IFNDEF FPC}<T_>{$ENDIF FPC}.MakeRefName(RefrenceName: SystemString): SystemString; begin Result := RefrenceName; if not Exists(Result) then Exit; repeat inc(FIncremental); Result := RefrenceName + umlIntToStr(FIncremental); until not Exists(Result); end; procedure Test_GListEngine; type TSL = {$IFDEF FPC}specialize {$ENDIF FPC}TGenericHashList<TCoreClassStringList>; var L: TSL; begin L := TSL.Create(True, 100, nil); L.Add('abc', TCoreClassStringList.Create).Text := '1'#10'2'#10'3'; L.Add('abc1', TCoreClassStringList.Create).Text := '11'#10'222'#10'33'; L.Add('abc2', TCoreClassStringList.Create).Text := '111'#10'222'#10'333'; L.Add('abc3', TCoreClassStringList.Create).Text := '1111'#10'2222'#10'3333'; DoStatus(L['abc'][0]); DoStatus(L['abc'][1]); DoStatus(L['abc'][2]); DoStatus(L['abc1'][0]); DoStatus(L['abc2'][0]); DoStatus(L['abc3'][0]); DisposeObject(L); end; end.
{ ****************************************************************************** } { * fast File query in Package * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } (* update history *) unit ObjectDataHashField; {$INCLUDE zDefine.inc} interface uses ObjectDataManager, ObjectDataHashItem, CoreClasses, PascalStrings, UnicodeMixedLib; type TObjectDataHashField = class(TCoreClassObject) private FList: TCoreClassListForObj; FDBEngine: TObjectDataManager; FRoot: TObjectDataHashItem; FRootDir: SystemString; FAutoFreeDataEngine: Boolean; protected function GetItems(index: Integer): TObjectDataHashItem; function GetNameItems(Name_: SystemString): TObjectDataHashItem; function GetPathItems(Path_: SystemString): PHashItemData; public constructor Create(DataEngine_: TObjectDataManager; RootDir_: SystemString); destructor Destroy; override; function Clone: TObjectDataHashField; function Count: Integer; procedure Clear; procedure Refresh; procedure ChangeRoot(NewRoot_: SystemString); function TotalCount: Integer; function New(Name_, Description_: SystemString): TObjectDataHashItem; function Delete(Name_: SystemString; ForceRefresh: Boolean): Boolean; function ReName(OLDName_, NewName_, Description_: SystemString; ForceRefresh: Boolean): Boolean; function Exists(Name_: SystemString): Boolean; property Items[index: Integer]: TObjectDataHashItem read GetItems; property NameItems[Name_: SystemString]: TObjectDataHashItem read GetNameItems; default; property PathItems[Path_: SystemString]: PHashItemData read GetPathItems; property DBEngine: TObjectDataManager read FDBEngine; property ROOT: TObjectDataHashItem read FRoot; property AutoFreeDataEngine: Boolean read FAutoFreeDataEngine write FAutoFreeDataEngine; end; implementation const PathDelim = ':\/'; var _LibManCloneAutoFreeList: TCoreClassListForObj = nil; function LibManCloneAutoFreeList: TCoreClassListForObj; begin if _LibManCloneAutoFreeList = nil then _LibManCloneAutoFreeList := TCoreClassListForObj.Create; Result := _LibManCloneAutoFreeList; end; procedure FreeLibManCloneAutoFreeList; var i: Integer; begin if _LibManCloneAutoFreeList = nil then Exit; i := 0; while i < _LibManCloneAutoFreeList.Count do DisposeObject(TObjectDataHashField(_LibManCloneAutoFreeList[i])); DisposeObject(_LibManCloneAutoFreeList); _LibManCloneAutoFreeList := nil; end; procedure DeleteLibManCloneFromAutoFreeList(p: TObjectDataHashField); var i: Integer; begin if _LibManCloneAutoFreeList = nil then Exit; i := 0; while i < _LibManCloneAutoFreeList.Count do begin if _LibManCloneAutoFreeList[i] = p then _LibManCloneAutoFreeList.Delete(i) else inc(i); end; end; function TObjectDataHashField.GetItems(index: Integer): TObjectDataHashItem; begin Result := TObjectDataHashItem(FList[index]); end; function TObjectDataHashField.GetNameItems(Name_: SystemString): TObjectDataHashItem; var i: Integer; begin Result := ROOT; if Count > 0 then for i := 0 to Count - 1 do if umlMultipleMatch(True, Name_, Items[i].Name) then begin Result := Items[i]; Break; end; end; function TObjectDataHashField.GetPathItems(Path_: SystemString): PHashItemData; var i: Integer; slst: TObjectDataHashItem; PhPrefix, phPostfix: SystemString; begin Result := nil; if Count > 0 then begin if umlGetIndexStrCount(Path_, PathDelim) > 1 then PhPrefix := umlGetFirstStr(Path_, PathDelim).Text else PhPrefix := ''; phPostfix := umlGetLastStr(Path_, PathDelim).Text; for i := 0 to Count - 1 do begin if umlMultipleMatch(True, PhPrefix, Items[i].Name) then begin slst := Items[i]; if slst <> nil then begin Result := slst.Names[phPostfix]; if Result <> nil then Break; end; end; end; end; end; constructor TObjectDataHashField.Create(DataEngine_: TObjectDataManager; RootDir_: SystemString); begin inherited Create; FList := TCoreClassListForObj.Create; FDBEngine := DataEngine_; FRoot := nil; FRootDir := RootDir_; Refresh; LibManCloneAutoFreeList.Add(Self); FAutoFreeDataEngine := False; end; destructor TObjectDataHashField.Destroy; begin DeleteLibManCloneFromAutoFreeList(Self); while FList.Count > 0 do begin DisposeObject(TObjectDataHashItem(FList[0])); FList.Delete(0); end; DisposeObject(FList); if FAutoFreeDataEngine then DisposeObject(FDBEngine); inherited Destroy; end; function TObjectDataHashField.Clone: TObjectDataHashField; begin Result := TObjectDataHashField.Create(DBEngine, FRootDir); end; function TObjectDataHashField.Count: Integer; begin Result := FList.Count; end; procedure TObjectDataHashField.Clear; begin while Count > 0 do begin DisposeObject(TObjectDataHashItem(FList[0])); FList.Delete(0); end; end; procedure TObjectDataHashField.Refresh; var fPos: Int64; hsList: TObjectDataHashItem; n, d: SystemString; fSearchHnd: TFieldSearch; begin if FDBEngine.isAbort then Exit; while FList.Count > 0 do begin DisposeObject(TObjectDataHashItem(FList[0])); FList.Delete(0); end; if FDBEngine.FieldFindFirst(FRootDir, '*', fSearchHnd) then begin repeat n := fSearchHnd.Name; d := fSearchHnd.Description; fPos := fSearchHnd.HeaderPOS; hsList := TObjectDataHashItem.Create(FDBEngine, fPos); hsList.Name := n; hsList.Description := d; FList.Add(hsList); until not FDBEngine.FieldFindNext(fSearchHnd); end; if FDBEngine.GetPathField(FRootDir, fPos) then begin n := 'Root'; d := '....'; hsList := TObjectDataHashItem.Create(FDBEngine, fPos); hsList.Name := n; hsList.Description := d; if FList.Count > 0 then FList.Insert(0, hsList) else FList.Add(hsList); FRoot := hsList; end; end; procedure TObjectDataHashField.ChangeRoot(NewRoot_: SystemString); begin FRootDir := NewRoot_; Refresh; end; function TObjectDataHashField.TotalCount: Integer; var i: Integer; begin Result := 0; if Count > 0 then for i := 0 to Count - 1 do Result := Result + Items[i].Count; end; function TObjectDataHashField.New(Name_, Description_: SystemString): TObjectDataHashItem; var fPos: Int64; n, d: SystemString; fSearchHnd: TFieldSearch; begin Result := nil; if not umlMultipleMatch(True, Name_, ROOT.Name) then begin if FDBEngine.CreateField((FRootDir + '/' + Name_), Description_) then begin if FDBEngine.FieldFindFirst(FRootDir, Name_, fSearchHnd) then begin n := fSearchHnd.Name; d := fSearchHnd.Description; fPos := fSearchHnd.HeaderPOS; Result := TObjectDataHashItem.Create(FDBEngine, fPos); Result.Name := n; Result.Description := d; FList.Add(Result); end; end; end else begin Result := ROOT; end; end; function TObjectDataHashField.Delete(Name_: SystemString; ForceRefresh: Boolean): Boolean; begin Result := FDBEngine.FieldDelete(FRootDir, Name_); if (ForceRefresh) and (Result) then Refresh; end; function TObjectDataHashField.ReName(OLDName_, NewName_, Description_: SystemString; ForceRefresh: Boolean): Boolean; var fPos: Int64; begin Result := False; if FDBEngine.FieldExists(FRootDir, NewName_) then Exit; if FDBEngine.GetPathField(FRootDir + '/' + OLDName_, fPos) then begin Result := FDBEngine.FieldReName(fPos, NewName_, Description_); if (Result) and (ForceRefresh) then Refresh; end; end; function TObjectDataHashField.Exists(Name_: SystemString): Boolean; var i: Integer; begin Result := False; if Count > 0 then for i := 0 to Count - 1 do begin if umlMultipleMatch(True, Name_, Items[i].Name) then begin Result := True; Exit; end; end; end; initialization finalization FreeLibManCloneAutoFreeList; end.
unit uMainDM; interface uses SysUtils, Classes, DB, WideStrings, Forms, FireDAC.Phys.IB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Comp.Client, FireDAC.DBX.Migrate, FireDAC.VCLUI.Wait, FireDAC.Phys.IBLiteDef, FireDAC.Phys.IBDef, FireDAC.Phys.IBBase, FireDAC.Comp.UI; type TMainDM = class(TDataModule) SQLConnection: TFDConnection; FDGUIxWaitCursor1: TFDGUIxWaitCursor; FDPhysIBDriverLink1: TFDPhysIBDriverLink; procedure DataModuleCreate(Sender: TObject); procedure SQLConnectionBeforeConnect(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainDM: TMainDM; implementation uses uMainForm, System.IOUtils; {$R *.dfm} procedure TMainDM.DataModuleCreate(Sender: TObject); begin try if not SQLConnection.Connected then SQLConnection.Open; TMainForm(Application.MainForm).DBConnection := SQLConnection; except on E: Exception do raise Exception.Create('Error Message: ' + E.Message); end; end; procedure TMainDM.SQLConnectionBeforeConnect(Sender: TObject); var fDBTemplate, fDBFile: string; const PackageID: string = 'MeetingOrganizer_5qpzh03rg74sm'; begin fDBTemplate := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'MEETINGORGANIZER.IB'; if Pos('WindowsApp', ExtractFilePath(ParamStr(0))) > 0 then fDBFile := TPath.GetCachePath + PathDelim + 'Packages' + PathDelim + PackageID + PathDelim + 'AppData' + PathDelim + 'MEETINGORGANIZER.IB' else fDBFile := fDBTemplate; try if not TFile.Exists(fDBFile) then TFile.Copy(fDBTemplate, fDBFile); if TFile.Exists(fDBFile) then SQLConnection.Params.Values['Database'] := fDBFile else raise Exception.Create('Error Message: ' + fDBFile + ' not found.'); except on E: Exception do raise Exception.Create('Error Message' + E.Message); end; end; end.
unit SDFilesystemCtrls; interface uses ComCtrls, Classes, Contnrs, Controls, Windows, Menus, SysUtils, SDUGeneral, SDUComCtrls, SDFilesystem; type {$M+} // Required to get rid of compiler warning "W1055 PUBLISHED caused RTTI ($M+) to be added to type '%s'" TFilesystemListViewColumn = ( flvcFilename, flvcSize, flvcFiletype, flvcTimestampModified, flvcTimestampCreated, flvcAttributes, flvcTimestampAccessed ); TFilesystemListViewColumn_Layout = record Visible: boolean; Position: integer; Width: integer; end; resourcestring FILESYSTEMLISTVIEWCOL_FILENAME = 'Name'; FILESYSTEMLISTVIEWCOL_SIZE = 'Size'; FILESYSTEMLISTVIEWCOL_FILETYPE = 'Type'; FILESYSTEMLISTVIEWCOL_TIMESTAMP_MODIFIED = 'Date Modified'; FILESYSTEMLISTVIEWCOL_TIMESTAMP_CREATED = 'Date Created'; FILESYSTEMLISTVIEWCOL_ATTRIBUTES = 'Attributes'; FILESYSTEMLISTVIEWCOL_TIMESTAMP_ACCESSED = 'Date Accessed'; const FilesystemListViewColumnTitlePtr: array [TFilesystemListViewColumn] of Pointer = ( @FILESYSTEMLISTVIEWCOL_FILENAME, @FILESYSTEMLISTVIEWCOL_SIZE, @FILESYSTEMLISTVIEWCOL_FILETYPE, @FILESYSTEMLISTVIEWCOL_TIMESTAMP_MODIFIED, @FILESYSTEMLISTVIEWCOL_TIMESTAMP_CREATED, @FILESYSTEMLISTVIEWCOL_ATTRIBUTES, @FILESYSTEMLISTVIEWCOL_TIMESTAMP_ACCESSED ); // Internal names used when saving/restoring layout FilesystemListViewColumnIntName: array [TFilesystemListViewColumn] of string = ( 'NAME', 'SIZE', 'FILETYPE', 'TS_MODIFIED', 'TS_CREATED', 'ATTRIBUTES', 'TS_ACCESSED' ); FilesystemListViewColumnAlignment: array [TFilesystemListViewColumn] of TAlignment = ( taLeftJustify, taRightJustify, taLeftJustify, taLeftJustify, taLeftJustify, taLeftJustify, taLeftJustify ); type TFilesystemListView_Layout = array [TFilesystemListViewColumn] of TFilesystemListViewColumn_Layout; TFilesystemListView_ColOrder = array of TFilesystemListViewColumn; const AUTOCALC_COL_WIDTH = -42; COL_ID_NONE = -1; FILESYSTEMLISTVIEWSTYLE_DEFAULT = vsReport; FILESYSTEMLISTVIEWCOLUMN_DEFAULTS: TFilesystemListView_Layout = ( (Visible: TRUE; Position: 0; Width: AUTOCALC_COL_WIDTH), (Visible: TRUE; Position: 1; Width: 75), (Visible: TRUE; Position: 2; Width: 150), (Visible: TRUE; Position: 3; Width: 120), (Visible: FALSE; Position: 4; Width: 120), (Visible: TRUE; Position: 5; Width: 100), (Visible: FALSE; Position: 6; Width: 120) ); type TNodeRec = record PlaceHolder: boolean; Name: string; ContentsLoaded: boolean; Contents: TSDDirItemList; end; PNodeRec = ^TNodeRec; // Forward declarations TSDLoadDirThread = class; TSDCustomFilesystemListView = class; TSDLoadDirThreadCallback = procedure (thread: TSDLoadDirThread) of object; TSDLoadDirThread = class(TThread) private FFilesystem: TSDCustomFilesystem; Paths: TStringList; procedure SyncMethod(); protected procedure Execute(); override; public LoadedPath: string; LoadedContents: TSDDirItemList; Callback: TSDLoadDirThreadCallback; destructor Destroy(); override; procedure AfterConstruction(); override; procedure AddPath(pathToLoad: string); published property Filesystem: TSDCustomFilesystem read FFilesystem write FFilesystem; end; TSDCustomFilesystemTreeView = class(TTreeView) private FFilesystem: TSDCustomFilesystem; FFilesystemListView: TSDCustomFilesystemListView; FNodeImgIdxClosed: integer; FNodeImgIdxOpen: integer; FNodeImgIdxDrive: integer; FNodeImages: TImageList; FShowHiddenItems: boolean; FCursorStack: TList; procedure AddRootNode(); procedure AddPlaceHolderNode(Node: TTreeNode); procedure DeletePlaceHolderNodesFrom(Node: TTreeNode); function NodeHasPlaceHolderNode(Node: TTreeNode): boolean; procedure CreateChildNodes(Node: TTreeNode); procedure DeleteAllNodes(); procedure LoadContents(Node: TTreeNode); function GetNodeForPath(path: string; farAsPossible: boolean): TTreeNode; procedure AddExpandedLeafNodes(Node: TTreeNode; expandedLeafNodes: TStringList); protected function CanExpand(Node: TTreeNode): boolean; override; procedure Delete(Node: TTreeNode); override; procedure Change(Node: TTreeNode); override; procedure ThreadLoadedContents(thread: TSDLoadDirThread); procedure SetFilesystem(newFilesystem: TSDCustomFilesystem); public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure Initialize(); function PathToNode(Node: TTreeNode): string; function GoToPath(path: string; farAsPossible: boolean): TTreeNode; procedure RefreshNodes(); procedure BeginUpdate(); procedure EndUpdate(); published property Filesystem: TSDCustomFilesystem read FFilesystem write SetFilesystem; property FilesystemListView: TSDCustomFilesystemListView read FFilesystemListView write FFilesystemListView; property ShowHiddenItems: boolean read FShowHiddenItems write FShowHiddenItems default FALSE; end; TSDFilesystemTreeView = class(TSDCustomFilesystemTreeView) end; TSDCustomFilesystemListView = class(TSDListView) private FFilesystem: TSDCustomFilesystem; FFilesystemTreeView: TSDCustomFilesystemTreeView; FPath: string; FContents: TSDDirItemList; FShowParentDir: boolean; FShowHiddenItems: boolean; FHideKnownFileExtns: boolean; FSuppressPopupMenu: boolean; FColumnHeaderPopup: TPopupMenu; FDirectoriesAlwaysSortFirst: boolean; FFileExtnToIconMap_Small: TStringList; FFileExtnToIconMap_Large: TStringList; FIconsLarge: TImageList; FIconsSmall: TImageList; FColumnIDs: array [TFilesystemListViewColumn] of integer; FCursorStack: TList; FInternalColOrder: TFilesystemListView_ColOrder; FInternalLayout: TFilesystemListView_Layout; procedure RecreateAllPosibleColHeaders(); // Update FInternalColOrder based on FInternalLayout procedure UpdateInternalColOrder(); protected procedure DblClick(); override; function LoadContents(path: string): boolean; procedure RepopulateDisplay(); procedure SyncIcons(); procedure GetIconsForFile( filename: string; subduedIcon: boolean; out smallIconIdx: integer; out largeIconIdx: integer ); procedure MakeIconSubdued(imgList: TImageList; idx: integer; treatAs32x32Icon: boolean); function GetDisplayName(item: TSDDirItem): string; function GetDirItemByListIdx(idx: integer): TSDDirItem; function GetDirItemSelected(): TSDDirItem; function GetDisplayedNameByListIdx(idx: integer): string; procedure SetFilesystem(newFilesystem: TSDCustomFilesystem); function GetColumn(colType: TFilesystemListViewColumn): TListColumn; procedure DefaultInternalLayout(); procedure SyncInternalLayoutToDisplayed(); procedure SyncDisplayedToInternalLayout(); function GetLayout(): string; procedure SetLayout(newLayout: string); procedure InitPopup(); function GetPopupMenu: TPopupMenu; override; procedure ColRightClick(Column: TListColumn; Point: TPoint); override; procedure ColumnHeaderPopupClick(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; // Note: This is *not* a published property property Layout: string read GetLayout write SetLayout; procedure Initialize(); procedure SetPath(path: string); procedure _ColumnSortCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); override; property DirItem[idx: integer]: TSDDirItem read GetDirItemByListIdx; property DisplayedName[idx: integer]: string read GetDisplayedNameByListIdx; procedure BeginUpdate(); procedure EndUpdate(); procedure ChooseColumns(); published property Filesystem: TSDCustomFilesystem read FFilesystem write SetFilesystem; property FilesystemTreeView: TSDCustomFilesystemTreeView read FFilesystemTreeView write FFilesystemTreeView; property Path: string read FPath write SetPath; property ShowParentDir: boolean read FShowParentDir write FShowParentDir default FALSE; property ShowHiddenItems: boolean read FShowHiddenItems write FShowHiddenItems default FALSE; property HideKnownFileExtns: boolean read FHideKnownFileExtns write FHideKnownFileExtns default TRUE; // If DirectoriesAlwaysSortFirst is set to TRUE, dirs will always appear // first when sorting by column // Otherwise, it'll follow MS Windows Explorer style, dirs all appear first // if ascending, last if descending property DirectoriesAlwaysSortFirst: boolean read FDirectoriesAlwaysSortFirst write FDirectoriesAlwaysSortFirst default FALSE; property DirItemSelected: TSDDirItem read GetDirItemSelected; end; TSDFilesystemListView = class(TSDCustomFilesystemListView) end; procedure Register; function GetLayoutColOrder(layout: TFilesystemListView_Layout; includeNonVisible: boolean): TFilesystemListView_ColOrder; function FilesystemListViewColumnTitle(col: TFilesystemListViewColumn): string; implementation uses Messages, Graphics, Math, SDFilesystem_FAT, SDUi18n, SDUGraphics, SDFilesystemCtrls_ColDetails; {$IFDEF _NEVER_DEFINED} // This is just a dummy const to fool dxGetText when extracting message // information // This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to // picks up SDUGeneral.SDUCRLF const SDUCRLF = ''#13#10; {$ENDIF} const PLACEHOLDER = '<placeholder node>'; // DO NOT TRANSLATE! Just a placeholder marker PATH_SEPARATOR = '\'; // Marker tag COLHEADERPOPUPMENUITEM_MORE = 9999; procedure Register; begin RegisterComponents('SDeanFilesystem', [TSDFilesystemTreeView]); RegisterComponents('SDeanFilesystem', [TSDFilesystemListView]); end; function FilesystemListViewColumnTitle(col: TFilesystemListViewColumn): string; begin Result := LoadResString(FilesystemListViewColumnTitlePtr[col]); end; function GetLayoutColOrder(layout: TFilesystemListView_Layout; includeNonVisible: boolean): TFilesystemListView_ColOrder; var retval: TFilesystemListView_ColOrder; colType: TFilesystemListViewColumn; order: TStringList; i: integer; begin order:= TStringList.Create(); try for colType:=low(colType) to high(colType) do begin if ( layout[colType].Visible or includeNonVisible ) then begin // Use IntToHex so that we have padding "0"'s, and the TStringList sort // sorts the items in the correct order order.AddObject(IntToHex(layout[colType].Position, 4), TObject(colType)); end; end; order.Sorted := TRUE; SetLength(retval, order.Count); for i:=0 to (order.Count - 1) do begin retval[i] := TFilesystemListViewColumn(order.Objects[i]); end; finally order.Free(); end; Result := retval; end; // farAsPossible - If the path isn't available, go as far along it as possible function TSDCustomFilesystemTreeView.GoToPath(path: string; farAsPossible: boolean): TTreeNode; var targetNode: TTreeNode; tmpNode: TTreeNode; begin BeginUpdate(); try targetNode := GetNodeForPath(path, farAsPossible); if (targetNode <> nil) then begin tmpNode := targetNode.Parent; while (tmpNode <> nil) do begin tmpNode.Expand(FALSE); tmpNode := tmpNode.Parent; end; targetNode.Selected := TRUE; targetNode.Focused := TRUE; end; finally EndUpdate(); end; Result := targetNode; end; procedure TSDCustomFilesystemTreeView.BeginUpdate(); begin FCursorStack.Add(Pointer(self.Cursor)); self.Cursor := crHourglass; Perform(WM_SETCURSOR, Handle, HTCLIENT); // Force cursor display to update Items.BeginUpdate(); end; procedure TSDCustomFilesystemTreeView.EndUpdate(); begin if (FCursorStack.Count > 0) then begin self.Cursor := TCursor(FCursorStack[FCursorStack.Count-1]); Perform(WM_SETCURSOR, Handle, HTCLIENT); // Force cursor display to update FCursorStack.Delete(FCursorStack.Count - 1); end; Items.EndUpdate(); end; // farAsPossible - If the path isn't available, go as far along it as possible function TSDCustomFilesystemTreeView.GetNodeForPath(path: string; farAsPossible: boolean): TTreeNode; var retval: TTreeNode; pathComponents: TStringList; i: integer; j: integer; lastNode: TTreeNode; checkNode: TTreeNode; checkNodeRec: PNodeRec; allOK: boolean; pathPartNode: TTreeNode; stlTmp: TStringList; pathFirst: string; pathRest: string; currNodeName: string; begin retval := nil; allOK := TRUE; // Normalise path path := Trim(path); path := StringReplace(path, '/', PATH_SEPARATOR, [rfReplaceAll]); path := StringReplace(path, '\', PATH_SEPARATOR, [rfReplaceAll]); if not(Filesystem.CaseSensitive) then begin path := uppercase(path); end; pathComponents := TStringList.Create(); try // Sanity check; a path was passed in, right? if allOK then begin if (length(path) <= 0) then begin allOK := FALSE; end; end; // Sanity check; the path started with a PATH_SEPARATOR, right? if allOK then begin if (path[1] <> PATH_SEPARATOR) then begin allOK := FALSE; end; end; // Split path into TStringList if allOK then begin // Remove leading PATH_SEPARATOR; otherwise this would cause the first // item taken off with SDUSplitString(...) to be a blank System.Delete(path, 1, 1); while SDUSplitString(path, pathFirst, pathRest, PATH_SEPARATOR) do begin pathComponents.Add(pathFirst); path := pathRest; end; // Reinsert the leading "/" we previously took off pathComponents.Insert(0, PATH_SEPARATOR); end; // Handle any "." and ".." in path if allOK then begin stlTmp := TStringList.Create(); try for i:=0 to (pathComponents.Count - 1) do begin if (pathComponents[i] = DIR_CURRENT_DIR) then begin // Do nothing - skip end else if (pathComponents[i] = DIR_PARENT_DIR) then begin if (stlTmp.Count > 0) then begin stlTmp.Delete(stlTmp.count-1); end else begin allOK := FALSE; break; end; end else begin stlTmp.Add(pathComponents[i]); end; end; pathComponents.Assign(stlTmp); finally stlTmp.Free(); end; end; // Seek node... if allOK then begin // Root node is always the root node lastNode := self.Items.GetFirstNode(); for i:=1 to (pathComponents.Count - 1) do begin // Create nodes as we go, if required... if NodeHasPlaceHolderNode(lastNode) then begin CreateChildNodes(lastNode); end; // Check all of the current node's children to try and find the next // path element pathPartNode := nil; for j:=0 to (lastNode.Count - 1) do begin checkNode := lastNode.Item[j]; checkNodeRec := checkNode.Data; // (We're case insensitive (and below)) currNodeName := checkNodeRec.Name; if not(Filesystem.CaseSensitive) then begin currNodeName := uppercase(currNodeName); end; if (currNodeName = pathComponents[i]) then begin pathPartNode := checkNode; break; end; end; if (pathPartNode = nil) then begin allOK := FALSE; break; end; lastNode := pathPartNode; end; retval := lastNode; end; // If there was a problem, make sure we return NIL if ( not(farAsPossible) and not(allOK) ) then begin retval := nil; end; finally pathComponents.Free(); end; Result := retval; end; constructor TSDCustomFilesystemTreeView.Create(AOwner: TComponent); begin inherited; FShowHiddenItems := FALSE; FCursorStack := TList.Create(); // Prevent user from changing node captions self.Readonly := TRUE; // Leave visual indicator of selected node when control not focussed self.HideSelection := FALSE; // No line to the root node self.ShowRoot := FALSE; FNodeImages:= TImageList.Create(nil); FNodeImages.BlendColor := self.Color; FNodeImages.BkColor := self.Color; // Get icon file and icon index within icon file FNodeImgIdxClosed := SDULoadDLLIconToList( DLL_SHELL32, TRUE, DLL_SHELL32_FOLDER_CLOSED, FNodeImages ); FNodeImgIdxOpen := SDULoadDLLIconToList( DLL_SHELL32, TRUE, DLL_SHELL32_FOLDER_OPEN, FNodeImages ); FNodeImgIdxDrive := SDULoadDLLIconToList( DLL_SHELL32, TRUE, DLL_SHELL32_HDD, FNodeImages ); end; destructor TSDCustomFilesystemTreeView.Destroy(); begin FNodeImages.Free(); FCursorStack.Free(); inherited; end; procedure TSDCustomFilesystemTreeView.Initialize(); begin self.Images := FNodeImages; DeleteAllNodes(); AddRootNode(); end; procedure TSDCustomFilesystemTreeView.SetFilesystem(newFilesystem: TSDCustomFilesystem); begin FFilesystem := newFilesystem; if (Filesystem = nil) then begin DeleteAllNodes(); end; end; procedure TSDCustomFilesystemTreeView.AddRootNode(); var newNode: TTreeNode; newNodeRec: PNodeRec; begin // Create initial root node newNodeRec := new(PNodeRec); newNodeRec.PlaceHolder := FALSE; newNodeRec.Name := PATH_SEPARATOR; newNodeRec.ContentsLoaded := FALSE; newNodeRec.Contents := nil; newNode:= self.Items.AddFirst(nil, newNodeRec.Name); newNode.Data := newNodeRec; newNode.ImageIndex := FNodeImgIdxDrive; newNode.SelectedIndex := FNodeImgIdxDrive; AddPlaceHolderNode(newNode); newNode.Selected := TRUE; newNode.Focused := TRUE; end; procedure TSDCustomFilesystemTreeView.AddPlaceHolderNode(Node: TTreeNode); var newNode: TTreeNode; newNodeRec: PNodeRec; begin newNodeRec := new(PNodeRec); newNodeRec.PlaceHolder := TRUE; newNodeRec.Name := PLACEHOLDER; newNodeRec.ContentsLoaded := FALSE; newNode := self.Items.AddChild(Node, newNodeRec.Name); newNode.Data := newNodeRec; end; // Delete all place holder nodes from the specified node procedure TSDCustomFilesystemTreeView.DeletePlaceHolderNodesFrom(Node: TTreeNode); var currNode: TTreeNode; currNodeRec: PNodeRec; i: integer; begin for i:=(Node.Count - 1) downto 0 do begin currNode := Node.Item[i]; currNodeRec := currNode.Data; if currNodeRec.PlaceHolder then begin Node.Item[i].Delete(); end; end; end; function TSDCustomFilesystemTreeView.NodeHasPlaceHolderNode(Node: TTreeNode): boolean; var currNode: TTreeNode; currNodeRec: PNodeRec; i: integer; retval: boolean; begin retval := FALSE; for i:=(Node.Count - 1) downto 0 do begin currNode := Node.Item[i]; currNodeRec := currNode.Data; if currNodeRec.PlaceHolder then begin retval := TRUE; break end; end; Result := retval; end; procedure TSDCustomFilesystemTreeView.DeleteAllNodes(); begin self.Items.Clear(); end; procedure TSDCustomFilesystemTreeView.CreateChildNodes(Node: TTreeNode); var newNode: TTreeNode; nodeRec: PNodeRec; newNodeRec: PNodeRec; i: integer; nodePath: string; currContent: TSDDirItem; showItemInTree: boolean; begin nodeRec := Node.Data; LoadContents(Node); if nodeRec.ContentsLoaded then begin DeletePlaceHolderNodesFrom(Node); nodePath := PathToNode(Node); for i:=0 to (nodeRec.Contents.Count - 1) do begin currContent := nodeRec.Contents[i]; showItemInTree := ( currContent.IsDirectory and (currContent.Filename <> DIR_CURRENT_DIR) and (currContent.Filename <> DIR_PARENT_DIR) ); // Skip hidden items, unless this control is set to show them if ( currContent.IsHidden and not(ShowHiddenItems) ) then begin showItemInTree := FALSE; end; if showItemInTree then begin newNodeRec := new(PNodeRec); newNodeRec.PlaceHolder := FALSE; newNodeRec.Name := currContent.Filename; newNodeRec.ContentsLoaded := FALSE; newNodeRec.Contents := nil; newNode:= self.Items.AddChild(Node, newNodeRec.Name); newNode.Data := newNodeRec; newNode.ImageIndex := FNodeImgIdxClosed; newNode.SelectedIndex:= FNodeImgIdxOpen; AddPlaceHolderNode(newNode); end; end; // Get the nodes just added into alphabetical order Node.AlphaSort(FALSE); end; end; procedure TSDCustomFilesystemTreeView.ThreadLoadedContents(thread: TSDLoadDirThread); var node: TTreeNode; nodeRec: PNodeRec; begin node := GetNodeForPath(thread.LoadedPath, FALSE); if (node <> nil) then begin nodeRec := Node.Data; if not(nodeRec.ContentsLoaded) then begin nodeRec.Contents := TSDDirItemList.Create(); nodeRec.Contents.Assign(thread.LoadedContents); nodeRec.ContentsLoaded := TRUE; if NodeHasPlaceHolderNode(node) then begin CreateChildNodes(node); end; end; end; end; procedure TSDCustomFilesystemTreeView.LoadContents(Node: TTreeNode); var nodeRec: PNodeRec; tmpDirItemList: TSDDirItemList; begin noderec := Node.Data; if not(nodeRec.ContentsLoaded) then begin tmpDirItemList := TSDDirItemList.Create(); try nodeRec.ContentsLoaded := FFileSystem.LoadContentsFromDisk(PathToNode(Node), tmpDirItemList); if nodeRec.ContentsLoaded then begin nodeRec.Contents := tmpDirItemList; end else begin // If there was a problem, free off dir list object created tmpDirItemList.Free(); end; except on E:Exception do begin tmpDirItemList.Free(); end; end; end; end; function TSDCustomFilesystemTreeView.PathToNode(Node: TTreeNode): string; var retval: string; currNode: TTreeNode; currNodeRec: PNodeRec; begin retval := ''; currNode := Node; while (currNode <> nil) do begin currNodeRec := currNode.Data; if (retval = '') then begin retval := currNodeRec.Name; end else begin if (currNode.Parent = nil) then begin retval := PATH_SEPARATOR + retval; end else begin retval := currNodeRec.Name + PATH_SEPARATOR + retval; end; end; currNode := currNode.Parent; end; Result := retval; end; procedure TSDCustomFilesystemTreeView.AddExpandedLeafNodes(Node: TTreeNode; expandedLeafNodes: TStringList); var i: integer; preChildCnt: integer; begin // Add all expanded leaf nodes to expandedLeafNodes (place holder nodes not // considered leaf nodes) if Node.Expanded then begin preChildCnt := expandedLeafNodes.Count; for i:=0 to (Node.Count - 1) do begin AddExpandedLeafNodes(Node.Item[i], expandedLeafNodes); end; // If none of the child nodes where expanded, add this node on if (preChildCnt = expandedLeafNodes.Count) then begin expandedLeafNodes.Add(PathToNode(Node)); end; end; end; function TSDCustomFilesystemTreeView.CanExpand(Node: TTreeNode): boolean; var i: integer; currNode: TTreeNode; currThread: TSDLoadDirThread; retval: boolean; begin retval := inherited CanExpand(Node); if retval then begin BeginUpdate(); try if NodeHasPlaceHolderNode(Node) then begin CreateChildNodes(Node); end; retval := Node.HasChildren; currThread := TSDLoadDirThread.Create(TRUE); for i:=0 to (Node.Count - 1) do begin currNode := Node.Item[i]; currThread.AddPath(PathToNode(currNode)); end; currThread.Filesystem := self.Filesystem; currThread.Callback := ThreadLoadedContents; currThread.FreeOnTerminate := TRUE; // Put the priority of the thread down; the application gets sluggish // otherwise currThread.Priority := tpLower; currThread.Resume(); finally EndUpdate(); end; end; Result := retval; end; procedure TSDCustomFilesystemTreeView.Delete(Node: TTreeNode); var nodeRec: PNodeRec; begin inherited; nodeRec := Node.Data; if not(nodeRec.PlaceHolder) then begin if nodeRec.ContentsLoaded then begin nodeRec.ContentsLoaded := FALSE; end; if (nodeRec.Contents <> nil) then begin nodeRec.Contents.Free(); nodeRec.Contents := nil; end; end; Dispose(nodeRec); end; procedure TSDCustomFilesystemTreeView.Change(Node: TTreeNode); begin LoadContents(Node); if NodeHasPlaceHolderNode(Node) then begin CreateChildNodes(Node); end; if Assigned(FFilesystemListView) then begin FFilesystemListView.SetPath(PathToNode(Node)); end; inherited; end; procedure TSDCustomFilesystemTreeView.RefreshNodes(); var expandedLeafNodes: TStringList; i: integer; currNode: TTreeNode; lastPath: string; lastExpanded: boolean; begin BeginUpdate(); try lastPath := PathToNode(self.Selected); lastExpanded := FALSE; if (self.Selected <> nil) then begin lastExpanded := self.Selected.Expanded; end; expandedLeafNodes:= TStringList.Create(); try // Note: We only ever process the one root node AddExpandedLeafNodes(self.Items.GetFirstNode(), expandedLeafNodes); DeleteAllNodes(); AddRootNode(); for i:=0 to (expandedLeafNodes.count - 1) do begin currNode := GoToPath(expandedLeafNodes[i], TRUE); currNode.Expanded := TRUE; end; finally expandedLeafNodes.Free(); end; currNode := GoToPath(lastPath, TRUE); if (lastPath = PathToNode(currNode)) then begin currNode.Expanded := lastExpanded; end else begin currNode.Expanded := TRUE; end; finally EndUpdate(); end; end; procedure TSDCustomFilesystemListView.SetFilesystem(newFilesystem: TSDCustomFilesystem); begin FFilesystem := newFilesystem; if (Filesystem = nil) then begin self.Clear(); end; end; function TSDCustomFilesystemListView.GetColumn(colType: TFilesystemListViewColumn): TListColumn; var retval: TListColumn; begin retval := nil; if (FColumnIDs[colType] <> COL_ID_NONE) then begin retval := self.GetColumnByID(FColumnIDs[colType]); end; Result := retval; end; procedure TSDCustomFilesystemListView.UpdateInternalColOrder(); begin FInternalColOrder := GetLayoutColOrder(FInternalLayout, FALSE); end; procedure TSDCustomFilesystemListView.RecreateAllPosibleColHeaders(); var currColType: TFilesystemListViewColumn; newCol: TListColumn; begin // Clear existing columns... self.Columns.Clear(); // Create list column for all possible columns for currColType:=low(currColType) to high(currColType) do begin newCol := self.AddCol(FilesystemListViewColumnTitle(currColType)); newCol.Alignment := FilesystemListViewColumnAlignment[currColType]; FColumnIDs[currColType] := newCol.ID; end; end; procedure TSDCustomFilesystemListView.DefaultInternalLayout(); begin FInternalLayout := FILESYSTEMLISTVIEWCOLUMN_DEFAULTS; UpdateInternalColOrder(); end; function TSDCustomFilesystemListView.GetLayout(): string; var retval: string; currColType: TFilesystemListViewColumn; stlColLayout: TStringList; colTypeName: string; colLayout: TFilesystemListViewColumn_Layout; begin retval := ''; SyncInternalLayoutToDisplayed(); stlColLayout:= TStringList.Create(); try stlColLayout.Values['VIEWSTYLE'] := inttostr(ord(self.ViewStyle)); for currColType:=low(currColType) to high(currColType) do begin colTypeName := FilesystemListViewColumnIntName[currColType]; colLayout := FInternalLayout[currColType]; stlColLayout.Values[colTypeName+'_VISIBLE'] := SDUBoolToStr(colLayout.Visible); stlColLayout.Values[colTypeName+'_WIDTH'] := inttostr(colLayout.Width); stlColLayout.Values[colTypeName+'_POSITION'] := inttostr(colLayout.Position); end; stlColLayout.Delimiter := ','; stlColLayout.QuoteChar := '"'; retval := stlColLayout.DelimitedText; finally stlColLayout.Free(); end; Result := retval; end; procedure TSDCustomFilesystemListView.SetLayout(newLayout: string); function GetStlValueOrDefault(stl: TStringList; itemName: string; defaultValue: string): string; var idx: integer; retval: string; begin idx := stl.IndexOfName(itemName); retval := defaultValue; if (idx >= 0) then begin retval := stl.Values[itemName]; end; Result := retval; end; var stlColLayout: TStringList; currColType: TFilesystemListViewColumn; colTypeName: string; colLayout: TFilesystemListViewColumn_Layout; begin // Set column defaults in case they're not mentioned in the layout provided DefaultInternalLayout(); stlColLayout:= TStringList.Create(); try stlColLayout.Delimiter := ','; stlColLayout.QuoteChar := '"'; stlColLayout.DelimitedText := newLayout; self.ViewStyle := TViewStyle(StrToInt(GetStlValueOrDefault( stlColLayout, 'VIEWSTYLE', inttostr(ord(FILESYSTEMLISTVIEWSTYLE_DEFAULT)) ))); for currColType:=low(currColType) to high(currColType) do begin // Get pre-set defaults colLayout := FInternalLayout[currColType]; colTypeName := FilesystemListViewColumnIntName[currColType]; colLayout.Visible := SDUStrToBool(GetStlValueOrDefault( stlColLayout, colTypeName+'_VISIBLE', SDUBoolToStr(colLayout.Visible) )); colLayout.Width := StrToInt(GetStlValueOrDefault( stlColLayout, colTypeName+'_WIDTH', inttostr(colLayout.Width) )); colLayout.Position := StrToInt(GetStlValueOrDefault( stlColLayout, colTypeName+'_POSITION', inttostr(colLayout.Position) )); FInternalLayout[currColType] := colLayout; end; finally stlColLayout.Free(); end; UpdateInternalColOrder(); RepopulateDisplay(); end; procedure TSDCustomFilesystemListView.SyncInternalLayoutToDisplayed(); var retval: string; currColType: TFilesystemListViewColumn; listCol: TListColumn; colTypeName: string; colLayout: TFilesystemListViewColumn_Layout; begin retval := ''; for currColType:=low(currColType) to high(currColType) do begin colTypeName := FilesystemListViewColumnIntName[currColType]; listCol := GetColumn(currColType); if (listCol = nil) then begin colLayout.Visible := FALSE; colLayout.Width := FILESYSTEMLISTVIEWCOLUMN_DEFAULTS[currColType].Width; colLayout.Position := FILESYSTEMLISTVIEWCOLUMN_DEFAULTS[currColType].Position; end else begin colLayout.Visible := TRUE; colLayout.Position := listCol.Index; colLayout.Width := RealColWidth[listCol]; end; // MS Windows Explorer doens't allow zero width columns - it sets then back // to the default width if (colLayout.Width <= 0) then begin colLayout.Width := FILESYSTEMLISTVIEWCOLUMN_DEFAULTS[currColType].Width; end; FInternalLayout[currColType] := colLayout; end; UpdateInternalColOrder(); end; // Note: This is called automatically as part of RepopulateDisplay(...) procedure TSDCustomFilesystemListView.SyncDisplayedToInternalLayout(); var currColType: TFilesystemListViewColumn; listCol: TListColumn; currColLayout: TFilesystemListViewColumn_Layout; i: integer; totalWidthUsed: integer; autoSizeCol: TListColumn; newColIdx: integer; begin UpdateInternalColOrder(); // Delete any columns which aren't visible for currColType:=low(currColType) to high(currColType) do begin if (currColType = flvcFilename) then begin // "Filename" column *always* visible continue; end; currColLayout := FInternalLayout[currColType]; if not(currColLayout.Visible) then begin listCol := GetColumn(currColType); if (listCol <> nil) then begin // Delete all subitems for that column for i:=0 to (self.Items.count - 1) do begin self.Items[i].SubItems.Delete(listCol.Index - 1); end; Self.Columns.Delete(listCol.Index); end; end; end; // Put columns into layout order... newColIdx := 0; for i:=low(FInternalColOrder) to high(FInternalColOrder) do begin currColType := FInternalColOrder[i]; currColLayout := FInternalLayout[currColType]; listCol := GetColumn(currColType); if (listCol <> nil) then begin // Note: DON'T USE currColLayout.Position HERE! // It *might* be wrong if a column was just removed... listCol.Index := newColIdx; inc(newColIdx); end; end; // Resize columns... // NOTE: This is done in a SEPARATE LOOP than the column ordering to prevent // problems with Delphi 2007 and earlier misreporting/setting column // widths totalWidthUsed := 0; autoSizeCol := nil; for i:=low(FInternalColOrder) to high(FInternalColOrder) do begin currColType := FInternalColOrder[i]; currColLayout := FInternalLayout[currColType]; listCol := GetColumn(currColType); if (listCol <> nil) then begin if (currColLayout.Width = AUTOCALC_COL_WIDTH) then begin autoSizeCol := listCol; end else begin RealColWidth[listCol] := currColLayout.Width; totalWidthUsed:= totalWidthUsed + listCol.Width; end; end; end; // If any of the columns were set to autosize, we do that now. if (autoSizeCol <> nil) then begin // -50 so the scrollbar doesn't show when first shown RealColWidth[autoSizeCol] := max( 100, (self.Width - totalWidthUsed - 50) ); end; end; procedure TSDCustomFilesystemListView.BeginUpdate(); begin FCursorStack.Add(Pointer(self.Cursor)); self.Cursor := crHourglass; Perform(WM_SETCURSOR, Handle, HTCLIENT); // Force cursor display to update Items.BeginUpdate(); end; procedure TSDCustomFilesystemListView.EndUpdate(); begin if (FCursorStack.Count > 0) then begin self.Cursor := TCursor(FCursorStack[FCursorStack.Count-1]); Perform(WM_SETCURSOR, Handle, HTCLIENT); // Force cursor display to update FCursorStack.Delete(FCursorStack.Count - 1); end; Items.EndUpdate(); end; procedure TSDCustomFilesystemListView.SetPath(path: string); begin BeginUpdate(); try self.Clear(); // Clear the display; otherwise when self.Clear() is called // in RepopulateDisplay(...) (below), it can fire off the // OnChanged event - at which point the display will be out // of sync with FContents - and if the OnChange event // accesses FContents via DirItem[...] based on self.Count, // it can crash the DirItem[...] caller try if LoadContents(path) then begin FPath := path; end; finally SyncInternalLayoutToDisplayed(); RepopulateDisplay(); end; finally EndUpdate(); end; end; // Update icons for display // Needed as large icon indexes may not match small icon indexes procedure TSDCustomFilesystemListView.SyncIcons(); var i: integer; dirItem: TSDDirItem; iconIdxSmall: integer; iconIdxLarge: integer; begin for i:=0 to (Self.Items.Count - 1) do begin dirItem := GetDirItemByListIdx(i); if dirItem.IsDirectory then begin GetIconsForFile( FILE_TYPE_DIRECTORY, dirItem.IsHidden, iconIdxSmall, iconIdxLarge ); end else begin GetIconsForFile( dirItem.Filename, dirItem.IsHidden, iconIdxSmall, iconIdxLarge ); end; if (self.ViewStyle = vsIcon) then begin self.Items[i].ImageIndex := iconIdxLarge; end else begin self.Items[i].ImageIndex := iconIdxSmall; end; end; end; // Clear and repopulate display with loaded dir content procedure TSDCustomFilesystemListView.RepopulateDisplay(); procedure ValuesToEnumOrder( Filename: string; Size: string; FileType: string; DateModified: string; DateCreated: string; Attributes: string; DateAccessed: string; stlUseColValues: TStringList ); var currColType: TFilesystemListViewColumn; begin stlUseColValues.Clear(); for currColType:=low(currColType) to high(currColType) do begin case currColType of flvcFilename: begin stlUseColValues.Add(Filename); end; flvcSize: begin stlUseColValues.Add(Size); end; flvcFiletype: begin stlUseColValues.Add(FileType); end; flvcTimestampModified: begin stlUseColValues.Add(DateModified); end; flvcTimestampCreated: begin stlUseColValues.Add(DateCreated); end; flvcAttributes: begin stlUseColValues.Add(Attributes); end; flvcTimestampAccessed: begin stlUseColValues.Add(DateAccessed); end; end; end; end; var i: integer; size: string; fileType: string; sizeKB: integer; dateModified: string; dateCreated: string; dateAccessed: string; attributes: string; currItem: TSDDirItem; currItemFAT: TSDDirItem_FAT; stlUseColValues: TStringList; dispFilename: string; knownFiletype: boolean; begin BeginUpdate(); try stlUseColValues := TStringList.Create(); try self.Clear(); RecreateAllPosibleColHeaders(); if (FContents <> nil) then begin for i:=0 to (FContents.Count - 1) do begin currItem := FContents[i]; currItemFAT := nil; if (currItem is TSDDirItem_FAT) then begin currItemFAT := TSDDirItem_FAT(currItem); end; // Skip volume labels, devices, and "." // Also skip "..", unless ShowParentDir is TRUE if not( currItem.IsFile or ( // It's a directory, but not the current directory currItem.IsDirectory and (currItem.Filename <> DIR_CURRENT_DIR) and ( (currItem.Filename <> DIR_PARENT_DIR) or ( (currItem.Filename = DIR_PARENT_DIR) and ShowParentDir ) ) ) ) then begin continue; end; // Skip hidden items, unless this control is set to show them if ( currItem.IsHidden and not(ShowHiddenItems) ) then begin continue; end; size := ''; knownFiletype := FALSE; if currItem.IsDirectory then begin fileType := SDUGetFileType_Description( FILE_TYPE_DIRECTORY, knownFiletype ); end else begin // Always display size in KB sizeKB := (currItem.Size div BYTES_IN_KILOBYTE); // Round up, like MS Explorer does... if ((currItem.Size mod BYTES_IN_KILOBYTE) > 0) then begin sizeKB := sizeKB + 1; end; // Format with thousands separator and KB units size := SDUIntToStrThousands(sizeKB) + ' ' + UNITS_STORAGE_KB; fileType := SDUGetFileType_Description( currItem.Filename, knownFiletype ); end; dateModified := ''; if (currItem.TimestampLastModified.Date <> 0) then begin dateModified := DateTimeToStr(TimeStampToDateTime(currItem.TimestampLastModified)); end; dateCreated := ''; dateAccessed := ''; if (currItem is TSDDirItem_FAT) then begin if (currItemFAT.TimestampCreation.Date <> 0) then begin dateCreated := DateTimeToStr(TimeStampToDateTime(currItemFAT.TimestampCreation)); end; if (currItemFAT.DatestampLastAccess <> 0) then begin dateAccessed := DateToStr(currItemFAT.DatestampLastAccess); end; end; attributes := ''; if currItem.IsReadonly then begin attributes := attributes + _('R'); end; if (currItem is TSDDirItem_FAT) then begin if currItemFAT.IsHidden then begin attributes := attributes + _('H'); end; if currItemFAT.IsSystem then begin attributes := attributes + _('S'); end; if currItemFAT.IsArchive then begin attributes := attributes + _('A'); end; end; dispFilename := currItem.Filename; if ( HideKnownFileExtns and knownFiletype and not(currItem.IsDirectory) ) then begin dispFilename := ChangeFileExt(currItem.Filename, ''); end; // Order the values to the same order they appear in the enum - this // is the order of the column headers after they've all been recreated ValuesToEnumOrder( dispFilename, size, fileType, dateModified, dateCreated, attributes, dateAccessed, stlUseColValues ); Self.AppendRow(stlUseColValues, Pointer(i)); end; SyncIcons(); end; finally stlUseColValues.Free(); end; // Sort the items... // These two methods of sorting don't work?! // self.SortType := stText; // self.AlphaSort(); self.Tag := 1; // Ensure that sort is on filename self.ColClick(GetColumn(flvcFilename)); SyncDisplayedToInternalLayout(); finally EndUpdate(); end; end; procedure TSDCustomFilesystemListView.DblClick(); var contentsIdx: integer; target: string; begin inherited; if (self.SelCount = 1) then begin contentsIdx := integer(self.Selected.Data); target := IncludeTrailingPathDelimiter(Path) + FContents[contentsIdx].Filename; if Assigned(FilesystemTreeView) then begin FilesystemTreeView.GoToPath(target, TRUE); end else begin self.SetPath(target); end; end; end; function TSDCustomFilesystemListView.LoadContents(path: string): boolean; var tmpDirItemList: TSDDirItemList; begin Result := FALSE; tmpDirItemList := TSDDirItemList.Create(); try Result := FFileSystem.LoadContentsFromDisk(path, tmpDirItemList); if Result then begin if (FContents <> nil) then begin FContents.Free(); end; FContents := tmpDirItemList; end else begin // If there was a problem, free off dir list object created tmpDirItemList.Free(); end; except on E:Exception do tmpDirItemList.Free(); end; end; constructor TSDCustomFilesystemListView.Create(AOwner: TComponent); var currColType: TFilesystemListViewColumn; begin FDirectoriesAlwaysSortFirst := FALSE; inherited; // Allow the user to reorder the columns by dragging them around self.FullDrag := TRUE; // Prevent user from changing filenames self.Readonly := TRUE; FCursorStack := TList.Create(); FShowParentDir := FALSE; for currColType:=low(currColType) to high(currColType) do begin FColumnIDs[currColType] := COL_ID_NONE; end; // Default the layout DefaultInternalLayout(); FContents := nil; FFileExtnToIconMap_Large:= TStringList.Create(); FIconsLarge:= TImageList.Create(nil); FIconsLarge.Width := 32; FIconsLarge.Height := 32; FIconsLarge.BkColor := self.Color; FFileExtnToIconMap_Small:= TStringList.Create(); FIconsSmall:= TImageList.Create(nil); FIconsSmall.Width := 16; FIconsSmall.Height := 16; FIconsSmall.BkColor := self.Color; FSuppressPopupMenu := FALSE; FColumnHeaderPopup:= TPopupMenu.Create(self); InitPopup(); end; procedure TSDCustomFilesystemListView.InitPopup(); var newPopupMnuItem: TMenuItem; currColType: TFilesystemListViewColumn; begin for currColType:=low(currColType) to high(currColType) do begin newPopupMnuItem := TMenuItem.Create(FColumnHeaderPopup); FColumnHeaderPopup.Items.Add(newPopupMnuItem); newPopupMnuItem.Caption := FilesystemListViewColumnTitle(currColType); newPopupMnuItem.Tag := ord(currColType); newPopupMnuItem.OnClick := ColumnHeaderPopupClick; end; // Add separator... newPopupMnuItem := TMenuItem.Create(FColumnHeaderPopup); FColumnHeaderPopup.Items.Add(newPopupMnuItem); newPopupMnuItem.Caption := '-'; // Add "More..." menuitem newPopupMnuItem := TMenuItem.Create(FColumnHeaderPopup); FColumnHeaderPopup.Items.Add(newPopupMnuItem); newPopupMnuItem.Caption := _('More...'); newPopupMnuItem.Tag := COLHEADERPOPUPMENUITEM_MORE; newPopupMnuItem.OnClick := ColumnHeaderPopupClick; end; // This is a bit of a kludge - because TControl.WMContextMenu(...) is called // after ColRightClick(...), it pops up any developer configured popupmenu! // i.e. The user sees the column header selection popup menu, then the // controls popup menu! // To get around this, we set FSuppressPopupMenu if our column header context // menu is displayed, then return nil here when TControl.WMContextMenu(...) // calls *this* function to get the developer configured popup menu function TSDCustomFilesystemListView.GetPopupMenu(): TPopupMenu; var retval: TPopupMenu; begin retval := inherited GetPopupMenu(); if FSuppressPopupMenu then begin retval := nil; FSuppressPopupMenu:= FALSE; end; Result := retval; end; procedure TSDCustomFilesystemListView.ChooseColumns; begin { TODO 1 -otdk -cfix : implement } end; procedure TSDCustomFilesystemListView.ColRightClick(Column: TListColumn; Point: TPoint); var i: integer; currColType: TFilesystemListViewColumn; currMenuItem: TMenuItem; begin if Assigned(OnColumnRightClick) then begin inherited; end else begin SyncInternalLayoutToDisplayed(); // Put checkmarks against all visible columns on the popup menu, clear // checkmarks against non-visible columns for currColType:=low(currColType) to high(currColType) do begin for i:=0 to (FColumnHeaderPopup.Items.count - 1) do begin currMenuItem := FColumnHeaderPopup.Items[i]; if (currColType = flvcFilename) then begin // "Filename" column must always be visible currMenuItem.Enabled := FALSE; end; if (TFilesystemListViewColumn(currMenuItem.Tag) = currColType) then begin currMenuItem.Checked := FInternalLayout[currColType].Visible; break; end; end; end; Point := self.ClientToScreen(Point); FColumnHeaderPopup.Popup(Point.X, Point.Y); FSuppressPopupMenu := TRUE; end; end; procedure TSDCustomFilesystemListView.ColumnHeaderPopupClick(Sender: TObject); var clickedColType: TFilesystemListViewColumn; mnuItemClicked: TMenuItem; colsChanged: boolean; dlg: TSDFilesystemListView_ColDetails; begin colsChanged := FALSE; SyncInternalLayoutToDisplayed(); mnuItemClicked := TMenuItem(Sender); if (mnuItemClicked.Tag = COLHEADERPOPUPMENUITEM_MORE) then begin // "More..." menuitem clicked dlg:= TSDFilesystemListView_ColDetails.Create(nil); try dlg.Layout := FInternalLayout; dlg.ShowModal(); if (dlg.ModalResult = mrOK) then begin FInternalLayout := dlg.Layout; colsChanged := TRUE; end; finally dlg.Free(); end; end else begin clickedColType := TFilesystemListViewColumn(mnuItemClicked.Tag); FInternalLayout[clickedColType].Visible := not(mnuItemClicked.Checked); colsChanged := TRUE; end; // Repopulate the display - if a column was added, it's data won't be a // subitem if colsChanged then begin RepopulateDisplay(); end; end; destructor TSDCustomFilesystemListView.Destroy(); begin FColumnHeaderPopup.Free(); FFileExtnToIconMap_Large.Free(); FIconsLarge.Free(); FFileExtnToIconMap_Small.Free(); FIconsSmall.Free(); FCursorStack.Free(); Freeandnil(FContents); inherited; end; procedure TSDCustomFilesystemListView.Initialize(); begin self.Items.Clear(); self.RowSelect := TRUE; Self.LargeImages := FIconsLarge; Self.SmallImages := FIconsSmall; RecreateAllPosibleColHeaders(); SyncDisplayedToInternalLayout(); end; procedure TSDCustomFilesystemListView._ColumnSortCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); var sortDirection: TColumnSortDirection; sortCol: TListColumn; dirItem1: TSDDirItem; dirItem2: TSDDirItem; begin Compare := 0; sortCol := self.GetColumnByID(FColumnToSort); sortDirection := TColumnSortDirection(sortCol.Tag); dirItem1:= FContents[integer(Item1.Data)]; dirItem2:= FContents[integer(Item2.Data)]; // Parent dir comes first, regardless of anything else... if dirItem1.Filename = DIR_PARENT_DIR then begin Compare := -1; end else if dirItem2.Filename = DIR_PARENT_DIR then begin Compare := 1; end; // Directories come before files... if (Compare = 0) then begin if (dirItem1.IsFile and dirItem2.IsDirectory) then begin if DirectoriesAlwaysSortFirst then begin Compare := 1; end else begin if (sortDirection = csdAscending) then begin Compare := 1; end else begin Compare := -1; end; end; end else if (dirItem1.IsDirectory and dirItem2.IsFile) then begin if DirectoriesAlwaysSortFirst then begin Compare := -1; end else begin if (sortDirection = csdAscending) then begin Compare := -1; end else begin Compare := 1; end; end; end end; // If the two items haven't got a mandatory sort order, fallback to the // default sort order... if (Compare = 0) then begin inherited; end; end; procedure TSDCustomFilesystemListView.GetIconsForFile( filename: string; subduedIcon: boolean; out smallIconIdx: integer; out largeIconIdx: integer ); var DLLFilename: string; DLLIconIdx: integer; ucExtn: string; begin // "Special" icons if (filename = FILE_TYPE_DIRECTORY) then begin // Lowercase intentional; this way it won't get confused with the // uppercase (*real*) extensions added to the TStringList later ucExtn := lowercase(filename); end else begin ucExtn := uppercase(ExtractFileExt(filename)); end; if subduedIcon then begin ucExtn := '***SUBDUED***'+ucExtn; end; smallIconIdx := FFileExtnToIconMap_Small.IndexOf(ucExtn); largeIconIdx := FFileExtnToIconMap_Large.IndexOf(ucExtn); // If neither icon already cached, get new icons if ( (smallIconIdx < 0) and (largeIconIdx < 0) ) then begin // Get icon file and icon index within icon file SDUGetFileType_Icon(filename, DLLFilename, DLLIconIdx); if (DLLFilename = '') then begin DLLFilename := DLL_SHELL32; DLLIconIdx := DLL_SHELL32_DEFAULT_FILE; end; if (SDULoadDLLIconToList(DLLFilename, TRUE, DLLIconIdx, FIconsSmall) >= 0) then begin FFileExtnToIconMap_Small.Add(ucExtn); end else begin if (SDULoadDLLIconToList(DLL_SHELL32, TRUE, DLL_SHELL32_DEFAULT_FILE, FIconsSmall) >= 0) then begin FFileExtnToIconMap_Small.Add(ucExtn); end; end; if (SDULoadDLLIconToList(DLLFilename, FALSE, DLLIconIdx, FIconsLarge) >= 0) then begin FFileExtnToIconMap_Large.Add(ucExtn); end else begin if (SDULoadDLLIconToList(DLL_SHELL32, FALSE, DLL_SHELL32_DEFAULT_FILE, FIconsLarge) >= 0) then begin FFileExtnToIconMap_Large.Add(ucExtn); end; end; smallIconIdx := FFileExtnToIconMap_Small.IndexOf(ucExtn); largeIconIdx := FFileExtnToIconMap_Large.IndexOf(ucExtn); if subduedIcon then begin if (smallIconIdx >= 0) then begin MakeIconSubdued(FIconsSmall, smallIconIdx, FALSE); end; if (largeIconIdx >= 0) then begin MakeIconSubdued(FIconsLarge, largeIconIdx, TRUE); end; end; end; end; procedure TSDCustomFilesystemListView.MakeIconSubdued(imgList: TImageList; idx: integer; treatAs32x32Icon: boolean); var srcIcon: TIcon; destIcon: TIcon; begin srcIcon:= TIcon.Create(); destIcon:= TIcon.Create(); try imgList.GetIcon(idx, srcIcon); SDUMakeIconGhosted(srcIcon, destIcon, treatAs32x32Icon); imgList.ReplaceIcon(idx, destIcon); finally destIcon.Free(); srcIcon.Free(); end; end; function TSDCustomFilesystemListView.GetDirItemByListIdx(idx: integer): TSDDirItem; begin Result := FContents[integer(self.Items[idx].Data)]; end; function TSDCustomFilesystemListView.GetDisplayName(item: TSDDirItem): string; var retval: string; knownFiletype: boolean; begin retval := ''; if (item <> nil) then begin retval := item.Filename; if ( HideKnownFileExtns and not(item.IsDirectory) ) then begin SDUGetFileType_Description( item.Filename, knownFiletype ); if knownFiletype then begin retval := ChangeFileExt(item.Filename, ''); end; end; end; Result := retval; end; function TSDCustomFilesystemListView.GetDisplayedNameByListIdx(idx: integer): string; var item: TSDDirItem; retval: string; begin item := DirItem[idx]; if (item <> nil) then begin retval := GetDisplayName(item); end; Result := retval; end; function TSDCustomFilesystemListView.GetDirItemSelected(): TSDDirItem; var retval: TSDDirItem; idx: integer; begin retval := nil; idx := self.SelectedIdx; if (idx >= 0) then begin retval := GetDirItemByListIdx(idx); end; Result := retval; end; procedure TSDLoadDirThread.AfterConstruction(); begin inherited; Paths := TStringList.Create(); LoadedContents := TSDDirItemList.Create(); end; destructor TSDLoadDirThread.Destroy(); begin LoadedContents.Free(); Paths.Free(); inherited; end; procedure TSDLoadDirThread.Execute(); var i: integer; begin for i:=0 to (Paths.count - 1) do begin LoadedContents.Clear(); if Filesystem.LoadContentsFromDisk(Paths[i], LoadedContents) then begin LoadedPath := Paths[i]; Synchronize(SyncMethod); end; end; end; procedure TSDLoadDirThread.SyncMethod(); begin Callback(self); end; procedure TSDLoadDirThread.AddPath(pathToLoad: string); begin Paths.Add(pathToLoad); end; END.
{============================================================================== Copyright (C) combit GmbH ------------------------------------------------------------------------------- File : picfm.pas, picfm.dfm, picture.dpr Module : picture box sample Descr. : D: Dieses Beispiel demonstriert die Übergabe von Grafikobjekten an List & Label. US: This example demonstrates how to define graphic-objects to List & Label. ===============================================================================} unit picfm; interface uses Windows, Messages, SysUtils, Classes, clipbrd, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, OleCtrls, Menus, L28, cmbtll28, Registry; type TPictureForm = class(TForm) Image1: TImage; Label2: TLabel; EMFButton: TButton; Label4: TLabel; BufferImage: TImage; Label3: TLabel; Bevel1: TBevel; Image2: TImage; Label6: TLabel; BitmapButton: TButton; Label5: TLabel; Button1: TButton; LL: TL28_; procedure PrintLabel; procedure FormCreate(Sender: TObject); procedure DesignButtonClick(Sender: TObject); procedure EMFButtonClick(Sender: TObject); procedure BitmapButtonClick(Sender: TObject); procedure LLDefineVariables(Sender: TObject; UserData: Integer; IsDesignMode: Boolean; var Percentage: Integer; var IsLastRecord: Boolean; var EventResult: Integer); private workingPath: String; WMFFlag: boolean; { Private declarations } public { Public declarations } end; var PictureForm: TPictureForm; implementation {$R *.DFM} procedure TPictureForm.FormCreate(Sender: TObject); var registry: TRegistry; var regKeyPath: String; var tmp: String; begin // D: Datenbankpfad auslesen // US: Read database path registry := TRegistry.Create(); registry.RootKey := HKEY_CURRENT_USER; regKeyPath := 'Software\combit\cmbtll\'; if registry.KeyExists(regKeyPath) then begin if registry.OpenKeyReadOnly(regKeyPath) then begin tmp := registry.ReadString('LL' + IntToStr(LL.LlGetVersion(LL_VERSION_MAJOR)) + 'SampleDir'); if (tmp[Length(tmp)] = '\') then begin workingPath := tmp + '\Delphi\BDE (Legacy)\Samples\'; end else workingPath := tmp + '\Delphi\BDE (Legacy)\Samples\'; registry.CloseKey(); end; end; registry.Free(); Image1.picture.LoadFromFile(workingPath + 'sunny.wmf'); Image2.picture.LoadFromFile(workingPath + 'fruchten.bmp'); // D: Verzeichnis setzen // US: Set current dir workingPath := GetCurrentDir() +'\'; end; procedure TPictureForm.EMFButtonClick(Sender: TObject); begin {D: WMF in Puffer übertragen} {US: Transfer WMF to buffer } BufferImage.Picture.Metafile:=Image1.Picture.Metafile; WMFFlag:=true; {D: Etikettendruck aufrufen; Projekt picture.lbl} {US: Start label printing; project picture.lbl } PrintLabel; end; procedure TPictureForm.BitmapButtonClick(Sender: TObject); begin {D: Bitmap in Puffer übertragen} {US: Transfer Bitmap to buffer } BufferImage.Picture.Bitmap:=Image2.Picture.Bitmap; WMFFlag:=false; {D: Etikettendruck aufrufen; Projekt picture.lbl} {US: Start label printing; project picture.lbl } PrintLabel; end; procedure TPictureForm.DesignButtonClick(Sender: TObject); begin {D: Etikettendesigner aufrufen; Projekt: picture.lbl } {US: Start label designer; project: picture.lbl } LL.Design(0,handle,'Design Labels', LL_PROJECT_LABEL, workingPath + 'picture.lbl',true, false); end; procedure TPictureForm.PrintLabel; begin LL.Print(0,LL_PROJECT_LABEL, workingPath + 'picture.lbl',true,LL_PRINT_PREVIEW, LL_BOXTYPE_STDWAIT,handle,'Print label to preview', true, ''); end; procedure TPictureForm.LLDefineVariables(Sender: TObject; UserData: Integer; IsDesignMode: Boolean; var Percentage: Integer; var IsLastRecord: Boolean; var EventResult: Integer); {D: Wird vom Programm aufgerufen, wenn Variablen definiert werden} {US: Is called by the program to define variables } begin if WMFFlag=false then LL.LlDefineVariableExtHandle('Picture', BufferImage.picture.bitmap.handle, LL_DRAWING_HBITMAP) else LL.LlDefineVariableExtHandle('Picture', BufferImage.picture.metafile.handle, LL_DRAWING_HEMETA); If not IsDesignMode then begin IsLastRecord:=true; Percentage:=100; end; end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PaxRunner.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PaxRunner; interface uses TypInfo, SysUtils, Classes, PaxInfos, PAXCOMP_CONSTANTS, PAXCOMP_SYS, PAXCOMP_MAP, PAXCOMP_RTI, PAXCOMP_BASERUNNER, PaxInvoke; const _rmRUN = 0; _rmTRACE_INTO = 1; _rmSTEP_OVER = 2; _rmRUN_TO_CURSOR = 3; _rmNEXT_SOURCE_LINE = 4; type TPaxRunner = class; TPaxPauseNotifyEvent = procedure (Sender: TPaxRunner; const ModuleName: String; SourceLineNumber: Integer) of object; TPaxHaltNotifyEvent = procedure (Sender: TPaxRunner; ExitCode: Integer; const ModuleName: String; SourceLineNumber: Integer) of object; TPaxErrNotifyEvent = procedure (Sender: TPaxRunner; E: Exception; const ModuleName: String; SourceLineNumber: Integer) of object; TPaxLoadProcEvent = procedure (Sender: TPaxRunner; const ProcName, DllName: String; var Address: Pointer) of object; TPaxObjectNotifyEvent = procedure (Sender: TPaxRunner; Instance: TObject) of object; TPaxIdNotifyEvent = procedure (Sender: TPaxRunner; Id: Integer) of object; TPaxClassNotifyEvent = procedure (Sender: TPaxRunner; C: TClass) of object; TPaxMapTableNamespaceEvent = procedure (Sender: TPaxRunner; const FullName: String; Global: Boolean) of object; TPaxMapTableVarAddressEvent = procedure (Sender: TPaxRunner; const FullName: String; Global: Boolean; var Address: Pointer) of object; TPaxMapTableProcAddressEvent = procedure (Sender: TPaxRunner; const FullName: String; OverCount: Byte; Global: Boolean; var Address: Pointer) of object; TPaxMapTableClassRefEvent = procedure (Sender: TPaxRunner; const FullName: String; Global: Boolean; var ClassRef: TClass) of object; TPaxPrintEvent = procedure (Sender: TPaxRunner; const Text: String) of object; TPaxPrintExEvent = procedure (Sender: TPaxRunner; Address: Pointer; Kind: Integer; FT: Integer; L1, L2: Integer) of object; TPaxPrintClassTypeFieldEvent = procedure (Sender: TPaxRunner; const Infos: TPrintClassTypeFieldInfo) of object; TPaxPrintClassTypePropEvent = procedure (Sender: TPaxRunner; const Infos: TPrintClassTypePropInfo) of object; TPaxCustomExceptionHelperEvent = procedure (Sender: TPaxRunner; RaisedException, DestException: Exception) of object; TPaxRunnerLoadPCUEvent = procedure (Sender: TPaxRunner; const UnitName: String; var result: TStream) of object; TPaxStreamEvent = procedure (Sender: TPaxRunner; Stream: TStream) of object; TPaxProcNotifyEvent = procedure (Sender: TPaxRunner; const FullName: String; OverCount: Byte) of object; TPaxVirtualObjectMethodCallEvent = procedure(Sender: TPaxRunner; const ObjectName, PropName: String; const Params: array of Variant; var result: Variant) of object; TPaxVirtualObjectPutPropertyEvent = procedure(Sender: TPaxRunner; const ObjectName, PropName: String; const Params: array of Variant; const value: Variant) of object; TPaxRunner = class(TComponent) private prog: TBaseRunner; function GetSourceLine: Integer; function GetModuleName: String; function GetDataPtr: Pointer; function GetCodePtr: Pointer; function GetDataSize: Integer; function GetCodeSize: Integer; function GetProgramSize: Integer; function GetResultPtr: Pointer; function GetPCUCount: Integer; function GetSearchPathList: TStringList; function GetRunMode: Integer; procedure SetRunMode(value: Integer); function GetConsole: Boolean; procedure SetConsole(value: Boolean); function GetOnPause: TPaxPauseNotifyEvent; procedure SetOnPause(value: TPaxPauseNotifyEvent); function GetOnPauseUpdated: TPaxPauseNotifyEvent; procedure SetOnPauseUpdated(value: TPaxPauseNotifyEvent); function GetOnHalt: TPaxHaltNotifyEvent; procedure SetOnHalt(value: TPaxHaltNotifyEvent); function GetOnException: TPaxErrNotifyEvent; procedure SetOnException(value: TPaxErrNotifyEvent); function GetOnUnhandledException: TPaxErrNotifyEvent; procedure SetOnUnhandledException(value: TPaxErrNotifyEvent); function GetOnLoadProc: TPaxLoadProcEvent; procedure SetOnLoadProc(value: TPaxLoadProcEvent); function GetOnBeforeCallHost: TPaxIdNotifyEvent; procedure SetOnBeforeCallHost(value: TPaxIdNotifyEvent); function GetOnAfterCallHost: TPaxIdNotifyEvent; procedure SetOnAfterCallHost(value: TPaxIdNotifyEvent); function GetOnCreateObject: TPaxObjectNotifyEvent; procedure SetOnCreateObject(value: TPaxObjectNotifyEvent); function GetOnAfterObjectCreation: TPaxObjectNotifyEvent; procedure SetOnAfterObjectCreation(value: TPaxObjectNotifyEvent); function GetOnAfterObjectDestruction: TPaxClassNotifyEvent; procedure SetOnAfterObjectDestruction(value: TPaxClassNotifyEvent); function GetOnDestroyObject: TPaxObjectNotifyEvent; procedure SetOnDestroyObject(value: TPaxObjectNotifyEvent); function GetOnCreateHostObject: TPaxObjectNotifyEvent; procedure SetOnCreateHostObject(value: TPaxObjectNotifyEvent); function GetOnDestroyHostObject: TPaxObjectNotifyEvent; procedure SetOnDestroyHostObject(value: TPaxObjectNotifyEvent); function GetOnMapTableNamespace: TPaxMapTableNamespaceEvent; procedure SetOnMapTableNamespace(value: TPaxMapTableNamespaceEvent); function GetOnMapTableVarAddress: TPaxMapTableVarAddressEvent; procedure SetOnMapTableVarAddress(value: TPaxMapTableVarAddressEvent); function GetOnMapTableProcAddress: TPaxMapTableProcAddressEvent; procedure SetOnMapTableProcAddress(value: TPaxMapTableProcAddressEvent); function GetOnMapTableClassRef: TPaxMapTableClassRefEvent; procedure SetOnMapTableClassRef(value: TPaxMapTableClassRefEvent); function GetOnPrint: TPaxPrintEvent; procedure SetOnPrint(value: TPaxPrintEvent); function GetOnPrintEx: TPaxPrintExEvent; procedure SetOnPrintEx(value: TPaxPrintExEvent); function GetCustomExceptionHelper: TPaxCustomExceptionHelperEvent; procedure SetCustomExceptionHelper(value: TPaxCustomExceptionHelperEvent); function GetOnLoadPCU: TPaxRunnerLoadPCUEvent; procedure SetOnLoadPCU(value: TPaxRunnerLoadPCUEvent); function GetOnStreamSave: TPaxStreamEvent; procedure SetOnStreamSave(value: TPaxStreamEvent); function GetOnStreamLoad: TPaxStreamEvent; procedure SetOnStreamLoad(value: TPaxStreamEvent); function GetOnBeginProcNotify: TPaxProcNotifyEvent; procedure SetOnBeginProcNotify(value: TPaxProcNotifyEvent); function GetOnEndProcNotify: TPaxProcNotifyEvent; procedure SetOnEndProcNotify(value: TPaxProcNotifyEvent); function GetOnVirtualObjectMethodCall: TPaxVirtualObjectMethodCallEvent; procedure SetOnVirtualObjectMethodCall(value: TPaxVirtualObjectMethodCallEvent); function GetOnVirtualObjectPutProperty: TPaxVirtualObjectPutPropertyEvent; procedure SetOnVirtualObjectPutProperty(value: TPaxVirtualObjectPutPropertyEvent); function GetExitCode: Integer; function GetIsEvent: Boolean; procedure SetSuspendFinalization(value: Boolean); function GetSuspendFinalization: Boolean; function GetPausedPCU: TBaseRunner; procedure SetPausedPCU(value: TBaseRunner); function GetPrintClassTypeField: TPaxPrintClassTypeFieldEvent; procedure SetPrintClassTypeField(value: TPaxPrintClassTypeFieldEvent); function GetPrintClassTypeProp: TPaxPrintClassTypePropEvent; procedure SetPrintClassTypeProp(value: TPaxPrintClassTypePropEvent); function GetPCUUnit(I: Integer): TBaseRunner; protected function GetRunnerClass: TBaseRunnerClass; virtual; public EmitProc: TEmitProc; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Run; function GetProgPtr: TBaseRunner; procedure RunInitialization; procedure RunFinalization; procedure Pause; function IsPaused: Boolean; function IsRunning: Boolean; procedure Resume; procedure RegisterClass(C: TClass; const FullName: String = ''); procedure SaveToBuff(var Buff); procedure LoadFromBuff(var Buff); procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); procedure SaveToFile(const Path: String); procedure LoadFromFile(const Path: String); function GetAddress(Handle: Integer): Pointer; overload; function GetAddress(const FullName: String): Pointer; overload; function GetAddressEx(const FullName: String; OverCount: Integer): Pointer; overload; function GetAddressEx(const FullName: String): Pointer; overload; function GetAddress(const FullName: String; OverCount: Integer): Pointer; overload; procedure SetAddress(Handle: Integer; P: Pointer); function SetHostAddress(const FullName: String; Address: Pointer): Boolean; function GetFieldAddress(X: TObject; const FieldName: String): Pointer; function GetCallConv(const FullName: String): Integer; function GetRetSize(const FullName: String): Integer; {$IFDEF PAXARM} {$ELSE} procedure SetEntryPoint(EntryPoint: TPaxInvoke); procedure ResetEntryPoint(EntryPoint: TPaxInvoke); {$ENDIF} procedure CreateGlobalJSObjects; procedure DiscardPause; function GetImageSize: Integer; procedure DiscardDebugMode; procedure AssignEventHandlerRunner(MethodAddress: Pointer; Instance: TObject); function RegisterNamespace(LevelId: Integer; const Name: String): Integer; function RegisterClassType(LevelId: Integer; C: TClass): Integer; procedure RegisterMember(LevelId: Integer; const Name: String; Address: Pointer); procedure MapGlobal; procedure MapLocal; function CreateScriptObject(const ScriptClassName: String; const ParamList: array of const): TObject; procedure DestroyScriptObject(X: TObject); procedure LoadDFMFile(Instance: TObject; const FileName: String); procedure LoadDFMStream(Instance: TObject; S: TStream); function GetTypeInfo(const FullTypeName: String): PTypeInfo; function CallRoutine(const FullName: String; const ParamList: array of OleVariant): OleVariant; function CallMethod(const FullName: String; Instance: TObject; const ParamList: array of OleVariant): OleVariant; function CallClassMethod(const FullName: String; Instance: TClass; const ParamList: array of OleVariant): OleVariant; procedure UnloadPCU(const FullPath: String); procedure LoadPCU(const FileName: String); function GetExceptionRecord: Pointer; function AddBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; function AddTempBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; function RemoveBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; overload; function RemoveBreakpoint(const ModuleName: String): Boolean; overload; function HasBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; function IsExecutableLine(const ModuleName: String; SourceLineNumber: Integer): Boolean; procedure RemoveAllBreakpoints; function GetCurrentFunctionFullName: String; procedure GetCurrentParams(result: TStrings); procedure GetCurrentLocalVars(result: TStrings); function HasPCU(const ModuleName: String): Boolean; property DataPtr: Pointer read GetDataPtr; property CodePtr: Pointer read GetCodePtr; property DataSize: Integer read GetDataSize; property CodeSize: Integer read GetCodeSize; property ProgramSize: Integer read GetProgramSize; property ImageSize: Integer read GetImageSize; property ResultPtr: Pointer read GetResultPtr; property ExitCode: Integer read GetExitCode; property IsEvent: Boolean read GetIsEvent; property SourceLine: Integer read GetSourceLine; property ModuleName: String read GetModuleName; property SuspendFinalization: Boolean read GetSuspendFinalization write SetSuspendFinalization; property RunMode: Integer read GetRunMode write SetRunMode; property PCUCount: Integer read GetPCUCount; property PausedPCU: TBaseRunner read GetPausedPCU write SetPausedPCU; property PCUUnits[I: Integer]: TBaseRunner read GetPCUUnit; property SearchPathList: TStringList read GetSearchPathList; published property Console: boolean read GetConsole write SetConsole; property OnPause: TPaxPauseNotifyEvent read GetOnPause write SetOnPause; property OnPauseUpdated: TPaxPauseNotifyEvent read GetOnPauseUpdated write SetOnPauseUpdated; property OnHalt: TPaxHaltNotifyEvent read GetOnHalt write SetOnHalt; property OnException: TPaxErrNotifyEvent read GetOnException write SetOnException; property OnUnhandledException: TPaxErrNotifyEvent read GetOnUnhandledException write SetOnUnhandledException; property OnLoadProc: TPaxLoadProcEvent read GetOnLoadProc write SetOnLoadProc; property OnCreateObject: TPaxObjectNotifyEvent read GetOnCreateObject write SetOnCreateObject; property OnAfterObjectCreation: TPaxObjectNotifyEvent read GetOnAfterObjectCreation write SetOnAfterObjectCreation; property OnDestroyObject: TPaxObjectNotifyEvent read GetOnDestroyObject write SetOnDestroyObject; property OnCreateHostObject: TPaxObjectNotifyEvent read GetOnCreateHostObject write SetOnCreateHostObject; property OnDestroyHostObject: TPaxObjectNotifyEvent read GetOnDestroyHostObject write SetOnDestroyHostObject; property OnAfterObjectDestruction: TPaxClassNotifyEvent read GetOnAfterObjectDestruction write SetOnAfterObjectDestruction; property OnMapTableNamespace: TPaxMapTableNamespaceEvent read GetOnMapTableNamespace write SetOnMapTableNamespace; property OnMapTableVarAddress: TPaxMapTableVarAddressEvent read GetOnMapTableVarAddress write SetOnMapTableVarAddress; property OnMapTableProcAddress: TPaxMapTableProcAddressEvent read GetOnMapTableProcAddress write SetOnMapTableProcAddress; property OnMapTableClassRef: TPaxMapTableClassRefEvent read GetOnMapTableClassRef write SetOnMapTableClassRef; property OnPrintEvent: TPaxPrintEvent read GetOnPrint write SetOnPrint; property OnPrintEx: TPaxPrintExEvent read GetOnPrintEx write SetOnPrintEx; property OnPrintClassTypeField: TPaxPrintClassTypeFieldEvent read GetPrintClassTypeField write SetPrintClassTypeField; property OnPrintClassTypeProp: TPaxPrintClassTypePropEvent read GetPrintClassTypeProp write SetPrintClassTypeProp; property OnCustomExceptionHelperEvent: TPaxCustomExceptionHelperEvent read GetCustomExceptionHelper write SetCustomExceptionHelper; property OnLoadPCU: TPaxRunnerLoadPCUEvent read GetOnLoadPCU write SetOnLoadPCU; property OnSaveToStream: TPaxStreamEvent read GetOnStreamSave write SetOnStreamSave; property OnLoadFromStream: TPaxStreamEvent read GetOnStreamLoad write SetOnStreamLoad; property OnBeginProc: TPaxProcNotifyEvent read GetOnBeginProcNotify write SetOnBeginProcNotify; property OnEndProc: TPaxProcNotifyEvent read GetOnEndProcNotify write SetOnEndProcNotify; property OnVirtualObjectMethodCall: TPaxVirtualObjectMethodCallEvent read GetOnVirtualObjectMethodCall write SetOnVirtualObjectMethodCall; property OnVirtualObjectPutProperty: TPaxVirtualObjectPutPropertyEvent read GetOnVirtualObjectPutProperty write SetOnVirtualObjectPutProperty; property OnBeforeCallHost: TPaxIdNotifyEvent read GetOnBeforeCallHost write SetOnBeforeCallHost; property OnAfterCallHost: TPaxIdNotifyEvent read GetOnAfterCallHost write SetOnAfterCallHost; end; TPaxRunnerClass = class of TPaxRunner; function ScalarValueToString(Address: Pointer; T: Integer): String; implementation // TPaxRunner ----------------------------------------------------------------- constructor TPaxRunner.Create(AOwner: TComponent); begin inherited; prog := GetRunnerClass.Create; prog.Owner := Self; end; destructor TPaxRunner.Destroy; begin FreeAndNil(prog); inherited; end; function TPaxRunner.GetRunnerClass: TBaseRunnerClass; begin result := nil; end; procedure TPaxRunner.Run; begin prog.RunExtended; end; procedure TPaxRunner.RunInitialization; begin prog.RunInitialization; end; procedure TPaxRunner.RunFinalization; begin prog.RunFinalization; end; procedure TPaxRunner.Pause; begin prog.Pause; end; function TPaxRunner.IsPaused: Boolean; begin result := prog.IsPaused; end; function TPaxRunner.IsRunning: Boolean; begin result := prog.IsRunning; end; procedure TPaxRunner.Resume; begin prog.Run; end; procedure TPaxRunner.DiscardPause; begin prog.DiscardPause; end; procedure TPaxRunner.SaveToBuff(var Buff); begin prog.SaveToBuff(Buff); end; procedure TPaxRunner.LoadFromBuff(var Buff); begin prog.LoadFromBuff(Buff); end; procedure TPaxRunner.SaveToStream(S: TStream); begin prog.SaveToStream(S); end; procedure TPaxRunner.LoadFromStream(S: TStream); begin prog.LoadFromStream(S); end; procedure TPaxRunner.SaveToFile(const Path: String); begin prog.SaveToFile(path); end; procedure TPaxRunner.LoadFromFile(const Path: String); begin prog.LoadFromFile(path); end; function TPaxRunner.GetAddress(Handle: Integer): Pointer; var MR: TMapRec; begin result := prog.GetAddress(Handle); if not NativeAddress(result) then begin MR := prog.ScriptMapTable.LookupByOffset(-Handle); if MR = nil then result := nil else if MR.IsMethod then prog.WrapMethodAddress(result) else if MR.Kind = KindSUB then prog.WrapGlobalAddress(result); end; end; function TPaxRunner.GetAddress(const FullName: String): Pointer; var MR: TMapRec; S, MethName: String; I: Integer; C: TClass; begin result := prog.GetAddress(FullName, MR); if result <> nil then begin if MR.IsMethod then prog.WrapMethodAddress(result) else if MR.Kind = KindSUB then prog.WrapGlobalAddress(result); Exit; end; S := ExtractClassName(FullName); if S = '' then Exit; I := prog.ClassList.IndexOf(S); if I = -1 then Exit; C := prog.ClassList[I].PClass.ClassParent; if C = nil then Exit; MethName := ExtractName(FullName); result := GetAddress(C.ClassName + '.' + MethName); prog.WrapMethodAddress(result); end; function TPaxRunner.GetAddress(const FullName: String; OverCount: Integer): Pointer; var MR: TMapRec; S, MethName: String; I: Integer; C: TClass; begin result := prog.GetAddressEx(FullName, OverCount, MR); if result <> nil then begin if MR.IsMethod then prog.WrapMethodAddress(result) else if MR.Kind = KindSUB then prog.WrapGlobalAddress(result); Exit; end; S := ExtractClassName(FullName); if S = '' then Exit; I := prog.ClassList.IndexOf(S); if I = -1 then Exit; C := prog.ClassList[I].PClass.ClassParent; if C = nil then Exit; MethName := ExtractName(FullName); result := GetAddress(C.ClassName + '.' + MethName, OverCount); prog.WrapMethodAddress(result); end; function TPaxRunner.GetAddressEx(const FullName: String): Pointer; var MR: TMapRec; begin result := prog.GetAddressExtended(FullName, MR); if MR = nil then Exit; if MR.IsMethod then prog.WrapMethodAddress(result) else if MR.Kind = KindSUB then prog.WrapGlobalAddress(result); end; function TPaxRunner.GetAddressEx(const FullName: String; OverCount: Integer): Pointer; var MR: TMapRec; begin result := prog.GetAddressExtended(FullName, OverCount, MR); if MR = nil then Exit; if MR.IsMethod then prog.WrapMethodAddress(result) else if MR.Kind = KindSUB then prog.WrapGlobalAddress(result); end; function TPaxRunner.GetCallConv(const FullName: String): Integer; begin result := prog.GetCallConv(FullName); end; function TPaxRunner.GetRetSize(const FullName: String): Integer; begin result := prog.GetRetSize(FullName); end; procedure TPaxRunner.SetAddress(Handle: Integer; P: Pointer); var Offset: Integer; begin Offset := prog.GetOffset(Handle); if Offset = -1 then Exit; prog.SetAddress(Offset, P); end; function TPaxRunner.SetHostAddress(const FullName: String; Address: Pointer): Boolean; begin result := prog.SetHostAddress(FullName, Address); end; function TPaxRunner.GetResultPtr: Pointer; begin result := prog.ResultPtr; end; function TPaxRunner.GetDataPtr: Pointer; begin result := prog.DataPtr; end; function TPaxRunner.GetCodePtr: Pointer; begin result := prog.CodePtr; end; function TPaxRunner.GetDataSize: Integer; begin result := prog.DataSize; end; function TPaxRunner.GetCodeSize: Integer; begin result := prog.CodeSize; end; function TPaxRunner.GetProgramSize: Integer; begin result := prog.ProgramSize; end; procedure TPaxRunner.RegisterClass(C: TClass; const FullName: String = ''); begin if FullName = '' then prog.RegisterClass(C, C.ClassName) else prog.RegisterClass(C, FullName); end; function TPaxRunner.GetProgPtr: TBaseRunner; begin result := prog; end; function TPaxRunner.GetOnPause: TPaxPauseNotifyEvent; begin result := TPaxPauseNotifyEvent(prog.OnPause); end; procedure TPaxRunner.SetOnPause(value: TPaxPauseNotifyEvent); begin prog.OnPause := TPauseNotifyEvent(value); end; function TPaxRunner.GetOnPauseUpdated: TPaxPauseNotifyEvent; begin result := TPaxPauseNotifyEvent(prog.OnPauseUpdated); end; procedure TPaxRunner.SetOnPauseUpdated(value: TPaxPauseNotifyEvent); begin prog.OnPauseUpdated := TPauseNotifyEvent(value); end; function TPaxRunner.GetOnBeforeCallHost: TPaxIdNotifyEvent; begin result := TPaxIdNotifyEvent(prog.OnBeforeCallHost); end; procedure TPaxRunner.SetOnBeforeCallHost(value: TPaxIdNotifyEvent); begin prog.OnBeforeCallHost := TIdNotifyEvent(value); end; function TPaxRunner.GetOnAfterCallHost: TPaxIdNotifyEvent; begin result := TPaxIdNotifyEvent(prog.OnAfterCallHost); end; procedure TPaxRunner.SetOnAfterCallHost(value: TPaxIdNotifyEvent); begin prog.OnAfterCallHost := TIdNotifyEvent(value); end; function TPaxRunner.GetOnCreateObject: TPaxObjectNotifyEvent; begin result := TPaxObjectNotifyEvent(prog.OnCreateObject); end; procedure TPaxRunner.SetOnCreateObject(value: TPaxObjectNotifyEvent); begin prog.OnCreateObject := TObjectNotifyEvent(value); end; function TPaxRunner.GetOnAfterObjectCreation: TPaxObjectNotifyEvent; begin result := TPaxObjectNotifyEvent(prog.OnAfterObjectCreation); end; procedure TPaxRunner.SetOnAfterObjectCreation(value: TPaxObjectNotifyEvent); begin prog.OnAfterObjectCreation := TObjectNotifyEvent(value); end; function TPaxRunner.GetOnAfterObjectDestruction: TPaxClassNotifyEvent; begin result := TPaxClassNotifyEvent(prog.OnAfterObjectDestruction); end; procedure TPaxRunner.SetOnAfterObjectDestruction(value: TPaxClassNotifyEvent); begin prog.OnAfterObjectDestruction := TClassNotifyEvent(value); end; function TPaxRunner.GetOnDestroyObject: TPaxObjectNotifyEvent; begin result := TPaxObjectNotifyEvent(prog.OnDestroyObject); end; procedure TPaxRunner.SetOnDestroyObject(value: TPaxObjectNotifyEvent); begin prog.OnDestroyObject := TObjectNotifyEvent(value); end; function TPaxRunner.GetOnCreateHostObject: TPaxObjectNotifyEvent; begin result := TPaxObjectNotifyEvent(prog.OnCreateHostObject); end; procedure TPaxRunner.SetOnCreateHostObject(value: TPaxObjectNotifyEvent); begin prog.OnCreateHostObject := TObjectNotifyEvent(value); end; function TPaxRunner.GetOnDestroyHostObject: TPaxObjectNotifyEvent; begin result := TPaxObjectNotifyEvent(prog.OnDestroyHostObject); end; procedure TPaxRunner.SetOnDestroyHostObject(value: TPaxObjectNotifyEvent); begin prog.OnDestroyHostObject := TObjectNotifyEvent(value); end; function TPaxRunner.GetOnHalt: TPaxHaltNotifyEvent; begin result := TPaxHaltNotifyEvent(prog.OnHalt); end; procedure TPaxRunner.SetOnHalt(value: TPaxHaltNotifyEvent); begin prog.OnHalt := THaltNotifyEvent(value); end; function TPaxRunner.GetOnLoadProc: TPaxLoadProcEvent; begin result := TPaxLoadProcEvent(prog.OnLoadProc); end; procedure TPaxRunner.SetOnLoadProc(value: TPaxLoadProcEvent); begin prog.OnLoadProc := TLoadProcEvent(value); end; function TPaxRunner.GetOnPrint: TPaxPrintEvent; begin result := TPaxPrintEvent(prog.OnPrint); end; procedure TPaxRunner.SetOnPrint(value: TPaxPrintEvent); begin prog.OnPrint := TPrintEvent(value); end; function TPaxRunner.GetOnPrintEx: TPaxPrintExEvent; begin result := TPaxPrintExEvent(prog.OnPrintEx); end; procedure TPaxRunner.SetOnPrintEx(value: TPaxPrintExEvent); begin prog.OnPrintEx := TPrintExEvent(value); end; function TPaxRunner.GetCustomExceptionHelper: TPaxCustomExceptionHelperEvent; begin result := TPaxCustomExceptionHelperEvent(prog.OnCustomExceptionHelper); end; procedure TPaxRunner.SetCustomExceptionHelper(value: TPaxCustomExceptionHelperEvent); begin prog.OnCustomExceptionHelper := TCustomExceptionHelperEvent(value); end; function TPaxRunner.GetOnMapTableNamespace: TPaxMapTableNamespaceEvent; begin result := TPaxMapTableNamespaceEvent(prog.OnMapTableNamespace); end; procedure TPaxRunner.SetOnMapTableNamespace(value: TPaxMapTableNamespaceEvent); begin prog.OnMapTableNamespace := TMapTableNamespaceEvent(value); end; function TPaxRunner.GetOnMapTableVarAddress: TPaxMapTableVarAddressEvent; begin result := TPaxMapTableVarAddressEvent(prog.OnMapTableVarAddress); end; procedure TPaxRunner.SetOnMapTableVarAddress(value: TPaxMapTableVarAddressEvent); begin prog.OnMapTableVarAddress := TMapTableVarAddressEvent(value); end; function TPaxRunner.GetOnMapTableProcAddress: TPaxMapTableProcAddressEvent; begin result := TPaxMapTableProcAddressEvent(prog.OnMapTableProcAddress); end; procedure TPaxRunner.SetOnMapTableProcAddress(value: TPaxMapTableProcAddressEvent); begin prog.OnMapTableProcAddress := TMapTableProcAddressEvent(value); end; function TPaxRunner.GetOnMapTableClassRef: TPaxMapTableClassRefEvent; begin result := TPaxMapTableClassRefEvent(prog.OnMapTableClassRef); end; procedure TPaxRunner.SetOnMapTableClassRef(value: TPaxMapTableClassRefEvent); begin prog.OnMapTableClassRef := TMapTableClassRefEvent(value); end; function TPaxRunner.GetOnException: TPaxErrNotifyEvent; begin result := TPaxErrNotifyEvent(prog.OnException); end; procedure TPaxRunner.SetOnException(value: TPaxErrNotifyEvent); begin prog.OnException := TErrNotifyEvent(value); end; function TPaxRunner.GetOnUnhandledException: TPaxErrNotifyEvent; begin result := TPaxErrNotifyEvent(prog.OnUnhandledException); end; procedure TPaxRunner.SetOnUnhandledException(value: TPaxErrNotifyEvent); begin prog.OnUnhandledException := TErrNotifyEvent(value); end; // added in v1.6 {$IFDEF PAXARM} {$ELSE} procedure TPaxRunner.SetEntryPoint(EntryPoint: TPaxInvoke); begin prog.SetEntryPoint(EntryPoint); end; procedure TPaxRunner.ResetEntryPoint(EntryPoint: TPaxInvoke); begin prog.ResetEntryPoint(EntryPoint); end; {$ENDIF} procedure TPaxRunner.CreateGlobalJSObjects; begin if Assigned(CrtJSObjects) then CrtJSObjects(prog, prog.JS_Record); end; function TPaxRunner.GetImageSize: Integer; begin result := prog.GetImageSize; end; function TPaxRunner.CreateScriptObject(const ScriptClassName: String; const ParamList: array of const): TObject; begin result := prog.CreateScriptObject(ScriptClassName, ParamList); end; procedure TPaxRunner.DestroyScriptObject(X: TObject); begin prog.DestroyScriptObject(X); end; function TPaxRunner.GetExitCode: Integer; begin result := prog.ExitCode; end; procedure TPaxRunner.RegisterMember(LevelId: Integer; const Name: String; Address: Pointer); begin prog.RegisterMember(LevelId, Name, Address); end; function TPaxRunner.RegisterNamespace(LevelId: Integer; const Name: String): Integer; begin result := prog.RegisterNamespace(LevelId, Name); end; function TPaxRunner.RegisterClassType(LevelId: Integer; C: TClass): Integer; begin result := prog.RegisterClassType(LevelId, C); end; procedure TPaxRunner.MapGlobal; begin prog.MapGlobal; end; procedure TPaxRunner.MapLocal; begin prog.MapLocal; end; function TPaxRunner.GetFieldAddress(X: TObject; const FieldName: String): Pointer; begin result := prog.GetFieldAddress(X, FieldName); end; procedure TPaxRunner.DiscardDebugMode; begin prog.DiscardDebugMode; end; procedure TPaxRunner.AssignEventHandlerRunner(MethodAddress: Pointer; Instance: TObject); begin prog.AssignEventHandlerRunner(MethodAddress, Instance); end; function TPaxRunner.GetIsEvent: Boolean; begin result := prog.RootIsEvent; end; procedure TPaxRunner.LoadDFMFile(Instance: TObject; const FileName: String); begin prog.LoadDFMFile(Instance, FileName); end; procedure TPaxRunner.LoadDFMStream(Instance: TObject; S: TStream); begin prog.LoadDFMStream(Instance, S); end; function TPaxRunner.GetTypeInfo(const FullTypeName: String): PTypeInfo; begin result := prog.GetTypeInfo(FullTypeName); end; function TPaxRunner.CallRoutine(const FullName: String; const ParamList: array of OleVariant): OleVariant; begin result := prog.CallFunc(FullName, nil, ParamList); end; function TPaxRunner.CallMethod(const FullName: String; Instance: TObject; const ParamList: array of OleVariant): OleVariant; begin result := prog.CallFunc(FullName, Instance, ParamList); end; function TPaxRunner.CallClassMethod(const FullName: String; Instance: TClass; const ParamList: array of OleVariant): OleVariant; begin result := prog.CallFunc(FullName, Instance, ParamList); end; function TPaxRunner.GetSourceLine: Integer; begin result := prog.GetSourceLine; end; function TPaxRunner.GetModuleName: String; begin result := prog.GetModuleName; end; function TPaxRunner.GetOnLoadPCU: TPaxRunnerLoadPCUEvent; begin result := TPaxRunnerLoadPCUEvent(prog.OnLoadPCU); end; procedure TPaxRunner.SetOnLoadPCU(value: TPaxRunnerLoadPCUEvent); begin prog.OnLoadPCU := TLoadPCUEvent(value); end; procedure TPaxRunner.SetSuspendFinalization(value: Boolean); begin prog.SuspendFinalization := value; end; function TPaxRunner.GetOnStreamSave: TPaxStreamEvent; begin result := TPaxStreamEvent(prog.OnSaveToStream); end; procedure TPaxRunner.SetOnStreamSave(value: TPaxStreamEvent); begin prog.OnSaveToStream := TStreamEvent(value); end; function TPaxRunner.GetOnStreamLoad: TPaxStreamEvent; begin result := TPaxStreamEvent(prog.OnLoadFromStream); end; procedure TPaxRunner.SetOnStreamLoad(value: TPaxStreamEvent); begin prog.OnLoadFromStream := TStreamEvent(value); end; function TPaxRunner.GetSuspendFinalization: Boolean; begin result := prog.SuspendFinalization; end; procedure TPaxRunner.UnloadPCU(const FullPath: String); begin prog.UnloadPCU(FullPath); end; procedure TPaxRunner.LoadPCU(const FileName: String); var DestProg: Pointer; begin prog.LoadPCU(FileName, DestProg); end; function TPaxRunner.GetExceptionRecord: Pointer; begin result := prog.ExceptionRec; end; function TPaxRunner.GetConsole: Boolean; begin result := prog.Console; end; procedure TPaxRunner.SetConsole(value: Boolean); begin prog.Console := value; end; function TPaxRunner.GetRunMode: Integer; begin result := prog.RunMode; end; procedure TPaxRunner.SetRunMode(value: Integer); begin if (value < 0) or (value > _rmRUN_TO_CURSOR) then prog.RaiseError(errIncorrectValue, []); prog.RunMode := value; end; function TPaxRunner.AddBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; var B: TBreakpoint; begin B := prog.AddBreakpoint(ModuleName, SourceLineNumber); result := B <> nil; end; function TPaxRunner.AddTempBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; var B: TBreakpoint; begin B := prog.AddTempBreakpoint(ModuleName, SourceLineNumber); result := B <> nil; end; function TPaxRunner.RemoveBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; begin result := prog.RemoveBreakpoint(ModuleName, SourceLineNumber); end; function TPaxRunner.RemoveBreakpoint(const ModuleName: String): Boolean; begin result := prog.RemoveBreakpoint(ModuleName); end; procedure TPaxRunner.RemoveAllBreakpoints; begin prog.RemoveAllBreakpoints; end; function TPaxRunner.HasBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; begin result := prog.HasBreakpoint(ModuleName, SourceLineNumber); end; function TPaxRunner.IsExecutableLine(const ModuleName: String; SourceLineNumber: Integer): Boolean; begin result := prog.IsExecutableLine(ModuleName, SourceLineNumber); end; function TPaxRunner.GetPCUCount: Integer; begin result := prog.ProgList.Count; end; function TPaxRunner.GetOnBeginProcNotify: TPaxProcNotifyEvent; begin result := TPaxProcNotifyEvent(prog.OnBeginProcNotifyEvent); end; procedure TPaxRunner.SetOnBeginProcNotify(value: TPaxProcNotifyEvent); begin prog.OnBeginProcNotifyEvent := TProcNotifyEvent(value); end; function TPaxRunner.GetOnEndProcNotify: TPaxProcNotifyEvent; begin result := TPaxProcNotifyEvent(prog.OnEndProcNotifyEvent); end; procedure TPaxRunner.SetOnEndProcNotify(value: TPaxProcNotifyEvent); begin prog.OnEndProcNotifyEvent := TProcNotifyEvent(value); end; function TPaxRunner.GetOnVirtualObjectMethodCall: TPaxVirtualObjectMethodCallEvent; begin result := TPaxVirtualObjectMethodCallEvent(prog.OnVirtualObjectMethodCall); end; procedure TPaxRunner.SetOnVirtualObjectMethodCall(value: TPaxVirtualObjectMethodCallEvent); begin prog.OnVirtualObjectMethodCall := TVirtualObjectMethodCallEvent(value); end; function TPaxRunner.GetOnVirtualObjectPutProperty: TPaxVirtualObjectPutPropertyEvent; begin result := TPaxVirtualObjectPutPropertyEvent(prog.OnVirtualObjectPutProperty); end; procedure TPaxRunner.SetOnVirtualObjectPutProperty(value: TPaxVirtualObjectPutPropertyEvent); begin prog.OnVirtualObjectPutProperty := TVirtualObjectPutPropertyEvent(value); end; function TPaxRunner.GetPausedPCU: TBaseRunner; begin result := prog.PausedPCU; end; procedure TPaxRunner.SetPausedPCU(value: TBaseRunner); begin prog.PausedPCU := value; end; function TPaxRunner.GetPrintClassTypeField: TPaxPrintClassTypeFieldEvent; begin result := TPaxPrintClassTypeFieldEvent(prog.OnPrintClassTypeField); end; procedure TPaxRunner.SetPrintClassTypeField(value: TPaxPrintClassTypeFieldEvent); begin prog.OnPrintClassTypeField := TPrintClassTypeFieldEvent(value); end; function TPaxRunner.GetPrintClassTypeProp: TPaxPrintClassTypePropEvent; begin result := TPaxPrintClassTypePropEvent(prog.OnPrintClassTypeProp); end; procedure TPaxRunner.SetPrintClassTypeProp(value: TPaxPrintClassTypePropEvent); begin prog.OnPrintClassTypeProp := TPrintClassTypePropEvent(value); end; function TPaxRunner.GetCurrentFunctionFullName: String; begin result := prog.GetCurrentFunctionFullName; end; procedure TPaxRunner.GetCurrentParams(result: TStrings); begin prog.GetCurrentParams(result); end; procedure TPaxRunner.GetCurrentLocalVars(result: TStrings); begin prog.GetCurrentLocalVars(result); end; function TPaxRunner.GetPCUUnit(I: Integer): TBaseRunner; begin if I < PCUCount then result := TBaseRunner(prog.ProgList[I].Prog) else result := nil; end; function TPaxRunner.HasPCU(const ModuleName: String): Boolean; var I: Integer; S: String; begin result := false; for I := 0 to PCUCount - 1 do begin S := prog.ProgList[I].FullPath; S := ExtractFullOwner(S); if StrEql(S, ModuleName) then begin result := true; Exit; end; end; end; function ScalarValueToString(Address: Pointer; T: Integer): String; begin result := PAXCOMP_SYS.ScalarValueToString(Address, T); end; function TPaxRunner.GetSearchPathList: TStringList; begin result := prog.RootSearchPathList; end; end.
{ PureMVC Delphi Port by Jorge L. Cangas <jorge.cangas@puremvc.org> PureMVC - Copyright(c) 2006-11 Futurescale, Inc., Some rights reserved. Your reuse is governed by the Creative Commons Attribution 3.0 License } unit PureMVC.Interfaces.IProxy; interface uses RTTI; type /// <summary> /// The interface definition for a PureMVC Proxy /// </summary> /// <remarks> /// <para>In PureMVC, <c>IProxy</c> implementors assume these responsibilities:</para> /// <list type="bullet"> /// <item>Implement a common method which returns the name of the Proxy</item> /// </list> /// <para>Additionally, <c>IProxy</c>s typically:</para> /// <list type="bullet"> /// <item>Maintain references to one or more pieces of model data</item> /// <item>Provide methods for manipulating that data</item> /// <item>Generate <c>INotifications</c> when their model data changes</item> /// <item>Expose their name as a <c>public const</c> called <c>NAME</c></item> /// <item>Encapsulate interaction with local or remote services used to fetch and persist model data</item> /// </list> /// </remarks> IProxy = interface ['{D04338EF-900E-4DC3-8F0C-0BE2F7D3B373}'] /// <summary> /// The Proxy instance name /// </summary> function GetProxyName: string; property ProxyName: string read GetProxyName; /// <summary> /// The data of the proxy /// </summary> function GetData: TValue; procedure SetData(Value: TValue); property Data: TValue read GetData write SetData; /// <summary> /// Called by the Model when the Proxy is registered /// </summary> procedure OnRegister(); /// <summary> /// Called by the Model when the Proxy is removed /// </summary> procedure OnRemove(); end; implementation end.
program console; {$mode objfpc}{$H+} uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} Classes, SysUtils, CustApp, { you can add units after this } StrUtils, DateUtils; type THrecord = Record Stunde : integer; Anzahl : integer; downloadrate : double; end; THrecordListe = Record recs : array[0..24] of THrecord; end; { TMyApplication } TMyApplication = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; var HrecordListe : THrecordListe; { TMyApplication } procedure TMyApplication.DoRun; var ErrorMsg, FName, MyZeit : string; Delimeters : TSysCharSet; lst : TStringList; x, Faktor: integer; DownloadRate, Zeit : String; MyRecListe : THrecordListe; sum : double; begin Delimeters := [' ', '(', ')', (#13)]; // quick check parameters aber schnell jetzt und wieder gešndert ErrorMsg := CheckOptions('h', 'help'); if ErrorMsg <> '' then begin ShowException(Exception.Create(ErrorMsg)); Terminate; Exit; end; // parse parameters if HasOption('h', 'help') then begin WriteHelp; Terminate; Exit; end; { add your program here } try lst := TStringList.Create; FName := ExtractFilePath(ExeName) + 'protokoll'; if not FileExists(FName) then begin writeln('Datei protokoll in ' + ExtractFilePath(FName) + ' wurde nich gefunden!'); terminate; end else begin lst.LoadFromFile(FName); //for x := 0 to lst.Count - 1 do writeln('Zeile ' + IntToStr(x) + ' ' + lst[x]); for x := lst.Count - 1 downto 0 do begin if pos('Offline',lst[x]) > 0 then lst.Delete(x); end; writeln('******************************'); for x := 0 to lst.Count - 1 do begin if pos('MB/s',lst[x]) > 0 then Faktor := 1024 else Faktor := 1; {$IFDEF Linux} DownloadRate := StringReplace(ExtractWord(7 ,lst[x],Delimeters),',','.', []); {$ELSE } DownloadRate := ExtractWord(7 ,lst[x],Delimeters); {$ENDIF } //writeln ('downloadrate ' + DownloadRate + ' mal Faktor ' + IntToStr(Faktor) + ' = ' + FloatToStr(StrToFloatDef(DownloadRate ,0) * Faktor)); MyZeit := Copy(ExtractWord(2 ,lst[x],Delimeters),1,2); HrecordListe.recs[StrToIntDef(MyZeit,0)].downloadrate := HrecordListe.recs[StrToIntDef(MyZeit,0)].downloadrate + StrToFloatDef(DownloadRate ,0) * Faktor; HrecordListe.recs[StrToIntDef(MyZeit,0)].Anzahl := HrecordListe.recs[StrToIntDef(MyZeit,0)].Anzahl +1; HrecordListe.recs[StrToIntDef(MyZeit,0)].Stunde := StrToIntDef(MyZeit,0); end; writeln('... und jetzt die gespeicherten records'); for x := 0 to 24 do begin if HrecordListe.recs[x].Anzahl > 0 then begin sum := (HrecordListe.recs[x].downloadrate / HrecordListe.recs[x].Anzahl) / Faktor; writeln('Urzeit ' + IntToStr(HrecordListe.recs[x].Stunde) + ' Anzahl ' + IntToStr(HrecordListe.recs[x].Anzahl) + ' Summe downloadrate ' + FloatToStr(HrecordListe.recs[x].downloadrate) + ' Mittelwert der downloadrate ' + FormatFloat('#,##0.00 MB',sum)); end; end; end; finally FreeAndNil(lst); end; // stop program loop Terminate; end; constructor TMyApplication.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException := True; end; destructor TMyApplication.Destroy; begin inherited Destroy; end; procedure TMyApplication.WriteHelp; begin { add your help code here } writeln('Usage: ', ExeName, ' -h'); end; var Application: TMyApplication; begin Application := TMyApplication.Create(nil); Application.Title := 'My Application'; Application.Run; Application.Free; end.
unit uDb; interface // uses ulang ,uparser,SysUtils; type TLispDb = class(TLispPackageBase) private function ldbQuery(lispNodes : TLispList) : TlispNode ; function ldbUpdate(lispNodes : TLispList) : TlispNode ; function dbupdate(aDsn ,aSql : string ;password:string ='';username:string =''):TLispNode; function dbquery(aDsn ,aSql : string ; password:string ='';username:string =''): TLispNode; public function CallFunction(fnName: String;list: TLispList): TLispNode;override ; function GetName:String;override ; function GetTestSrc:String;override ; end; var LispDb : TLispDb; implementation uses odbc,ulangException ; function TLispDb.dbupdate(aDsn ,aSql : string ;password:string ='';username:string =''):TLispNode; var query1 : Todbcst; begin try PSQLAllocEnv; PSQLAllocConnect; If PSQLConnect(pchar(aDsn),'','') = 0 Then Begin Try Query1 := Todbcst.Create; With Query1 do Begin Try Sql := asql; execute; Except On E: Error_Odbc do ; End; End; Finally Query1.Free; End; End; Finally PSQLDisconnect; PSQLFreeConnect; PSQLFreeEnv; End; //RESULT := TlispNode.create ('',nil,TT_TRUE) RESULT := TlispNodeTrue.create (FLispLang); end; function TLispDb.dbquery(aDsn ,aSql : string ; password:string ='';username:string =''): TLispNode; var query1 : Todbcst; i : integer ; r : TLispNode ; rl ,rl1: TLispList ; begin try PSQLAllocEnv; PSQLAllocConnect; If PSQLConnect(pchar(aDsn),'','') = 0 Then Begin Try Query1 := Todbcst.Create; With Query1 do Begin Try Sql := asql; execute; // table - rl := TLispList.create (FLispLang); While Next do Begin // table - rl1 := TLispList.create(FLispLang) ; for i :=1 to NumbCols do //form1.caption := form1.caption + cellstring(i) ; begin //rl1.append(TLispNode.create (cellstring(i),nil,TT_STRING)); rl1.append(TLispNodeString.create (FLispLang,cellstring(i))); end; End; //rl.append (TLispNode.Create('',rl1,TT_LIST)); rl.append (TLispNodeList.Create(FLispLang,rl1)); Except On E: Error_Odbc do ; End; End; Finally Query1.Free; End; End; Finally PSQLDisconnect; PSQLFreeConnect; PSQLFreeEnv; End; //result := TLispNode.Create('',rl1,TT_LIST); result := TLispNodeList.Create(FLispLang,rl1); end; { TLispDb } function TLispDb.ldbQuery(lispNodes: TLispList): TlispNode; var aDsn ,aSql : string ; password:string ;username:string ; lispNode : TLispNode ; begin if ((lispnodes.size <> 3) and (lispnodes.size <> 5)) then raise ELispParameterSize.Create ; lispNode := lispNodes.nth(1).iEvaluate; if not lispNode.isStr then raise ELispParameterTypeNotMatch.Create else aDsn := lispNode.getStr ; lispNode := lispNodes.nth(2).iEvaluate; if not lispNode.isStr then raise ELispParameterTypeNotMatch.Create else aSql := lispNode.getStr ; if (lispnodes.size = 5) then begin lispNode := lispNodes.nth(3).iEvaluate; if not lispNode.isStr then raise ELispParameterTypeNotMatch.Create else username := lispNode.getStr ; // lispNode := lispNodes.nth(4).iEvaluate; if not lispNode.isStr then raise ELispParameterTypeNotMatch.Create else password := lispNode.getStr ; end; result := dbquery (adsn,asql,username,password); end; function TLispDb.ldbUpdate(lispNodes: TLispList): TlispNode; var aDsn ,aSql : string ; password:string ;username:string ; lispNode : TLispNode ; begin if not ((lispnodes.size = 3) or (lispnodes.size = 5)) then raise ELispParameterSize.Create ; lispNode := lispNodes.nth(1).iEvaluate; if not lispNode.isStr then raise ELispParameterTypeNotMatch.Create else aDsn := lispNode.getStr ; lispNode := lispNodes.nth(2).iEvaluate; if not lispNode.isStr then raise ELispParameterTypeNotMatch.Create else aSql := lispNode.getStr ; if (lispnodes.size = 5) then begin lispNode := lispNodes.nth(3).iEvaluate; if not lispNode.isStr then raise ELispParameterTypeNotMatch.Create else username := lispNode.getStr ; // lispNode := lispNodes.nth(4).iEvaluate; if not lispNode.isStr then raise ELispParameterTypeNotMatch.Create else password := lispNode.getStr ; end; result := dbUpdate (adsn,asql,username,password); end; function TLispDb.CallFunction(fnName: String;list: TLispList): TLispNode; begin Result := nil ; if SameText(fnName ,'dbQuery') then Result := ldbQuery(list) else if SameText(fnName ,'dbUpdate') then Result := ldbUpdate(list); end; function TLispDb.GetName: String; begin Result := 'LispDb'; end; function TLispDb.GetTestSrc: String; begin Result := '(quote ("Not yet"))'; end; initialization end.
unit OTFEUnified_U; // Description: Delphi Unified OTFE Component // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OTFE_U, OTFEConsts_U, OTFEBestCrypt_U, OTFEE4M_U, OTFETrueCrypt_U, OTFEPGPDisk_U, OTFEScramDisk_U, OTFECrossCrypt_U, OTFEFreeOTFE_U; type TOTFESystem = ( otfesFreeOTFE, otfesBestCrypt, otfesCrossCrypt, otfesE4M, otfesPGPDisk, otfesScramDisk, otfesTrueCrypt ); const // !!!!!!!!!!!!!!! // !!!!!!!!!!!!!!! // !!! WARNING !!! // !!!!!!!!!!!!!!! // !!!!!!!!!!!!!!! // THIS MUST BE IN THE SAME ORDER AS TOTFESystem // Display names for each of the different types of OTF crypto system // Note: Each display name must be unique OTFESDispNames: array [TOTFESystem] of string = ( 'FreeOTFE', 'BestCrypt', 'CrossCrypt', 'E4M', 'PGPDisk', 'ScramDisk', 'TrueCrypt' ); const // !!!!!!!!!!!!!!! // !!!!!!!!!!!!!!! // !!! WARNING !!! // !!!!!!!!!!!!!!! // !!!!!!!!!!!!!!! // THIS MUST BE IN THE SAME ORDER AS TOTFESystem // "Internal" names for each of the different types of OTF crypto system // Note: Each internal name must be unique, and contain no spaces or // punctuation. // This is intended that the user can use this where a display name would be // useless (e.g. if the corrosponding display name contains spaces, etc) OTFESInternalNames: array [TOTFESystem] of string = ( 'FREEOTFE', 'BESTCRYPT', 'CROSSCRYPT', 'E4M', 'PGPDISK', 'SCRAMDISK', 'TRUECRYPT' ); type TOTFEUnified = class(TOTFE) private { private declarations here} protected // Set the component active/inactive procedure SetActive(status: Boolean); override; public OTFComponents: array [TOTFESystem] of TOTFE; OTFEnabledComponents: array [TOTFESystem] of boolean; constructor Create(AOwner : TComponent); override; destructor Destroy(); override; function Title(): string; overload; override; function Mount(volumeFilename: Ansistring; readonly: boolean = FALSE): Ansichar; overload; override; function Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean; overload; override; function MountDevices(): Ansistring; override; function CanMountDevice(): boolean; override; function Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean; overload; override; function Dismount(driveLetter: Ansichar; emergency: boolean = FALSE): boolean; overload; override; function IsDriverInstalled(): boolean; overload; override; function IsDriverInstalled(otfeSystem: TOTFESystem): boolean; overload; function Version(): cardinal; overload; override; function VersionStr(): string; overload; override; function IsEncryptedVolFile(volumeFilename: string): boolean; override; function DrivesMounted(): Ansistring; overload; override; function GetVolFileForDrive(driveLetter: Ansichar): string; override; function GetDriveForVolFile(volumeFilename: string): Ansichar; override; function GetMainExe(): string; override; function TypeOfEncryptedVolFile(volumeFilename: string; var typeOfFile: TOTFESystem): boolean; function TypeOfEncryptedDrive(driveLetter: Ansichar; var typeOfFile: TOTFESystem): boolean; // OTF Crypto "internal" name to system type function OTFSystemFromDispName(dispName: string; var OTFSystem: TOTFESystem): boolean; // OTF Crypto display name to system type function OTFSystemFromInternalName(internalName: string; var OTFSystem: TOTFESystem): boolean; // For a *mounted* volume, sets OTFSystem to the OTF crypto system used for // that volume function OTFSystemForDrive(driveLetter: Ansichar; var OTFSystem: TOTFESystem): boolean; // For a *mounted* volume, sets OTFSystem to the OTF crypto system used for // that volume function OTFSystemForVolFile(volumeFilename: string; var OTFSystem: TOTFESystem): boolean; end; procedure Register; implementation uses OTFEUnified_frmSelectOTFESystem; procedure Register; begin RegisterComponents('OTFE', [TOTFEUnified]); end; constructor TOTFEUnified.Create(AOwner : TComponent); var OTFSystemLoop: TOTFESystem; begin inherited; OTFComponents[otfesBestCrypt ] := TOTFEBestCrypt.Create(nil); OTFComponents[otfesE4M ] := TOTFEE4M.Create(nil); OTFComponents[otfesTrueCrypt ] := TOTFETrueCrypt.Create(nil); OTFComponents[otfesPGPDisk ] := TOTFEPGPDisk.Create(nil); OTFComponents[otfesScramDisk ] := TOTFEScramDisk.Create(nil); OTFComponents[otfesCrossCrypt] := TOTFECrossCrypt.Create(nil); OTFComponents[otfesFreeOTFE ] := TOTFEFreeOTFE.Create(nil); for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin OTFEnabledComponents[OTFSystemLoop] := TRUE; end; end; destructor TOTFEUnified.Destroy(); var OTFSystemLoop: TOTFESystem; begin for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin OTFComponents[OTFSystemLoop].Free(); end; inherited; end; procedure TOTFEUnified.SetActive(status: Boolean); var OTFSystemLoop: TOTFESystem; begin inherited; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFEnabledComponents[OTFSystemLoop] then begin try OTFComponents[OTFSystemLoop].Active := status; OTFEnabledComponents[OTFSystemLoop] := OTFComponents[OTFSystemLoop].Active; except // Damn. Oh well, better disable this component if OTFComponents[OTFSystemLoop].Active<>status then begin OTFEnabledComponents[OTFSystemLoop] := FALSE; FLastErrCode := OTFComponents[OTFSystemLoop].LastErrorCode; end; end; end; end; // If at least one of the components was set active, then we accept that this // unified component may also be set active FActive := FALSE; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFComponents[OTFSystemLoop].Active then begin FActive := TRUE; break; end; end; end; function TOTFEUnified.Mount(volumeFilename: Ansistring; readonly: boolean = FALSE): Ansichar; var stlTemp: TStringList; mountedAs: Ansistring; begin stlTemp := TStringList.Create(); try stlTemp.Add(volumeFilename); if Mount(stlTemp, mountedAs, readonly) then begin Result := mountedAs[1]; end else begin Result := #0; end; finally stlTemp.Free(); end; end; function TOTFEUnified.Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean; var useOTFSystem: TOTFESystem; OTFSystemLoop: TOTFESystem; matchingOTFE: array [TOTFESystem] of boolean; cntMatched: integer; retVal: boolean; lastMatched: TOTFESystem; dlgSelect: TfrmSelectOTFESystem; begin retVal := FALSE; cntMatched := 0; lastMatched := otfesFreeOTFE; // Doesn't matter; this value should never be used if (volumeFilenames.Count>0) then begin for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin matchingOTFE[OTFSystemLoop] := FALSE; if OTFComponents[OTFSystemLoop].Active then begin matchingOTFE[OTFSystemLoop] := OTFComponents[OTFSystemLoop].IsEncryptedVolFile(volumeFilenames[0]); if (matchingOTFE[OTFSystemLoop]) then begin inc(cntMatched); lastMatched := OTFSystemLoop; end; end; end; if (cntMatched=1) then begin // Detected single OTFE system capable of mounting... retVal := OTFComponents[lastMatched].Mount(volumeFilenames, mountedAs, readonly); FLastErrCode := OTFComponents[lastMatched].LastErrorCode; end else if (cntMatched>1) then begin // Detected multiple OTFE systems capable of mounting; prompt user... dlgSelect:= TfrmSelectOTFESystem.Create(nil); try for useOTFSystem:=low(matchingOTFE) to high(matchingOTFE) do begin if matchingOTFE[useOTFSystem] then begin dlgSelect.Add(useOTFSystem); end; end; if (dlgSelect.ShowModal = mrOK) then begin useOTFSystem := dlgSelect.GetSelected(); retVal := OTFComponents[useOTFSystem].Mount(volumeFilenames, mountedAs, readonly); FLastErrCode := OTFComponents[useOTFSystem].LastErrorCode; end else begin FLastErrCode := OTFE_ERR_USER_CANCEL; end; finally dlgSelect.Free(); end; end; end; Result := retVal; end; function TOTFEUnified.Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean; var OTFSystem: TOTFESystem; begin Result := FALSE; if OTFSystemForVolFile(volumeFilename, OTFSystem) then begin Result := OTFComponents[OTFSystem].Dismount(volumeFilename, emergency); FLastErrCode := OTFComponents[OTFSystem].LastErrorCode; end; end; function TOTFEUnified.Dismount(driveLetter: Ansichar; emergency: boolean = FALSE): boolean; var OTFSystem: TOTFESystem; begin Result := FALSE; if OTFSystemForDrive(driveLetter, OTFSystem) then begin Result := OTFComponents[OTFSystem].Dismount(driveLetter, emergency); FLastErrCode := OTFComponents[OTFSystem].LastErrorCode; end; end; function TOTFEUnified.IsDriverInstalled(): boolean; var retVal: boolean; OTFSystemLoop: TOTFESystem; begin retVal := FALSE; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFComponents[OTFSystemLoop].Active then begin retVal := retVal OR OTFComponents[OTFSystemLoop].IsDriverInstalled(); if retVal then begin break; end; end; end; Result := retVal; end; // Determine if a specific OTFE driver is installed function TOTFEUnified.IsDriverInstalled(otfeSystem: TOTFESystem): boolean; begin Result := OTFComponents[otfeSystem].IsDriverInstalled(); end; function TOTFEUnified.Title(): string; begin Result := ''; end; function TOTFEUnified.Version(): cardinal; begin Result := $FFFFFFFF; end; function TOTFEUnified.VersionStr(): string; begin Result := ''; end; function TOTFEUnified.IsEncryptedVolFile(volumeFilename: string): boolean; var junkOTFSystem: TOTFESystem; begin Result := TypeOfEncryptedVolFile(volumeFilename, junkOTFSystem); end; function TOTFEUnified.TypeOfEncryptedVolFile(volumeFilename: string; var typeOfFile: TOTFESystem): boolean; var retVal: boolean; OTFSystemLoop: TOTFESystem; begin retVal := FALSE; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFComponents[OTFSystemLoop].Active then begin retVal := retVal OR OTFComponents[OTFSystemLoop].IsEncryptedVolFile(volumeFilename); if retVal then begin typeOfFile := OTFSystemLoop; break; end; end; end; Result := retVal; end; function TOTFEUnified.TypeOfEncryptedDrive(driveLetter: Ansichar; var typeOfFile: TOTFESystem): boolean; var OTFSystemLoop: TOTFESystem; begin Result := FALSE; driveLetter := AnsiChar((uppercase(driveLetter))[1]); for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFComponents[OTFSystemLoop].Active then begin if (Pos(driveLetter, OTFComponents[OTFSystemLoop].DrivesMounted())>0) then begin typeOfFile := OTFSystemLoop; Result := TRUE; break; end; end; end; end; function TOTFEUnified.DrivesMounted(): Ansistring; var retVal: Ansistring; OTFSystemLoop: TOTFESystem; begin retVal := ''; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFComponents[OTFSystemLoop].Active then begin retVal := retVal + OTFComponents[OTFSystemLoop].DrivesMounted(); end; end; Result := SortString(retVal); end; function TOTFEUnified.GetVolFileForDrive(driveLetter: Ansichar): string; var retVal: string; OTFSystemLoop: TOTFESystem; begin retVal := ''; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFComponents[OTFSystemLoop].Active then begin retVal := OTFComponents[OTFSystemLoop].GetVolFileForDrive(driveLetter); if retVal<>'' then begin break; end; end; end; Result := retVal; end; function TOTFEUnified.GetDriveForVolFile(volumeFilename: string): Ansichar; var retVal: Ansichar; OTFSystemLoop: TOTFESystem; begin retVal := #0; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFComponents[OTFSystemLoop].Active then begin retVal := OTFComponents[OTFSystemLoop].GetDriveForVolFile(volumeFilename); if retVal<>#0 then begin break; end; end; end; Result := retVal; end; function TOTFEUnified.OTFSystemFromDispName(dispName: string; var OTFSystem: TOTFESystem): boolean; var OTFSystemLoop: TOTFESystem; begin Result := FALSE; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if dispName=OTFESDispNames[OTFsystem] then begin OTFSystem := OTFSystemLoop; Result := TRUE; break; end; end; end; function TOTFEUnified.OTFSystemFromInternalName(internalName: string; var OTFSystem: TOTFESystem): boolean; var OTFSystemLoop: TOTFESystem; begin Result := FALSE; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if internalName=OTFESInternalNames[OTFsystem] then begin OTFSystem := OTFSystemLoop; Result := TRUE; break; end; end; end; function TOTFEUnified.OTFSystemForDrive(driveLetter: Ansichar; var OTFSystem: TOTFESystem): boolean; var OTFSystemLoop: TOTFESystem; begin Result := FALSE; driveLetter := Ansichar((uppercase(driveLetter))[1]); for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFComponents[OTFSystemLoop].Active then begin if pos(driveLetter, OTFComponents[OTFSystemLoop].DrivesMounted())>0 then begin OTFSystem := OTFSystemLoop; Result := TRUE; break; end; end; end; end; function TOTFEUnified.OTFSystemForVolFile(volumeFilename: string; var OTFSystem: TOTFESystem): boolean; var OTFSystemLoop: TOTFESystem; begin Result := FALSE; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFComponents[OTFSystemLoop].Active then begin if GetDriveForVolFile(volumeFilename)<>#0 then begin OTFSystem := OTFSystemLoop; Result := TRUE; break; end; end; end; end; function TOTFEUnified.GetMainExe(): string; begin FLastErrCode:= OTFE_ERR_UNABLE_TO_LOCATE_FILE; Result := ''; end; // ----------------------------------------------------------------------------- // Prompt the user for a device (if appropriate) and password (and drive // letter if necessary), then mount the device selected // Returns the drive letter of the mounted devices on success, #0 on failure function TOTFEUnified.MountDevices(): Ansistring; var useOTFSystem: TOTFESystem; OTFSystemLoop: TOTFESystem; matchingOTFE: array [TOTFESystem] of boolean; cntMatched: integer; retVal: Ansistring; lastMatched: TOTFESystem; dlgSelect: TfrmSelectOTFESystem; begin retVal := ''; cntMatched := 0; lastMatched := otfesFreeOTFE; // Doesn't matter; this value should never be used for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin matchingOTFE[OTFSystemLoop] := FALSE; if OTFComponents[OTFSystemLoop].Active then begin matchingOTFE[OTFSystemLoop] := OTFComponents[OTFSystemLoop].CanMountDevice(); if (matchingOTFE[OTFSystemLoop]) then begin inc(cntMatched); lastMatched := OTFSystemLoop; end; end; end; // for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do if (cntMatched=1) then begin // Detected single OTFE system capable of mounting... retVal := OTFComponents[lastMatched].MountDevices(); FLastErrCode := OTFComponents[lastMatched].LastErrorCode; end else if (cntMatched>1) then begin // Detected multiple OTFE systems capable of mounting; prompt user for // which one to use... dlgSelect:= TfrmSelectOTFESystem.Create(nil); try for useOTFSystem:=low(matchingOTFE) to high(matchingOTFE) do begin if matchingOTFE[useOTFSystem] then begin dlgSelect.Add(useOTFSystem); end; end; if (dlgSelect.ShowModal = mrOK) then begin useOTFSystem := dlgSelect.GetSelected(); retVal := OTFComponents[useOTFSystem].MountDevices(); FLastErrCode := OTFComponents[useOTFSystem].LastErrorCode; end else begin FLastErrCode := OTFE_ERR_USER_CANCEL; end; finally dlgSelect.Free(); end; end; Result := retVal; end; // ----------------------------------------------------------------------------- // Determine if any OTFE components can mount devices. // Returns TRUE if it can, otherwise FALSE function TOTFEUnified.CanMountDevice(): boolean; var retVal: boolean; OTFSystemLoop: TOTFESystem; begin retVal := FALSE; for OTFSystemLoop:=low(OTFComponents) to high(OTFComponents) do begin if OTFComponents[OTFSystemLoop].Active then begin retVal := OTFComponents[OTFSystemLoop].CanMountDevice(); if retVal then begin break; end; end; end; Result := retVal; end; // ----------------------------------------------------------------------------- END.
unit RegExUtils; interface uses RegularExpressions, RegularExpressionsCore, Generics.Collections; const //Standard unicode zones - names not supported by PCRE pHiragana = '\x{3040}-\x{309F}'; pKatakana = '\x{30A0}-\x{30FF}'; pCJKUnifiedIdeographs = '\x{4E00}-\x{9FFF}'; pCJKUnifiedIdeographsExtA = '\x{3400}-\x{4DBF}'; pCJKUnifiedIdeographsExtB = '\x{20000}-\x{2A6DF}'; pCJKUnifiedIdeographsExtC = '\x{2A700}-\x{2B73F}'; pCJKSymbolsAndPunctuation = '\x{3000}-\x{303F}'; const //Useful unions pCJKChar = '(?:'+pHiragana+'|'+pKatakana+'|' +pCJKUnifiedIdeographs+'|' +pCJKUnifiedIdeographsExtA+'|' +pCJKUnifiedIdeographsExtB+'|' +pCJKUnifiedIdeographsExtC+'|' +pCJKSymbolsAndPunctuation+')'; type TPerlRegExHelper = class helper for TPerlRegEx public function HasMatches(const subj: string): boolean; function ReplaceMatches(const subj, repl: string): string; function DeleteAll(const subj: string): string; end; TRegexLib = class(TObjectDictionary<string, TRegex>) public constructor Create; function Get(const regex: string): TRegex; function Replace(const subj, regex, repl: string): string; procedure Replace2(var subj: string; const regex, repl: string); overload; procedure Replace2(var subj: string; const regex: string; const AEvaluator: TMatchEvaluator); overload; property Items[const Index: string]: TRegex read Get; default; end; function Regex(const s: string): TPerlRegEx; implementation uses SysUtils, Generics.Defaults; function Regex(const s: string): TPerlRegEx; begin Result := TPerlRegEx.Create; Result.RegEx := UTF8String(s); Result.Compile; Result.Study; end; function TPerlRegExHelper.HasMatches(const subj: string): boolean; begin Self.Subject := UTF8String(subj); Result := Match; end; function TPerlRegExHelper.ReplaceMatches(const subj, repl: string): string; begin Self.Subject := UTF8String(subj); Self.Replacement := UTF8String(repl); if Self.ReplaceAll then Result := UnicodeString(Self.Subject) //after replacements else Result := subj; end; function TPerlRegExHelper.DeleteAll(const subj: string): string; begin Result := Self.ReplaceMatches(subj,''); end; function _compareString(const Left, Right: string): Boolean; begin Result := CompareStr(Left, Right)=0; end; function _hashString(const Value: string): Integer; begin if Value='' then Result := 0 else Result := BobJenkinsHash(Value[1], Length(Value)*SizeOf(Value[1]), 1234567); end; constructor TRegexLib.Create; begin inherited Create( TDelegatedEqualityComparer<string>.Create( _compareString, _hashString ) ); end; function TRegexLib.Get(const regex: string): TRegex; begin if not Self.TryGetValue(regex, Result) then begin Result := TRegex.Create(regex); Self.Add(regex, Result); end; end; function TRegexLib.Replace(const subj, regex, repl: string): string; var obj: TRegex; begin obj := Get(regex); Result := obj.Replace(subj, repl); end; procedure TRegexLib.Replace2(var subj: string; const regex, repl: string); var obj: TRegex; begin obj := Get(regex); subj := obj.Replace(subj, repl); end; procedure TRegexLib.Replace2(var subj: string; const regex: string; const AEvaluator: TMatchEvaluator); var obj: TRegex; begin obj := Get(regex); subj := obj.Replace(subj, AEvaluator); end; end.
unit GLForceFields; interface uses System.Classes, GLVectorGeometry, GLXCollection, GLScene, GLCoordinates, GLBehaviours, GLInertias, GLPhysics { GLRigidBodyInertia}; type TGLUniformGravityEmitter = class(TGLBaseForceFieldEmitter) private fGravity:TGLCoordinates; protected procedure SetGravity(const val : TGLCoordinates); public constructor Create(aOwner : TXCollection); override; destructor Destroy;override; procedure Assign(Source: TPersistent); override; procedure WriteToFiler(writer : TWriter); override; procedure ReadFromFiler(reader : TReader); override; class function FriendlyName : String; override; class function FriendlyDescription : String; override; class function UniqueItem : Boolean; override; function CalculateForceField(Body:TGLBaseSceneObject):TAffineVector;override; published property Gravity:TGLCoordinates read fGravity write SetGravity; end; TGLRadialGravityEmitter = class(TGLBaseForceFieldEmitter) private fMass:Real; fMassOverG:Real; public constructor Create(aOwner : TXCollection); override; destructor Destroy;override; procedure Assign(Source: TPersistent); override; procedure WriteToFiler(writer : TWriter); override; procedure ReadFromFiler(reader : TReader); override; class function FriendlyName : String; override; class function FriendlyDescription : String; override; class function UniqueItem : Boolean; override; function CalculateForceField(Body:TGLBaseSceneObject):TAffineVector;override; published property Mass:Real read fMass write fMass; end; TGLDampingFieldEmitter = class(TGLBaseForceFieldEmitter) private fDamping:TGLDamping; protected procedure SetDamping(const val: TGLDamping); public constructor Create(aOwner : TXCollection); override; destructor Destroy;override; procedure Assign(Source: TPersistent); override; procedure WriteToFiler(writer : TWriter); override; procedure ReadFromFiler(reader : TReader); override; class function FriendlyName : String; override; class function FriendlyDescription : String; override; class function UniqueItem : Boolean; override; function CalculateForceField(Body:TGLBaseSceneObject):TAffineVector;override; published property Damping:TGLDamping read fDamping write SetDamping; end; const GravitationalConstant=6.6726E-11; //================================================================== implementation //================================================================== //------------------------------------- //---- TGLUniformGravityEmitter //------------------------------------- constructor TGLUniformGravityEmitter.Create(aOwner : TXCollection); begin inherited Create(aOwner); fGravity:=TGLCoordinates.CreateInitialized(Self,nullHmgVector,csVector); end; destructor TGLUniformGravityEmitter.Destroy; begin fGravity.Free; inherited Destroy; end; procedure TGLUniformGravityEmitter.Assign(Source: TPersistent); begin if Source.ClassType=Self.ClassType then begin fGravity := TGLUniformGravityEmitter(Source).fGravity; end; end; class function TGLUniformGravityEmitter.FriendlyName : String; begin Result := 'Uniform Gravity'; end; class function TGLUniformGravityEmitter.FriendlyDescription : String; begin Result := 'Uniform Gravity, appropriate near surface of planet'; end; class function TGLUniformGravityEmitter.UniqueItem : Boolean; begin Result:=false; end; procedure TGLUniformGravityEmitter.WriteToFiler(writer : TWriter); begin inherited; with Writer do begin fGravity.WriteToFiler(writer); end; end; procedure TGLUniformGravityEmitter.ReadFromFiler(reader : TReader); begin inherited; with Reader do begin fGravity.ReadFromFiler(reader); end; end; procedure TGLUniformGravityEmitter.SetGravity(const val : TGLCoordinates); begin fGravity.Assign(val); end; // CalculateForceField (TODO: ParticleInertia -> BaseInertia, add BaseInertia.ApplyAcceleration) function TGLUniformGravityEmitter.CalculateForceField(Body:TGLBaseSceneObject):TAffineVector; var inertia1:TGLParticleInertia; begin Inertia1:=TGLParticleInertia(Body.Behaviours.GetByClass(TGLParticleInertia)); if Assigned(inertia1) then begin Result:=VectorScale(fGravity.AsAffineVector,Inertia1.Mass); inertia1.ApplyForce(Result); end else Result:=nullVector; end; //------------------------------------------------------------------------------ //------------------------------Radial Gravity Emitter ------------------------- //------------------------------------------------------------------------------ constructor TGLRadialGravityEmitter.Create(aOwner : TXCollection); begin inherited Create(aOwner); end; destructor TGLRadialGravityEmitter.Destroy; begin inherited Destroy; end; procedure TGLRadialGravityEmitter.Assign(Source: TPersistent); begin if Source.ClassType=Self.ClassType then begin fMass:=TGLRadialGravityEmitter(Source).fMass; end; end; class function TGLRadialGravityEmitter.FriendlyName : String; begin Result:='Radial Gravity'; end; class function TGLRadialGravityEmitter.FriendlyDescription : String; begin Result:='Radial Gravity, can be applied anywhere (use for planets)'; end; class function TGLRadialGravityEmitter.UniqueItem : Boolean; begin Result:=false; end; procedure TGLRadialGravityEmitter.WriteToFiler(writer : TWriter); begin inherited; with Writer do begin WriteFloat(fMass); end; end; procedure TGLRadialGravityEmitter.ReadFromFiler(reader : TReader); begin inherited; with Reader do begin fMass:=ReadFloat();; end; end; // CalculateForceField (TODO: ParticleInertia -> BaseInertia if possible) function TGLRadialGravityEmitter.CalculateForceField(Body:TGLBaseSceneObject):TAffineVector; var inertia1:TGLParticleInertia; R:TAffineVector; L:Real; begin Inertia1:=TGLParticleInertia(Body.Behaviours.GetByClass(TGLParticleInertia)); if Assigned(inertia1) then begin R:=VectorSubtract(Body.Position.AsAffineVector,Self.OwnerBaseSceneObject.Position.AsAffineVector); L:=VectorLength(R); Result:=VectorScale(R,-GravitationalConstant*(fMass/L)); inertia1.ApplyForce(Result); end else Result:=nullvector; end; //----------------------------------------------------------------------------- //------------------------------Damping Field Emitter ------------------------- //----------------------------------------------------------------------------- constructor TGLDampingFieldEmitter.Create(aOwner : TXCollection); begin inherited Create(aOwner); fDamping:=TGLDamping.Create(Self); end; destructor TGLDampingFieldEmitter.Destroy; begin fDamping.Free; inherited Destroy; end; procedure TGLDampingFieldEmitter.Assign(Source: TPersistent); begin if Source.ClassType=Self.ClassType then begin fDamping:=TGLDampingFieldEmitter(Source).fDamping; end; end; class function TGLDampingFieldEmitter.FriendlyName : String; begin Result := 'Damping Field'; end; class function TGLDampingFieldEmitter.FriendlyDescription : String; begin Result := 'Damping Field, to approximate air/fluid resistance'; end; class function TGLDampingFieldEmitter.UniqueItem : Boolean; begin Result := false; end; procedure TGLDampingFieldEmitter.WriteToFiler(writer : TWriter); begin inherited; with Writer do begin fDamping.WriteToFiler(writer); end; end; procedure TGLDampingFieldEmitter.ReadFromFiler(reader : TReader); begin inherited; with Reader do begin fDamping.ReadFromFiler(reader); end; end; procedure TGLDampingFieldEmitter.SetDamping(const val : TGLDamping); begin fDamping.Assign(val); end; // CalculateForceField (TODO: ParticleInertia -> BaseInertia, BaseInertia.ApplyDamping?) function TGLDampingFieldEmitter.CalculateForceField(Body:TGLBaseSceneObject):TAffineVector; var inertia1:TGLParticleInertia; // velocity:TAffineVector; // v:Real; begin Inertia1:=TGLParticleInertia(Body.Behaviours.GetByClass(TGLParticleInertia)); if Assigned(inertia1) then Inertia1.ApplyDamping(Damping); { Inertia1:=TGLParticleInertia(Body.Behaviours.GetByClass(TGLParticleInertia)); if Assigned(inertia1) then begin velocity:=VectorScale(inertia1.LinearMomentum, 1/Inertia1.Mass); // v = p/m //apply force in opposite direction to velocity v:=VectorLength(velocity); // F = -Normalised(V)*( Constant + (Linear)*(V) + (Quadtratic)*(V)*(V) ) Result:=VectorScale(VectorNormalize(velocity),-(fDamping.Constant+fDamping.Linear*v+fDamping.Quadratic*v*v)); inertia1.ApplyForce(Result); end else Result:=nullvector; } end; //------------------------------------------------------------------------- initialization //------------------------------------------------------------------------- RegisterXCollectionItemClass(TGLUniformGravityEmitter); RegisterXCollectionItemClass(TGLRadialGravityEmitter); RegisterXCollectionItemClass(TGLDampingFieldEmitter); end.
program UpperCaseConvert; uses SysUtils; var InputString: String; begin Write('Enter a string: '); Readln(InputString); Writeln(UpperCase(InputString)); Readln end.
unit ImageRGBIntData; interface uses Windows, Graphics, BasicDataTypes, Abstract2DImageData, RGBIntDataSet, dglOpenGL; type T2DImageRGBIntData = class (TAbstract2DImageData) private FDefaultColor: TPixelRGBIntData; // Gets function GetData(_x, _y, _c: integer):integer; function GetDefaultColor:TPixelRGBIntData; // Sets procedure SetData(_x, _y, _c: integer; _value: integer); procedure SetDefaultColor(_value: TPixelRGBIntData); protected // Constructors and Destructors procedure Initialize; override; // Gets function GetBitmapPixelColor(_Position: longword):longword; override; function GetRPixelColor(_Position: longword):byte; override; function GetGPixelColor(_Position: longword):byte; override; function GetBPixelColor(_Position: longword):byte; override; function GetAPixelColor(_Position: longword):byte; override; function GetRedPixelColor(_x,_y: integer):single; override; function GetGreenPixelColor(_x,_y: integer):single; override; function GetBluePixelColor(_x,_y: integer):single; override; function GetAlphaPixelColor(_x,_y: integer):single; override; // Sets procedure SetBitmapPixelColor(_Position, _Color: longword); override; procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override; procedure SetRedPixelColor(_x,_y: integer; _value:single); override; procedure SetGreenPixelColor(_x,_y: integer; _value:single); override; procedure SetBluePixelColor(_x,_y: integer; _value:single); override; procedure SetAlphaPixelColor(_x,_y: integer; _value:single); override; public // Gets function GetOpenGLFormat:TGLInt; override; // copies procedure Assign(const _Source: TAbstract2DImageData); override; // Misc procedure ScaleBy(_Value: single); override; procedure Invert; override; // properties property Data[_x,_y,_c:integer]:integer read GetData write SetData; default; property DefaultColor:TPixelRGBIntData read GetDefaultColor write SetDefaultColor; end; implementation // Constructors and Destructors procedure T2DImageRGBIntData.Initialize; begin FDefaultColor.r := 0; FDefaultColor.g := 0; FDefaultColor.b := 0; FData := TRGBIntDataSet.Create; end; // Gets function T2DImageRGBIntData.GetData(_x, _y, _c: integer):integer; begin if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) and (_c >= 0) and (_c <= 2) then begin case (_c) of 0: Result := (FData as TRGBIntDataSet).Red[(_y * FXSize) + _x]; 1: Result := (FData as TRGBIntDataSet).Green[(_y * FXSize) + _x]; else begin Result := (FData as TRGBIntDataSet).Blue[(_y * FXSize) + _x]; end; end; end else begin case (_c) of 0: Result := FDefaultColor.r; 1: Result := FDefaultColor.g; else begin Result := FDefaultColor.b; end; end; end; end; function T2DImageRGBIntData.GetDefaultColor:TPixelRGBIntData; begin Result := FDefaultColor; end; function T2DImageRGBIntData.GetBitmapPixelColor(_Position: longword):longword; begin Result := RGB((FData as TRGBIntDataSet).Blue[_Position],(FData as TRGBIntDataSet).Green[_Position],(FData as TRGBIntDataSet).Red[_Position]); end; function T2DImageRGBIntData.GetRPixelColor(_Position: longword):byte; begin Result := (FData as TRGBIntDataSet).Red[_Position] and $FF; end; function T2DImageRGBIntData.GetGPixelColor(_Position: longword):byte; begin Result := (FData as TRGBIntDataSet).Green[_Position] and $FF; end; function T2DImageRGBIntData.GetBPixelColor(_Position: longword):byte; begin Result := (FData as TRGBIntDataSet).Blue[_Position] and $FF; end; function T2DImageRGBIntData.GetAPixelColor(_Position: longword):byte; begin Result := 0; end; function T2DImageRGBIntData.GetRedPixelColor(_x,_y: integer):single; begin Result := (FData as TRGBIntDataSet).Red[(_y * FXSize) + _x]; end; function T2DImageRGBIntData.GetGreenPixelColor(_x,_y: integer):single; begin Result := (FData as TRGBIntDataSet).Green[(_y * FXSize) + _x]; end; function T2DImageRGBIntData.GetBluePixelColor(_x,_y: integer):single; begin Result := (FData as TRGBIntDataSet).Blue[(_y * FXSize) + _x]; end; function T2DImageRGBIntData.GetAlphaPixelColor(_x,_y: integer):single; begin Result := 0; end; function T2DImageRGBIntData.GetOpenGLFormat:TGLInt; begin Result := GL_RGB; end; // Sets procedure T2DImageRGBIntData.SetBitmapPixelColor(_Position, _Color: longword); begin (FData as TRGBIntDataSet).Red[_Position] := GetRValue(_Color); (FData as TRGBIntDataSet).Green[_Position] := GetGValue(_Color); (FData as TRGBIntDataSet).Blue[_Position] := GetBValue(_Color); end; procedure T2DImageRGBIntData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); begin (FData as TRGBIntDataSet).Red[_Position] := _r; (FData as TRGBIntDataSet).Green[_Position] := _g; (FData as TRGBIntDataSet).Blue[_Position] := _b; end; procedure T2DImageRGBIntData.SetRedPixelColor(_x,_y: integer; _value:single); begin (FData as TRGBIntDataSet).Red[(_y * FXSize) + _x] := Round(_value); end; procedure T2DImageRGBIntData.SetGreenPixelColor(_x,_y: integer; _value:single); begin (FData as TRGBIntDataSet).Green[(_y * FXSize) + _x] := Round(_value); end; procedure T2DImageRGBIntData.SetBluePixelColor(_x,_y: integer; _value:single); begin (FData as TRGBIntDataSet).Blue[(_y * FXSize) + _x] := Round(_value); end; procedure T2DImageRGBIntData.SetAlphaPixelColor(_x,_y: integer; _value:single); begin // do nothing end; procedure T2DImageRGBIntData.SetData(_x, _y, _c: integer; _value: integer); begin if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) and (_c >= 0) and (_c <= 2) then begin case (_c) of 0: (FData as TRGBIntDataSet).Red[(_y * FXSize) + _x] := _value; 1: (FData as TRGBIntDataSet).Green[(_y * FXSize) + _x] := _value; 2: (FData as TRGBIntDataSet).Blue[(_y * FXSize) + _x] := _value; end; end; end; procedure T2DImageRGBIntData.SetDefaultColor(_value: TPixelRGBIntData); begin FDefaultColor.r := _value.r; FDefaultColor.g := _value.g; FDefaultColor.b := _value.b; end; // Copies procedure T2DImageRGBIntData.Assign(const _Source: TAbstract2DImageData); begin inherited Assign(_Source); FDefaultColor.r := (_Source as T2DImageRGBIntData).FDefaultColor.r; FDefaultColor.g := (_Source as T2DImageRGBIntData).FDefaultColor.g; FDefaultColor.b := (_Source as T2DImageRGBIntData).FDefaultColor.b; end; // Misc procedure T2DImageRGBIntData.ScaleBy(_Value: single); var x,maxx: integer; begin maxx := (FXSize * FYSize) - 1; for x := 0 to maxx do begin (FData as TRGBIntDataSet).Red[x] := Round((FData as TRGBIntDataSet).Red[x] * _Value); (FData as TRGBIntDataSet).Green[x] := Round((FData as TRGBIntDataSet).Green[x] * _Value); (FData as TRGBIntDataSet).Blue[x] := Round((FData as TRGBIntDataSet).Blue[x] * _Value); end; end; procedure T2DImageRGBIntData.Invert; var x,maxx: integer; begin maxx := (FXSize * FYSize) - 1; for x := 0 to maxx do begin (FData as TRGBIntDataSet).Red[x] := 255 - (FData as TRGBIntDataSet).Red[x]; (FData as TRGBIntDataSet).Green[x] := 255 - (FData as TRGBIntDataSet).Green[x]; (FData as TRGBIntDataSet).Blue[x] := 255 - (FData as TRGBIntDataSet).Blue[x]; end; end; end.
{----------------------------------------------------------------------------- Unit Name: D2DSVGHandler Author: PyScripter Purpose: High-level encapsuation of Direct2D Svg functionality History: -----------------------------------------------------------------------------} unit PasSVGFactory; interface Uses Winapi.D2D1, SVGInterfaces; // Factory Methods function GetPasSVGFactory: ISVGFactory; implementation Uses Winapi.Windows, Winapi.Messages, Winapi.GDIPAPI, System.Types, System.UIConsts, System.UITypes, System.SysUtils, System.Classes, SvgTypes, SvgCommon, Svg; type TPasSVG = class(TInterfacedObject, ISVG) private fSvgDoc: TSVG; // property access methods function GetWidth: Single; function GetHeight: Single; function GetOpacity: Single; procedure SetOpacity(const Opacity: Single); function GetGrayScale: Boolean; procedure SetGrayScale(const IsGrayScale: Boolean); function GetFixedColor: TColor; procedure SetFixedColor(const Color: TColor); function GetSource: string; procedure SetSource(const ASource: string); // procedures and functions function IsEmpty: Boolean; procedure Clear; procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: string); procedure LoadFromStream(Stream: TStream); procedure LoadFromFile(const FileName: string); procedure PaintTo(DC: HDC; R: TRectF; KeepAspectRatio: Boolean = True); public constructor Create; destructor Destroy; override; end; TPasSVGFactory = class(TInterfacedObject, ISVGFactory) function NewSvg: ISVG; end; { TPasSVG } procedure TPasSVG.Clear; begin fSvgDoc.Clear; end; constructor TPasSVG.Create; begin inherited; fSvgDoc := TSVG.Create; end; procedure TPasSVG.LoadFromFile(const FileName: string); begin fSvgDoc.LoadFromFile(FileName); end; destructor TPasSVG.Destroy; begin fSvgDoc.Free; inherited; end; function TPasSVG.GetFixedColor: TColor; begin Result := fSvgDoc.FixedColor; end; function TPasSVG.GetGrayScale: Boolean; begin Result := fSvgDoc.GrayScale; end; function TPasSVG.GetHeight: Single; begin Result := fSvgDoc.Height; end; function TPasSVG.GetOpacity: Single; // ReadOnly property begin Result := 1; end; function TPasSVG.GetSource: string; begin Result := fSvgDoc.Source; end; function TPasSVG.GetWidth: Single; begin Result := fSvgDoc.Width; end; function TPasSVG.IsEmpty: Boolean; begin Result := fSvgDoc.Count = 0; end; procedure TPasSVG.LoadFromStream(Stream: TStream); begin fSvgDoc.LoadFromStream(Stream); end; function FitInto(const Source : TRectF; const ADesignatedArea: TRectF; out Ratio: Single): TRectF;overload; begin if (ADesignatedArea.Width <= 0) or (ADesignatedArea.Height <= 0) then begin Ratio := 1; Exit(Source); end; if (Source.Width / ADesignatedArea.Width) > (Source.Height / ADesignatedArea.Height) then Ratio := Source.Width / ADesignatedArea.Width else Ratio := Source.Height / ADesignatedArea.Height; if Ratio = 0 then Exit(Source) else begin Result := TRectF.Create(0, 0, Source.Width / Ratio, Source.Height / Ratio); RectCenter(Result, ADesignatedArea); end; end; function FitInto(const Source : TRectF; const ADesignatedArea: TRectF): TRectF;overload; var ratio : Single; begin result := FitInto(Source, ADesignatedArea, ratio); end; procedure TPasSVG.PaintTo(DC: HDC; R: TRectF; KeepAspectRatio: Boolean); var SvgRect : TRectF; begin SvgRect:= R; if (fSvgDoc.Width > 0) and (fSvgDoc.Height > 0) and KeepAspectRatio then begin SvgRect := TRectF.Create(0, 0, fSvgDoc.Width, fSvgDoc.Height); SvgRect := FitInto(SvgRect, R); end; fSvgDoc.PaintTo(DC, ToGPRectF(SvgRect), nil, 0); end; procedure TPasSVG.SaveToFile(const FileName: string); begin fSvgDoc.SaveToFile(FileName); end; procedure TPasSVG.SaveToStream(Stream: TStream); begin fSvgDoc.SaveToStream(Stream); end; procedure TPasSVG.SetFixedColor(const Color: TColor); begin if Color < 0 then fSvgDoc.FixedColor := GetSysColor(Color and $000000FF) else fSvgDoc.FixedColor := Color; end; procedure TPasSVG.SetGrayScale(const IsGrayScale: Boolean); begin fSvgDoc.GrayScale := IsGrayScale; end; procedure TPasSVG.SetOpacity(const Opacity: Single); begin fSvgDoc.SVGOpacity := Opacity; end; procedure TPasSVG.SetSource(const ASource: string); begin fSvgDoc.LoadFromText(ASource); end; { TPasSVGHandler } function TPasSVGFactory.NewSvg: ISVG; begin Result := TPasSVG.Create; end; // Factory methods function GetPasSVGFactory: ISVGFactory; begin Result := TPasSVGFactory.Create; end; end.
unit pasmysql; {$IFDEF FPC} {$MODE Delphi} {$H+} {$ELSE} {$IFNDEF LINUX} {$DEFINE WIN32} {$ENDIF} {$ENDIF} interface uses {$IFDEF WIN32} Windows, {$ENDIF} Classes, SysUtils, libmysql, passql, sqlsupport; //This library is compliant with arbitrary //versions of libmysql.dll and libmysqld.dll //////////////////////////////////////////////// // // // TMyDB component by rene@dubaron.com // // TMyDB is a MySQL specific interface // // Nom part of libsql library // // // //////////////////////////////////////////////// // by R.M. Tegel rene@dubaron.com const MY_DEFAULT_PORT=3306; type TMyVersion = (mvUnknown, mv3_23, mv4_0, mv4_1, mv5_0); TMyDB = class (TSQLDB) private function GetHasResult: Boolean; procedure SetEmbedded(const Value: Boolean); protected MyHandle:MySQL; PMyHandle:PMySQL; FLibrary:String; FHostInfo:String; FInfo:String; FRealConnect:Boolean; FUnixSock:String; FConnectOptions:Integer; FEmbedded: Boolean; FMyVersion: TMyVersion; mf: TMySQLFunctions; //short name, less typing.. procedure StoreResult(Res: PMYSQL_RES); procedure FillDBInfo; override; function MapDataType (_datatype: Integer): TSQLDataTypes; procedure FillFieldInfo (Res: PMYSQL_RES); public FClientVersion: String; //holds version info of libmysql.dll constructor Create (AOwner:TComponent); override; destructor Destroy; override; function Query (SQL:String):Boolean; override; function Connect (Host, User, Pass:String; DataBase:String=''):Boolean; override; procedure Close; override; function ExplainTable (Table:String): Boolean; override; function ShowCreateTable (Table:String): Boolean; override; function DumpTable (Table:String): Boolean; override; function DumpDatabase (Table:String): Boolean; override; //typical MySQL functions: function SelectDatabase(Database:String):Boolean; // function GetSelectedDatabase:String; procedure SetDatabase(Value:String); override; function CreateDatabase(Database:String):Boolean; virtual; function DropDatabase(Database:String):Boolean; procedure ListDatabases(wildcard:String=''); procedure ListTables(wildcard:String=''); procedure ListFields(table:String; wildcard:String=''); procedure ListProcesses; function ShutDown:Boolean; function Kill (Pid:Integer):Boolean; //Kill specific process procedure SetPort (Port:Integer); override; procedure SetRealConnect(DoRealConnect:Boolean); function Ping:Boolean; //See if server is alive function GetLastError:String; function GetServerInfo:String; function ShowTables: Boolean; override; function Flush (Option:String): Boolean; override; function TruncateTable (Table:String): Boolean; override; function LockTables (Statement:String): Boolean; override; function UnLockTables: Boolean; override; function Vacuum: Boolean; override; function Execute (SQL: String): THandle; override; function FetchRow (Handle: THandle; var row: TResultRow): Boolean; override; procedure FreeResult (Handle: THandle); override; property DBHandle:MySQL read MyHandle; //Actual libmysql.dll / mysqlclient.so handle, use it if you want to call functions yourself property HasResult:Boolean read GetHasResult;// write FHasResult; //Queryhas valid result set property ServerInfo:String read GetServerInfo; //additional server info property Info:String read FInfo; property HostInfo:String read FHostInfo; property UnixSock:String read FUnixSock write FUnixSock; published property Embedded: Boolean read FEmbedded write SetEmbedded; property RealConnect:Boolean read FRealConnect write SetRealConnect; property ClientVersion: String read FClientVersion write FDummyString; end; implementation //TMyDB has a constructor. Set some variabels to default, nothing more... constructor TMyDB.Create; begin FLibrary:=DEFAULT_DLL_LOCATION; {$IFDEF WIN32} DLL:=FLibrary; {$ENDIF} FHost:='localhost'; FPort:=MY_DEFAULT_PORT; FActive:=False; FActivateOnLoad:=False; FRealConnect:=False; FConnectOptions:=_CLIENT_COMPRESS or _CLIENT_CONNECT_WITH_DB; FDataBaseType := dbMySQL; PrimaryKey := 'auto_increment primary key'; inherited Create(AOwner); end; destructor TMyDB.Destroy; begin if Active then Close; inherited Destroy; end; procedure TMyDB.Close; begin if FActive then try mf.mysql_close(@MyHandle); { if Assigned (mf.mysql_thread_end) then //embedded mysql begin //don't.. probably mysql_thread_start also returned false. // mf.mysql_thread_end; // mf.mysql_server_end; end; } if Assigned(FOnClose) then FOnClose(Self); except // raise Exception.Create('An error occured while closing'); end; FActive:=False; end; function TMyDB.Connect(Host, User, Pass:String; DataBase:String):Boolean; var AHandle:PMySQL; begin Result := False; //Close if already active if FActive then Close; { $IFDEF WIN32} //Allow user to change shared library if FLibrary<>'' then DLL_Client:=FLibrary; {$IFDEF WIN32} //Embedded mysql 4.1 will definitively not work without config file. if FEmbedded and not fileexists ('c:\my.cnf') then //for some reason or another, %sysdir%\mysql.ini is not sufficient begin FCurrentSet.FLastError := -1; FCurrentSet.FLastErrorText := 'File c:\my.cnf does not exist'; exit; end; {$ENDIF} FDllLoaded := MySQLLoadLib (mf, FLibraryPath, FEmbedded); if not FDllLoaded then exit; //Succesfully loaded if assigned(mf.mysql_thread_init) then begin if FEmbedded then FActive := mf.mysql_thread_init = 0 else begin mf.mysql_thread_init; //call anyway. FActive := True; end; end else FActive := True; if not FActive then exit; if Assigned (mf.mysql_get_client_info) then FClientVersion := mf.mysql_get_client_info; FMyVersion := mvUnknown; if pos ('3.23.', FClientVersion)>0 then FMyVersion := mv3_23; if pos ('4.0.', FClientVersion)>0 then FMyVersion := mv4_0; if pos ('4.1.', FClientVersion)>0 then FMyVersion := mv4_1; if pos ('5.0.', FCLientVersion)>0 then FMyVersion := mv5_0; if FEmbedded then //some extra actions if embedded begin if Assigned (mf.mysql_server_init) then Result := 0 = mf.mysql_server_init (3, @DEFAULT_PARAMS, @SERVER_GROUPS) else exit; end else //libmysql client init: begin if assigned(mf.mysql_init) then PMyHandle := mf.mysql_init(@MyHandle) else exit; end; FDataBase := DataBase; PMyHandle := @MyHandle; if FEmbedded and (FDatabase='') then exit; //no database selected yet. if FEmbedded then //the 'dummy' connect proc begin if Assigned (mf.mysql_connect) then begin mf.mysql_connect (@MyHandle, nil, nil, nil); end else if Assigned (mf.mysql_real_connect) then mf.mysql_real_connect (@MyHandle, nil, nil, nil, PChar(String(FDataBase)), 0, nil, 0); if FActive and (FDataBase<>'') then mf.mysql_select_db(PMyHandle, PChar(FDataBase)); end else //connect to our database server begin //Enable realconnect by default, not overridable... FRealConnect := True; if FRealConnect then try PMyHandle:= mf.mysql_real_connect(@MyHandle, PChar(String(Host)), PChar(String(User)), PChar(String(Pass)), PChar(String(FDataBase)), FPort, nil {PChar(String(FUnixSock))}, Integer(CLIENT_COMPRESS){ FConnectOptions}); FActive := PMyHandle<>nil; if not FActive then begin FCurrentSet.FLastErrorText := mf.mysql_error (@MyHandle); if pos(#0, FCurrentSet.FLastErrorText)>0 then //probably is FCurrentSet.FLastErrorText := copy (FCurrentSet.FLastErrorText, 1, pos(#0, FCurrentSet.FLastErrorText)-1); FCurrentSet.FLastError := mf.mysql_errno(@MyHandle); LogError; end else FCurrentSet.FLastError := 0; except FActive:=False; end else begin AHandle{PMyHandle}:=mf.mysql_connect(@MyHandle, PChar(Host), PChar(User), PChar(Pass)); FActive := AHandle<>nil; //Select database if assigned: if FActive and (FDataBase<>'') then mf.mysql_select_db(@MyHandle, PChar(FDataBase)); end; end; PMyHandle := @MyHandle; Result := FActive; if FActive and not (csDesigning in ComponentState) then begin //Fill in some variables: if Assigned (mf.mysql_get_server_info) then FVersion := mf.mysql_get_server_info (PMyHandle); if Assigned (mf.mysql_character_set_name) then FEncoding := mf.mysql_character_set_name(PMyHandle); if Assigned (mf.mysql_get_host_info) then FHostInfo := mf.mysql_get_host_info (PMyHandle); if Assigned (mf.mysql_get_proto_info) then FInfo := IntToStr (mf.mysql_get_proto_info (PMyHandle)); end; if FActive then FillDBInfo; if FActive and Assigned(FOnOpen) then FOnOpen(Self); end; //An active property was added to allow //database-access in development state ;) //Quite direct MySQL functions: function TMyDB.CreateDatabase(Database:String):Boolean; begin if FActive{ and assigned (mf.mysql_create_db) }then Result := FormatQuery ('create database %u', [DataBase]) //(0=mf.mysql_create_db(@MyHandle, PChar(Database))) else Result := False; end; function TMyDB.DropDatabase(Database:String):Boolean; begin if FActive and assigned (mf.mysql_drop_db) then Result := (0=mf.mysql_drop_db(@MyHandle, PChar(Database))) else Result := False; if Result and (lowercase(FDataBase) = lowercase(DataBase)) then FDatabase:=''; end; function TMyDB.SelectDatabase(Database:String):Boolean; begin if FActive and assigned (mf.mysql_select_db) then Result := (0 = mf.mysql_select_db(@MyHandle, PChar(Database))) else Result := False; if Result then FDatabase:=Database; end; function TMyDB.Kill(Pid:Integer):Boolean; begin if FActive and assigned (mf.mysql_kill) then Result := (0=mf.mysql_kill(@MyHandle, Pid)) else Result := False; end; function TMyDB.Ping: Boolean; begin Result:=False; if FActive and assigned (mf.mysql_ping) then Result:=(mf.mysql_ping(@MyHandle)<>0); end; function TMyDB.ShutDown: Boolean; begin if FActive then Result := (0=mf.mysql_shutdown(@MyHandle)) else Result := False; end; //This is where the results from a query are stored in delphi string-arrays procedure TMyDB.StoreResult; //Loop all rows from a result set and put fields in 2D-array var i, j, ri: Integer; // myrow: mysql_row; pmyrow: pmysql_row; //fields: Pmysql_fields; R: TResultRow; begin with FCurrentSet do begin FHasResult:=False; if Res<>nil then begin FHasResult:=True; //reset memory usage counter FQuerySize := 0; FRowCount := mf.mysql_num_rows(res); //res^.row_count; for i:=0 to FRowCount - 1 do begin if FCallBackOnly then ri:=0 //only 1 row needed else begin ri := i; //Check ranges; break if rowlimit or memory limit reached: if ((FFetchRowLimit<>0) and ((i+1)>=FFetchRowLimit)) or ((FFetchMemoryLimit<>0) and (FQuerySize>=FFetchMemoryLimit)) then break; //mem limit exceeded... end; //Fetch a row: //myrow:=mf.mysql_fetch_row(res)^; pmyrow:=mf.mysql_fetch_row(res); if ri<FRowList.Count then begin R := TResultRow(FRowList[ri]); R.Clear; R.FNulls.Clear; end else begin R := TResultRow.Create; R.FFields := FFields; //copy pointer to ffields array FRowList.Add(R); end; for j:=0 to mf.mysql_num_fields(res) - 1 do begin if Assigned (pmyrow^[j]) then R.Add(pmyrow^[j]) else R.Add(''); R.FNulls.Add(Pointer(Integer(pmyrow^[j]<>nil))); inc (FQuerySize, length(String(pmyrow^[j]))); end; if Assigned (FOnFetchRow) then try FOnFetchRow (Self, R); except end; end; FillFieldInfo (Res); //Some more vars: FColCount := mf.mysql_num_fields(res); mf.mysql_free_result(res); FHasResult:=True; if Assigned (FOnSuccess) then try FOnSuccess(Self); except end; if Assigned (FOnQueryComplete) then try FOnQueryComplete(Self); except end; end else //May be invalid result or just no result begin //Result = nil; Clear; // FLastInsertID := -1; // FRowsAffected := -1; FLastErrorText := mf.mysql_error(@MyHandle); FLastError := mf.mysql_errno(@MyHandle); if (FLastError<>0) and (Assigned (OnError)) then OnError (Self); // 8-12-2007 JGB TOEGEVOEGD ****************************************** if FLastError = 0 then begin if Assigned (FOnSuccess) then try FOnSuccess(Self); except end; if Assigned (FOnQueryComplete) then try FOnQueryComplete(Self); except end; end; //******************************************************************** end; //those can also be set on empty result sets: FLastInsertID := mf.mysql_insert_id (@MyHandle); FRowsAffected := mf.mysql_affected_rows (@MyHandle); end; end; //This is the main function to perform a query: function TMyDB.Query (SQL: String): Boolean; begin Result := False; if not FActive then SetActive(True); //Try once if client just performs query Clear; with FCurrentSet do begin FHasResult := False; if not FActive then exit; //sorry... nothing to do here, handle is invalid. if SQL='' then //clear the results: begin StoreResult (nil); //FCurrentSet.Clear; exit; end; if FActive then begin //Allow user to view or edit query: FSQL:=SQL; if Assigned (FOnBeforeQuery) then FOnBeforeQuery(Self, FSQL); SQL:=FSQL; //Perform actual query: if 0=mf.mysql_query(@MyHandle, PChar(SQL)) then //seems noor version of libmysql //returns on, even on failure (...) begin StoreResult(mf.mysql_store_result(@MyHandle)); FLastError := mf.mysql_errno(@MyHandle); Result := FLastError=0; FLastErrorText := ''; FHasResult := True; end else begin //StoreResult is able to handle errors and will call OnError as well //Calling it with nill forces a result cleanup: StoreResult(nil); FLastErrorText := mf.mysql_error(@MyHandle); //MyHandle._net.last_error; if pos(#0, FLastErrorText)>0 then //probably is FLastErrorText := copy (FLastErrorText, 1, pos(#0, FLastErrorText)-1); FLastError := mf.mysql_errno(@MyHandle); //MyHandle._net.last_errno; //if Assigned (FOnError) then // FOnError(Self); LogError; end; end; end; end; //Common libmysql / libmysqlclient functions: procedure TMyDB.ListDatabases; begin if FActive then StoreResult(mf.mysql_list_dbs(@MyHandle, PChar(wildcard))); end; procedure TMyDB.ListTables; begin if FActive then StoreResult(mf.mysql_list_tables(@MyHandle, PChar(wildcard))); end; procedure TMyDB.ListProcesses; begin if FActive then StoreResult(mf.mysql_list_processes(@MyHandle)); end; procedure TMyDB.ListFields; begin if FActive then StoreResult(mf.mysql_list_fields(@MyHandle, PChar(table), PChar(wildcard))); end; function TMyDB.GetServerInfo: String; begin if FActive then Result:=mf.mysql_get_server_info(@MyHandle) else Result:='Inactive'; end; function TMyDB.GetLastError: String; begin Result := FCurrentSet.FLastErrorText; end; //TMyDB control functions: procedure TMyDB.SetPort; begin if (Port<=0) or (Port>65535) then //Simply don't accept value exit; if Port<>MY_DEFAULT_PORT then //Force real connect: FRealConnect:=True; FPort:=Port; end; procedure TMyDB.SetRealConnect; begin if not DoRealConnect then //Only connect to default port: FPort:=MY_DEFAULT_PORT; FRealConnect:=DoRealConnect; end; procedure TMyDB.SetDatabase; begin if FActive then begin if SelectDataBase(Value) then FDataBase :=Value; end else FDataBase := Value; end; function TMyDB.DumpDatabase(Table: String): Boolean; begin Result := False; end; function TMyDB.DumpTable(Table: String): Boolean; begin Result := False; end; function TMyDB.ExplainTable(Table: String): Boolean; begin Result := FormatQuery ('explain table %q', [Table]); end; function TMyDB.ShowCreateTable(Table: String): Boolean; begin Result := False; end; function TMyDB.GetHasResult: Boolean; begin Result := FCurrentSet.FHasResult; end; procedure TMyDB.SetEmbedded(const Value: Boolean); begin FEmbedded := Value; if FEmbedded then FLibrary := MYSQLD_DLL_LOCATION else FLibrary := DEFAULT_DLL_LOCATION; end; procedure TMyDB.FillDBInfo; begin inherited; //clears tables and indexes ShowTables; Tables := GetColumnAsStrings (0); //list indexes //Query ('SHOW INDEXES'); Query(''); //this returns a lot more than index name (* SHOW INDEX returns the index information in a format that closely resembles the SQLStatistics call in ODBC. The following columns are returned: Column Meaning Table Name of the table. Non_unique 0 if the index can't contain duplicates. Key_name Name of the index. Seq_in_index Column sequence number in index, starting with 1. Column_name Column name. Collation How the column is sorted in the index. In MySQL, this can have values `A' (Ascending) or NULL (Not sorted). Cardinality Number of unique values in the index. This is updated by running isamchk -a. Sub_part Number of indexed characters if the column is only partly indexed. NULL if the entire key is indexed. Comment Various remarks. For now, it tells whether index is FULLTEXT or not. *) Indexes := GetColumnAsStrings (2); end; function TMyDB.ShowTables: Boolean; begin // mf.mysql_list_tables Result := Query ('SHOW TABLES'); end; function TMyDB.Flush (Option:String): Boolean; begin Result := Query ('FLUSH '+Option); end; function TMyDB.TruncateTable (Table:String): Boolean; begin Result := Query ('TRUNCATE TABLE '+Table); end; function TMyDB.LockTables (Statement:String): Boolean; begin Result := Query ('LOCK TABLES '+Statement); end; function TMyDB.UnLockTables: Boolean; begin Result := Query ('UNLOCK TABLES'); end; function TMyDB.Vacuum: Boolean; begin Result := false; end; function TMyDB.MapDataType(_datatype: Integer): TSQLDataTypes; begin case _datatype of FIELD_TYPE_DECIMAL, FIELD_TYPE_TINY, FIELD_TYPE_SHORT, FIELD_TYPE_LONG : Result := dtInteger; FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE: Result := dtFloat; FIELD_TYPE_NULL: Result := dtNull; FIELD_TYPE_TIMESTAMP: Result := dtTimeStamp; FIELD_TYPE_LONGLONG: Result := dtInt64; FIELD_TYPE_INT24: Result := dtInteger; FIELD_TYPE_DATE, FIELD_TYPE_TIME, FIELD_TYPE_DATETIME: Result := dtDateTime; FIELD_TYPE_YEAR: Result := dtInteger; FIELD_TYPE_NEWDATE: Result := dtDateTime; FIELD_TYPE_ENUM, FIELD_TYPE_SET: Result := dtOther; FIELD_TYPE_TINY_BLOB, FIELD_TYPE_MEDIUM_BLOB, FIELD_TYPE_LONG_BLOB, FIELD_TYPE_BLOB: Result := dtBlob; FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING: Result := dtString; FIELD_TYPE_GEOMETRY: Result := dtOther; else Result := dtUnknown; end; end; function TMyDB.Execute(SQL: String): THandle; begin Result := 0; if not FDllLoaded then exit; if 0=mf.mysql_query(@MyHandle, PChar(SQL)) then begin Result := Integer (mf.mysql_store_result(@MyHandle)); UseResultSet (Result); FCurrentSet.Clear; if Result <> 0 then begin FillFieldInfo (PMYSQL_RES(Result)); FCurrentSet.FColCount := mf.mysql_num_fields(PMYSQL_RES(Result)); end; end; end; function TMyDB.FetchRow(Handle: THandle; var row: TResultRow): Boolean; var //myrow: mysql_row; pmyrow: PMysql_row; j: Integer; begin Result := False; if not FDllLoaded or (Handle = 0) then exit; UseResultSet (Handle); row := FCurrentSet.FNilRow; pmyrow:=mf.mysql_fetch_row(PMYSQL_RES(Handle)); if not Assigned (pmyrow) then exit; //bug fix by paul di aggio //myrow := pmyrow^; FCurrentSet.FCurrentRow.Clear; for j:=0 to mf.mysql_num_fields(PMYSQL_RES(Handle)) - 1 do begin if Assigned (pmyrow^[j]) then FCurrentSet.FCurrentRow.Add(pmyrow^[j]) else FCurrentSet.FCurrentRow.Add(''); FCurrentSet.FCurrentRow.FNulls.Add(Pointer(Integer(pmyrow^[j]<>nil))); end; row := FCurrentSet.FCurrentRow; Result := True; end; procedure TMyDB.FreeResult(Handle: THandle); begin if not FDllLoaded or (Handle = 0) then exit; mf.mysql_free_result(PMYSQL_RES(Handle)); DeleteResultSet (Handle); end; procedure TMyDB.FillFieldInfo(Res: PMYSQL_RES); var i: Integer; Field: PMysql_field; FieldDesc: TFieldDesc; begin with FCurrentSet do begin for i:=0 to mf.mysql_num_fields(res)-1 do begin Field := mf.mysql_fetch_field(res); if not Assigned (Field) then continue; FieldDesc := TFieldDesc.Create; FFields.AddObject(field.Name, FieldDesc); with FieldDesc do begin //Copy data mainly for PChar/String converting //Makes field info available after resource handle is closed! //assume field.name is always at same (1st) position: name:=field.name; case FMyVersion of mv3_23: begin def:=PMysql_field_32(field).def; table:=PMysql_field_32(field).table; _datatype:=PMysql_field_32(field).enum_field_type; max_length:=PMysql_field_32(field).max_length; flags:=PMysql_field_32(field).flags; decimals:=PMysql_field_32(field).decimals; end; mv4_0: begin def:=PMysql_field_40(field).def; table:=PMysql_field_40(field).table; _datatype:=PMysql_field_40(field).enum_field_type; max_length:=PMysql_field_40(field).max_length; flags:=PMysql_field_40(field).flags; decimals:=PMysql_field_40(field).decimals; end; mv4_1, mv5_0: begin def:=PMysql_field_50(field).def; table:=PMysql_field_50(field).table; _datatype:=PMysql_field_50(field).enum_field_type; max_length:=PMysql_field_50(field).max_length; flags:=PMysql_field_50(field).flags; decimals:=PMysql_field_50(field).decimals; end; end; //map mysql flags to some properties //just hope this is compatible across all mysql versions //afaik this is 4.1 (3.2 compatible) flag specification IsNullable := 0 <> (Flags and NOT_NULL_FLAG); IsPrimaryKey := 0 <> (Flags and PRI_KEY_FLAG); IsUnique := 0 <> (Flags and UNIQUE_KEY_FLAG); IsKey := 0 <> (Flags and MULTIPLE_KEY_FLAG); IsBlob := 0 <> (Flags and BLOB_FLAG); IsUnsigned := 0 <> (Flags and UNSIGNED_FLAG); IsAutoIncrement := 0 <> (Flags and AUTO_INCREMENT_FLAG); IsNumeric := 0 <> (Flags and NUM_FLAG); (* non mapped flags: ZEROFILL_FLAG { Field is zerofill } BINARY_FLAG { Field is binary } ENUM_FLAG { Field is an enum } TIMESTAMP_FLAG { Field is a timestamp } SET_FLAG { Field is a set } *) end; end; end; end; end.
unit uDM; interface uses {Windows,} Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBTables, WinTypes, WinProcs, Grids, DBGrids, IBCustomDataSet, jvProgressDlg, IBQuery, IBDatabase, uGTSUICommonDlg; type TDBType = (dbtPOS, dbtStore); type TDM = class(TForm) dbPOS: TIBDatabase; qrView: TIBQuery; qryTransaction: TIBQuery; qryTransactionInsProdAlias: TIBQuery; qryTransactionInsert: TIBQuery; qryTransactionView: TIBQuery; IBQuery: TIBQuery; dbStore: TIBDatabase; transPOS: TIBTransaction; transStore: TIBTransaction; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; procedure cCommitTrans(ADBType: TDBType = dbtPOS); procedure cRollbackTrans(ADBType: TDBType = dbtPOS); function cOpenQuery(ASQL: String; ADBType: TDBType = dbtPOS): TIBQuery; function cExecSQL(ASQL: String; ADBType: TDBType = dbtPOS; ALangsungCommit: Boolean = False): boolean; overload; function cExecSQLSelfCommit(ASQL: String; ADBType: TDBType = dbtPOS): boolean; function cExecSQL(ASQLs : TStrings; ADBType: TDBType = dbtPOS; ALangsungCommint: Boolean = False; ACaption : String = 'Execute SQL'): Boolean; overload; procedure StepProgress(AJVProgress : TJvProgressDlg; ACaption : String); function GetDataByDataField(AField: TField): string; var DM: TDM; IsStoreConnected : Boolean; IsPOSConnected : Boolean; implementation uses ufrmMain, Windows; {$R *.DFM} procedure cCommitTrans(ADBType: TDBType = dbtPOS); begin if ADBType = dbtPOS then begin if DM.transPOS = nil then exit; if DM.transPOS.InTransaction then begin DM.transPOS.Commit; end; end else if ADBType = dbtStore then begin if DM.transStore = nil then exit; if DM.transStore.InTransaction then begin DM.transStore.Commit; end; end; end; procedure cRollbackTrans(ADBType: TDBType = dbtPOS); begin if ADBType = dbtPOS then begin if DM.transPOS = nil then exit; if DM.transPOS.InTransaction then begin DM.transPOS.Rollback; end; end else if ADBType = dbtStore then begin if DM.transStore = nil then exit; if DM.transStore.InTransaction then begin DM.transStore.Rollback; end; end; end; function cOpenQuery(ASQL: String; ADBType: TDBType = dbtPOS): TIBQuery; var saveCursor: TCursor; begin Result := TIBQuery.Create(Application); if ADBType = dbtPOS then begin Result.Database := DM.dbPOS; Result.Transaction := DM.transPOS; end else if ADBType = dbtStore then begin Result.Database := DM.dbStore; Result.Transaction := DM.transStore; end; Result.SQL.Clear; Result.SQL.Add(ASQL); Application.ProcessMessages; try saveCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try Result.Open; finally Screen.Cursor := saveCursor; end; // try/finally Application.ProcessMessages; except FreeAndNil(Result); raise; end; end; function cExecSQLSelfCommit(ASQL: String; ADBType: TDBType = dbtPOS): boolean; var saveCursor: TCursor; lIBTransaction: TIBTransaction; Query1 : TIBQuery; begin Result := False; saveCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try if UpperCase(Copy(Trim(ASQL),1,6)) = 'SELECT' then begin Exit; end; lIBTransaction := TIBTransaction.Create(Application); with lIBTransaction do begin if ADBType = dbtPOS then AddDatabase(DM.dbPOS) else if ADBType = dbtStore then AddDatabase(DM.dbStore); Params.Clear; Params.Append('read_committed'); Params.Append('rec_version'); Params.Append('nowait'); end; // with Query1 := TIBQuery.Create(Application); Application.ProcessMessages; if ADBType = dbtPOS then begin Query1.Database := DM.dbPOS; end else if ADBType = dbtStore then begin Query1.Database := DM.dbStore; end; Query1.Transaction := lIBTransaction; Query1.Params.Clear; Query1.ParamCheck := true; Query1.SQL.Clear; query1.SQL.Text := ASQL; try Application.ProcessMessages; if not lIBTransaction.InTransaction then begin lIBTransaction.StartTransaction; end; Query1.ExecSQL; lIBTransaction.Commit; Result := True; except lIBTransaction.Rollback; //raise; end; finally Screen.Cursor := saveCursor; end; // try/finally FreeAndNil(Query1); FreeAndNil(lIBTransaction); end; //-----------cExecSQL Try------------------------------------------------// function cExecSQL(ASQL: String; ADBType: TDBType = dbtPOS; ALangsungCommit: Boolean = False): boolean; var saveCursor: TCursor; Query1 : TIBQuery; begin Result := False; saveCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try if UpperCase(Copy(ASQL,1,6)) = 'SELECT' then begin Exit; end; Query1 := TIBQuery.Create(Application); Application.ProcessMessages; if ADBType = dbtPOS then begin Query1.Database := DM.dbPOS; Query1.Transaction := DM.transPOS; end else if ADBType = dbtStore then begin Query1.Database := DM.dbStore; Query1.Transaction := DM.transStore; end; Query1.Params.Clear; Query1.ParamCheck := true; Query1.SQL.Clear; query1.SQL.Text := ASQL; try Application.ProcessMessages; if not Query1.Transaction.InTransaction then begin Query1.Transaction.StartTransaction; end; Query1.ExecSQL; if ALangsungCommit then begin cCommitTrans; end; Result := True; except cRollbackTrans; raise; end; FreeAndNil(Query1); finally Screen.Cursor := saveCursor; end; // try/finally end; function cExecSQL(ASQLs : TStrings; ADBType: TDBType = dbtPOS; ALangsungCommint: Boolean = False; ACaption : String = 'Execute SQL'): Boolean; var LjvProgressDlg: TJvProgressDlg; i: Integer; begin Result := False; LjvProgressDlg := TJvProgressDlg.Create(nil); try with LjvProgressDlg do begin Value := 0; Text := aCaption; Text := aCAption; Value := 0; Maximum := ASQLs.Count; Show; StartProgression; end; for i := 0 to ASQLs.count - 1 do begin if not cExecSQL(ASQLs[i], ADBType, ALangsungCommint) then begin LjvProgressDlg.Close; cRollbackTrans; Exit; end; Application.ProcessMessages; StepProgress(LjvProgressDlg, aCaption); end; finally LjvProgressDlg.Close; LjvProgressDlg.Free; end; Result := True; end; procedure StepProgress(AJVProgress : TJvProgressDlg; ACaption : String); begin AJVProgress.Value := AJVProgress.Value + 1; AJVProgress.Text := ACaption + ' (' + InTtOStr(AJVProgress.Value) + '/' + IntToStr(AJVProgress.Maximum) + ' )'; Application.ProcessMessages; end; function GetDataByDataField(AField: TField): string; begin Result := ''; case TFieldType(Ord(aField.DataType)) of ftBlob: begin if aField.AsString = '' then Result := 'null' else Result := aField.AsString; end; ftString: begin if aField.AsString ='' then Result :='null' //Put a default string else Result := aField.AsString; end; ftInteger, ftWord, ftSmallint: begin if aField.AsInteger > 0 then Result := IntToStr(aField.AsInteger) else Result := '0'; end; ftFloat, ftCurrency, ftBCD: begin if aField.AsFloat > 0 then Result := FloatToStr(aField.AsFloat) else Result := '0'; end; ftBoolean: begin if aField.Value then Result:= 'True' else Result:= 'False'; end; ftDate: begin if (not aField.IsNull) or (Length(aField.AsString) > 0) then Result := FormatDateTime('MM/DD/YYYY',aField.AsDateTime) else Result:= FormatDateTime('MM/DD/YYYY',Now); //put a valid default date end; ftDateTime: begin if (not aField.IsNull) or (Length(Trim(aField.AsString)) > 0) then Result := FormatDateTime('MM/DD/YYYY hh:nn:ss', aField.AsDateTime) else Result := FormatDateTime('MM/DD/YYYY hh:nn:ss', Now); //Put a valid default date and time end; ftTime: begin if (not aField.IsNull) or (Length(Trim(aField.AsString)) > 0) then Result := FormatDateTime('hh:nn:ss', aField.AsDateTime) else Result := FormatDateTime('hh:nn:ss', Now); //Put a valid default time end; end; end; procedure TDM.FormCreate(Sender: TObject); begin { with dbPOS do begin DatabaseName := frmMain.FIBServerPOS; Params.Clear; Params.Add('USER_NAME=' + frmMain.FIBUserPOS); Params.Add('PASSWORD=' + frmMain.FIBPasswordPOS); end; try dbPOS.Open; except end; } with dbStore do begin DatabaseName := frmMain.FIBServerStore; Params.Clear; Params.Add('USER_NAME=' + frmMain.FIBUserStore); Params.Add('PASSWORD=' + frmMain.FIBPasswordStore); end; try dbStore.Open; except end; IsStoreConnected := dbStore.Connected; IsPOSConnected := dbPOS.Connected; //CommonDlg.ShowMessage(BoolToStr(IsStoreConnected,True) + ' : ' + BoolToStr(IsPOSConnected,True)); end; end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvMemo, Vcl.StdCtrls; const DEMO_TITLE = 'FNC Core Utils - URL encoding/decoding'; DEMO_BUTTON = 'Execute'; type TFrmMain = class(TForm) btnExecute: TButton; txtLog: TAdvMemo; procedure btnExecuteClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure DoExecute; public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses System.JSON, TMSFNCUtils; procedure TFrmMain.btnExecuteClick(Sender: TObject); begin DoExecute; end; procedure TFrmMain.DoExecute; var LBase : String; LQuery: String; begin LBase := 'https://myapp.com/names?'; LQuery := '$filter=name eq ''Flick'''; txtLog.Lines.Add( 'Original: ' + LBase + LQuery ); LQuery := TTMSFNCUtils.URLEncode(LQuery); txtLog.Lines.Add( 'Encoded : ' + LBase + LQuery); LQuery := TTMSFNCUtils.URLDecode(LQuery); txtLog.Lines.Add( 'Decoded : ' + LBase + LQuery ); end; procedure TFrmMain.FormCreate(Sender: TObject); begin btnExecute.Caption := DEMO_BUTTON; self.Caption := DEMO_TITLE; txtLog.Lines.Clear; end; end.
unit uQueryInventory; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, Grids, DBGrids, DBCtrls, StdCtrls, Mask, LblEffct, ExtCtrls, DBTables, DB, Buttons, ComCtrls, ADODB, SuperComboADO, siComp, siLangRT, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, SubListPanel, mrBarCodeEdit, uFrmBarcodeSearch; type TQueryInventory = class(TFrmParent) dsModel: TDataSource; btDetail: TButton; Label6: TLabel; spHelp: TSpeedButton; pnlModel: TPanel; Label1: TLabel; scModel: TSuperComboADO; Label2: TLabel; DBEdit1: TDBEdit; Label3: TLabel; DBEdit2: TDBEdit; Label4: TLabel; DBEdit3: TDBEdit; pnlCostPrice: TPanel; lblCost: TLabel; btShowCost: TSpeedButton; EditCost: TDBEdit; Label5: TLabel; pglModel: TPageControl; tbsQty: TTabSheet; tbsBarCodes: TTabSheet; Panel4: TPanel; quShowBarcodes: TADOQuery; dsShowBarcodes: TDataSource; quShowBarcodesIDBarcode: TStringField; quShowBarcodesIDModel: TIntegerField; quShowBarcodesData: TDateTimeField; dxDBGrid1: TDBGrid; SubQty: TSubListPanel; tsPO: TTabSheet; SubPO: TSubListPanel; btnPicture: TSpeedButton; quModel: TADODataSet; quModelName: TStringField; quModelPeso: TBCDField; quModelDescription: TStringField; quModelCurrentCost: TBCDField; quModelVendorCost: TBCDField; quModelOtherCost: TBCDField; quModelFreightCost: TBCDField; quModelLastCost: TBCDField; quModelReplacementCost: TBCDField; quModelStoreSellingPrice: TBCDField; quModelInventoryPrice: TBCDField; quModelSellingPrice: TCurrencyField; edtBarcode: TmrBarCodeEdit; btnSearchDesc: TBitBtn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure scModelSelectItem(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure btDetailClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btShowCostClick(Sender: TObject); procedure spHelpClick(Sender: TObject); procedure btnPictureClick(Sender: TObject); procedure quModelCalcFields(DataSet: TDataSet); procedure edtBarcodeAfterSearchBarcode(Sender: TObject); procedure btnSearchDescClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private fFrmBarcodeSearch : TFrmBarcodeSearch; public { Public declarations } IsDetail : Boolean; end; implementation uses uPassword, uMsgBox, uDM, uMsgConstant, uDMGlobal, uFrmModelPicture, uSystemConst; {$R *.DFM} procedure TQueryInventory.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; quModel.Close; quShowBarcodes.Close; Action := caFree; end; procedure TQueryInventory.FormShow(Sender: TObject); begin inherited; btDetail.Visible := IsDetail; btShowCostClick(nil); pnlCostPrice.Visible := Password.HasFuncRight(2); //scModel.SetFocus; edtBarcode.SetFocus; end; procedure TQueryInventory.scModelSelectItem(Sender: TObject); begin inherited; if scModel.LookUpValue <> '' then begin if not(DM.ModelRestored(StrToInt(scModel.LookUpValue))) then begin edtBarcode.Text := ''; scModel.LookUpValue := ''; exit; end; with quModel do begin if Active then Close; Parameters.ParambyName('IDModel').Value := StrToInt(scModel.LookUpValue); Parameters.ParambyName('IDStore').Value := DM.fStore.ID; Open; end; SubQty.Param := 'IDModel='+scModel.LookUpValue+';'; SubPO.Param := 'IDModel='+scModel.LookUpValue+';ViewType=1;'; with quShowBarcodes do begin If Active then Close; Parameters.ParambyName('IDModel').Value := StrToInt(scModel.LookUpValue); Open; end; end; end; procedure TQueryInventory.btCloseClick(Sender: TObject); begin inherited; Close; end; procedure TQueryInventory.btDetailClick(Sender: TObject); begin inherited; scModel.CallUpdate; end; procedure TQueryInventory.FormCreate(Sender: TObject); begin inherited; IsDetail := False; SubQty.CreateSubList; SubPO.CreateSubList; DM.imgSmall.GetBitmap(BTN18_CAMERA, btnPicture.Glyph); DM.imgSmall.GetBitmap(BTN18_LAMP, btShowCost.Glyph); DM.imgSmall.GetBitmap(BTN18_SEARCH, btnSearchDesc.Glyph); edtBarcode.CheckBarcodeDigit := DM.fSystem.SrvParam[PARAM_REMOVE_BARCODE_DIGIT]; edtBarcode.MinimalDigits := DM.fSystem.SrvParam[PARAM_MIN_BARCODE_LENGTH]; edtBarcode.RunSecondSQL := DM.fSystem.SrvParam[PARAM_SEARCH_MODEL_AFTER_BARCODE]; fFrmBarcodeSearch := TFrmBarcodeSearch.Create(Self); end; procedure TQueryInventory.btShowCostClick(Sender: TObject); begin inherited; editCost.Visible := btShowCost.Down; lblCost.Visible := btShowCost.Down; end; procedure TQueryInventory.spHelpClick(Sender: TObject); begin inherited; Application.HelpContext(1190); end; procedure TQueryInventory.btnPictureClick(Sender: TObject); begin inherited; if scModel.LookUpValue <> '' then with TFrmModelPicture.Create(Self) do Start(scModel.LookUpValue); end; procedure TQueryInventory.quModelCalcFields(DataSet: TDataSet); begin inherited; if quModelStoreSellingPrice.AsCurrency <> 0 then quModelSellingPrice.AsCurrency := quModelStoreSellingPrice.AsCurrency else quModelSellingPrice.AsCurrency := quModelInventoryPrice.AsCurrency; end; procedure TQueryInventory.edtBarcodeAfterSearchBarcode(Sender: TObject); var IDModel : Integer; begin inherited; with edtBarcode do begin if SearchResult then begin IDModel := GetFieldValue('IDModel'); scModel.LookUpValue := IntToStr(IDModel); scModelSelectItem(nil); end else MsgBox(MSG_CRT_NO_BARCODE, vbCritical + vbOkOnly); end; edtBarcode.Clear; end; procedure TQueryInventory.btnSearchDescClick(Sender: TObject); var R: integer; begin inherited; with fFrmBarcodeSearch do begin R := Start; if R <> -1 then begin scModel.LookUpValue := IntToStr(R); scModelSelectItem(nil); end; end; end; procedure TQueryInventory.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(fFrmBarcodeSearch); end; end.
//------------------------------------------------------------------------------ //BufferIO UNIT //------------------------------------------------------------------------------ // What it does- // Unit contains all incoming and outgoing packet procedures // to place data in and out of a databuffer. Everything here is self // explanitory and should not be changed anytime soon. // // Changes: // [2007/03/25] CR - Added a thorough commenting and header to // WriteBufferTwoPoints. This legacy routine is cryptic, and Rube // Goldbergian in the way it does it's job, thus a good explanation is needed. //------------------------------------------------------------------------------ unit BufferIO; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses //IDE Types, //Helios PacketTypes, CommClient, //3rd Party IdContext; procedure WriteBufferByte(const Index:word; const ByteIn:byte; var Buffer : TBuffer); procedure WriteBufferWord(const Index:word; const WordIn:word; var Buffer : TBuffer); procedure WriteBufferLongWord(const Index:word; const LongWordIn:LongWord; var Buffer : TBuffer); procedure WriteBufferString(const Index:word; const StringIn:string; const Count:word; var Buffer : TBuffer); procedure WriteBufferPointAndDirection( const index:word; const xy:TPoint; var Buffer : TBuffer; const Dir:byte = 0 ); Procedure WriteBufferTwoPoints( const Index : Word; const SourcePt : TPoint; const DestPt : TPoint; var Buffer : TBuffer ); procedure WriteBufferMD5String( const Index:word; const MD5String:string; var Buffer : TBuffer ); function BufferReadByte(const Index:word; const Buffer : TBuffer) : byte; function BufferReadWord(const Index:word; const Buffer : TBuffer) : word; function BufferReadLongWord(const Index:word; const Buffer : TBuffer) : LongWord; function BufferReadString(const Index:word; const Count:word; const Buffer : TBuffer) : string; function BufferReadMD5(const Index : word; const Buffer : TBuffer) : string; function BufferReadOnePoint(const Index:word; const Buffer : TBuffer) : TPoint; procedure SendPadding(var AClient : TIdContext;const ID:LongWord); procedure SendBuffer(var AClient : TIdContext;const Buffer : TBuffer; const Size : LongWord);overload; procedure SendBuffer(var AClient : TInterClient; const Buffer : TBuffer; const Size : LongWord);overload; procedure RecvBuffer( var AClient : TIdContext; var Buffer; const Size : LongWord ); overload; procedure RecvBuffer( var AClient : TInterClient; var Buffer; const Size : LongWord ); overload; implementation uses {IDE} SysUtils, {Third Party} IdGlobal; //------------------------------------------------------------------------------ //PUSHING DATA INTO THE BUFFER METHODS PROCEDURES //------------------------------------------------------------------------------ //Socket Method WriteBuffer - Writes a Byte to the buffer. procedure WriteBufferByte(const Index:word; const ByteIn:byte; var Buffer : TBuffer); begin Assert(Index <= 32767, 'WriteBuffer - Byte: index overflow ' + IntToStr(Index)); Move(ByteIn, Buffer[Index], 1); end; //Socket Method WriteBuffer - Writes a Word to the buffer. procedure WriteBufferWord(const Index : word; const WordIn : word; var Buffer : TBuffer); begin Assert(Index <= 32766, 'WriteBuffer - Word: index overflow ' + IntToStr(Index)); Move(WordIn, Buffer[Index], 2); end; //Socket Method WriteBuffer - Writes a LongWord to the buffer. procedure WriteBufferLongWord(const index : word; const LongWordIn : LongWord; var Buffer : TBuffer); begin Assert(Index <= 32766, 'WriteBuffer - LongWord: index overflow ' + IntToStr(Index)); Move(LongWordIn, Buffer[Index], 4); end; //Socket Method WriteBuffer - Writes a String to the buffer. procedure WriteBufferString(const Index:word; const StringIn : string; const Count : word; var Buffer : TBuffer); var StrLength :integer; begin Assert(Index <= 32767, 'WriteBuffer - String: Index overflow ' + IntToStr(Index)); Assert(Index + Count <= 32767, 'WriteBuffer - String: Index+Count overflow ' + IntToStr(Index+Count)); FillChar(Buffer[Index], Count, 0); StrLength := Length(StringIn); if StrLength <> 0 then begin if StrLength > Count then begin StrLength := Count; end; Move(StringIn[1], Buffer[Index], StrLength); end; end; (*-----------------------------------------------------------------------------* Proc WriteBufferTwoPoints -- Overview: -- Based on WFIFOM2 used in prior projects (eWeiss, Fusion, Prometheus), only with a spiffier and much more descriptive naName! The code here is VERY cryptic, but what it boils down to: We take two xy pairs, sending them in the smallest (40 bit) size possible given the "architectural" limit for map sizes, and then we perform a byte reversal: 01234 bytes becomes 43210 At best, we can only speculate why this reversal was done. Best guesses are that this was done within the packets to foil botting clients from reading and emulating these "encrypted" packets. In my own experience... I first saw this routine in Fusion, in early 2004, so this "encryption" was well know by that time. Thus the original purpose as best we can figure has been long defeated, and it's merely an obscure speed bump. ChrstphrR -- Revisions: -- [2007/03/25] CR - Added Comment Header, and described routine in detail, and in summary. Made remaining three passed parameters constant. Renamed local variables for more clarity: Halloween 2008 - Tsusai - Updated WriteBufferTwoPoints settings & Simplified. [yyyy/mm/dd] <Author> - <Comment> *-----------------------------------------------------------------------------*) Procedure WriteBufferTwoPoints( const Index : Word; const SourcePt : TPoint; const DestPt : TPoint; var Buffer : TBuffer ); Begin WriteBufferByte(Index+0, Byte((SourcePt.X) shr 2),Buffer); WriteBufferByte(Index+1, Byte(((SourcePt.X) shl 6) or (((SourcePt.Y) shr 4) and $3f)), Buffer); WriteBufferByte(Index+2, Byte(((SourcePt.Y) shl 4) or (((DestPt.X) shr 6) and $0f)), Buffer); WriteBufferByte(Index+3, Byte(((DestPt.X) shl 2) or (((DestPt.Y) shr 8) and $03)), Buffer); WriteBufferByte(Index+4, Byte(DestPt.Y), Buffer); WriteBufferByte(Index+5, Byte(((8) shl 4) or ((8) and $0f)), Buffer); End; (* Proc WriteBufferTwoPoints *-----------------------------------------------------------------------------*) //Halloween 2008 - Tsusai - Simplified procedure WriteBufferPointAndDirection( const index:word; const xy:TPoint; var Buffer : TBuffer; const Dir:byte = 0 ); {var l :LongWord; ByteArray :array[0..3] of Byte;} begin WriteBufferByte(Index+0, Byte((xy.X) shr 2), Buffer); WriteBufferByte(Index+1, Byte(((xy.x) shl 6) or (((xy.y) shr 4) and $3f)), Buffer); WriteBufferByte(Index+2, Byte(((xy.y) shl 4) or ((dir) and $f)), Buffer); End; (* Proc WriteBufferPointAndDirection *) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //WriteBufferMD5String FUNCTION //------------------------------------------------------------------------------ // What it does- // A MD5 string has 32 individual characters, each 2 make a byte. This string // needs to be dumped as is without conversions to the buffer. The loop grabs // every two characters in the string as is (lets say 9C). It then puts a $ in // front to denote it is a hex string to delphi, then that number is written to // the buffer as one byte. // // Changes - // March 12th, 2007 - Aeomin - Moved Header // //------------------------------------------------------------------------------ procedure WriteBufferMD5String(const Index:word; const MD5String:string; var Buffer : TBuffer); var cnt : integer; AByte : byte; begin {for header: } for cnt := 0 to 15 do begin AByte := StrToIntDef( ('$' + MD5String[cnt*2+1] + MD5String[cnt*2+2]), 0); WriteBufferByte(Index+cnt,AByte,Buffer); end; end; (*------------------------------------------------------------------------------ READING DATA FROM THE BUFFER METHODS ------------------------------------------------------------------------------*) //Socket Method BufferReadByte - Reads a Byte from the buffer. function BufferReadByte(const Index:word; const Buffer : TBuffer) : byte; begin Assert(Index <= 32766, 'BufferReadByte: Index overflow ' + IntToStr(Index)); Move(Buffer[Index], Result, 1); end; //Socket Method BufferReadWord - Reads a Word from the buffer. function BufferReadWord(const Index:word; const Buffer : TBuffer) : word; begin Assert(Index <= 32766, 'BufferReadWord: Index overflow ' + IntToStr(Index)); Move(Buffer[Index], Result, 2); end; //Socket Method BufferReadLongWord - Reads a LongWord from the buffer. function BufferReadLongWord(const Index:word; const Buffer : TBuffer) : LongWord; begin Assert(Index <= 32766, 'BufferReadLongWord: Index overflow ' + IntToStr(Index)); Move(Buffer[Index], Result, 4); end; //------------------------------------------------------------------------------ //ReadMD5Password FUNCTION //------------------------------------------------------------------------------ // What it does- // Reads MD5Bytes and makes it into a string. Its 16 bytes long. // // Changes - // December 17th, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ function BufferReadMD5(const Index : word; const Buffer : TBuffer) : string; var cnt : integer; begin Result := ''; //Read every byte, and convert that bite value into a hex string //Attach all hexstrings together to make the MD5 hash string. for cnt := 0 to 16-1 do begin Result := Result + IntToHex(BufferReadByte(Index+cnt,Buffer),2); end; end;//ReadMD5Password //------------------------------------------------------------------------------ (*- Function ------------------------------------------------------------------* BufferReadString -------------------------------------------------------------------------------- Overview: -- Socket Method BufferReadString - Reads a String from the buffer. [2007/06/03] CR - Reverted to original weiss-based code, instead of the latest RFIFOS code that was present in Prometheus when Tsusai began filling out his buffer read/write routines. Contains Tricky Code: By using an array of character (StrArray) as an intermediary, it trims the Result string up to the first Null (#0) character. This sidesteps the need to do an explicit Trim(), for the one case where the Client completely foregoes security when re-logging into the Login server when dropping from the Zone -- it sends the password, a null, and whatever random data you have in that 24 byte block of RAM. Just hope your credit card number wasn't that spot before! -- Pre: (Our buffers are 32k in size, which is also the max packet size for RO packets by design. So:) Ensure that Index is less than the 32k barrier. Ensure that Index + Count together, are less than the 32k barrier. Post: None. -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/03/12] Aeomin - Reformat Header. [2007/06/03] CR - Bugfix - allows clients to re-login now. Thoroughly commented code, and pre-requisite assertions, so that no one haphazardly goes into this code to "improve" it without knowing the perils before them. *-----------------------------------------------------------------------------*) Function BufferReadString( const Index : Word; //Starting point on the buffer. const Count : Word; //Max number of characters to copy to the string. const Buffer : TBuffer //Our source Byte Buffer ) : String; Var StrArray : TCBuffer; Begin //Pre Assert(Index <= 32767, 'BufferReadString: Index overflow ' + IntToStr(Index)); Assert( Index + Count <= 32767, 'BufferReadString: Index+Count overflow ' + IntToStr(Index+Count) ); //-- StrArray[Count] := #0; //Ensure the string is null terminated, just in case. Move(Buffer[Index], StrArray, Count); Result := StrArray; //Does more than you think here (read description). End; (* Func BufferReadString *-----------------------------------------------------------------------------*) //------------------------------------------------------------------------------ //BufferReadOnePoint FUNCTION //------------------------------------------------------------------------------ // What it does- // Socket Method BufferReadLongWord - Reads one point from the buffer. // // Changes - // March 12th, 2007 - Aeomin - Reformat Header. // Dec 2, 2008 - Tsusai - Implemented better bit shifting // //------------------------------------------------------------------------------ function BufferReadOnePoint(const Index:word; const Buffer : TBuffer) : TPoint; var bb :array[0..2] of byte; begin Move(Buffer[index], bb[0], 3); Result.X := (bb[0] * 4) + (bb[1] shr 6); Result.Y := ((bb[1] and $3f) shl 4) + (bb[2] shr 4); end; //------------------------------------------------------------------------------ (*------------------------------------------------------------------------------ PREMADE SENDING OF BUFFER TO CLIENT ------------------------------------------------------------------------------*) //------------------------------------------------------------------------------ //SendPadding PROCEDURE //------------------------------------------------------------------------------ // What it does- // Padding Packet, // used for antibot/antihack upon charaserv and mapserv connections // // Changes - // March 12th, 2007 - Aeomin - Reformat Header. // //------------------------------------------------------------------------------ procedure SendPadding(var AClient : TIdContext;const ID:LongWord); var ABuf : TBuffer; begin WriteBufferLongWord(0,ID,ABuf); SendBuffer(AClient,ABuf,4); end; //Socket Method SendBuffer - Writes the buffer to the socket. procedure SendBuffer(var AClient : TInterClient; const Buffer : TBuffer; const Size : LongWord); var SendBytes : TIdBytes; begin SendBytes := RawToBytes(Buffer,Size); AClient.IOHandler.Write(SendBytes); end; //Socket Method SendBuffer - Writes the buffer to the socket. procedure SendBuffer(var AClient : TIdContext;const Buffer : TBuffer; const Size : LongWord); var SendBytes : TIdBytes; begin SendBytes := RawToBytes(Buffer,Size); {if AClient.Data is TClientLink then begin if (TClientLink(AClient.Data).EncKey1 > 0)AND(TClientLink(AClient.Data).EncKey2 > 0) then begin WriteBufferWord(0, TClientLink(AClient.Data).DecryptMessageID(BufferReadWord(0,Buffer)), Buffer); end; end;} AClient.Connection.IOHandler.Write(SendBytes); end; //Socket Method RecvBuffer - Reads the buffer from the socket. procedure RecvBuffer( var AClient : TIdContext; var Buffer; const Size : LongWord ); var RecvBytes : TIdBytes; begin if Size > 0 then begin FillChar(Buffer,Size,0); AClient.Connection.IOHandler.ReadBytes(RecvBytes,Size); BytesToRaw(RecvBytes,Buffer,Size); end; end; //Socket Method RecvBuffer - Reads the buffer from the socket. procedure RecvBuffer(var AClient : TInterClient; var Buffer; const Size : LongWord); var RecvBytes : TIdBytes; begin FillChar(Buffer,Size,0); AClient.IOHandler.ReadBytes(RecvBytes,Size); BytesToRaw(RecvBytes,Buffer,Size); end; end.
unit PublishSubscribe; interface uses System.SysUtils, System.Generics.Collections, System.SyncObjs; type TPubSub = class public type TCallback = TProc<integer>; TLockingScheme = (lockNone, lockCS, lockMonitor, lockMREW, lockLightweightMREW); strict private FLockCS: TCriticalSection; FLockMREW: TMREWSync; FLockLight: TLightweightMREW; FSubscribers: TList<TCallback>; FLockReader: TProc; FUnlockReader: TProc; FLockWriter: TProc; FUnlockWriter: TProc; FOnEndNotify: TProc; FOnStartNotify: TProc; strict private procedure SetOnEndNotify(const Value: TProc); procedure SetOnStartNotify(const Value: TProc); public constructor Create(lockingScheme: TLockingScheme); destructor Destroy; override; procedure Subscribe(callback: TCallback); procedure Unsubscribe(callback: TCallback); procedure Notify(value: integer); property OnStartNotify: TProc read FOnStartNotify write SetOnStartNotify; property OnEndNotify: TProc read FOnEndNotify write SetOnEndNotify; end; implementation { TPubSub } constructor TPubSub.Create(lockingScheme: TLockingScheme); begin inherited Create; FSubscribers := TList<TCallback>.Create; case lockingScheme of lockNone: begin FLockReader := procedure begin end; FLockWriter := procedure begin end; FUnlockReader := procedure begin end; FUnlockWriter := procedure begin end; end; lockCS: begin FLockCS := TCriticalSection.Create; FLockReader := procedure begin FLockCS.Acquire; end; FLockWriter := procedure begin FLockCS.Acquire; end; FUnlockReader := procedure begin FLockCS.Release; end; FUnlockWriter := procedure begin FLockCS.Release; end; end; lockMonitor: begin FLockCS := TCriticalSection.Create; FLockReader := procedure begin MonitorEnter(Self); end; FLockWriter := procedure begin MonitorEnter(Self); end; FUnlockReader := procedure begin MonitorExit(Self); end; FUnlockWriter := procedure begin MonitorExit(Self); end; end; lockMREW: begin FLockMREW := TMREWSync.Create; FLockReader := procedure begin FLockMREW.BeginRead; end; FLockWriter := procedure begin FLockMREW.BeginWrite; end; FUnlockReader := procedure begin FLockMREW.EndRead; end; FUnlockWriter := procedure begin FLockMREW.EndWrite; end; end; lockLightweightMREW: begin FLockReader := procedure begin FLockLight.BeginRead; end; FLockWriter := procedure begin FLockLight.BeginWrite; end; FUnlockReader := procedure begin FLockLight.EndRead; end; FUnlockWriter := procedure begin FLockLight.EndWrite; end; end; end; end; destructor TPubSub.Destroy; begin FreeAndNil(FLockCS); FreeAndNil(FLockMREW); FreeAndNil(FSubscribers); inherited; end; procedure TPubSub.Notify(value: integer); begin FLockReader(); if assigned(FOnStartNotify) then FOnStartNotify(); for var subscriber in FSubscribers do subscriber(value); if assigned(FOnEndNotify) then FOnEndNotify(); FUnlockReader(); end; procedure TPubSub.SetOnEndNotify(const Value: TProc); begin FOnEndNotify := Value; end; procedure TPubSub.SetOnStartNotify(const Value: TProc); begin FOnStartNotify := Value; end; procedure TPubSub.Subscribe(callback: TCallback); begin FLockWriter(); FSubscribers.Add(callback); FUnlockWriter(); end; procedure TPubSub.Unsubscribe(callback: TCallback); begin FLockWriter(); FSubscribers.Remove(callback); FUnlockWriter(); end; end.
{==============================================================================| | Project : Delphi HTML/XHTML parser module | 1.1.2 | |==============================================================================| | Content: | |==============================================================================| | The contents of this file are subject to the Mozilla Public License Ver. 1.0 | | (the "License"); you may not use this file except in compliance with the | | License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ | | | | Software distributed under the License is distributed on an "AS IS" basis, | | WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for | | the specific language governing rights and limitations under the License. | |==============================================================================| | Initial Developers of the Original Code are: | | Sandbil (Russia) sandbil@ya.ru | | All Rights Reserved. | | Last Modified: | | 25.10.2014, Sandbil | |==============================================================================| | History: see README | |==============================================================================|} unit parser; interface uses System.Classes, System.RegularExpressionsCore, System.Generics.Collections, System.Contnrs, System.StrUtils, System.SysUtils; type TNodeList = class; TChildList=class; TDomTreeNode = class; TDomTree = class private FCount: Integer; fParseErr: TStringList; fRootNode: TDomTreeNode; public constructor Create; destructor destroy; override; property Count: Integer read fCount; property RootNode: TDomTreeNode read fRootNode; property ParseErr: TStringList read fParseErr; end; TDomTreeNode = class(TObject) private fTag: string; fAttributesTxt: string; fAttributes: TDictionary<string, string>; fText: string; fTypeTag: string; fChild: TChildList; fParent: Pointer; fOwner: TDomTree; public property Tag: string read fTag; property AttributesTxt: string read fAttributesTxt; property Attributes: TDictionary<string, string> read fAttributes; property Text: string read fText; property TypeTag: string read fTypeTag; property Child: TChildList read fChild; property Parent: Pointer read fParent; property Owner: TDomTree read fOwner; constructor create(hOwner: TDomTree; hParent: Pointer; hTag, hAttrTxt: string; hAttr: TDictionary<string, string>; hTypeTag, hText: string); destructor destroy; override; function FindNode(hNameTag: string; hIndex:integer; hAttrTxt: String; hAnyLevel: Boolean; dListNode: TNodeList): Boolean; function FindTagOfIndex(hNameTag: String; hIndex:integer; hAnyLevel: Boolean; dListNode: TNodeList): Boolean; function FindXPath(hXPathTxt: String; dListNode: TNodeList; dListValue:TStringList): Boolean; function GetAttrValue(hAttrName:string): string; function GetComment(hIndex: Integer): string; function GetTagName: string; function GetTextValue(hIndex:Integer): string; function GetXPath(hRelative:boolean): string; function RunParse(HtmlTxt: String): Boolean; end; TChildList = class(TList) private function Get(Index: Integer): TDomTreeNode; public destructor Destroy; override; property Items[Index: Integer]: TDomTreeNode read Get; default; end; TNodeList = class(TList) private function Get(Index: Integer): TDomTreeNode; public property Items[Index: Integer]: TDomTreeNode read Get; default; end; PPrmRec=^TPrmRec; TPrmRec = record TagName: string; ind: Integer; Attr: string; AnyLevel: Boolean; end; TPrmRecList = class(TList) private function Get(Index: Integer): PPrmRec; public destructor Destroy; override; property Items[Index: Integer]: PPrmRec read Get; default; end; implementation { TDomTree } { *********************************** TDomTree *********************************** } constructor TDomTree.Create; begin fParseErr:= TStringList.Create; fRootnode:= TDomTreeNode.Create(self,self,'Root','',nil,'',''); FCount:=0; end; destructor TDomTree.destroy; begin FreeAndNil(fParseErr); FreeAndNil(fRootNode); inherited; end; { TChildList } { ********************************** TChildList ********************************** } destructor TChildList.Destroy; var i: Integer; begin for i := 0 to Count - 1 do self[i].Free; inherited; end; function TChildList.Get(Index: Integer): TDomTreeNode; begin Result := TDomTreeNode(inherited Get(Index)); end; { TNodeList } function TNodeList.Get(Index: Integer): TDomTreeNode; begin Result := TDomTreeNode(inherited Get(Index)); end; { TPrmRecList } { ********************************* TPrmRecList ********************************** } destructor TPrmRecList.Destroy; var i: Integer; begin for i := 0 to Count - 1 do FreeMem(Items[i]); inherited; end; function TPrmRecList.Get(Index: Integer): PPrmRec; begin Result := PPrmRec(inherited Get(Index)); end; { TDomTreeNode } { ********************************* TDomTreeNode ********************************* } constructor TDomTreeNode.create(hOwner: TDomTree; hParent: Pointer; hTag, hAttrTxt: string; hAttr: TDictionary<string, string>; hTypeTag, hText: string); begin fChild := TChildList.create; fParent := hParent; fTag := hTag; fAttributesTxt := hAttrTxt; fAttributes := hAttr; fTypeTag:= hTypeTag; fText := hText; fOwner:=hOwner; inc(hOwner.FCount); end; destructor TDomTreeNode.destroy; begin FreeAndNil(fAttributes); FreeAndNil(fChild); inherited; end; //***********FindAttr************* // hNameTag - name Tag // hIndex - number of a tag one after another (0 - all tag, 1 - each first ..) // hAttrTxt - attribute. ex. alt=1 // hAnyLevel - true - all levels after start node; false - only one child level after start node // dListNode - return TNodeList of TDomTreeNode function TDomTreeNode.FindNode(hNameTag: string; hIndex:integer; hAttrTxt: String; hAnyLevel: Boolean; dListNode: TNodeList): Boolean; var RegEx: TPerlRegEx; i,a: integer; TagNodeList:TNodeList; tValue: string; Function FindAttrChildNode(aNode:TDomTreeNode;AttrName,AttrValue: String):TNodeList; var aValue: String; j: integer; begin for j := 0 to aNode.Child.Count - 1 do begin if aNode.Child[j].Attributes <> nil then if aNode.Child[j].Attributes.ContainsKey(AttrName) then if aNode.Child[j].Attributes.TryGetValue(AttrName, aValue) then if AttrValue = aValue then dListNode.Add(aNode.Child[j]); if hAnyLevel then FindAttrChildNode(aNode.Child[j], AttrName, AttrValue); end; result:=dListNode; end; begin RegEx:=nil; try result:=false; RegEx := TPerlRegEx.create; RegEx.Subject := hAttrTxt; RegEx.RegEx :='([^\s]*?[^\S]*)=([^\S]*".*?"[^\S]*)|'+ '([^\s]*?[^\S]*)=([^\S]*#39.*?#39[^\S]*)|'+ '([^\s]*?[^\S]*)=([^\S]*[^\s]+[^\S]*)|'+ '(autofocus[^\S]*)()|'+ '(disabled[^\S]*)()|'+ '(selected[^\S]*)()'; if (not (hAttrTxt = '')) and (RegEx.Match) then begin for i := 1 to RegEx.GroupCount do if trim(RegEx.Groups[i]) <> '' then break; if hNameTag = '' then begin if FindAttrChildNode(self,RegEx.Groups[i],RegEx.Groups[i+1]).Count>0 then result:=true; end else begin TagNodeList:=TNodeList.Create; if FindTagOfIndex(hNameTag,hIndex,hAnyLevel,TagNodeList) then for a := 0 to TagNodeList.Count - 1 do if TagNodeList[a].Attributes <> nil then if TagNodeList[a].Attributes.ContainsKey(RegEx.Groups[i]) then if TagNodeList[a].Attributes.TryGetValue(RegEx.Groups[i], tValue) then //There was a strong compareson of values of attribute // if RegEx.Groups = tValue) if pos(RegEx.Groups[i+1],tValue)>0 then begin dListNode.Add(TagNodeList[a]); result:=true; end; TagNodeList.Free; end; end else if hAttrTxt = '' then begin TagNodeList:=TNodeList.Create; if FindTagOfIndex(hNameTag,hIndex,hAnyLevel,TagNodeList) then for a := 0 to TagNodeList.Count - 1 do begin dListNode.Add(TagNodeList[a]); result:=true; end; TagNodeList.Free; end else raise Exception.create('Attribute not found: '+ hAttrTxt ); finally RegEx.free end; end; //***********FindTagOfIndex************* // hNameTag - name Tag (* - any tag, except text tag) // hIndex - number of a tag one after another (0 - all tag, 1 - each first ..) // hAnyLevel - true - all level after start node; false - only one child level after start node // dListNode - return TNodeList of TDomTreeNode function TDomTreeNode.FindTagOfIndex(hNameTag: String; hIndex:integer; hAnyLevel: Boolean; dListNode: TNodeList): Boolean; function SubStringOccurences(const subString, sourceString : string; caseSensitive : boolean) : integer; var pEx: integer; sub, source : string; begin if caseSensitive then begin sub := subString; source := sourceString; end else begin sub := LowerCase(subString); source := LowerCase(sourceString); end; result := 0; pEx := PosEx(sub, source, 1); while pEx <> 0 do begin Inc(result); pEx := PosEx(sub, source, pEx + Length(sub)); end; end; Function FindChildTagOfIndex(aNode:TDomTreeNode):TNodeList; var countNode,j: integer; enumTags:string; begin countNode:=0; for j := 0 to aNode.Child.Count - 1 do begin if hNameTag <> '*' then begin if ((AnsiUpperCase(aNode.Child[j].Tag) = AnsiUpperCase(hNameTag)) and (aNode.Child[j].TypeTag <> '</%s>')) or ((AnsiUpperCase(aNode.Child[j].Tag) = '') and (AnsiUpperCase(hNameTag)='TEXT()') and (aNode.Child[j].Text <> '')) or ((LeftStr(AnsiUpperCase(aNode.Child[j].Tag),4) = '<!--') and (AnsiUpperCase(hNameTag)='COMMENT()')) then begin Inc(countNode); if (countNode = hIndex ) or (hIndex = 0) then dListNode.Add(aNode.Child[j]) end; if (hAnyLevel) and (aNode.Child.Count > 0) then FindChildTagOfIndex(aNode.Child[j]) ; end else begin if (aNode.Child[j].TypeTag <> '</%s>') then begin enumTags:=enumTags + AnsiUpperCase(aNode.Child[j].Tag)+','; if (SubStringOccurences(AnsiUpperCase(aNode.Child[j].Tag)+',',enumTags, false) = hIndex ) or (hIndex = 0) then dListNode.Add(aNode.Child[j]) end; if (hAnyLevel) and (aNode.Child.Count > 0) then FindChildTagOfIndex(aNode.Child[j]) ; end; end; result:=dListNode; end; begin result:=false; if FindChildTagOfIndex(self).Count > 0 then result:=true; end; function TDomTreeNode.FindXPath(hXPathTxt: String; dListNode: TNodeList; dListValue:TStringList): Boolean; var RegExXPath, RegExXPathElmt: TPerlRegEx; i: integer; NextAnyLevel:boolean; PrmXPath:TPrmRecList; PrmXPathSTR: String; PrmCount:integer; procedure MatchXpath(Context,mTxtElmt:string) ; var Prm: PPrmRec; begin if (Context='/') and (trim(mTxtElmt)='') then NextAnyLevel:=true else if (Context='/') and (trim(mTxtElmt)='..') then begin New(prm); Prm.TagName:='..'; Prm.ind:=0; Prm.Attr:=''; Prm.AnyLevel:=false; PrmXPath.Add(Prm); end else begin RegExXPathElmt.Options := [preCaseLess]; RegExXPathElmt.Subject:=trim(mTxtElmt); RegExXPathElmt.RegEx:='^([\.\*@A-Z][-A-Z0-9\(\)]*)\[?([0-9]*)\]?\[?@?([^\]]*)'; if RegExXPathElmt.Match then begin New(prm); Prm.TagName:=RegExXPathElmt.Groups[1]; if not TryStrToInt( RegExXPathElmt.Groups[2], Prm.ind ) then Prm.ind:=0; Prm.Attr:=RegExXPathElmt.Groups[3]; Prm.AnyLevel:=NextAnyLevel; if (Context='/') then NextAnyLevel:=False; PrmXPath.Add(Prm); end else raise Exception.create('XPath is not correct '+ Context + mTxtElmt ); end; end; Function FindWithPrm(cPrm:integer; CurNode:TDomTreeNode; dListNode: TNodeList) : boolean; var i: integer; cLNode: TNodeList; begin result:=false; if PrmXPath[cPrm].TagName = '..' then FindWithPrm(cPrm + 1,CurNode.Parent, dListNode) else begin cLNode:=TNodeList.Create; if CurNode.FindNode(PrmXPath[cPrm].TagName,PrmXPath[cPrm].ind,PrmXPath[cPrm].Attr,PrmXPath[cPrm].AnyLevel,cLNode) then for I := 0 to cLNode.Count - 1 do if cPrm < PrmCount then FindWithPrm(cPrm + 1,cLNode[i], dListNode) else dListNode.Add(cLNode[i]) ; cLNode.free; end; if dListNode.Count > 0 then result:=true end; begin PrmXPath:=nil; RegExXPath:=nil; RegExXPathElmt:=nil; try result:=false; NextAnyLevel:=false; PrmXPath:=TPrmRecList.Create; PrmXPathSTR:=''; RegExXPath := TPerlRegEx.create; RegExXPathElmt := TPerlRegEx.create; RegExXPath.Subject:= hXPathTxt; RegExXPath.RegEx:='(/)([\*@]?[^/]*)'; if RegExXPath.Match then begin MatchXpath(RegExXPath.Groups[1],RegExXPath.Groups[2]); while RegExXPath.MatchAgain do MatchXpath(RegExXPath.Groups[1],RegExXPath.Groups[2]); for i := 0 to PrmXPath.Count-1 do PrmXPathSTR:=PrmXPathSTR + PrmXPath[i].TagName +',' + inttostr(PrmXPath[i].ind) +',' + PrmXPath[i].Attr+',' + BoolToStr(PrmXPath[i].AnyLevel,True)+chr(13)+chr(10); if PrmXPath.Count > 0 then begin if (PrmXPath[PrmXPath.Count-1].TagName[1]='@') then begin PrmCount:= PrmXPath.Count - 2; PrmXPath[PrmXPath.Count-1].TagName:=AnsiReplaceStr(PrmXPath[PrmXPath.Count-1].TagName,'@',''); if FindWithPrm(0,self,dListNode) then begin for I := 0 to dListNode.Count-1 do if dListNode[i].GetAttrValue(PrmXPath[PrmXPath.Count-1].TagName)<>'' then dListValue.Add(dListNode[i].GetAttrValue(PrmXPath[PrmXPath.Count-1].TagName)); if dListValue.Count > 0 then result:= true else result:=false; end else result:=false; end else begin PrmCount:= PrmXPath.Count - 1; result:= FindWithPrm(0,self,dListNode); if (AnsiLowerCase(PrmXPath[PrmXPath.Count-1].TagName)='comment()') or (AnsiLowerCase(PrmXPath[PrmXPath.Count-1].TagName)='text()') then for I := 0 to dListNode.Count-1 do begin if (AnsiLowerCase(PrmXPath[PrmXPath.Count-1].TagName)='text()') then dListValue.Add(dListNode[i].Text) else dListValue.Add(TDomTreeNode(dListNode[i]).Tag) ; end; end; end else raise Exception.create('XPath is not correct or empty.'); end else raise Exception.create('XPath is not correct or empty.'); finally PrmXPath.Free; RegExXPath.Free; RegExXPathElmt.Free; end; end; function TDomTreeNode.GetAttrValue(hAttrName:string): string; begin result:=''; if self.Attributes <> nil then if self.Attributes.ContainsKey(hAttrName) then if not self.Attributes.TryGetValue(hAttrName, result) then result:=''; end; function TDomTreeNode.GetComment(hIndex: Integer): string; var countNode,j: integer; begin result:=''; countNode:=0; for j := 0 to self.Child.Count - 1 do if (LeftStr(self.Child[j].Tag,4) = '<!--') and (self.Child[j].TypeTag = '%s') and (self.Child[j].Text = '') then begin Inc(countNode); if (countNode = hIndex ) or (hIndex = 0) then begin result:= self.Child[j].Tag; break; end; end; end; function TDomTreeNode.GetTagName: string; begin if self.TypeTag='</%s>' then result:= format(AnsiReplaceStr(self.TypeTag,'/',''),[self.Tag + ' ' + self.AttributesTxt] ) else result:= format(self.TypeTag,[self.Tag + ' ' + self.AttributesTxt] ); end; function TDomTreeNode.GetTextValue(hIndex:Integer): string; var countNode,j: integer; begin result:=''; countNode:=0; for j := 0 to self.Child.Count - 1 do if (self.Child[j].Tag = '') and (self.Child[j].TypeTag = '') and (self.Child[j].Text <> '') then begin Inc(countNode); if (countNode = hIndex ) or (hIndex = 0) then begin result:= self.Child[j].Text; break; end; end; end; function TDomTreeNode.GetXPath(hRelative:boolean): string; function GetCountTag(Node: TDomTreeNode): string; var CountNode, nNode, i: integer; begin CountNode:=0; result:= ''; if TObject(Node.Parent) is TDomTreeNode then begin for i:=0 to TDomTreeNode(Node.Parent).Child.Count - 1 do begin if (Node.Tag = TDomTreeNode(Node.Parent).Child[i].Tag) or ((LeftStr(Node.Tag,4)='<!--') and (LeftStr(TDomTreeNode(Node.Parent).Child[i].Tag,4)='<!--')) then inc(CountNode); if Node = TDomTreeNode(Node.Parent).Child[i] then nNode:= CountNode; end; if (CountNode <> nNode) or ((CountNode = nNode) and (CountNode > 1)) then result:= format('[%d]',[nNode]); end; end; function GetParent(Node: TDomTreeNode): string; begin if TObject(Node.Parent) is TDomTreeNode then begin if (hRelative) and (TDomTreeNode(Node.Parent).GetAttrValue('id') <>'') then result:=format('//*[@id=%s]',[TDomTreeNode(Node.Parent).GetAttrValue('id')])+ '/' + result else result:=GetParent(Node.Parent)+ TDomTreeNode(Node.Parent).Tag + GetCountTag(Node.Parent) + '/' + result end else result:='.'+result; end; begin if (LeftStr(self.Tag,2) <> '<?') and (LeftStr(self.Tag,9) <> '<!DOCTYPE') then begin if LeftStr(self.Tag,4) = '<!--' then result:='comment()' else if self.Tag <> '' then result:=self.Tag else result:='text()'; result:=GetParent(self) + result + GetCountTag(self); if result[1]='.' then result:='.'+RightStr(result, length(result)-pos('/',result,1)+1); end else result:=''; end; function TDomTreeNode.RunParse(HtmlTxt: String): Boolean; var RegExHTML, RegExTag: TPerlRegEx; prev, ErrParseHTML, ind: integer; ChildTree: TDomTreeNode; HtmlUtf8, RegExException: string; tag_txt: TArray<String>; function getAttr(mAttrTxt: string): TDictionary<string, string>; var CheckAttr: String; procedure MatchAttr; var i: integer; begin CheckAttr := StuffString(CheckAttr,RegExTag.MatchedOffset+1, RegExTag.MatchedLength, StringOfChar(' ',RegExTag.MatchedLength)); for i := 1 to RegExTag.GroupCount do if trim(RegExTag.Groups[i]) <> '' then begin try result.Add(trim(RegExTag.Groups[i]), trim(RegExTag.Groups[i + 1])); except on E: Exception do Owner.fParseErr.Add('Warning: not add Attributtes ' + E.ClassName + ' : ' + E.Message + 'Sourse string: ' + mAttrTxt + ';' + chr(13)+chr(10)+' attributtes: ' + RegExTag.Groups[i]); end; break; end; end; begin try result := TDictionary<string, string>.create; if trim(mAttrTxt) <> '' then begin RegExTag.Subject := mAttrTxt; CheckAttr := mAttrTxt; RegExTag.Options := [preCaseLess, preMultiLine, preSingleLine]; RegExTag.Replacement:=''; // here RegExp for processing attributes of tags // First not Empty - attribute, next - value RegExTag.RegEx :='([^\s]*?[^\S]*)=([^\S]*".*?"[^\S]*)|'+ '([^\s]*?[^\S]*)=([^\S]*'#39'.*?'#39'[^\S]*)|'+ '([^\s]*?[^\S]*)=([^\S]*[^\s]+[^\S]*)|'+ '(allowTransparency[^\S]*)()|'+ '(allowfullscreen[^\S]*)()|'+ '(novalidate[^\S]*)()|'+ '(autofocus[^\S]*)()|'+ '(itemscope[^\S]*)()|'+ '(disabled[^\S]*)()|'+ '(readonly[^\S]*)()|'+ '(selected[^\S]*)()|'+ '(checked[^\S]*)()|'+ '(pubdate[^\S]*)()|'+ '(nowrap[^\S]*)()|'+ '(hidden[^\S]*)()|'+ '(async[^\S]*)()'; if RegExTag.Match then begin MatchAttr; while RegExTag.MatchAgain do MatchAttr; // ***Start Check Parsing Tag Attributes Error**** if Length(Trim(CheckAttr)) > 0 then Owner.fParseErr.Add('Warning: parsed not all attributes, ' + 'sourse string: ' + mAttrTxt + chr(13)+chr(10)+ 'not parsed string: ' + Trim(CheckAttr)); // ***End Check Parsing Tag Attributes Error************ end else Owner.fParseErr.Add('Attributtes not found - ' + 'Sourse string: ' + mAttrTxt); end; except on E: Exception do Owner.fParseErr.Add('Attributtes - ' + E.ClassName + ' : ' + E.Message + 'Sourse string: ' + mAttrTxt); end; end; function getTagTxt(mTxt: string): TArray<String>; begin try SetLength(result, 4); result[0] := ''; // name tag result[1] := ''; // text attributes result[2] := ''; // text value following for tag result[3] := ''; // type tag if LeftStr(trim(mTxt),2) = '</' then result[3] :='</%s>' //close else if RightStr(trim(mTxt),2) = '/>' then result[3] :='<%s/>' //selfclose else if LeftStr(trim(mTxt),2) = '<!' then result[3] :='%s' else if LeftStr(trim(mTxt),2) = '<?' then result[3] :='%s' else result[3] :='<%s>'; // open RegExTag.Subject := mTxt; RegExTag.Options := [preCaseLess, preMultiLine, preSingleLine]; // here RegExp for processing HTML tags // Group 1- tag, 2- attributes, 3- text RegExTag.RegEx := '<([/A-Z][:A-Z0-9]*)\b([^>]*)>([^<]*)'; if RegExTag.Match then begin // ****************Start Check Parsing HTML Tag Error************ if mTxt <> '<' + RegExTag.Groups[1] + RegExTag.Groups[2] + '>' + RegExTag.Groups[3] then Owner.fParseErr.Add('Check error Tags parsing - ' + 'Sourse string: ' + mTxt); // ****************End Check Parsing HTML Tag Error************ result[0] := trim(RegExTag.Groups[1]); if trim(RegExTag.Groups[2])<> '' then if RightStr(trim(RegExTag.Groups[2]),1)= '/' then result[1] := leftStr(trim(RegExTag.Groups[2]),length(trim(RegExTag.Groups[2]))-1) else result[1] := trim(RegExTag.Groups[2]); result[2] := trim(RegExTag.Groups[3]); end else result[0] := trim(mTxt); except on E: Exception do Owner.fParseErr.Add('Tags - ' + E.ClassName + ' : ' + E.Message + 'Sourse string: ' + mTxt); end; end; function getPairTagTxt(mTxt, mPattern: string): TArray<String>; begin try SetLength(result, 4); result[0] := ''; // name tag result[1] := ''; // text attributes result[2] := ''; // text value following for tag result[3] := ''; // close tag RegExTag.Subject := mTxt; RegExTag.Options := [preCaseLess, preMultiLine, preSingleLine]; // here RegExp for processing HTML tags // Group 1- tag, 2- attributes, 3- text RegExTag.RegEx := mPattern; if RegExTag.Match then begin // ****************Start Check Parsing HTML Tag Error************ if trim(mTxt) <> '<' + RegExTag.Groups[1] + RegExTag.Groups[2] + '>' + RegExTag.Groups[3] + '<' +RegExTag.Groups[4] +'>' then Owner.fParseErr.Add('Check error Exception Tags parsing - ' + 'Sourse string: ' + mTxt); // ****************End Check Parsing HTML Tag Error************ result[0] := trim(RegExTag.Groups[1]); result[1] := trim(RegExTag.Groups[2]); result[2] := trim(RegExTag.Groups[3]); result[3] := trim(RegExTag.Groups[4]); end else result[0] := mTxt; except on E: Exception do Owner.fParseErr.Add('Exception Tags - ' + E.ClassName + ' : ' + E.Message + 'Sourse string: ' + mTxt); end; end; Function CheckParent(aChildTree: TDomTreeNode; tTag: string):TDomTreeNode; var ParentTag: string; begin result := aChildTree.Parent; if tTag = '<%s>' then result := aChildTree else if tTag = '</%s>' then if TObject(TDomTreeNode(aChildTree.Parent).Parent) is TDomTreeNode then begin ParentTag := TDomTreeNode(aChildTree.Parent).Tag; if ParentTag = RightStr(aChildTree.Tag, length(aChildTree.Tag) - 1) then result := TDomTreeNode(aChildTree.Parent).Parent end; end; procedure MatchTag(mTxtMatch:string); var ExceptTag: string; begin // tag without close tag ExceptTag := ',META,LINK,IMG,COL,AREA,BASE,BASEFONT,ISINDEX,BGSOUNDCOMMAND,PARAM,INPUT,EMBED,FRAME,BR,WBR,HR,TRACK,'; if (leftstr(mTxtMatch, 4) = '<!--') then begin tag_txt[0] := trim(mTxtMatch); tag_txt[1] := ''; tag_txt[2] := ''; tag_txt[3] := '%s'; ChildTree.Child.Add(TDomTreeNode.create(ChildTree.Owner,ChildTree, tag_txt[0], '', nil, '%s','')) ; end else if (AnsiUpperCase(leftstr(mTxtMatch, 7)) = '<TITLE>') // tag with any symbol or (AnsiUpperCase(leftstr(mTxtMatch, 10)) = '<PLAINTEXT>') or (AnsiUpperCase(leftstr(mTxtMatch, 5)) = '<XMP>') or (AnsiUpperCase(leftstr(mTxtMatch, 7)) = '<SCRIPT') or (AnsiUpperCase(leftstr(mTxtMatch, 9)) = '<TEXTAREA') //or (AnsiUpperCase(leftstr(mTxtMatch, 4)) = '<PRE') then begin tag_txt := getPairTagTxt(mTxtMatch,'<([A-Z][A-Z0-9]*)\b([^>]*?)>(.*)<(/\1)>'); ind:=ChildTree.Child.Add(TDomTreeNode.create(ChildTree.Owner,ChildTree, tag_txt[0], tag_txt[1], getAttr(tag_txt[1]), '<%s>','')) ; if tag_txt[2] <> '' then ChildTree.Child[ind].Child.Add(TDomTreeNode.create(ChildTree.Owner,ChildTree.Child[ind], '', '', nil, '', tag_txt[2])); ChildTree.Child[ind].Child.Add(TDomTreeNode.create(ChildTree.Owner,ChildTree.Child[ind], tag_txt[3], '', nil, '</%s>','')) ; end else begin tag_txt := getTagTxt(mTxtMatch); ind := ChildTree.Child.Add(TDomTreeNode.create(ChildTree.Owner,ChildTree, tag_txt[0], tag_txt[1], getAttr(tag_txt[1]), tag_txt[3],'')); if (pos(',' + AnsiUpperCase(trim(tag_txt[0])) + ',', ExceptTag) = 0) and (LeftStr(tag_txt[0],2) <> '<?') and (LeftStr(tag_txt[0],2) <> '<!') then ChildTree := CheckParent(ChildTree.Child[ind],tag_txt[3]); if tag_txt[2] <> '' then ChildTree.Child.Add(TDomTreeNode.create(ChildTree.Owner,ChildTree, '', '', nil, '',tag_txt[2])); end; end; // *************************** START PARSE HTML************************* begin RegExHTML:=nil; RegExTag:=nil; try HtmlUtf8 := HtmlTxt; RegExHTML := TPerlRegEx.create; RegExTag := TPerlRegEx.create; ErrParseHTML:=0; RegExHTML.Options := [preCaseLess, preMultiLine, preSingleLine]; ChildTree := self; with RegExHTML do begin // *********RegExp for parsing HTML************** // (<title>.*</title>[^<]*) - title // (<\!--.+?-->[^<]*) - comment // (<script.*?</script>[^<]*) - script // (<[^>]+>[^<]*) - all remaining tags // [^<]* - text RegExException :='(<PLAINTEXT>.*?</PLAINTEXT>[^<]*)|'+ '(<title>.*?</title>[^<]*)|'+ '(<xmp>.*?</xmp>[^<]*)|'+ '(<script.*?</script>[^<]*)|'+ '(<textarea.*?</textarea>[^<]*)|'+ // '(<pre.*?</pre>[^<]*)|'+ '(<!--.+?-->[^<]*)|'; RegEx := RegExException + '(<[^>]+>[^<]*)'; // all teg and text Subject := HtmlUtf8; if Match then begin MatchTag(RegExHTML.MatchedText); prev := MatchedOffset + MatchedLength; while MatchAgain do begin MatchTag(RegExHTML.MatchedText); // *****Start Check Parsing HTML Error************ if MatchedOffset - prev > 0 then begin Owner.fParseErr.Add(IntToStr(ErrParseHTML) + '- Check error found after HTML parsing'); inc(ErrParseHTML) end; prev := MatchedOffset + MatchedLength; // *****End Check Parsing HTML Error************ end; // ***********End RegExp match cycle************ end else raise Exception.create('Input text not contain HTML tags'); // *************End RegExp match ************ end; Finally RegExHTML.Free; RegExTag.Free; if Owner.FCount>0 then result := True else result := False ; end; end; end.
program dosidcli; {$APPTYPE CONSOLE} uses windows, Classes, SysUtils; const AGROW_ALLOC = 256; ADEFAULT_SIZE = 1024; type tfile = record sf:string; //filename parent:string; //parent file if is inside a packed file hit:boolean; size:cardinal; container:string; //container type if inside a packed file end; IMAGE_DOS_HEADER = packed record e_magic : Word; // Magic number ("MZ") e_cblp : Word; // Bytes on last page of file e_cp : Word; // Pages in file e_crlc : Word; // Relocations e_cparhdr : Word; // Size of header in paragraphs e_minalloc: Word; // Minimum extra paragraphs needed e_maxalloc: Word; // Maximum extra paragraphs needed e_ss : Word; // Initial (relative) SS value e_sp : Word; // Initial SP value e_csum : Word; // Checksum e_ip : Word; // Initial IP value e_cs : Word; // Initial (relative) CS value e_lfarlc : Word; // Address of relocation table e_ovno : Word; // Overlay number e_res : packed array [0..3] of Word; // Reserved words e_oemid : Word; // OEM identifier (for e_oeminfo) e_oeminfo : Word; // OEM info; e_oemid specific e_res2 : packed array [0..9] of Word; // Reserved words e_lfanew : Longint; // File address of new exe header end; TExeFileKind = ( fkUnknown, // unknown file kind: not an executable fkError, // error file kind: used for files that don't exist fkDOS, // DOS executable fkExe32, // 32 bit executable fkExe16, // 16 bit executable fkDLL32, // 32 bit DLL fkDLL16, // 16 bit DLL fkVXD // virtual device driver ); var b:array[0..4095] of byte; //i/o buffer exepath: String; // path to the exe file exekind: TExeFileKind; // kind of exe ///////////////////////////////////////////////////////////////////////////////// function ExeType(const FileName: string): TExeFileKind; {Examines given file and returns a code that indicates the type of executable file it is (or if it isn't an executable)} const cDOSRelocOffset = $18; // offset of "pointer" to DOS relocation table cWinHeaderOffset = $3C; // offset of "pointer" to windows header in file cNEAppTypeOffset = $0D; // offset in NE windows header app type field cDOSMagic = $5A4D; // magic number identifying a DOS executable cNEMagic = $454E; // magic number identifying a NE executable (Win 16) cPEMagic = $4550; // magic nunber identifying a PE executable (Win 32) cLEMagic = $454C; // magic number identifying a Virtual Device Driver cNEDLLFlag = $80; // flag in NE app type field indicating a DLL var FS: TFileStream; // stream to executable file WinMagic: Word; // word that contains PE or NE magic numbers HdrOffset: LongInt; // offset of windows header in exec file DOSHeader: IMAGE_DOS_HEADER; // DOS header AppFlagsNE: Byte; // byte defining DLLs in NE format DOSFileSize: Integer; // size of DOS file begin try // Open stream onto file: raises exception if can't be read FS := TFileStream.Create(FileName, fmOpenRead + fmShareDenyNone); try // Assume unkown file Result := fkUnknown; // Any exec file is at least size of DOS header long if FS.Size < SizeOf(DOSHeader) then Exit; FS.ReadBuffer(DOSHeader, SizeOf(DOSHeader)); // DOS files begin with "MZ" if DOSHeader.e_magic <> cDOSMagic then Exit; // DOS files have length >= size indicated at offset $02 and $04 // (offset $02 indicates length of file mod 512 and offset $04 indicates // no. of 512 pages in file) if (DOSHeader.e_cblp = 0) then DOSFileSize := DOSHeader.e_cp * 512 else DOSFileSize := (DOSHeader.e_cp - 1) * 512 + DOSHeader.e_cblp; if FS.Size < DOSFileSize then Exit; // DOS file relocation offset must be within DOS file size. if DOSHeader.e_lfarlc > DOSFileSize then Exit; // We know we have an executable file: assume its a DOS program Result := fkDOS; // Try to find offset of Windows program header if FS.Size <= cWinHeaderOffset + SizeOf(LongInt) then // file too small for windows header "pointer": it's a DOS file Exit; // read it FS.Position := cWinHeaderOffset; FS.ReadBuffer(HdrOffset, SizeOf(LongInt)); // Now try to read first word of Windows program header if FS.Size <= HdrOffset + SizeOf(Word) then // file too small to contain header: it's a DOS file Exit; FS.Position := HdrOffset; // This word should be NE, PE or LE per file type: check which FS.ReadBuffer(WinMagic, SizeOf(Word)); case WinMagic of cPEMagic: begin // 32 bit Windows application: now check whether app or DLL Result := fkExe32; end; cNEMagic: begin // We have 16 bit Windows executable: check whether app or DLL if FS.Size <= HdrOffset + cNEAppTypeOffset + SizeOf(AppFlagsNE) then // app flags field would be beyond EOF: assume DOS Exit; // read app flags byte FS.Position := HdrOffset + cNEAppTypeOffset; FS.ReadBuffer(AppFlagsNE, SizeOf(AppFlagsNE)); if (AppFlagsNE and cNEDLLFlag) = cNEDLLFlag then // app flags indicate DLL Result := fkDLL16 else // app flags indicate program Result := fkExe16; end; cLEMagic: // We have a Virtual Device Driver Result := fkVXD; else // DOS application {Do nothing - DOS result already set}; end; finally FS.Free; end; except // Exception raised in function => error result Result := fkError; end; end; begin if paramcount<1 then begin writeln('dosidcli v1.0'); writeln('---------------------'); writeln(''); writeln('Usage: dosidcli "x:\full\path\to\file.exe"'); exit; end; exepath:=paramstr(1); if fileexists(exepath)=false then begin writeln('file not found.'); exit; end; exekind := ExeType(exepath); if exekind = fkDOS then begin writeln('DOS!'); exit; end else begin writeln('SOMETHINGELSE!'); exit; end; writeln('Done.'); end.
unit uFrmConexao; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, System.IniFiles, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet; type TDMCon = class(TDataModule) tfdConexao: TFDConnection; procedure DataModuleCreate(Sender: TObject); private FSenhaDB: String; FUserDB: String; FPathDB: String; { Private declarations } Procedure ConectarAoBanco; Procedure LerPropriedadesConexaoIni; Procedure ConfigurarConexao; Procedure ConectarAoBancoDeDados; procedure SetPathDB(const Value: String); procedure SetSenhaDB(const Value: String); procedure SetUserDB(const Value: String); procedure LerPropriedadesIni(ArquivoIni: TIniFile); procedure GravarPropriedadesIni(ArquivoIni: TIniFile); public { Public declarations } property PathDB : String read FPathDB write SetPathDB; property UserDB : String read FUserDB write SetUserDB; property SenhaDB : String read FSenhaDB write SetSenhaDB; end; var DMCon : TDMCon; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TDMCon.ConectarAoBanco; begin LerPropriedadesConexaoIni; ConfigurarConexao; ConectarAoBancoDeDados; end; procedure TDMCon.ConectarAoBancoDeDados; begin try tfdConexao.Close; tfdConexao.Open(); except on E: Exception do raise Exception.Create('Falha ao conectar ao banco de dados da aplicação'); end; end; procedure TDMCon.ConfigurarConexao; begin tfdConexao.Params.Database := PathDB; tfdConexao.Params.UserName := UserDB; tfdConexao.Params.Password := SenhaDB; end; procedure TDMCon.DataModuleCreate(Sender: TObject); begin ConectarAoBanco; end; procedure TDMCon.LerPropriedadesConexaoIni; var ArquivoIni : TIniFile; begin ArquivoIni := nil; try ArquivoIni := TIniFile.Create('C:\MiniCRM\MiniCRM.DB\ConfigDB.ini'); LerPropriedadesIni(ArquivoIni); GravarPropriedadesIni(ArquivoIni); finally ArquivoIni.Free end; end; procedure TDMCon.SetPathDB(const Value: String); begin FPathDB := Value; end; procedure TDMCon.SetSenhaDB(const Value: String); begin FSenhaDB := Value; end; procedure TDMCon.SetUserDB(const Value: String); begin FUserDB := Value; end; procedure TDMCon.LerPropriedadesIni(ArquivoIni: TIniFile); begin PathDB := ArquivoIni.ReadString('CONEXAO', 'PATH', EmptyStr); UserDB := ArquivoIni.ReadString('CONEXAO', 'USER', EmptyStr); SenhaDB := ArquivoIni.ReadString('CONEXAO', 'PASSWORD', EmptyStr); end; procedure TDMCon.GravarPropriedadesIni(ArquivoIni: TIniFile); begin if (PathDB = EmptyStr) or (UserDB = EmptyStr) or (SenhaDB = EmptyStr) then begin ArquivoIni.WriteString('CONEXAO', 'PATH', 'C:\MiniCRM\MiniCRM.DB\MINICRM.FDB'); ArquivoIni.WriteString('CONEXAO', 'USER', 'SYSDBA'); ArquivoIni.WriteString('CONEXAO', 'PASSWORD', 'masterkey'); end; end; initialization finalization FreeAndNil(DMCon); end.
unit ufrmDialogCompany; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterDialog, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, Vcl.ExtCtrls, uInterface, uModCompany, Vcl.StdCtrls; type TfrmDialogCompany = class(TfrmMasterDialog, ICRUDAble) lblCode: TLabel; edtCode: TEdit; edtName: TEdit; lblLblName: TLabel; procedure actDeleteExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure FormCreate(Sender: TObject); private FCompany: TModCompany; function GetCompany: TModCompany; property Company: TModCompany read GetCompany write FCompany; { Private declarations } public procedure LoadData(AID : String); { Public declarations } end; var frmDialogCompany: TfrmDialogCompany; implementation uses uAppUtils, uDXUtils, System.DateUtils, uDBUtils, uDMClient, uTSCommonDlg; {$R *.dfm} procedure TfrmDialogCompany.actDeleteExecute(Sender: TObject); begin inherited; if TAppUtils.ConfirmHapus then begin if DMClient.CrudClient.DeleteFromDB(FCompany) then Self.ModalResult := mrOk; end; end; procedure TfrmDialogCompany.actSaveExecute(Sender: TObject); begin inherited; if not ValidateEmptyCtrl([1]) then Exit; if TAppUtils.ConfirmSimpan then begin try Company.COMP_CODE := edtCode.Text; Company.COMP_NAME := edtName.Text; if DMClient.CrudClient.SaveToDB(FCompany) then ModalResult := mrOk; except raise; end; end; end; procedure TfrmDialogCompany.FormCreate(Sender: TObject); begin inherited; Self.AssignKeyDownEvent; end; function TfrmDialogCompany.GetCompany: TModCompany; begin if FCompany =nil then FCompany := TModCompany.Create; Result := FCompany; end; procedure TfrmDialogCompany.LoadData(AID : String); begin FreeAndNil(FCompany); edtCode.Text := ''; edtName.Text := ''; FCompany := DMClient.CrudClient.Retrieve(TModCompany.ClassName, AID) as TModCompany; if FCompany <> nil then begin edtCode.Text := FCompany.COMP_CODE; edtName.Text := FCompany.COMP_NAME; end; end; end.
unit uEnviarMail; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Buttons, StdCtrls, XMailer, uDAOSolicitar ; type { TFormEmail } TFormEmail = class(TForm) edtMail: TEdit; Label1: TLabel; SpeedButton1: TSpeedButton; SpeedButtonEnviar: TSpeedButton; procedure SpeedButton1Click(Sender: TObject); procedure SpeedButtonEnviarClick(Sender: TObject); private public function IsValidEmail(email: string): boolean; function EmailValido(correo: String): boolean; end; var FormEmail: TFormEmail; implementation {$R *.lfm} { TFormEmail } function TFormeMail.IsValidEmail(email: string): boolean; const charslist = ['_', '-', '.', '0'..'9', 'A'..'Z', 'a'..'z']; var Arobasc, lastpoint : boolean; i, n : integer; c : char; begin n := Length(email); i := 1; Arobasc := false; lastpoint := false; result := true; while (i <= n) do begin c := email[i]; if c = '@' then begin if Arobasc then begin result := false; exit; end; Arobasc := true; end else if (c = '.') and Arobasc then begin lastpoint := true; end else if not(c in charslist) then begin result := false; exit; end; inc(i); end; if not(lastpoint) or (email[n] = '.')then result := false; end; procedure TFormEmail.SpeedButton1Click(Sender: TObject); begin close; end; procedure TFormEmail.SpeedButtonEnviarClick(Sender: TObject); var Mail: TSendMail; begin Mail:= TSendMail.Create; if EmailValido(edtMail.text) then begin try Mail.Sender:='<lepra99@outlook.com>'; Mail.Subject:= 'Falta de Stock'; Mail.Receivers.Add(edtMail.text); Mail.Message.add('Se adjunta el pedido de stock'); mail.smtp.UserName:= 'lepra99@outlook.com'; Mail.smtp.password:='lu15m3ND35'; mail.smtp.Host:= 'smtp.office365.com'; Mail.smtp.port:= '587'; Mail.Smtp.FullSSL:= False; Mail.Smtp.TLS:=True; Mail.Attachments.Add(rutaActual); Mail.Send; finally if mail.Smtp.Login=false then ShowMessage('No hay conexion a internet') else begin Mail.Free; ShowMessage('Correo Enviado Exitosamente'); edtMail.Text:=''; end end; end; end; function Tformemail.EmailValido(correo: String): boolean; begin EmailValido:=false; if (IsValidEmail(edtMail.Text)) then begin EmailValido:=true end else begin ShowMessage('Dirección de Email Inválida'); edtMail.text:=''; end; end; end.
unit MsgPick; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, ExtCtrls; type TMsgPicker = class(TForm) Panel1: TPanel; MsgList: TListBox; BNOK: TButton; BNCancel: TButton; SBHelp: TSpeedButton; LBDetails: TLabel; BNFind: TButton; FindText: TFindDialog; procedure MsgListClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BNFindClick(Sender: TObject); procedure FindTextFind(Sender: TObject); private curMsg:integer; Procedure ClearMsgs; Procedure LoadMsgs; Procedure SelectMsg(nMsg:Integer); { Private declarations } public { Public declarations } Function PickMsg(oldMsg:Integer):Integer; end; var MsgPicker: TMsgPicker; implementation {$R *.DFM} uses Files, FileOperations, GlobalVars, misc_utils; Type TMSGDetails=class ID:Integer; N:Integer; end; Procedure TMsgPicker.ClearMsgs; var i:integer; begin for i:=0 to MsgList.Items.Count-1 do MsgList.Items.Objects[i].Free; MsgList.Items.Clear; end; Procedure TMsgPicker.SelectMsg(nMsg:Integer); var i:integer; begin for i:=0 to MsgList.Items.Count-1 do With MsgList.Items.Objects[i] as TMsgDetails do begin if ID=nMsg then begin MsgList.ItemIndex:=i; exit; end; end; MsgList.ItemIndex:=0; end; Procedure TMsgPicker.LoadMsgs; var t:TLECTextFile; s,w:string; p:integer; md:TMSGDetails; n,nSel:Integer; begin nSel:=0; n:=0; ClearMsgs; t:=TLECTextFile.CreateRead(OpenGameFile('local.msg')); Try While not t.eof do begin t.Readln(s); s:=Trim(s); if s='' then continue; md:=TMsgDetails.Create; p:=GetWord(s,1,w); ValInt(w,md.ID); p:=GetWord(s,p,w); SetLength(w,length(w)); ValInt(w,md.n); MsgList.Items.AddObject(Copy(s,p,Length(s)-p+1),md); if md.ID=CurMsg then nSel:=n; inc(n); end; MsgList.ItemIndex:=nSel; MsgListClick(nil); finally t.FClose; end; end; Function TMsgPicker.PickMsg(oldMsg:Integer):Integer; var i:integer; begin CurMsg:=oldMsg; SelectMsg(oldMsg); ActiveControl:=MsgList; if ShowModal<>idOK then Result:=oldMsg else begin Result:=oldMsg; i:=MsgList.ItemIndex; if i>=0 then With MsgList.Items.Objects[i] as TMSGDetails do Result:=ID; end; end; procedure TMsgPicker.MsgListClick(Sender: TObject); begin if MsgList.ItemIndex<0 then exit; With MsgList.Items.Objects[MsgList.ItemIndex] as TMsgDetails do LBDetails.Caption:=Format('ID: %d',[ID]); end; procedure TMsgPicker.FormCreate(Sender: TObject); begin LoadMsgs; end; procedure TMsgPicker.BNFindClick(Sender: TObject); begin FindText.Execute; end; procedure TMsgPicker.FindTextFind(Sender: TObject); var i,n:integer;s,w:string; begin n:=MsgList.ItemIndex; if n<0 then n:=-1; for i:=n+1 to MsgList.Items.Count-1 do begin s:=Uppercase(MsgList.Items[i]); w:=UpperCase(FindText.FindText); if Pos(w,s)<>0 then begin MsgList.ItemIndex:=i; MsgList.OnClick(MsgList); exit; end; end; ShowMessage('Text not found'); end; end.
unit ibSHDataBlobFrm; interface uses SHDesignIntf, ibSHDriverIntf, ibSHDesignIntf, ibSHDataCustomFrm, ibSHConsts, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, ExtCtrls, StdCtrls, ComCtrls, DBCtrls, ToolWin, VirtualTrees, ImgList, DB, SynEdit, pSHSynEdit, pSHDBSynEdit, PrnDbgeh, AppEvnts, ActnList, ExtDlgs, Clipbrd, Jpeg, Menus, DBGrids, SHOptionsIntf, DBGridEh, GridsEh; type TibSHBLOBEditorType = (betTEXT, betRTF, betSQL, betBMP, betNone); TibSHDataBlobForm = class(TibSHDataCustomForm) Panel1: TPanel; Splitter1: TSplitter; Panel2: TPanel; DBGridEh1: TDBGridEh; Panel3: TPanel; Splitter2: TSplitter; Panel4: TPanel; TEXTPanel: TPanel; RTFPanel: TPanel; SQLPanel: TPanel; Panel5: TPanel; Tree: TVirtualStringTree; dsTextControl: TDataSource; TextControl: TDBMemo; RTFControl: TDBRichEdit; SQLControl: TpSHDBSynEdit; dsGrid: TDataSource; dsRTFControl: TDataSource; dsSQLControl: TDataSource; ImageList1: TImageList; ApplicationEvents1: TApplicationEvents; sdGrid: TSaveDialog; PrintDBGridEh1: TPrintDBGridEh; PrintDBGridEh2: TPrintDBGridEh; dsImageControl: TDataSource; odText: TOpenDialog; odRTF: TOpenDialog; odImage: TOpenPictureDialog; ImagePanel: TScrollBox; sdText: TSaveDialog; sdRTF: TSaveDialog; sdImage: TSavePictureDialog; ImageControl: TImage; Panel6: TPanel; ToolBar1: TToolBar; DBNavigator1: TDBNavigator; ToolButton1: TToolButton; ComboBox1: TComboBox; Panel7: TPanel; pSHSynEdit2: TpSHSynEdit; Splitter3: TSplitter; PopupMenuMessage: TPopupMenu; pmiHideMessage: TMenuItem; procedure ControlBar1Resize(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); procedure AnyControlChange(Sender: TObject); procedure dsImageControlDataChange(Sender: TObject; Field: TField); procedure pmiHideMessageClick(Sender: TObject); private { Private declarations } FBLOBEditorType: TibSHBLOBEditorType; FFieldImageIndex: Integer; FCurrentField: TField; FJPEGSource: TJpegImage; FImageFormat: TibSHImageFormat; FBlobPopupMenu: TPopupMenu; procedure SetBLOBEditorType(Value: TibSHBLOBEditorType); procedure BuildTree; procedure SetTreeEvents; procedure SetDataLinks; procedure SetDataField; procedure SafeShowPicture; procedure ClearEditor; { Tree } procedure TreeClick(Sender: TObject); procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); procedure TreeIncrementalSearch(Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: WideString; var Result: Integer); procedure TreeDblClick(Sender: TObject); procedure TreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure GutterDrawNotify(Sender: TObject; ALine: Integer; var ImageIndex: Integer); function IsDBGridSelected: Boolean; protected { Protected declarations } procedure ShowMessages; override; procedure HideMessages; override; { ISHFileCommands } function GetCanOpen: Boolean; override; function GetCanSave: Boolean; override; function GetCanSaveAs: Boolean; override; function GetCanPrint: Boolean; override; procedure Open; override; procedure Save; override; procedure SaveAs; override; procedure Print; override; { ISHEditCommands } function GetCanUndo: Boolean; override; function GetCanRedo: Boolean; override; function GetCanCut: Boolean; override; function GetCanCopy: Boolean; override; function GetCanPaste: Boolean; override; function GetCanSelectAll: Boolean; override; function GetCanClearAll: Boolean; override; procedure Undo; override; procedure Redo; override; procedure Cut; override; procedure Copy; override; procedure Paste; override; procedure SelectAll; override; procedure ClearAll; override; { ISHSearchCommands } function GetCanFind: Boolean; override; function GetCanReplace: Boolean; override; function GetCanSearchAgain: Boolean; override; function GetCanSearchIncremental: Boolean; override; function GetCanGoToLineNumber: Boolean; override; procedure Find; override; procedure Replace; override; procedure SearchAgain; override; procedure SearchIncremental; override; procedure GoToLineNumber; override; procedure SetDBGridOptions(ADBGrid: TComponent); override; {IibDRVDatasetNotification} procedure DoOnPopupBlobMenu(Sender: TObject); procedure FillBlobPopupMenu; procedure OnFetchRecord(ADataset: IibSHDRVDataset); override; procedure DoUpdateStatusBarByState(Changes: TSynStatusChanges); override; procedure DoUpdateStatusBar; override; procedure DoOnIdle; override; function DoOnOptionsChanged: Boolean; override; function GetCanDestroy: Boolean; override; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure BringToTop; override; procedure ShowResult(AEnableFetchEvent: Boolean = True); override; property BLOBEditorType: TibSHBLOBEditorType read FBLOBEditorType write SetBLOBEditorType; end; var ibSHDataBlobForm: TibSHDataBlobForm; implementation uses ibSHComponentFrm, ibSHMessages; type PTreeRec = ^TTreeRec; TTreeRec = record FieldName: string; end; {$R *.dfm} { TibSHDataBlobForm } constructor TibSHDataBlobForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin inherited Create(AOwner, AParent, AComponent, ACallString); FCurrentField := nil; FBLOBEditorType := betNone; DBGrid := DBGridEh1; // EditorMsg := pSHSynEdit2; ResultEdit := pSHSynEdit2; ResultEdit.Lines.Clear; ResultEdit.OnGutterDraw := GutterDrawNotify; ResultEdit.GutterDrawer.ImageList := ImageList1; ResultEdit.GutterDrawer.Enabled := True; HideMessages; TEXTPanel.Align := alClient; RTFPanel.Align := alClient; SQLPanel.Align := alClient; ImagePanel.Align := alClient; ComboBox1.ItemIndex := 0; BLOBEditorType := betTEXT; Editor := SQLControl; RegisterEditors; CatchRunTimeOptionsDemon; DoOnOptionsChanged; SetTreeEvents; SetDataLinks; // BuildTree; FFieldImageIndex := Designer.GetImageIndex(IibSHField); TextControl.Font.Charset := RUSSIAN_CHARSET; FJPEGSource := TJpegImage.Create; FocusedControl := DBGrid; FBlobPopupMenu := TPopupMenu.Create(nil); FBlobPopupMenu.OnPopup := DoOnPopupBlobMenu; FillBlobPopupMenu; TextControl.PopupMenu := FBlobPopupMenu; RTFControl.PopupMenu := FBlobPopupMenu; SQLControl.PopupMenu := FBlobPopupMenu; ImageControl.PopupMenu := FBlobPopupMenu; end; destructor TibSHDataBlobForm.Destroy; begin FBlobPopupMenu.Free; FJPEGSource.Free; inherited Destroy; end; procedure TibSHDataBlobForm.ControlBar1Resize(Sender: TObject); begin ToolBar1.Width := ToolBar1.Parent.ClientWidth; end; procedure TibSHDataBlobForm.ComboBox1Change(Sender: TObject); begin BLOBEditorType := TibSHBLOBEditorType(ComboBox1.ItemIndex); end; procedure TibSHDataBlobForm.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); begin DoOnIdle; end; procedure TibSHDataBlobForm.AnyControlChange(Sender: TObject); begin if Assigned(StatusBar) and (StatusBar.Panels.Count >= 3) then begin if FBLOBEditorType = betText then begin StatusBar.Panels[0].Text := IntToStr(TextControl.CaretPos.Y) + ': ' + IntToStr(TextControl.CaretPos.X); //Позиция курсора if TextControl.Modified then StatusBar.Panels[1].Text := Format(' Modified', []) //First space required! else StatusBar.Panels[1].Text := EmptyStr; if TextControl.ReadOnly then StatusBar.Panels[2].Text := Format(' Read only', []) //First space required! else StatusBar.Panels[2].Text := EmptyStr; end else if FBLOBEditorType = betRTF then begin StatusBar.Panels[0].Text := IntToStr(RTFControl.CaretPos.Y) + ': ' + IntToStr(RTFControl.CaretPos.X); //Позиция курсора if RTFControl.Modified then StatusBar.Panels[1].Text := Format(' Modified', []) //First space required! else StatusBar.Panels[1].Text := EmptyStr; if RTFControl.ReadOnly then StatusBar.Panels[2].Text := Format(' Read only', []) //First space required! else StatusBar.Panels[2].Text := EmptyStr; end else if FBLOBEditorType = betBMP then //betSQL, begin StatusBar.Panels[0].Text := EmptyStr; StatusBar.Panels[1].Text := EmptyStr; case FImageFormat of imBitmap: StatusBar.Panels[2].Text := ' Bitmap'; imJPEG: StatusBar.Panels[2].Text := ' JPEG'; imWMF: StatusBar.Panels[2].Text := ' WMF'; imEMF: StatusBar.Panels[2].Text := ' EMF'; imICO: StatusBar.Panels[2].Text := ' ICO'; else StatusBar.Panels[2].Text := EmptyStr; end; // Format(' Read only', []) //First space required! end; end; end; procedure TibSHDataBlobForm.SetBLOBEditorType(Value: TibSHBLOBEditorType); begin if FBLOBEditorType <> Value then begin FBLOBEditorType := Value; TEXTPanel.Visible := False; RTFPanel.Visible := False; SQLPanel.Visible := False; ImagePanel.Visible := False; case FBLOBEditorType of betTEXT: TEXTPanel.Visible := True; betRTF: RTFPanel.Visible := True; betSQL: SQLPanel.Visible := True; betBMP: ImagePanel.Visible := True; end; SetDataField; AnyControlChange(nil); end; end; procedure TibSHDataBlobForm.BuildTree; var I: Integer; Node: PVirtualNode; NodeData: PTreeRec; begin if Assigned(Data) then begin Tree.BeginUpdate; try Tree.Clear; for I := 0 to Pred(Data.Dataset.Dataset.FieldCount) do begin if Data.Dataset.Dataset.Fields[I].DataType in [ftBlob, ftMemo, ftGraphic, ftFmtMemo, ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor, ftOraBlob] then begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.FieldName := Data.Dataset.Dataset.Fields[I].FieldName; end; end; Node := Tree.GetFirst; if Assigned(Node) then begin Tree.FocusedNode := Node; Tree.Selected[Tree.FocusedNode] := True; SetDataField; end; finally Tree.EndUpdate; end; end; end; procedure TibSHDataBlobForm.SetTreeEvents; begin Tree.Images := Designer.ImageList; Tree.OnClick := TreeClick; Tree.OnGetNodeDataSize := TreeGetNodeDataSize; Tree.OnFreeNode := TreeFreeNode; Tree.OnGetImageIndex := TreeGetImageIndex; Tree.OnGetText := TreeGetText; Tree.OnPaintText := TreePaintText; Tree.OnIncrementalSearch := TreeIncrementalSearch; Tree.OnDblClick := TreeDblClick; Tree.OnCompareNodes := TreeCompareNodes; end; procedure TibSHDataBlobForm.SetDataLinks; begin dsGrid.DataSet := Data.Dataset.Dataset; dsTextControl.DataSet := Data.Dataset.Dataset; dsRTFControl.DataSet := Data.Dataset.Dataset; dsSQLControl.DataSet := Data.Dataset.Dataset; dsImageControl.DataSet := Data.Dataset.Dataset; DBNavigator1.DataSource := dsGrid; end; procedure TibSHDataBlobForm.SetDataField; var Node: PVirtualNode; NodeData: PTreeRec; begin Node := Tree.FocusedNode; if Assigned(Node) then begin NodeData := Tree.GetNodeData(Node); if Assigned(NodeData) then begin FCurrentField := Data.Dataset.Dataset.FindField(NodeData.FieldName); if Assigned(FCurrentField) then FCurrentField.FreeNotification(Self); TextControl.DataField := EmptyStr; RTFControl.DataField := EmptyStr; SQLControl.DataField := EmptyStr; case FBLOBEditorType of betTEXT: begin TextControl.DataField := NodeData.FieldName; TEXTPanel.Visible := True; end; betRTF: begin RTFControl.DataField := NodeData.FieldName; RTFPanel.Visible := True; end; betSQL: begin SQLControl.DataField := NodeData.FieldName; SQLPanel.Visible := True; end; betBMP: begin SafeShowPicture; ImagePanel.Visible := True; end; end; end; end else begin TEXTPanel.Visible := False; RTFPanel.Visible := False; SQLPanel.Visible := False; ImagePanel.Visible := False; TextControl.DataField := EmptyStr; RTFControl.DataField := EmptyStr; SQLControl.DataField := EmptyStr; if Assigned(FCurrentField) then RemoveFreeNotification(FCurrentField); FCurrentField := nil; SafeShowPicture; end; end; procedure TibSHDataBlobForm.SafeShowPicture; var BlobStream: TStream; begin if Assigned(dsImageControl.DataSet) and dsImageControl.DataSet.Active and Assigned(FCurrentField) and (FBLOBEditorType = betBMP) then begin BlobStream := dsImageControl.DataSet.CreateBlobStream(FCurrentField, bmRead); try ImageControl.Visible := False; ImagePanel.Width := 0; ImagePanel.Height := 0; ImagePanel.HorzScrollBar.Range := 0; ImagePanel.VertScrollBar.Range := 0; FImageFormat := GetImageStreamFormat(BlobStream); case FImageFormat of imBitmap: ImageControl.Picture.Bitmap.LoadFromStream(BlobStream); imJPEG: begin FJPEGSource.LoadFromStream(BlobStream); ImageControl.Picture.Graphic := FJPEGSource; end; imWMF, imEMF: ImageControl.Picture.Metafile.LoadFromStream(BlobStream); imICO: ImageControl.Picture.Icon.LoadFromStream(BlobStream); end; if FImageFormat <> imUnknown then begin ImagePanel.Width := ImageControl.Picture.Width + 2; ImagePanel.Height := ImageControl.Picture.Height + 2; ImagePanel.HorzScrollBar.Range := ImageControl.Picture.Width + 2; ImagePanel.VertScrollBar.Range := ImageControl.Picture.Height + 2; ImageControl.Visible := True; end; finally BlobStream.Free; end; AnyControlChange(nil); end; end; procedure TibSHDataBlobForm.ClearEditor; begin Tree.Clear; if Assigned(ImageControl.Picture.Graphic) then ImageControl.Picture.Graphic := nil; ImageControl.Visible := False; SetDataField; end; { Tree } procedure TibSHDataBlobForm.TreeClick(Sender: TObject); begin SetDataField; end; procedure TibSHDataBlobForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TTreeRec); end; procedure TibSHDataBlobForm.TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Assigned(Data) then begin Finalize(Data^); end; end; procedure TibSHDataBlobForm.TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Assigned(Data) then case Column of 0: if (Kind = ikNormal) or (Kind = ikSelected) then ImageIndex := FFieldImageIndex; end; end; procedure TibSHDataBlobForm.TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Assigned(Data) then case Column of 0: case TextType of ttNormal: CellText := Data.FieldName; ttStatic: CellText := EmptyStr; (*case Sender.GetNodeLevel(Node) of 0: ; 1: CellText := Data.Description; end;*) end; end; end; procedure TibSHDataBlobForm.TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); begin if Assigned(Node) then case Column of 0: case TextType of ttNormal: ; ttStatic: if Sender.Focused and (vsSelected in Node.States) then TargetCanvas.Font.Color := clWindow else TargetCanvas.Font.Color := clGray; end; end; end; procedure TibSHDataBlobForm.TreeIncrementalSearch(Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: WideString; var Result: Integer); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Pos(AnsiUpperCase(SearchText), AnsiUpperCase(Data.FieldName)) <> 1 then Result := 1; end; procedure TibSHDataBlobForm.TreeDblClick(Sender: TObject); begin end; procedure TibSHDataBlobForm.TreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var Data1, Data2: PTreeRec; begin Data1 := Sender.GetNodeData(Node1); Data2 := Sender.GetNodeData(Node2); Result := CompareStr(Data1.FieldName, Data2.FieldName); end; procedure TibSHDataBlobForm.GutterDrawNotify(Sender: TObject; ALine: Integer; var ImageIndex: Integer); begin if ALine = 0 then ImageIndex := 1; end; function TibSHDataBlobForm.IsDBGridSelected: Boolean; begin Result := DBGrid.Focused or (Assigned(DBGrid.InplaceEditor) and DBGrid.InplaceEditor.Visible) or ((GetGridWideEditor<>nil) and TWinControl(GetGridWideEditor).Focused) ; end; procedure TibSHDataBlobForm.ShowMessages; begin Panel7.Visible := True; Splitter3.Visible := True; end; procedure TibSHDataBlobForm.HideMessages; begin Panel7.Visible := False; Splitter3.Visible := False; end; { ISHFileCommands } function TibSHDataBlobForm.GetCanOpen: Boolean; begin Result := False; if Assigned(Data) and Assigned(Data.Dataset) and Data.Dataset.Active and Assigned(FCurrentField) then begin case FBLOBEditorType of betTEXT: Result := True; betRTF: Result := True; betSQL: Result := inherited GetCanOpen; betBMP: Result := True; end; end; end; function TibSHDataBlobForm.GetCanSave: Boolean; begin Result := False; if IsDBGridSelected then begin Result := Assigned(SHCLDatabase) and (not SHCLDatabase.WasLostConnect) and Assigned(Data) and Data.Dataset.Active; end else if Assigned(Data) and Assigned(Data.Dataset) and Data.Dataset.Active and Assigned(FCurrentField) then begin case FBLOBEditorType of betTEXT: Result := True; betRTF: Result := True; betSQL: Result := inherited GetCanSave; betBMP: Result := Assigned(FCurrentField) and (not FCurrentField.IsNull); end; end; end; function TibSHDataBlobForm.GetCanSaveAs: Boolean; begin Result := GetCanSave; end; function TibSHDataBlobForm.GetCanPrint: Boolean; begin Result := False; if IsDBGridSelected then begin Result := GetCanSave end else if Assigned(Data) and Assigned(Data.Dataset) and Data.Dataset.Active and Assigned(FCurrentField) then begin case FBLOBEditorType of betTEXT: Result := False; betRTF: Result := True; betSQL: Result := inherited GetCanPrint; betBMP: Result := False; end; end; end; procedure TibSHDataBlobForm.Open; var vFileStream: TFileStream; vBLOBStream: TStream; begin if GetCanOpen then begin case FBLOBEditorType of betTEXT: begin if odText.Execute then begin if not (Data.Dataset.Dataset.State in [dsEdit, dsInsert]) then Data.Dataset.Dataset.Edit; try TextControl.Lines.LoadFromFile(odText.FileName); except Designer.ShowMsg(Format('%s', ['Cannot load from file.']), mtError); end; end; end; betRTF: begin if odRTF.Execute then begin try vFileStream := TFileStream.Create(odRTF.FileName, fmOpenRead); if not (Data.Dataset.Dataset.State in [dsEdit, dsInsert]) then Data.Dataset.Dataset.Edit; vBLOBStream := Data.Dataset.Dataset.CreateBlobStream(RTFControl.Field, bmWrite); try try vBLOBStream.CopyFrom(vFileStream, vFileStream.Size); except Designer.ShowMsg(Format('%s', ['Cannot load from RTF stream.']), mtError); end; RTFControl.LoadMemo; finally vFileStream.Free; vBLOBStream.Free; end; except Designer.ShowMsg(Format('%s', ['Cannot load from file.']), mtError); end; end; end; betSQL: inherited Open; betBMP: begin if odImage.Execute then begin try vFileStream := TFileStream.Create(odImage.FileName, fmOpenRead); if not (Data.Dataset.Dataset.State in [dsEdit, dsInsert]) then Data.Dataset.Dataset.Edit; vBLOBStream := Data.Dataset.Dataset.CreateBlobStream(FCurrentField, bmWrite); try try vBLOBStream.CopyFrom(vFileStream, vFileStream.Size); except Designer.ShowMsg(Format('%s', ['Cannot load from stream.']), mtError); end; SafeShowPicture; finally vFileStream.Free; vBLOBStream.Free; end; except Designer.ShowMsg(Format('%s', ['Cannot load from file.']), mtError); end; end; end; end; end; end; procedure TibSHDataBlobForm.Save; begin SaveAs; end; procedure TibSHDataBlobForm.SaveAs; var vFileStream: TFileStream; vBLOBStream: TStream; // For grid saving vDataSaver: ISHDataSaver; vServerOptions: IibSHServerOptions; I, J: Integer; vFilter: string; vFileName: string; vInputExt: string; vExt: TStringList; vSaved: Boolean; begin if GetCanSaveAs then begin if IsDBGridSelected then begin vFilter := ''; vExt := TStringList.Create; try for I := Pred(Designer.Components.Count) downto 0 do if Supports(Designer.Components[I], ISHDataSaver, vDataSaver) then for J := 0 to Pred(vDataSaver.SupportsExtentions.Count) do begin if vExt.IndexOf(vDataSaver.SupportsExtentions[J]) = -1 then begin vExt.Add(vDataSaver.SupportsExtentions[J]); vFilter := vFilter + Format(SExportExtentionTemplate, [vDataSaver.ExtentionDescriptions[J], vDataSaver.SupportsExtentions[J], vDataSaver.SupportsExtentions[J]]) + '|'; end; end; if Length(vFilter) > 0 then begin Delete(vFilter, Length(vFilter), 1); sdGrid.Filter := vFilter; (* dk: заремил 27.06.2004 по причине сноса проперти DatabaseAliaOptions.Paths if Supports(Designer.GetOptions(ISHSystemOptions), ISHSystemOptions, vSystemOptions) then sdGrid.InitialDir := BTCLDatabase.DatabaseAliasOptions.Paths.ForExtracts; *) if IsEqualGUID(Component.BranchIID, IibSHBranch) then Supports(Designer.GetOptions(IibSHServerOptions), IibSHServerOptions, vServerOptions) else if IsEqualGUID(Component.BranchIID, IfbSHBranch) then Supports(Designer.GetOptions(IfbSHServerOptions), IibSHServerOptions, vServerOptions); if Assigned(vServerOptions) then sdGrid.FilterIndex := vServerOptions.SaveResultFilterIndex; if sdGrid.Execute then begin vFileName := sdGrid.FileName; vInputExt := ExtractFileExt(sdGrid.FileName); if not SameText(vInputExt, vExt[sdGrid.FilterIndex - 1]) then vFileName := ChangeFileExt(vFileName, vExt[sdGrid.FilterIndex - 1]); vSaved := False; for I := Pred(Designer.Components.Count) downto 0 do if Supports(Designer.Components[I], ISHDataSaver, vDataSaver) then begin if vDataSaver.SupportsExtentions.IndexOf(vInputExt) <> -1 then begin vDataSaver.SaveToFile(Component, Data.Dataset.Dataset, DBGridEh1, vFileName); vSaved := True; Break; end; end; if vSaved and Assigned(vServerOptions) then begin vServerOptions.SaveResultFilterIndex := sdGrid.FilterIndex; end; end; end else Designer.ShowMsg(SNoExportersRegisted, mtWarning); finally vExt.Free; end; end else case FBLOBEditorType of betTEXT: begin if sdText.Execute then begin try TextControl.Lines.SaveToFile(sdText.FileName); except Designer.ShowMsg(Format('%s', ['Cannot save file.']), mtError); end; end; end; betRTF: begin if sdRTF.Execute then begin try vFileStream := TFileStream.Create(sdRTF.FileName, fmCreate); vBLOBStream := Data.Dataset.Dataset.CreateBlobStream(RTFControl.Field, bmRead); try try vFileStream.CopyFrom(vBLOBStream, vBLOBStream.Size); except Designer.ShowMsg(Format('%s', ['Cannot load from BLOB stream.']), mtError); end; finally vFileStream.Free; vBLOBStream.Free; end; except Designer.ShowMsg(Format('%s', ['Cannot save file.']), mtError); end; end; end; betSQL: inherited SaveAs; betBMP: begin if sdImage.Execute then begin try vFileStream := TFileStream.Create(sdImage.FileName, fmCreate); vBLOBStream := Data.Dataset.Dataset.CreateBlobStream(FCurrentField, bmRead); try try vFileStream.CopyFrom(vBLOBStream, vBLOBStream.Size); except Designer.ShowMsg(Format('%s', ['Cannot load from BLOB stream.']), mtError); end; finally vFileStream.Free; vBLOBStream.Free; end; except Designer.ShowMsg(Format('%s', ['Cannot save file.']), mtError); end; end; end; end; end; end; procedure TibSHDataBlobForm.Print; begin if GetCanPrint then begin if IsDBGridSelected then begin PrintDBGridEh1.Preview; end else case FBLOBEditorType of betTEXT: ; betRTF: RTFControl.Print(Format('%s', [RTFControl.Field.FieldName])); betSQL: inherited Print; betBMP: ; end; end; end; function TibSHDataBlobForm.GetCanUndo: Boolean; begin if IsDBGridSelected then begin Result := GetCanSave and Assigned(DBGrid) and Assigned(DBGrid.InplaceEditor) and DBGrid.InplaceEditor.Visible and DBGrid.InplaceEditor.CanUndo; end else begin Result := Assigned(FCurrentField); if Result then case FBLOBEditorType of betTEXT: Result := TextControl.CanUndo; betRTF: Result := RTFControl.CanUndo; betSQL: inherited GetCanUndo; betBMP: ; end; end; end; function TibSHDataBlobForm.GetCanRedo: Boolean; begin if IsDBGridSelected then Result := False else begin Result := Assigned(FCurrentField); if Result then case FBLOBEditorType of betTEXT: ; betRTF: ; betSQL: inherited GetCanRedo; betBMP: ; end; end; end; function TibSHDataBlobForm.GetCanCut: Boolean; begin if IsDBGridSelected then begin Result := inherited GetCanCut end else begin Result := GetCanCopy; if Result then case FBLOBEditorType of betTEXT: Result := not TextControl.Field.ReadOnly; betRTF: Result := not RTFControl.Field.ReadOnly; betSQL: Result := not SQLControl.Field.ReadOnly; betBMP: Result := GetCanCopy and GetCanClearAll; end; end; end; function TibSHDataBlobForm.GetCanCopy: Boolean; begin if IsDBGridSelected then begin Result := inherited GetCanCopy end else begin Result := Assigned(FCurrentField); if Result then if GetCanSave then case FBLOBEditorType of betTEXT: Result := Length(TextControl.SelText) > 0; betRTF: Result := Length(RTFControl.SelText) > 0; // betSQL: Result := inherited GetCanCopy; betSQL: Result := Length(SQLControl.SelText) > 0; betBMP: Result := Assigned(ImageControl.Picture.Graphic); end; end; end; function TibSHDataBlobForm.GetCanPaste: Boolean; begin try if IsDBGridSelected then begin Result := inherited GetCanPaste end else begin Result := Assigned(FCurrentField); if Result then case FBLOBEditorType of betTEXT: Result := not TextControl.Field.ReadOnly and IsClipboardFormatAvailable(CF_TEXT); betRTF: Result := not RTFControl.Field.ReadOnly and IsClipboardFormatAvailable(CF_TEXT); betSQL: Result := not SQLControl.Field.ReadOnly and IsClipboardFormatAvailable(CF_TEXT); // betSQL: Result := inherited GetCanPaste; betBMP: Result := Assigned(FCurrentField) and (not FCurrentField.ReadOnly) and IsClipboardFormatAvailable(CF_BITMAP); end; end; except Result := False; end; end; function TibSHDataBlobForm.GetCanSelectAll: Boolean; begin if IsDBGridSelected then Result := GetCanSave else begin Result := GetCanSave; if Result then case FBLOBEditorType of { betTEXT: ; betRTF: ; betSQL: inherited GetCanSelectAll;} betBMP: Result := False; end; end; end; function TibSHDataBlobForm.GetCanClearAll: Boolean; begin if IsDBGridSelected then begin Result := False; end else begin Result := GetCanSave; if Result then case FBLOBEditorType of betTEXT: Result := not TextControl.Field.ReadOnly; betRTF: Result := not RTFControl.Field.ReadOnly; // betSQL: Result := inherited GetCanClearAll; betSQL: Result :=not SQLControl.Field.ReadOnly; betBMP: Result := (not FCurrentField.ReadOnly) and Assigned(ImageControl.Picture.Graphic); end; end; end; procedure TibSHDataBlobForm.Undo; begin if GetCanUndo then begin if IsDBGridSelected then DBGrid.InplaceEditor.Undo else begin case FBLOBEditorType of betTEXT: TextControl.Undo; betRTF: RTFControl.Undo; betSQL: SQLControl.Undo; betBMP: ; end; end; end; end; procedure TibSHDataBlobForm.Redo; begin if GetCanRedo then begin case FBLOBEditorType of betTEXT: ; betRTF: ; betSQL: SQLControl.Redo; betBMP: ; end; end; end; procedure TibSHDataBlobForm.Cut; begin if GetCanCut then if IsDBGridSelected then inherited // DBGrid.InplaceEditor.Perform(WM_CUT, 0, 0) else begin case FBLOBEditorType of betTEXT: TextControl.CutToClipboard; betRTF: RTFControl.CutToClipboard; betSQL: SQLControl.CutToClipboard; betBMP: begin Copy; ClearAll; end; end; end; end; procedure TibSHDataBlobForm.Copy; var vFormat: Word; vData: THandle; vPalette: HPALETTE; begin if GetCanCopy then if IsDBGridSelected then begin inherited end else begin case FBLOBEditorType of betTEXT: TextControl.CopyToClipboard; betRTF: RTFControl.CopyToClipboard; betSQL: SQLControl.CopyToClipboard; betBMP: begin ImageControl.Picture.Graphic.SaveToClipboardFormat(vFormat, vData, vPalette); ClipBoard.SetAsHandle(vFormat, vData); end; end; end; end; procedure TibSHDataBlobForm.Paste; var vBLOBStream: TStream; begin if GetCanPaste then if IsDBGridSelected then begin inherited end else begin case FBLOBEditorType of betTEXT: TextControl.PasteFromClipboard; betRTF: RTFControl.PasteFromClipboard; betSQL: SQLControl.PasteFromClipboard; betBMP: begin ImageControl.Picture.LoadFromClipBoardFormat(CF_BITMAP, ClipBoard.GetAsHandle(CF_BITMAP), 0); if not (Data.Dataset.Dataset.State in [dsEdit, dsInsert]) then Data.Dataset.Dataset.Edit; vBLOBStream := Data.Dataset.Dataset.CreateBlobStream(FCurrentField, bmWrite); try try ImageControl.Picture.Graphic.SaveToStream(vBLOBStream); except Designer.ShowMsg(Format('%s', ['Cannot save to stream.']), mtError); end; SafeShowPicture; finally vBLOBStream.Free; end; end; end; end; end; procedure TibSHDataBlobForm.SelectAll; begin if GetCanSelectAll then if IsDBGridSelected then begin if Assigned(DBGrid) and Assigned(DBGrid.InplaceEditor) and DBGrid.InplaceEditor.Visible then DBGrid.InplaceEditor.SelectAll else DBGridEh1.Selection.SelectAll; end else begin case FBLOBEditorType of betTEXT: TextControl.SelectAll; betRTF: RTFControl.SelectAll; betSQL: SQLControl.SelectAll; betBMP: ; end; end; end; procedure TibSHDataBlobForm.ClearAll; begin if GetCanClearAll then begin if not (Data.Dataset.Dataset.State in [dsEdit, dsInsert]) then Data.Dataset.Dataset.Edit; case FBLOBEditorType of betTEXT: TextControl.Clear; betRTF: RTFControl.Clear; betSQL: SQLControl.Clear; betBMP: begin if not (Data.Dataset.Dataset.State in [dsEdit, dsInsert]) then Data.Dataset.Dataset.Edit; FCurrentField.Clear; SafeShowPicture; end; end; end; end; function TibSHDataBlobForm.GetCanFind: Boolean; begin Result := Assigned(FCurrentField); if Result then case FBLOBEditorType of betTEXT: ; betRTF: ; // betSQL: inherited GetCanFind; betBMP: ; end; end; function TibSHDataBlobForm.GetCanReplace: Boolean; begin Result := Assigned(FCurrentField); if Result then case FBLOBEditorType of betTEXT: ; betRTF: ; // betSQL: inherited GetCanReplace; betBMP: ; end; end; function TibSHDataBlobForm.GetCanSearchAgain: Boolean; begin Result := Assigned(FCurrentField); if Result then case FBLOBEditorType of betTEXT: ; betRTF: ; // betSQL: inherited GetCanSearchAgain; betBMP: ; end; end; function TibSHDataBlobForm.GetCanSearchIncremental: Boolean; begin Result := Assigned(FCurrentField); if Result then case FBLOBEditorType of betTEXT: ; betRTF: ; // betSQL: inherited GetCanSearchIncremental; betBMP: ; end; end; function TibSHDataBlobForm.GetCanGoToLineNumber: Boolean; begin Result := Assigned(FCurrentField); if Result then case FBLOBEditorType of betTEXT: ; betRTF: ; // betSQL: inherited GetCanGoToLineNumber; betBMP: ; end; end; procedure TibSHDataBlobForm.Find; begin case FBLOBEditorType of betTEXT: ; betRTF: ; // betSQL: inherited Find; betBMP: ; end; end; procedure TibSHDataBlobForm.Replace; begin case FBLOBEditorType of betTEXT: ; betRTF: ; // betSQL: inherited Replace; betBMP: ; end; end; procedure TibSHDataBlobForm.SearchAgain; begin case FBLOBEditorType of betTEXT: ; betRTF: ; // betSQL: inherited SearchAgain; betBMP: ; end; end; procedure TibSHDataBlobForm.SearchIncremental; begin case FBLOBEditorType of betTEXT: ; betRTF: ; // betSQL: inherited SearchIncremental; betBMP: ; end; end; procedure TibSHDataBlobForm.GoToLineNumber; begin case FBLOBEditorType of betTEXT: ; betRTF: ; // betSQL: inherited GoToLineNumber; betBMP: ; end; end; procedure TibSHDataBlobForm.SetDBGridOptions(ADBGrid: TComponent); var vDBGrid: TDBGridEh; begin inherited SetDBGridOptions(ADBGrid); if Assigned(ADBGrid) then begin if ADBGrid is TDBGridEh then begin vDBGrid := TDBGridEh(ADBGrid); vDBGrid.Options := vDBGrid.Options - [dgCancelOnExit]; end; end; end; procedure TibSHDataBlobForm.DoOnPopupBlobMenu(Sender: TObject); //var // vCurrentMenuItem: TMenuItem; begin MenuItemByName(FBlobPopupMenu.Items, SOpenFile).Enabled := GetCanOpen; MenuItemByName(FBlobPopupMenu.Items, SSaveToFile).Enabled := GetCanSave; MenuItemByName(FBlobPopupMenu.Items, SCut).Enabled := GetCanCut; MenuItemByName(FBlobPopupMenu.Items, SCopy).Enabled := GetCanCopy; MenuItemByName(FBlobPopupMenu.Items, SPaste).Enabled := GetCanPaste; MenuItemByName(FBlobPopupMenu.Items, SUndo).Enabled := GetCanUndo; MenuItemByName(FBlobPopupMenu.Items, SRedo).Enabled := GetCanRedo; MenuItemByName(FBlobPopupMenu.Items, SSelectAll).Enabled := GetCanSelectAll; MenuItemByName(FBlobPopupMenu.Items, SPrint).Enabled := GetCanPrint; // vCurrentMenuItem := MenuItemByName(FBlobPopupMenu.Items, SOtherEdit); // MenuItemByName(vCurrentMenuItem, SUndo).Enabled := GetCanUndo; // MenuItemByName(vCurrentMenuItem, SRedo).Enabled := GetCanRedo; // MenuItemByName(vCurrentMenuItem, SSelectAll).Enabled := GetCanSelectAll; end; procedure TibSHDataBlobForm.FillBlobPopupMenu; //var // vCurrentItem: TMenuItem; begin AddMenuItem(FBlobPopupMenu.Items, SOpenFile, mnOpenFileClick, ShortCut(Ord('O'), [ssCtrl])); AddMenuItem(FBlobPopupMenu.Items, SSaveToFile, mnSaveToFileClick, ShortCut(Ord('S'), [ssCtrl])); AddMenuItem(FBlobPopupMenu.Items, '-', nil, 0, 21); AddMenuItem(FBlobPopupMenu.Items, SCut, mnCut, ShortCut(Ord('X'), [ssCtrl])); AddMenuItem(FBlobPopupMenu.Items, SCopy, mnCopy, ShortCut(Ord('C'), [ssCtrl])); AddMenuItem(FBlobPopupMenu.Items, SPaste, mnPaste, ShortCut(Ord('V'), [ssCtrl])); AddMenuItem(FBlobPopupMenu.Items, '-', nil, 0, 22); AddMenuItem(FBlobPopupMenu.Items, SUndo, mnUndo, ShortCut(Ord('Z'), [ssCtrl])); AddMenuItem(FBlobPopupMenu.Items, SRedo, mnRedo, ShortCut(Ord('Z'), [ssShift, ssCtrl])); AddMenuItem(FBlobPopupMenu.Items, '-', nil, 0, 23); AddMenuItem(FBlobPopupMenu.Items, SSelectAll, mnSelectAll, ShortCut(Ord('A'), [ssCtrl])); AddMenuItem(FEditorPopupMenu.Items, '-', nil, 0, 8); AddMenuItem(FBlobPopupMenu.Items, SPrint, mnPrintClick, ShortCut(Ord('P'), [ssCtrl])); // vCurrentItem := AddMenuItem(FBlobPopupMenu.Items, SOtherEdit); // AddMenuItem(vCurrentItem, SUndo, mnUndo, ShortCut(Ord('Z'), [ssCtrl])); // AddMenuItem(vCurrentItem, SRedo, mnRedo, ShortCut(Ord('Z'), [ssShift, ssCtrl])); // AddMenuItem(vCurrentItem, '-', nil, 0, 23); // AddMenuItem(vCurrentItem, SSelectAll, mnSelectAll, ShortCut(Ord('A'), [ssCtrl])); end; procedure TibSHDataBlobForm.OnFetchRecord(ADataset: IibSHDRVDataset); begin if EnabledFetchEvent then begin if Assigned(SHCLDatabase) and (not SHCLDatabase.WasLostConnect) then begin DoUpdateStatusBar; Application.ProcessMessages; Designer.UpdateActions; if Assigned(SHCLDatabase) and (SHCLDatabase.WasLostConnect) then begin Data.Dataset.IsFetching := False; Exit; end; end else if Assigned(SHCLDatabase) and (SHCLDatabase.WasLostConnect) then Data.Dataset.IsFetching := False; end; end; procedure TibSHDataBlobForm.DoUpdateStatusBarByState( Changes: TSynStatusChanges); begin if (FBLOBEditorType = betSQL) then inherited DoUpdateStatusBarByState(Changes); end; procedure TibSHDataBlobForm.DoUpdateStatusBar; begin inherited DoUpdateStatusBar; end; procedure TibSHDataBlobForm.DoOnIdle; begin inherited DoOnIdle; // tbCommit.Visible := (not AutoCommit); // tbRollback.Visible := (not AutoCommit); // ToolButton4.Visible := (not AutoCommit); // actPause.Enabled := GetCanPause; // actCommit.Enabled := GetCanCommit; // actRollback.Enabled := GetCanRollback; // actRefresh.Enabled := GetCanRefresh; // actFilter.Enabled := Assigned(Data) and Data.Dataset.Active; if (not GetCanCommit) then ClearEditor; DoUpdateStatusBar; end; function TibSHDataBlobForm.DoOnOptionsChanged: Boolean; var vEditorGeneralOptions: ISHEditorGeneralOptions; begin Result := inherited DoOnOptionsChanged; if Result and Supports(Designer.GetDemon(ISHEditorGeneralOptions), ISHEditorGeneralOptions, vEditorGeneralOptions) then begin TextControl.WordWrap := vEditorGeneralOptions.WordWrap; RTFControl.WordWrap := vEditorGeneralOptions.WordWrap; end; end; function TibSHDataBlobForm.GetCanDestroy: Boolean; begin Result := True; if Supports(Component, IibSHSQLEditor) then begin if (not Designer.ExistsComponent(Component, SCallQueryResults)) and (not Designer.ExistsComponent(Component, SCallDataForm)) then Result := inherited GetCanDestroy; end else begin if (not Designer.ExistsComponent(Component, SCallData)) and (not Designer.ExistsComponent(Component, SCallDataForm)) then Result := inherited GetCanDestroy; end; end; procedure TibSHDataBlobForm.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FCurrentField) then ClearEditor; end; procedure TibSHDataBlobForm.BringToTop; var vTestNode: PVirtualNode; begin if Assigned(Data) then Data.Dataset.DatasetNotification := Self as IibDRVDatasetNotification; inherited BringToTop; if StatusBar.Panels.Count >= 2 then StatusBar.Panels[1].Width := 150; vTestNode := Tree.GetFirst; if not Assigned(vTestNode) then BuildTree; end; procedure TibSHDataBlobForm.ShowResult(AEnableFetchEvent: Boolean); begin inherited ShowResult(AEnableFetchEvent); BuildTree; end; procedure TibSHDataBlobForm.dsImageControlDataChange(Sender: TObject; Field: TField); begin SafeShowPicture; end; procedure TibSHDataBlobForm.pmiHideMessageClick(Sender: TObject); begin HideMessages; end; end.
unit SqliteConnection; interface uses classes, DatabaseConnection; type // SQLite database connection TSqliteConnection = class(TDatabaseConnection) public // Creates a new instance with default database name constructor Create(AOwner: TComponent); reintroduce; overload; // Creates a new instance constructor Create(AOwner: TComponent; dbFileName : String); reintroduce; overload; end; implementation uses SysUtils; { TSqliteConnection } constructor TSqliteConnection.Create(AOwner: TComponent); const DatabasFileName = 'Data.sqlite'; begin self.Create(AOwner, DatabasFileName); end; constructor TSqliteConnection.Create(AOwner: TComponent; dbFileName: String); begin inherited Create(AOWner); self.ConnectionName := 'Devart SQLite'; self.DriverName := 'DevartSQLite'; self.GetDriverFunc := 'getSQLDriverSQLite'; self.LibraryName := 'dbexpsqlite.dll'; self.VendorLib := 'sqlite3.dll'; Self.LoginPrompt := False; self.Params.Add('BlobSize=-1'); self.Params.Add(format('DataBase=%s', [dbFileName])); self.Params.Add('ASCIIDataBase=False'); self.Params.Add('DriverName=dbexpsqlite.dll'); self.Params.Add('BusyTimeout=0'); self.Params.Add('EnableSharedCache=False'); self.Params.Add('EncryptionKey='); self.Params.Add('FetchAll=True'); self.Params.Add('ForceCreateDatabase=true'); self.Params.Add('ForeignKeys=True'); self.Params.Add('UseUnicode=True'); self.Params.Add('EnableLoadExtension=False'); self.Params.Add('UnknownAsString=False'); self.Params.Add('DateFormat='); self.Params.Add('TimeFormat='); end; end.
(* Desciption: Input score and then rate it. Excellent: 9, 10. Good: 7, 8. Average: 5, 6. Bad: 4. Useless: 0, 1, 2, 3 Programmer: Loc Pham Date: 22/11/2016 Version: v1.0 *) (* Program name *) program HomeWork5; (* Unit's inclusion *) uses crt; (* Variable's declration *) var score : integer; (* Function's declaration *) function RateScore(score : integer) : string; (* Local variables *) var result : string = ''; (* Funtion body *) begin case (score) of 0, 1, 2, 3 : begin result := 'Useless'; end; 4 : begin result := 'Bad'; end; 5, 6 : begin result := 'Average'; end; 7, 8 : begin result := 'Good'; end; 9, 10 : begin result := 'Excellent'; end; else begin result := 'Unknown'; end; end; RateScore := result; end; (* Main program *) begin write('Enter score: '); readln(score); writeln('Rate: ', RateScore(score)); end.
program Main_blending; uses UBlending; // Имя модуля,содержащего описание расчетов const flow_count = 6; comp_count = 64; var comp_RON: TArrOfDouble; flow_composition: TArrOfArrOfDouble; mix_composition: TArrOfDouble; RONc: double; treb_RON: double; i: integer; procedure get_data(var RON:TArrOfDouble; flow_composition: TArrOfArrOfDouble); var f1, f2: text; i, j: integer; begin assign(f1, 'RON.txt'); assign(f2, 'flow_comp.txt'); reset(f1); reset(f2); for i := 0 to comp_count-1 do begin readln(f1, RON[i]); for j := 0 to flow_count-1 do read(f2, flow_composition[i, j]); readln(f2); end; close(f1); close(f2); end; procedure get_result(mix_composition: TArrOfDouble; RONc: double); var f: text; i: integer; begin assign(f, 'result.txt'); rewrite(f); for i := 0 to flow_count-1 do writeln({f,} 'Доля потока ', i+1, ' = ', mix_composition[i] * 100:8:2); writeln({f}); writeln({f,} 'Октановое число смешения = ', RONc:8:2); close(f); end; begin SetLength(comp_RON, comp_count); SetLength(flow_composition, comp_count); for i := 0 to comp_count-1 do SetLength(flow_composition[i], flow_count); SetLength(mix_composition, flow_count); write('Введите требуемое ОЧ: '); readln(treb_RON); get_data(comp_RON, flow_composition); blending(comp_count, flow_count, comp_RON, flow_composition, treb_RON, 5e-2, 5e-6, mix_composition, RONc); get_result(mix_composition, RONc); end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TForm1 = class(TForm) btnConvertToJson: TButton; edtNome: TLabeledEdit; edtIdade: TLabeledEdit; edtCpf: TLabeledEdit; edtDataNasc: TLabeledEdit; mmoJson: TMemo; btnConvertToObject: TButton; btnLimpar: TButton; procedure btnConvertToJsonClick(Sender: TObject); procedure btnLimparClick(Sender: TObject); procedure btnConvertToObjectClick(Sender: TObject); private { Private declarations } public { Public declarations } end; TPessoa = class private FDNascimento: TDateTime; FCPF: String; FIdade: Integer; FNome: String; public property Nome: String read FNome write FNome; property Idade: Integer read FIdade write FIdade; property DataNascimento: TDateTime read FDNascimento write FDNascimento; property CPF: String read FCPF write FCPF; end; var Form1: TForm1; implementation {$R *.dfm} uses Data.DBXJSONReflect, json; procedure TForm1.btnConvertToJsonClick(Sender: TObject); var Marshal: TJSONMarshal; json: TJSONObject; Pessoa: TPessoa; begin Pessoa := TPessoa.Create; Pessoa.Nome := edtNome.Text; Pessoa.Idade := StrToInt(edtIdade.Text); Pessoa.CPF := edtCpf.Text; Pessoa.DataNascimento := StrToDateTime(edtDataNasc.Text); { Realiza a serialização do pedido } Marshal := TJSONMarshal.Create(TJSONConverter.Create); json := Marshal.Marshal(Pessoa) as TJSONObject; mmoJson.Text := json.ToString(); Marshal.Free; Pessoa.Free; json.Free; end; procedure TForm1.btnConvertToObjectClick(Sender: TObject); var unMarshal: TJSONUnMarshal; json: TJSONObject; Pessoa: TPessoa; begin json := TJSONObject.Create; json := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(mmoJson.Text),0) as TJSONObject; unMarshal := TJSONUnMarshal.Create; Pessoa := TPessoa.Create; Pessoa := unMarshal.unMarshal(json) as TPessoa; unMarshal.Free; json.Free; edtNome.Text := Pessoa.Nome; edtIdade.Text := Pessoa.Idade.ToString; edtCpf.Text := Pessoa.CPF; edtDataNasc.Text := DateTimeToStr(Pessoa.DataNascimento); Pessoa.Free; end; procedure TForm1.btnLimparClick(Sender: TObject); begin edtNome.Text := ''; edtIdade.Text := ''; edtCpf.Text := ''; edtDataNasc.Text := ''; end; end.
unit emr_Compiler; interface uses System.Classes, System.SysUtils, HCCompiler, PaxRegister, HCEmrElementItem, emr_Common; type TEmrCompiler = class(THCCompiler) private TDePropTypeID, TDeItemTypeID, TPatientInfoTypeID, TRecordInfoTypeID: Integer; public constructor CreateByScriptType(AOwner: TComponent; const AScriptType: TScriptType = stpPascal); override; /// <summary> 注册 SetDeItemText 需要的类和要设置的字符串 </summary> procedure RegClassVariable(const ADeItem, APatientInfo, ARecordInfo, AText: Pointer); end; implementation function TDeItem_GetValue(Self: TDeItem; const Key: String): String; begin Result := Self[Key]; end; procedure TDeItem_SetValue(Self: TDeItem; const Key: string; const Value: string); begin Self[Key] := Value; end; constructor TEmrCompiler.CreateByScriptType(AOwner: TComponent; const AScriptType: TScriptType); var vH, i: Integer; begin inherited CreateByScriptType(AOwner, AScriptType); vH := PaxRegister.RegisterNamespace(0, 'HCEmrElementItem'); TDePropTypeID := PaxRegister.RegisterClassType(vH, TDeProp); i := FCompilerConverts.New('Index', '\image{0} \column{} const \column{}\style{+B}Index\style{-B}: string; \color{' + ProposalCommColor + '} // 唯一索引', 'Index', 'HCEmrElementItem', 'TDeProp', nil); FCompilerConverts[i].Constant := True; PaxRegister.RegisterConstant(TDePropTypeID, 'Index', TDeProp.Index); i := FCompilerConverts.New('Unit', '\image{0} \column{} const \column{}\style{+B}Unit\style{-B}: string; \color{' + ProposalCommColor + '} // 单位', 'Unit', 'HCEmrElementItem', 'TDeProp', nil); FCompilerConverts[i].Constant := True; PaxRegister.RegisterConstant(TDePropTypeID, 'Unit', TDeProp.&Unit); i := FCompilerConverts.New('CMV', '\image{0} \column{} const \column{}\style{+B}CMV\style{-B}: string; \color{' + ProposalCommColor + '} // 值域代码', 'CMV', 'HCEmrElementItem', 'TDeProp', nil); FCompilerConverts[i].Constant := True; PaxRegister.RegisterConstant(TDePropTypeID, 'CMV', TDeProp.CMV); i := FCompilerConverts.New('CMVVCode', '\image{0} \column{} const \column{}\style{+B}CMVVCode\style{-B}: string; \color{' + ProposalCommColor + '} // 值代码', 'CMVVCode', 'HCEmrElementItem', 'TDeProp', nil); FCompilerConverts[i].Constant := True; PaxRegister.RegisterConstant(TDePropTypeID, 'CMVVCode', TDeProp.CMVVCode); // AInsertList.Add('Index'); // AItemList.Add('\image{0} \column{} property \column{}\style{+B}Index\style{-B}: string; // 唯一索引'); // AInsertList.Add('Code'); // AItemList.Add('\image{0} \column{} property \column{}\style{+B}Code\style{-B}: string; // 编码'); // AInsertList.Add('Name'); // AItemList.Add('\image{0} \column{} property \column{}\style{+B}Name\style{-B}: string; // 名称'); // AInsertList.Add('Frmtp'); // AItemList.Add('\image{0} \column{} property \column{}\style{+B}Frmtp\style{-B}: string; // 类别 单选、多选、数值、日期时间等'); // AInsertList.Add('Unit'); // AItemList.Add('\image{0} \column{} property \column{}\style{+B}Unit\style{-B}: string; // 单位'); // AInsertList.Add('CMV'); // AItemList.Add('\image{0} \column{} property \column{}\style{+B}CMV\style{-B}: string; // 受控词汇表(值域代码)'); // AInsertList.Add('CMVVCode'); // AItemList.Add('\image{0} \column{} property \column{}\style{+B}CMVVCode\style{-B}: string; // 受控词汇表(值域代码) '); // AInsertList.Add('Trace'); // AItemList.Add('\image{0} \column{} property \column{}\style{+B}Trace\style{-B}: string; // 痕迹信息'); // 注册数据元 TDeItemTypeID := PaxRegister.RegisterClassType(vH, TDeItem); // property Values i := FCompilerConverts.New('function TDeItem_GetValue(const Key: String): string;', '\image{0} \column{} function \column{}\style{+B}TDeItem_GetValue\style{-B}(const Key: string): string; \color{' + ProposalCommColor + '} // ', 'TDeItem_GetValue', 'HCEmrElementItem', 'TDeItem', @TDeItem_GetValue, True); PaxRegister.RegisterFakeHeader(TDeItemTypeID, FCompilerConverts[i].FullName, FCompilerConverts[i].Address); i := FCompilerConverts.New('procedure TDeItem_SetValue(const Key: string; const Value: string);', '\image{0} \column{} procedure \column{}\style{+B}TDeItem_SetValue\style{-B}(const Key: string; const Value: string); \color{' + ProposalCommColor + '} // ', 'TDeItem_SetValue', 'HCEmrElementItem', 'TDeItem', @TDeItem_SetValue, True); PaxRegister.RegisterFakeHeader(TDeItemTypeID, FCompilerConverts[i].FullName, FCompilerConverts[i].Address); i := FCompilerConverts.New('property Values[const Key: string]: string read TDeItem_GetValue write TDeItem_SetValue; default', '\image{3} \column{} property \column{}\style{+B}Values[const Key: string]\style{-B}: string; \color{' + ProposalCommColor + '} // 获取指定属性的值', 'Values['''']', 'HCEmrElementItem', 'TDeItem', nil); PaxRegister.RegisterProperty(TDeItemTypeID, FCompilerConverts[i].FullName); // 注册患者 vH := PaxRegister.RegisterNamespace(0, 'emr_Common'); TPatientInfoTypeID := PaxRegister.RegisterClassType(vH, TPatientInfo); TRecordInfoTypeID := PaxRegister.RegisterClassType(vH, TRecordInfo); end; procedure TEmrCompiler.RegClassVariable(const ADeItem, APatientInfo, ARecordInfo, AText: Pointer); begin if FindRegisterVariable(TDeItemTypeID, 'DeItem') then Exit; Self.RegisterVariable(0, 'DeItem', TDeItemTypeID, ADeItem); // 注册数据元 FCompilerVariables.New(TDeItemTypeID, ADeItem, 'DeItem', '当前数据元'); Self.RegisterVariable(0, 'PatientInfo', TPatientInfoTypeID, APatientInfo); // 注册患者 FCompilerVariables.New(TPatientInfoTypeID, APatientInfo, 'PatientInfo', '当前患者信息'); Self.RegisterVariable(0, 'RecordInfo', TRecordInfoTypeID, ARecordInfo); // 注册病历信息 FCompilerVariables.New(TRecordInfoTypeID, ARecordInfo, 'RecordInfo', '当前病历信息'); // 注册要设置的文本变量 Self.RegisterVariable(0, 'Text', _typeSTRING, AText); FCompilerVariables.New(_typeSTRING, AText, 'Text', '当前数据将要设置的内容'); end; end.
{ a helper function: quicksort in descending order } procedure quicksort_descending(N : longint; var a : array of longint); procedure sort(l,r: longint); var i,j,x,y: longint; begin i:=l; j:=r; x:=a[(l+r) div 2]; repeat while a[i]>x do inc(i); while x>a[j] do dec(j); if not(i>j) then begin y:=a[i]; a[i]:=a[j]; a[j]:=y; inc(i); dec(j); end; until i>j; if l<j then sort(l,j); if i<r then sort(i,r); end; begin sort(0,N-1); end; { helper functions: maximum and minimum } function max(a, b : longint) : longint; begin if a>b then max:=a else max:=b; end; function min(a, b : longint) : longint; begin if a<b then min:=a else min:=b; end; function Alla (N : longint; cubes : array of longint) : longint; var first, second, first_tower, second_tower, M, i, res : longint; remains : array of longint; begin SetLength(remains,N); quicksort_descending(N,cubes); { if there are more than 15 cubes, take 15 largest } if N > 15 then N := 15; res := 0; { try all possible sets of cubes in the first tower } for first := 0 to ((1 shl N)-1) do begin first_tower := 0; M := 0; for i := 0 to N-1 do if (first and (1 shl i)) <> 0 then inc( first_tower, cubes[i] ) else begin remains[M]:=cubes[i]; inc(M); end; { try all possible sets of cubes in the second tower } for second := 0 to ((1 shl M)-1) do begin second_tower := 0; for i := 0 to N-1 do if (second and (1 shl i)) <> 0 then inc( second_tower, remains[i] ); if first_tower=second_tower then res := max( res, first_tower ); end; end; Alla := res; end; function partition (N : longint; cubes : array of longint) : boolean; var i, j, S : longint; possible : array of boolean; begin S := 0; for i := 0 to N-1 do inc( S, cubes[i] ); if S mod 2 <> 0 then begin partition:=false; exit; end; SetLength( possible, S+1 ); for i := 0 to S do possible[i] := (i=0); for i := 0 to N-1 do for j := S downto cubes[i] do if possible[j-cubes[i]] then possible[j] := true; partition := possible[ S div 2 ]; end; function Bob (N : longint; cubes : array of longint) : longint; var i, j, k, l, S, res : longint; tmp : array of longint; begin S := 0; for i := 0 to N-1 do inc( S, cubes[i] ); if partition(N,cubes) then begin Bob:=S div 2; exit; end; res := 0; { try all possibilities without one cube } for i := 0 to N-1 do begin SetLength( tmp, N-1 ); k := 0; for l := 0 to N-1 do if l <> i then begin tmp[k]:=cubes[l]; inc(k); end; if partition(N-1,tmp) then res := max( res, (S-cubes[i]) div 2 ); end; { try all possibilities without two cubes } for i := 0 to N-1 do for j:=0 to i-1 do begin SetLength( tmp, N-2 ); k := 0; for l := 0 to N-1 do if (l <> i) and (l <> j) then begin tmp[k]:=cubes[l]; inc(k); end; if partition(N-2,tmp) then res := max( res, (S-cubes[i]-cubes[j]) div 2 ); end; Bob := res; end; function Chermi (N : longint; cubes : array of longint) : longint; var i, j, S, height, first_tower, second_tower : longint; begin quicksort_descending(N,cubes); S := 0; for i := 0 to N-1 do inc( S, cubes[i] ); for height := (S div 2) downto 1 do begin first_tower := 0; second_tower := 0; for i := 0 to N-1 do begin if first_tower + cubes[i] <= height then inc( first_tower, cubes[i] ); if first_tower > second_tower then begin j := first_tower; first_tower := second_tower; second_tower := j; end; end; if (first_tower = height) and (second_tower = height) then begin Chermi := height; exit; end; end; Chermi := 0; end; function Dominika (N : longint; cubes : array of longint) : longint; var i, j, S, height : longint; ways : array of longint; begin S := 0; for i := 0 to N-1 do inc( S, cubes[i] ); SetLength( ways, S+1 ); for i := 0 to S do ways[i] := 0; ways[0] := 1; for i := 0 to N-1 do for j := S downto cubes[i] do ways[j] := min( 2, ways[j] + ways[j-cubes[i]] ); for height := (S div 2) downto 1 do if (ways[2*height]>0) and (ways[height]>1) then begin Dominika := height; exit; end; Dominika := 0; end; var N, i : longint; cubes : array of longint; begin read(N); SetLength(cubes, N); for i := 0 to N-1 do read(cubes[i]); writeln('Alla: ',Alla(N,cubes)); writeln('Bob: ',Bob(N,cubes)); writeln('Chermi: ',Chermi(N,cubes)); writeln('Dominika: ',Dominika(N,cubes)); end.
unit ExecOnTime; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TExecOnTime = class(TComponent) private CheckTimer : TTimer; FDayTimeHour : word; FDayTimeMinute : word; FOnDayTimeExecute : TNotifyEvent; FActive : boolean; _Interval: Cardinal; _NextTrigger : TDateTime; procedure TimeCheck(Sender : TObject); procedure SetActive(value : boolean); procedure NewTrigger; procedure setInterval(const Value: Cardinal); function MillisecondToTimeStr(aValue: Cardinal): string; function MillisecondToDateTime(aValue: Cardinal): TDateTime; { Private-Deklarationen } protected { Protected-Deklarationen } public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure ForceTimeCheck; { Public-Deklarationen } published property DayTimeHour : word read FDayTimeHour write FDayTimeHour; property DayTimeMinute : word read FDayTimeMinute write FDayTimeMinute; property Active : boolean read FActive write SetActive; property Interval: Cardinal read _Interval write setInterval; property NextTrigger: TDateTime read _NextTrigger; property OnDayTimeExecute : TNotifyEvent read FOnDayTimeExecute write FOnDayTimeExecute; { Published-Deklarationen } end; procedure Register; implementation procedure Register; begin RegisterComponents('ASS', [TExecOnTime]); end; constructor TExecOnTime.Create(AOwner : TComponent); begin inherited; CheckTimer := TTimer.Create(self); with CheckTimer do begin Interval := 1000; Enabled := FActive; OnTimer := TimeCheck; end; end; destructor TExecOnTime.Destroy; begin FreeandNil(CheckTimer); inherited; end; procedure TExecOnTime.ForceTimeCheck; begin TimeCheck(self); end; function TExecOnTime.MillisecondToDateTime(aValue: Cardinal): TDateTime; var Timestr: String; begin TimeStr := MillisecondToTimeStr(aValue); Result := StrToTime(TimeStr); end; function TExecOnTime.MillisecondToTimeStr(aValue: Cardinal): string; var Milli: Integer; sMilli: string; begin Milli := aValue mod 1000; if Milli > 99 then sMilli := ':' + IntToSTr(Milli) else if (Milli > 9) and (Milli < 100) then sMilli := ':0' + IntToSTr(Milli) else sMilli := ':00' + IntToSTr(Milli); aValue := aValue div 1000; // -> seconds result := IntToStr(aValue mod 60); case aValue mod 60 < 10 of true: result := '0' + result; end; Result := Result + sMilli; aValue := aValue div 60; //minutes result := IntToStr(aValue mod 60) + ':' + result; case aValue mod 60 < 10 of true: result := '0' + result; end; aValue := aValue div 60; //hours result := IntToStr(aValue mod 24) + ':' + result; case aValue mod 60 < 10 of true: result := '0' + result; end; end; procedure TExecOnTime.NewTrigger; begin _NextTrigger := Date + EncodeTime(DayTimeHour, DayTimeMinute, 0, 0); if _NextTrigger < now then _NextTrigger := _NextTrigger + 1; end; procedure TExecOnTime.SetActive(value : boolean); begin CheckTimer.Enabled := value; FActive := value; if Value then NewTrigger; end; procedure TExecOnTime.setInterval(const Value: Cardinal); var Time: TDateTime; Sec: Word; Milli: Word; begin _Interval := Value; Time := MillisecondToDateTime(Value); DecodeTime(Time, FDayTimeHour, FDayTimeMinute, Sec, Milli); end; procedure TExecOnTime.TimeCheck(Sender : TObject); begin if (not (Self.ComponentState = [csDesigning])) and Assigned(FOnDayTimeExecute) then begin if (_NextTrigger < now) and FActive then begin FOnDayTimeExecute(self); NewTrigger; end; end; end; end.
{*****************************************************} { CRUD orientado a objetos, com banco de dados Oracle } { Reinaldo Silveira - reinaldopsilveira@gmail.com } { set/2019 } {*****************************************************} unit U_BaseCadastro; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons; type TStatusCad = (stsVazio, stsConsulta, stsInclusao, stsAlteracao); TF_BaseCadastro = class(TForm) pnlBottom: TPanel; btnIncluir: TBitBtn; btnAlterar: TBitBtn; btnExcluir: TBitBtn; sep1: TBevel; btnSalvar: TBitBtn; btnCancelar: TBitBtn; sep2: TBevel; btnPesquisar: TBitBtn; procedure FormShow(Sender: TObject); procedure btnIncluirClick(Sender: TObject); procedure btnAlterarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnPesquisarClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private FstatusCad: TStatusCad; procedure SetstatusCad(const Value: TStatusCad); { Private declarations } public { Public declarations } property statusCad: TStatusCad read FstatusCad write SetstatusCad; procedure AlteraStatusBotoes; procedure LimpaCampos; end; var F_BaseCadastro: TF_BaseCadastro; implementation {$R *.dfm} { TF_BaseCadastro } procedure TF_BaseCadastro.AlteraStatusBotoes; var i: Integer; begin btnIncluir.Enabled := statusCad in [stsVazio, stsConsulta]; btnAlterar.Enabled := statusCad = stsConsulta; btnExcluir.Enabled := statusCad = stsConsulta; btnSalvar.Enabled := statusCad in [stsInclusao, stsAlteracao]; btnCancelar.Enabled := statusCad in [stsInclusao, stsAlteracao]; btnPesquisar.Enabled := statusCad in [stsVazio, stsConsulta]; for i := 0 to ComponentCount -1 do if Components[i] is TCustomEdit then TCustomEdit(Components[i]).ReadOnly := statusCad in [stsVazio, stsConsulta]; end; procedure TF_BaseCadastro.btnAlterarClick(Sender: TObject); begin statusCad := stsAlteracao; end; procedure TF_BaseCadastro.btnCancelarClick(Sender: TObject); begin if Application.MessageBox('Deseja realmente cancelar a operação?', 'Confirmação', MB_ICONQUESTION+MB_YESNO+MB_DEFBUTTON2) = mrNo then Abort; if statusCad = stsInclusao then statusCad := stsVazio else statusCad := stsConsulta; end; procedure TF_BaseCadastro.btnExcluirClick(Sender: TObject); begin LimpaCampos; statusCad := stsVazio; end; procedure TF_BaseCadastro.btnIncluirClick(Sender: TObject); begin LimpaCampos; statusCad := stsInclusao; end; procedure TF_BaseCadastro.btnPesquisarClick(Sender: TObject); begin statusCad := stsConsulta; end; procedure TF_BaseCadastro.btnSalvarClick(Sender: TObject); begin statusCad := stsConsulta; end; procedure TF_BaseCadastro.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := statusCad in [stsVazio, stsConsulta]; if not CanClose then Application.MessageBox('Salve ou cancele antes de sair!', 'Aviso', MB_ICONWARNING); end; procedure TF_BaseCadastro.FormShow(Sender: TObject); begin statusCad := stsVazio; end; procedure TF_BaseCadastro.LimpaCampos; var i: Integer; begin for i := 0 to ComponentCount -1 do if Components[i] is TCustomEdit then TCustomEdit(Components[i]).Clear; end; procedure TF_BaseCadastro.SetstatusCad(const Value: TStatusCad); begin FstatusCad := Value; AlteraStatusBotoes; end; end.
unit uGenericSubtitleFile; { base generic class for a text based subtitle file. has some abstract methods for descendant classes. look at uSubripFile for example. Copyright (C) 2017 Mohammadreza Bahrami m.audio91@gmail.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA. } {$mode objfpc}{$H+}{$modeswitch advancedrecords} interface uses Classes, SysUtils, uMinimalList, uTimeSlice; type { TPlainSubtitleEvent } TPlainSubtitleEvent = record TimeSlice: TTimeSlice; // <-- any subtitle event type should contain this. Text: String; end; { TGenericSubtitleFile } generic TGenericSubtitleFile<T> = class private type TGenericSubtitleEvents = specialize TArray<T>; type TCustomGenericSubtitleEventList = specialize TMinimalList<T>; type TGenericSubtitleEventList = class(TCustomGenericSubtitleEventList) private procedure SetItem(AIndex: Integer; AItem: T); override; end; strict private FEvents: TGenericSubtitleEventList; FTimeSlice: TTimeSlice; private function EventsInRange(ARange: TTimeSlice): TGenericSubtitleEvents; public procedure Clear; procedure Cleanup; virtual; procedure LoadFromFile(const AFileName: String); overload; procedure LoadFromFile(const AFileName: String; AEncoding: TEncoding); overload; procedure LoadFromString(const AContents: String); virtual; abstract; procedure SaveToFile(const AFileName: String); overload; procedure SaveToFile(const AFileName: String; AEncoding: TEncoding); overload; procedure SaveToString(out AContents: String); virtual; abstract; function MakeNewFromRanges(ARanges: TTimeSliceList; AFinalStartOffset : Double = 0): TGenericSubtitleEvents; procedure FixOverlapsForward; procedure FixOverlapsBackward; public property Events: TGenericSubtitleEventList read FEvents write FEvents; property TimeSlice: TTimeSlice read FTimeSlice write FTimeSlice; constructor Create; virtual; destructor Destroy; override; end; implementation { TGenericSubtitleFile.TGenericSubtitleEventList } procedure TGenericSubtitleFile.TGenericSubtitleEventList.SetItem( AIndex: Integer; AItem: T); begin inherited SetItem(AIndex, AItem); if Assigned(Owner) then with (Owner as TGenericSubtitleFile) do begin FTimeSlice.Value.StartPos.Value := AItem.TimeSlice.Value.StartPos.Value; FTimeSlice.Value.EndPos.Value := AItem.TimeSlice.Value.EndPos.Value; PItems[AIndex]^.TimeSlice := FTimeSlice; end; end; { TGenericSubtitleFile } function TGenericSubtitleFile.EventsInRange(ARange: TTimeSlice ): TGenericSubtitleEvents; var i,j: Integer; begin SetLength(Result, FEvents.Count); j := 0; for i := 0 to FEvents.Count-1 do begin FEvents.PItems[i]^.TimeSlice.Delay := ARange.Delay; if ((FEvents[i].TimeSlice.ValueWithDelay.StartPos.ValueAsDouble >= ARange.Value.StartPos.ValueAsDouble) and (FEvents[i].TimeSlice.ValueWithDelay.StartPos.ValueAsDouble < ARange.Value.EndPos.ValueAsDouble)) or ((FEvents[i].TimeSlice.ValueWithDelay.StartPos.ValueAsDouble < ARange.Value.StartPos.ValueAsDouble) and (FEvents[i].TimeSlice.ValueWithDelay.EndPos.ValueAsDouble > ARange.Value.StartPos.ValueAsDouble)) then begin FEvents.PItems[i]^.TimeSlice.Delay := 0; Result[j] := FEvents[i]; Inc(j); end; end; SetLength(Result, j); for i := 0 to j-1 do begin if Result[i].TimeSlice.Value.StartPos.ValueAsDouble < ARange.Value.StartPos.ValueAsDouble then Result[i].TimeSlice.Value.StartPos.Value := ARange.Value.StartPos.Value else if Result[i].TimeSlice.Value.EndPos.ValueAsDouble > ARange.Value.EndPos.ValueAsDouble then Result[i].TimeSlice.Value.EndPos.Value := ARange.Value.EndPos.Value; end; end; procedure TGenericSubtitleFile.Clear; begin FEvents.Clear; end; procedure TGenericSubtitleFile.Cleanup; var i: Integer; begin for i := FEvents.Count-1 downto 0 do if not FEvents[i].TimeSlice.Valid then FEvents.Remove(i); end; procedure TGenericSubtitleFile.LoadFromFile(const AFileName: String); var sl: TStringList; begin sl := TStringList.Create; try sl.LoadFromFile(AFileName); LoadFromString(sl.Text); finally sl.Free; end; end; procedure TGenericSubtitleFile.LoadFromFile(const AFileName: String; AEncoding: TEncoding); var sl: TStringList; begin sl := TStringList.Create; try sl.LoadFromFile(AFileName, AEncoding); LoadFromString(sl.Text); finally sl.Free; end; end; procedure TGenericSubtitleFile.SaveToFile(const AFileName: String); var sl: TStringList; s: String; begin SaveToString(s); sl := TStringList.Create; try sl.Text := s; sl.SaveToFile(AFileName); finally sl.Free; end; end; procedure TGenericSubtitleFile.SaveToFile(const AFileName: String; AEncoding: TEncoding); var sl: TStringList; s: String; begin SaveToString(s); sl := TStringList.Create; try sl.DefaultEncoding := AEncoding; sl.Text := s; sl.SaveToFile(AFileName, AEncoding); finally sl.Free; end; end; function TGenericSubtitleFile.MakeNewFromRanges(ARanges: TTimeSliceList; AFinalStartOffset: Double): TGenericSubtitleEvents; var dlgs, dlgsr: TGenericSubtitleEvents; ts: TTimeSlice; i,j,k: Integer; Offset: Double; begin Result := nil; if not ARanges.Valid then Exit; if Events.Count < 1 then Exit; ARanges.Initialize(FTimeSlice.TimeSliceFormat); SetLength(dlgs, Events.Count); k := 0; Offset := 0; for i := 0 to ARanges.Count-1 do begin dlgsr := EventsInRange(ARanges.Values[i]); if Length(dlgsr) < 1 then Continue; ts.Reset; if i > 0 then ts.Value.StartPos.Value := ARanges.Values[i-1].Value.EndPos.Value; ts.Value.EndPos.Value := ARanges.Values[i].Value.StartPos.Value; Offset := Offset +ts.Duration.ValueAsDouble; for j := 0 to High(dlgsr) do begin dlgs[k] := dlgsr[j]; dlgs[k].TimeSlice.Delay := -Offset +ARanges.Values[i].Delay; Inc(k); end; end; SetLength(dlgs, k); if AFinalStartOffset > 0 then for i := 0 to k-1 do dlgs[i].TimeSlice.Delay := dlgs[i].TimeSlice.Delay +AFinalStartOffset; for i := 0 to k-1 do begin dlgs[i].TimeSlice.Value := dlgs[i].TimeSlice.ValueWithDelay; dlgs[i].TimeSlice.Delay := 0; end; Result := dlgs; end; procedure TGenericSubtitleFile.FixOverlapsForward; var i: Integer; begin i := -1; while i < FEvents.Count-2 do begin Inc(i); if FEvents[i+1].TimeSlice.Value.StartPos.ValueAsDouble < FEvents[i].TimeSlice.Value.EndPos.ValueAsDouble then begin FEvents.PItems[i+1]^.TimeSlice.Value.StartPos.ValueAsDouble := FEvents[i].TimeSlice.Value.EndPos.ValueAsDouble+0.001; Cleanup; i := -1; end; end; end; procedure TGenericSubtitleFile.FixOverlapsBackward; var i: Integer; begin i := FEvents.Count; while i > 1 do begin Dec(i); if FEvents[i].TimeSlice.Value.StartPos.ValueAsDouble < FEvents[i-1].TimeSlice.Value.EndPos.ValueAsDouble then begin FEvents.PItems[i-1]^.TimeSlice.Value.EndPos.ValueAsDouble := FEvents[i].TimeSlice.Value.StartPos.ValueAsDouble-0.001; Cleanup; i := FEvents.Count; end; end; end; constructor TGenericSubtitleFile.Create; begin FEvents := TGenericSubtitleEventList.Create(Self); end; destructor TGenericSubtitleFile.Destroy; begin if Assigned(FEvents) then FEvents.Free; inherited Destroy; end; end.
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ // // Unidad: Buscador.pas // // Propósito: // Se implementa un componente no visual (heredado de TComponent) que realiza una serie de // búsquedas simultaneas utilizando programación multi-hilo. // El componente se puede registrar incluyéndolo en un paquete, o bien crearlo dinamicamente. // // Autor: Salvador Jover (www.sjover.com) y JM (www.lawebdejm.com) // Fecha: 01/07/2003 // Observaciones: Unidad creada en Delphi 5 // Copyright: Este código es de dominio público y se puede utilizar y/o mejorar siempre que // SE HAGA REFERENCIA AL AUTOR ORIGINAL, ya sea a través de estos comentarios // o de cualquier otro modo. // //~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ unit Buscador; interface uses classes, windows, HiloBusqueda, SysUtils, syncobjs; type // // TBusqueda: representa una búsqueda // TBusqueda = class(TObject) private FRuta: string; FSubcarpetas: boolean; public constructor Create(ARuta: string; ASubcarpetas: boolean); published property Ruta: string read FRuta write FRuta; property Subcarpetas: boolean read FSubcarpetas write FSubcarpetas; end; // // Componente "Buscador" // // excepciones ESinRutas = class(Exception); EBuscando = class(Exception); // estados posibles del buscador TEstadoBuscador = (ebInactivo, ebBuscando, ebPausado, ebCancelado); TEstadosBuscador = set of TEstadoBuscador; TBuscador = class; // forward // definición de los eventos TOnEncontrado = procedure(Sender: TThread; archivo: string; index: integer) of object; TOnFinHilo = procedure(Sender: TThread; TotalEncontrado: integer) of object; TOnFinBusqueda = procedure(Sender: TBuscador) of object; TBuscador = class(TComponent) private FRutas: TStrings; FEstado: TEstadosBuscador; FResultado: TStrings; // lista de resultados FHilos: TListaHilos; // lista de hilos activos // eventos del componente FOnEncontrado: TOnEncontrado; FOnFinHilo: TOnFinHilo; FOnFinBusqueda: TOnFinBusqueda; procedure CrearBusquedas; // lanzamiento de eventos del componente procedure CallOnEncontrado(hilo: THiloBusqueda; ind: integer); procedure CallOnFinHilo(hilo: THiloBusqueda); procedure CallOnFinBusqueda; // eventos del hilo procedure OnHiloEncontrado(hilo: THiloBusqueda; ruta: string); procedure OnHiloTerminate(Sender: TObject); // getters/setters function GetPausado: boolean; procedure SetPausado(value: boolean); procedure SetRutas(value: TStrings); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function AddRuta(ruta: string; subcarpetas: boolean): Integer; procedure Execute; procedure Cancel; property Estado: TEstadosBuscador read FEstado; property Pausado: boolean read GetPausado write SetPausado; property Resultado: TStrings read FResultado; published property Rutas: TStrings read FRutas write SetRutas; // eventos property OnEncontrado: TOnEncontrado read FOnEncontrado write FOnEncontrado; property OnFinHilo: TOnFinHilo read FOnFinHilo write FOnFinHilo; property OnFinBusqueda: TOnFinBusqueda read FOnFinBusqueda write FOnFinBusqueda; end; procedure Register; implementation uses forms; procedure Register; begin RegisterComponents('JM', [TBuscador]); end; {class TBusqueda} // // TBusqueda // // Proc/Fun : constructor Create // // Valor retorno: vacío // Parametros : ARuta: string; ASubcarpetas: boolean // // Comentarios : Contructor de la clase TBusqueda. Esta clase encapsulta los // datos minimos que representan una busqueda, como son la ruta, // el token y el boleano subdirectorios (si hay que`proseguir // la busqueda en las subcarpetas) // El objeto TBuscador crea una instancia por cada una de las rutas // constructor TBusqueda.Create(ARuta: string; ASubcarpetas: boolean); begin inherited Create; FRuta := ARuta; FSubcarpetas := ASubcarpetas; end; {class TBuscador} // // TBuscador // // Proc/Fun : constructor Create // // Valor retorno: vacío // Parametros : AOwner: TComponent // // Comentarios : Constructor de la clase TBuscador. Es el objeto central, // sobre el que recae la responsabilidad de ofrecer resultados // Mantiene una lista para almacenar los hilos creados, otra // lista para las rutas y una tercera para los resultados // encontrados. // Se hace necesario mantener un estado del componente: partimos // siempre de un estado inactivo y se alcanza de nuevo al finalizar // la busqueda, con cancelación o con exito. Si se ha finalizado // mediante cancelación, el estado del compomente también lo indica. // constructor TBuscador.Create(AOwner: TComponent); begin inherited; FHilos := TListaHilos.Create; FRutas := TStringList.Create; FResultado := TStringList.Create; FEstado := [ebInactivo]; end; // Proc/Fun : destructor Destroy // // Valor retorno: vacio // Parametros : vacio // // Comentarios : Destructor de la clase Tbuscador. // Se liberan aquellas clases creadas dinámicamente y la memoria // asociada. // destructor TBuscador.Destroy; var i: integer; begin // importante cancelar todo antes de que desaparezcamos de este mundo if ebBuscando in FEstado then Cancel(); FHilos.Free; FResultado.Free; // liberar los objetos TBusqueda que han quedado almacenados dentro de FRutas. for i:=FRutas.count-1 downto 0 do if FRutas.Objects[i] <> nil then FRutas.Objects[i].Free; FRutas.Free; inherited; end; // Proc/Fun : procedure AddRuta // // Valor retorno: Integer // Parametros : ruta: string; subcarpetas: boolean // // Comentarios : Procedimiento público para la inserción de una nueva ruta. // Se facilita como parametros la ruta y el booleano subcarpetas. // Hay que tener en cuenta que una ruta puede ser añadida de dos // formas distintas: mediante ésta, y mediante la asignación de // la propiedad Rutas (procedimiento de escritura SetRutas) // Devuelve como retorno el indice de la inserción // function TBuscador.AddRuta(ruta: string; subcarpetas: boolean): Integer; begin Result:= FRutas.AddObject(ruta, TBusqueda.Create(ruta, subcarpetas)); end; // Proc/Fun : procedure Execute // // Valor retorno: vacío // Parametros : vacío // // Comentarios : Metodo de ejecución del buscador // Condicionamos la ejecución a que existan rutas de búsqueda // y que el buscador no se encuentre en estado activo // procedure TBuscador.Execute; begin if FRutas.count = 0 then raise ESinRutas.Create('No hay rutas de búsqueda configuradas.'); if ebBuscando in FEstado then raise EBuscando.Create('La búsqueda ya está activa.'); FEstado := [ebPausado, ebBuscando]; FResultado.BeginUpdate; try FResultado.Clear; finally FResultado.EndUpdate; end; CrearBusquedas; // creación de las busquedas - lanzamiento del algoritmo Pausado := false; end; // Proc/Fun : procedure CrearBusquedas // // Valor retorno: vacío // Parametros : vacío // // Comentarios : Lanzamiento del algoritmos de busqueda y creación de un hilo // de ejecución por ruta solicitada por el usuario // Finalmente son asignados los eventos de actualización del // interfaz y comunicación de resultados // procedure TBuscador.CrearBusquedas; var i: integer; hilo: THiloBusqueda; busqueda: TBusqueda; begin for i:=0 to FRutas.count - 1 do begin if FRutas.Strings[i] <> '' then begin busqueda := TBusqueda(FRutas.Objects[i]); if busqueda = nil then hilo := THiloBusqueda.Create(FRutas.Strings[i], true) else hilo := THiloBusqueda.Create(busqueda.Ruta, busqueda.Subcarpetas); hilo.FreeOnTerminate := true; hilo.OnEncontrado := OnHiloEncontrado; hilo.OnTerminate := OnHiloTerminate; FHilos.Add(hilo); end; end; end; // Proc/Fun : procedure Cancel // // Valor retorno: vacío // Parametros : vacío // // Comentarios : Acción de cancelar la búsqueda. // procedure TBuscador.Cancel; var it: TIteradorHilos; hilo: TThread; begin // primero pauso todo Pausado := true; // se utiliza el iterador para acceder al primer elemto. it := FHilos.CreateIterator(); Include(FEstado, ebCancelado); try // cancelar los hilos y esperar a que cada uno de ellos se haya cancelado while it.Next <> nil do begin hilo := it.Current; hilo.Terminate(); hilo.Resume(); end; finally FEstado := [ebInactivo, ebCancelado]; FHilos.ReleaseIterator(it); end; end; // // Llamadas a los eventos del componente // // Proc/Fun : procedure CallOnEncontrado // // Valor retorno: vacío // Parametros : hilo: THiloBusqueda; ind: integer // // Comentarios : Lanzamiento del evento FOnEncontrado // Cada vez que es resulta positivamente una coincidencia es // invocado este metodo que dispara el evento, comunicando a // nuestra aplicacion usuaria la cadena encontrada y el indice // procedure TBuscador.CallOnEncontrado(hilo: THiloBusqueda; ind: integer); begin // // Atento: se llama al evento si está asignado *Y* no se está destruyendo el componente. // Esto es debido a que, cuando el componente se está destruyendo, no quiero que se // lancen los eventos, ya que es muy posible que dentro de esos eventos se haga // referencia a objetos del Form que ya no existan. // if Assigned(FOnEncontrado) and (not (csDestroying in ComponentState)) then FOnEncontrado(hilo, FResultado[ind], ind); end; // Proc/Fun : procedure CallOnFinHilo // // Valor retorno: vacío // Parametros : hilo: THiloBusqueda // // Comentarios : Lanzamiento del evento OnFinHilo. // Cada vez que ha finalizado la exploración de una ruta y antes // de que se produzca la destrucción del thread, lanzamos el evento // de comunicación, indicando el total de encuentros obtenidos por // el hilo // procedure TBuscador.CallOnFinHilo(hilo: THiloBusqueda); begin if Assigned(FOnFinHilo) and (not (csDestroying in ComponentState)) then FOnFinHilo(hilo, hilo.TotalEncontrado); end; // Proc/Fun : procedure CallOnFinBusqueda // // Valor retorno: vacío // Parametros : vacío // // Comentarios : Lanzamiento del evento FinBusqueda // El componente Buscador, necesita comunicar a nuestra aplicación // usuaria que ha finalizado su ejecución y que el último de los // threads esta siendo destruido. // La aplicación hará uso de este evento para restaurar los controles // bloqueados, si ha echo uso de enabled para ello. // procedure TBuscador.CallOnFinBusqueda; begin if Assigned(FOnFinBusqueda) and (not (csDestroying in ComponentState)) then FOnFinBusqueda(self); end; // // Eventos del hilo // // Proc/Fun : procedure OnHiloEncontrado // // Valor retorno: vacío // Parametros : hilo: THiloBusqueda; ruta: string // // Comentarios : Evento de uso privado del componente. // Su implementación es un enlace intermedio hacia el evento público // procedure TBuscador.OnHiloEncontrado(hilo: THiloBusqueda; ruta: string); var ind: integer; begin ind := FResultado.AddObject(ruta, hilo); CallOnEncontrado(hilo, ind); end; // Proc/Fun : procedure OnHiloTerminate // // Valor retorno: vacío // Parametros : Sender: TObject // // Comentarios : Evento de uso privado del componente. // Su implementación es un enlace intermedio hacia el evento público // Es asignado al evento OnTerminate de la clase TThread, que es // lanzado previo a su destrucción y destro del ambito de Synchronize() // procedure TBuscador.OnHiloTerminate(Sender: TObject); var hilo: THiloBusqueda; begin hilo := sender as THiloBusqueda; FHilos.Remove(hilo); // se notifica del fin de hilo CallOnFinHilo(hilo); // // se notifica de que ya no quedan hilos (fin de la busqueda) // if FHilos.count = 0 then begin Exclude(FEstado, ebBuscando); Include(FEstado, ebInactivo); CallOnFinBusqueda(); end; end; // // setters/getters // // Proc/Fun : function GetPausado // // Valor retorno: Boolean // Parametros : Vacío // // Comentarios : Método de lectura de la propiedad Pausado. // function TBuscador.GetPausado: boolean; begin result := (ebPausado in FEstado); end; // Proc/Fun : procedure SetPausado // // Valor retorno: Vacío // Parametros : value: boolean // // Comentarios : Método de escritura de la propiedad Pausado // Se puede resaltar el uso de una clase especializada en la // gestión y manipulación de los hilos, que es la clase iteradora, // TIterador. // procedure TBuscador.SetPausado(value: boolean); var it: TIteradorHilos; begin if GetPausado <> value then begin if value then begin if ebBuscando in FEstado then Include(FEstado, ebPausado) else exit; end else Exclude(FEstado, ebPausado); // // recorrer la lista de hilos haciendo el resume/suspend. // Este es el típico ejemplo del uso del patrón "Iterator" // it := FHilos.CreateIterator(); try while it.Next <> nil do if value then it.Current.Suspend() else it.Current.Resume(); finally FHilos.ReleaseIterator(it); end; end; end; // Proc/Fun : procedure SetRutas // // Valor retorno: Vacío // Parametros : value: TStrings // // Comentarios : Una de las ideas que se persigue es hacer uso de la clase // TCollection para almacenar las rutas en tiempo de diseño, // creando en un plazo futuro un editor especializado para la // introducción de las rutas desde el ide y que están sean // almacenadas mediante persistencia. // // Comentario interno: esto desaparecerá cuando utilizamos el TCollection // procedure TBuscador.SetRutas(value: TStrings); begin FRutas.Assign(value); end; end.
namespace RemObjects.Elements.EUnit; interface type BaseException = public class({$IF NOUGAT}Foundation.NSException{$ELSE}Exception{$ENDIF}) public constructor (aMessage: String); {$IF NOUGAT} property Message: String read reason; {$ENDIF} end; implementation constructor BaseException(aMessage: String); begin {$IF NOUGAT} result := inherited initWithName('SugarTestException') reason(aMessage) userInfo(nil); {$ELSE} inherited constructor(aMessage); {$ENDIF} end; end.
unit udmNFe; interface uses SysUtils, Classes, ACBrNFeDANFEClass, ACBrNFeDANFERave, ACBrNFe, ACBrNFeNotasFiscais, pcnNFE, pcnConversao, Dialogs; const NFE_RESULT_LOT_SUCESSO = 103; NFE_RESULT_DUPLICIDADE = 204; NFE_RESULT_SUCESSO = 106; NFE_TEMP_FILE = 'C:\temp.xml'; type TdmNFe = class(TDataModule) ACBrNFe: TACBrNFe; ACBrNFeDANFERave: TACBrNFeDANFERave; procedure DataModuleCreate(Sender: TObject); private { Private declarations } function IntToFormaEmissao(i: integer): TpcnTipoEmissao; function IntToAmbiente(i: integer): TpcnTipoAmbiente; function IntToTipoDanfe(i: integer): TpcnTipoImpressao; procedure ConsultaNotaCorrente; procedure EnviaNotaCorrente; procedure ImprimeNotaCorrente(XML : WideString); procedure CancelaNotaCorrente; public procedure ReadConfig; procedure EnviaNotasSelecionadas; procedure ImprimirNotasSelecionadas; procedure ConsultaNotasSelecionadas; procedure CancelaNotasSelecionadas; procedure InutilizaNotas; end; var dmNFe: TdmNFe; implementation uses udmSQL, uFrmProgresso, IniFiles, uFrmUnitilizaNota; {$R *.dfm} { TdmNFe } procedure TdmNFe.ConsultaNotasSelecionadas; var frmWait: TfrmProgresso; begin frmWait := TFrmProgresso.Create(Self); try with dmSQL.daNotaFiscal do begin // Mostra o formulario de progresso frmWait.Start(SelectedCount); // Navega para a primeira nota (selecionada ou nao) First; // Laco pelas notas selecionadas // Se a corrente ja esta selecionada, ProximaSelecionada nao faz nada while ProximaSelecionada and not frmWait.Cancelar do begin // Consulta a nota corrente ConsultaNotaCorrente;; // Atualiza a progressbar frmWait.StepUp; // vai para a proxima nota Next; end; end; finally frmWait.Free; end; end; procedure TdmNFe.EnviaNotasSelecionadas; var frmWait: TfrmProgresso; begin frmWait := TFrmProgresso.Create(Self); try with dmSQL.daNotaFiscal do begin // Mostra o formulario de progresso frmWait.Start(SelectedCount); // Navega para a primeira nota (selecionada ou nao) First; // Laco pelas notas selecionadas // Se a corrente ja esta selecionada, ProximaSelecionada nao faz nada while ProximaSelecionada and not frmWait.Cancelar do begin // Envia a nota corrente EnviaNotaCorrente; // Atualiza a progressbar frmWait.StepUp; // vai para a proxima nota Next; end; end; finally frmWait.Free; end; end; procedure TdmNFe.ConsultaNotaCorrente; var sPath : String; begin if (dmSQL.RetornaXMLNotaFiscal <> '') then begin with TStringList.Create do try Text := dmSQL.RetornaXMLNotaFiscal; SaveToFile(NFE_TEMP_FILE); sPath := NFE_TEMP_FILE; finally Free; end; if FileExists(sPath) then begin ACBrNFe.NotasFiscais.Clear; ACBrNFe.NotasFiscais.LoadFromFile(sPath); ACBrNFe.Consultar; if ACBrNFe.WebServices.Retorno.cStat in [0, NFE_RESULT_LOT_SUCESSO, NFE_RESULT_DUPLICIDADE, NFE_RESULT_SUCESSO] then begin // Grava o sucesso dmSQL.SalvaAprovacaoEnvio(ACBrNFe.WebServices.Consulta.RetWS); ImprimeNotaCorrente(''); end; end; end; end; procedure TdmNFe.EnviaNotaCorrente; var aNFe: TNFe; sXMLEnviado, sXMLRecebido: WideString; sNFe : String; begin try // Limpar os dados do componente de envio ACBrNFe.NotasFiscais.Clear; // Criar uma nova nota no componente aNFe := ACBrNFe.NotasFiscais.Add.NFe; // Preencher a nota fiscal recem criada a partir do banco dmSQL.PreecheNotaFiscal(aNFe); // Realiza o envio ACBrNFe.Enviar(0,False); // Recolhe os XMLs sXMLEnviado := UTF8Encode(ACBrNFe.NotasFiscais.Items[0].XML); sXMLRecebido := UTF8Encode(ACBrNFe.WebServices.Enviar.RetWS); //Retornar o ID da nota fiscal eletronica (Verificar se tem outro methodo) sNFe := Copy(sXMLEnviado, Pos('Id="', sXMLEnviado)+4, Pos('Id="', sXMLEnviado)+50); sNFe := Copy(sNFe, 1, Pos('">', sNFe)-2); // Grava o sucesso dmSQL.SalvaEnvioCompleto(sXMLEnviado, sXMLRecebido, sNFe); //Imprime nota corrente ImprimeNotaCorrente(sXMLEnviado); except on E: Exception do begin // Recolhe os XMLs sXMLEnviado := UTF8Encode(ACBrNFe.NotasFiscais.Items[0].XML); sXMLRecebido := UTF8Encode(ACBrNFe.WebServices.Enviar.RetWS); if ACBrNFe.WebServices.Retorno.cStat in [NFE_RESULT_LOT_SUCESSO, NFE_RESULT_DUPLICIDADE, NFE_RESULT_SUCESSO] then // Grava o sucesso dmSQL.SalvaSucessoEnvio(sXMLEnviado, sXMLRecebido, sNFe) else // Grava a falha dmSQL.SalvaFalhaEnvio(sXMLEnviado, sXMLRecebido, E.Message); end; end; end; procedure TdmNFe.DataModuleCreate(Sender: TObject); begin dmNFe.ReadConfig; ACBrNFeDANFERave.CasasDecimais._qCom := dmSQL.FDecimal; ACBrNFeDANFERave.CasasDecimais._vUnCom := dmSQL.FDecimal; end; procedure TdmNFe.ReadConfig; begin with TIniFile.Create( ChangeFileExt( ParamStr(0), '.ini') ) do try ACBrNFe.Configuracoes.Certificados.NumeroSerie := ReadString( 'Certificado','NumSerie',''); ACBrNFe.Configuracoes.Geral.FormaEmissao := IntToFormaEmissao(ReadInteger( 'Geral', 'FormaEmissao',1)); ACBrNFe.Configuracoes.WebServices.UF := ReadString( 'WebService', 'UF', 'RJ'); ACBrNFe.Configuracoes.WebServices.Ambiente := IntToAmbiente(ReadInteger( 'WebService', 'Ambiente', 1)); dmSQL.FAmbiente := ACBrNFe.Configuracoes.WebServices.Ambiente; //set o tipo de ambiente para o DM ACBrNFe.Configuracoes.Geral.PathSalvar := ReadString( 'Geral','PathSalvar',''); ACBrNFe.Configuracoes.Geral.Salvar := ReadBool( 'Geral','Salvar', False); ACBrNFeDANFERave.TipoDANFE := IntToTipoDanfe(ReadInteger( 'Geral', 'DANFE',1)); ACBrNFeDANFERave.Logo := ReadString( 'Geral', 'LogoMarca', ''); ACBrNFeDANFERave.RavFile := ReadString( 'Geral', 'RavFile', ''); ACBrNFeDANFERave.Sistema := 'MainRetail'; ACBrNFeDANFERave.Email := ReadString( 'Empresa','Email',''); ACBrNFeDANFERave.Site := ReadString( 'Empresa','Website',''); dmSQL.FCalcFreete := ReadBool( 'MR','CalcFrete', True); dmSQL.FHideItemDesc := ReadBool( 'MR','HideDescontoItem', False); dmSQL.FIDEmpresaVenda := StrToIntDef(ReadString('MR','IDEmpresa',''), 0); dmSQL.FDecimal := ReadInteger( 'MR','Decimal', 2); dmSQL.FNumCopia := ReadInteger( 'MR','NumCopia', 1); finally Free; end; end; function TdmNFe.IntToFormaEmissao(i: integer): TpcnTipoEmissao; begin case i of 0: result := teNormal; 1: result := teContingencia; 2: result := teSCAN; 3: result := teDPEC; 4: result := teFSDA; else result := teNormal; end; end; function TdmNFe.IntToAmbiente(i: integer): TpcnTipoAmbiente; begin case i of 0: result := taProducao; 1: result := taHomologacao; else result := taHomologacao; end; end; function TdmNFe.IntToTipoDanfe(i: integer): TpcnTipoImpressao; begin case i of 0: result := tiRetrato; 1: result := tiPaisagem; else result := tiRetrato; end; end; procedure TdmNFe.ImprimirNotasSelecionadas; begin with dmSQL.daNotaFiscal do begin // Navega para a primeira nota (selecionada ou nao) First; // Laco pelas notas selecionadas // Se a corrente ja esta selecionada, ProximaSelecionada nao faz nada while ProximaSelecionada do begin // Imprime a nota corrente ImprimeNotaCorrente(''); // vai para a proxima nota Next; end; end; end; procedure TdmNFe.ImprimeNotaCorrente(XML : WideString); var sPath : String; i : Integer; begin if XML = '' then XML := dmSQL.RetornaXMLNotaFiscal; if (XML <> '') then begin with TStringList.Create do try Text := XML; SaveToFile(NFE_TEMP_FILE); sPath := NFE_TEMP_FILE; finally Free; end; if FileExists(sPath) then begin ACBrNFe.NotasFiscais.Clear; ACBrNFe.NotasFiscais.LoadFromFile(sPath); for i:=1 to dmSQL.FNumCopia do ACBrNFe.NotasFiscais.Imprimir; dmSQL.SalvaImpressao; end; end; end; procedure TdmNFe.CancelaNotasSelecionadas; begin with dmSQL.daNotaFiscal do begin // Navega para a primeira nota (selecionada ou nao) First; // Laco pelas notas selecionadas // Se a corrente ja esta selecionada, ProximaSelecionada nao faz nada while ProximaSelecionada do begin // Cancela a nota corrente CancelaNotaCorrente; // vai para a proxima nota Next; end; end; end; procedure TdmNFe.CancelaNotaCorrente; var sPath, vAux : String; begin if (dmSQL.RetornaXMLNotaFiscal <> '') then begin with TStringList.Create do try Text := dmSQL.RetornaXMLNotaFiscal; SaveToFile(NFE_TEMP_FILE); sPath := NFE_TEMP_FILE; finally Free; end; if FileExists(sPath) then if (InputQuery('Cancelamento da NF-e', 'Justificativa :', vAux)) then begin ACBrNFe.NotasFiscais.Clear; ACBrNFe.NotasFiscais.LoadFromFile(sPath); ACBrNFe.Cancelamento(vAux); dmSQL.SalvaCancelamentoEnvio(ACBrNFe.WebServices.Cancelamento.RetWS); end; end; end; procedure TdmNFe.InutilizaNotas; var CNPJ, Modelo, Serie, Ano, NumeroInicial, NumeroFinal, Justificativa : String; sXMLRecebido: WideString; begin with TFrmUnitilizaNota.Create(Self) do try if Start(CNPJ, Modelo, Serie, Ano, NumeroInicial, NumeroFinal, Justificativa) then begin ACBrNFe.WebServices.Inutiliza(CNPJ, Justificativa, StrToInt(Ano), StrToInt(Modelo), StrToInt(Serie), StrToInt(NumeroInicial), StrToInt(NumeroFinal)); sXMLRecebido := ACBrNFe.WebServices.Inutilizacao.RetWS; end; finally Free; end; end; end.
unit uSprQuery; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, ADODB, StdCtrls, Grids, DBGrids, StrUtils, ImgList, uSprFilter, uSprJoin, Math, Buttons, uSprOrder; type TsprDateFormat = (dfDate, dfMonth); TsprQuery = class; TEnabledMethod = function(DataSet: TsprQuery): Boolean of Object; TActionExecMethod = procedure(DataSet: TsprQuery) of Object; TQueryAction = class(TCollectionItem) private FEnabled: TEnabledMethod; FOnExecute: TActionExecMethod; FCaption: string; FName: string; FConfirmation: string; public property Enabled: TEnabledMethod read FEnabled write FEnabled; property OnExecute: TActionExecMethod read FOnExecute write FOnExecute; property Caption: string read FCaption write FCaption; property Name: string read FName write FName; property Confirmation: string read FConfirmation write FConfirmation; end; TQueryActions = class(TOwnedCollection) public function Find(const AName: string): TQueryAction; function IndexOf(const AName: string): Integer; end; TsprQuery = class(TADOQuery) private FStartDate: TDateTime; FEndDate: TDateTime; FOrder: TsprOrder; FFilters: TsprFilters; FJoins: TStringList; FSQLTemplate: TStrings; //FFieldsStr: string; //FJoinStr: string; //FOrderByStr: string; FAutoOpen: Boolean; FDebug: Boolean; FDateFieldName: string; FBaseTable: string; FItemDlgClassName: string; FDateFilterEnabled: Boolean; FReadOnly: Boolean; FActions: TQueryActions; function GetSQLTemplate: TStrings; procedure SetSQLTemplate(const Value: TStrings); function FindMacro(const Value: string; ASQL: TStrings): Integer; procedure ProcessFilters(ASQL: TStrings); procedure ProcessOrder(ASQL: TStrings); procedure ProcessJoins(ASQL: TStrings); procedure ProcessJoin(AJoin: TsprJoin; AAlias: string); // procedure SetOrderByStr(const Value: string); protected //procedure ConditionChanged(Sender: TObject); procedure DoBeforeOpen; override; procedure DoBeforeRefresh; override; procedure BuildSQL; function ParamExists(ParamName: string): Boolean; procedure SetStartDate(const Value: TDateTime); virtual; procedure SetEndDate(const Value: TDateTime); virtual; procedure DisableContextParam(AParamName: string); procedure DisableDateFilter; virtual; procedure SetDateFilter; virtual; procedure SetContextFilter(FilterName, AExpression: string); procedure DisableContextFilter(FilterName: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function CanFilterDate: Boolean; virtual; procedure ReOpen; procedure DSOpen; // function GetDateFieldName: string; virtual; property DateFieldName: string read FDateFieldName write FDateFieldName; property ItemDlgClassName: string read FItemDlgClassName write FItemDlgClassName; function GetDateFormat: TsprDateFormat; virtual; function AddField(FieldName: string; DisplayLabel: string; FieldType: TFieldType; TableAlias: string = ''; Visible: Boolean = True): TField; function AddLookupField(FieldName: string; DisplayLabel: string; FieldType: TFieldType; LookupDataSet: TDataSet; KeyFields: string; LookupKeyFields: string; LookupResultField: string): TField; function GetDescription: string; procedure RevertToDefault; procedure AddFilter(FilterName, AExpression, AGroupName: string); procedure DisableFilter(FilterName: string); function AddAction(Name: string; Caption: string; OnExecute: TActionExecMethod): TQueryAction; property Actions: TQueryActions read FActions write FActions; published //property OrderBy: string read FOrderByStr write SetOrderByStr; property SQLTemplate: TStrings read GetSQLTemplate write SetSQLTemplate; property Order: TsprOrder read FOrder; property Debug: Boolean read FDebug write FDebug; property Filters: TsprFilters read FFilters; property StartDate: TDateTime read FStartDate write SetStartDate; property EndDate: TDateTime read FEndDate write SetEndDate; property BaseTable: string read FBaseTable write FBaseTable; property DateFilterEnabled: Boolean read FDateFilterEnabled write FDateFilterEnabled; property ReadOnly: Boolean read FReadOnly write FReadOnly; end; function SQLStartDateTimeToStr(Value: TDateTime): string; function SQLEndDateTimeToStr(Value: TDateTime): string; function CreateField(DataSet: TDataSet; FieldName: string; DisplayLabel: string; FieldType: TFieldType; Origin: string; AVisible: Boolean = True): TField; procedure SetFieldsFormat(DataSet: TDataSet); function AsString(DataSet: TDataSet; FieldName: string): string; type TsprDSCreateMethod = function: TsprQuery of object; const clrf = #13#10; sprDateTimeFieldFormat = 'dd.mm.yyyy hh:nn:ss'; sprDateFieldFormat = 'dd.mm.yyyy'; sprPriceFieldFormat = '0.00'; implementation uses DateUtils; function SQLStartDateTimeToStr(Value: TDateTime): string; begin Result := '''' + FormatDateTime('yyyy-mm-dd', Value) + ' 00:00:00'''; end; function SQLEndDateTimeToStr(Value: TDateTime): string; begin Result := '''' + FormatDateTime('yyyy-mm-dd', Value) + ' 23:59:59'''; end; function CreateField(DataSet: TDataSet; FieldName: string; DisplayLabel: string; FieldType: TFieldType; Origin: string; AVisible: Boolean = True): TField; begin Result := DataSet.FindField(FieldName); if nil = Result then case FieldType of ftDate: begin Result := TDateField.Create(DataSet); end; ftDateTime: begin Result := TDateTimeField.Create(DataSet); end; ftFloat: begin Result := TFloatField.Create(DataSet); end; ftString: begin Result := TStringField.Create(DataSet); Result.DisplayWidth := 25; end; ftWideString: begin Result := TWideStringField.Create(DataSet); Result.DisplayWidth := 25; end; ftInteger: begin Result := TIntegerField.Create(DataSet); end; ftSmallInt: begin Result := TSmallIntField.Create(DataSet); end; ftBCD: begin Result := TBCDField.Create(DataSet); end; else Result := nil; end; if nil <> Result then begin Result.FieldName := FieldName; Result.DisplayLabel := DisplayLabel; Result.DataSet := DataSet; Result.Origin := Origin; Result.Visible := AVisible; end; end; function TsprQuery.AddField(FieldName: string; DisplayLabel: string; FieldType: TFieldType; TableAlias: string = ''; Visible: Boolean = True): TField; begin Result := CreateField(Self, FieldName, DisplayLabel, FieldType, IfThen(TableAlias = '', BaseTable, TableAlias) + '.' + FieldName, Visible); end; function TsprQuery.AddLookupField(FieldName: string; DisplayLabel: string; FieldType: TFieldType; LookupDataSet: TDataSet; KeyFields: string; LookupKeyFields: string; LookupResultField: string): TField; begin Result := AddField(FieldName, DisplayLabel, FieldType); Result.Lookup := true; Result.FieldKind := fkLookup; Result.KeyFields := KeyFields; Result.LookupDataSet := LookupDataSet; Result.LookupKeyFields := LookupKeyFields; Result.LookupResultField := LookupResultField; //'dbo.ava_apteks,id_gamma,names,left'; end; function TsprQuery.GetSQLTemplate: TStrings; begin Result := FSQLTemplate; end; procedure TsprQuery.SetSQLTemplate(const Value: TStrings); begin FSQLTemplate.Assign(Value); end; constructor TsprQuery.Create(AOwner: TComponent); begin inherited Create(AOwner); FReadOnly := True; CursorType := ctKeySet; FSQLTemplate := TStringList.Create; FOrder := TsprOrder.Create(Self); FFilters := TsprFilters.Create(Self); FJoins := TStringList.Create; FDebug := False; //FOrderByStr := ''; FAutoOpen := false; FDateFieldName := 'ReleaseDate'; Self.CommandTimeout := 100; FDateFilterEnabled := True; FActions := TQueryActions.Create(Self, TQueryAction); end; destructor TsprQuery.Destroy; begin Close; FreeAndNil(FJoins); FreeAndNil(FOrder); FreeAndNil(FFilters); FreeAndNil(FSQLTemplate); FreeAndNil(FActions); inherited Destroy; end; { procedure TsprQuery.SetOrderByStr(const Value: string); begin if Value <> FOrderByStr then begin FOrderByStr := Value; BuildSQL; //if FAutoOpen then end; end; } procedure TsprQuery.DoBeforeOpen; begin inherited; BuildSQL; end; procedure TsprQuery.DoBeforeRefresh; begin inherited; //BuildSQL; end; function TsprQuery.FindMacro(const Value: string; ASQL: TStrings): Integer; var I: Integer; S: string; begin Result := -1; for I := 0 to ASQL.Count - 1 do begin S := ASQL[I]; if Pos(AnsiUpperCase(Value), AnsiUpperCase(S)) > 0 then begin Result := I; break; end; end; end; procedure TsprQuery.ProcessJoin(AJoin: TsprJoin; AAlias: string); var vStr: string; begin vStr := Format('%s join %s %s %s on %s.%s = %s', [ AJoin.Kind, AJoin.Table, AAlias, AJoin.Options, AAlias, AJoin.FieldLeft, AJoin.FieldRight ]); FJoins.Add(vStr); end; procedure TsprQuery.ProcessFilters(ASQL: TStrings); var idxWhere: Integer; idxWhereValue: Integer; vFilter: TsprFilter; vIncludeCombineOperator: Boolean; I: Integer; S, vWhereStr: string; begin vWhereStr := ''; idxWhere := -1; idxWhereValue := FindMacro('&WHEREVALUE', ASQL); if idxWhereValue < 0 then idxWhere := FindMacro('&WHERE', ASQL); if (idxWhere >= 0) or (idxWhereValue >= 0) then begin vIncludeCombineOperator := idxWhereValue >= 0; for I := 0 to FFilters.Count - 1 do begin vFilter := FFilters.Items[I]; if vFilter.Enabled then begin S := vFilter.GetAsString(vIncludeCombineOperator); if S <> '' then begin vWhereStr := vWhereStr + ' ' + S + clrf; vIncludeCombineOperator := True; if vFilter.Join.Table <> '' then ProcessJoin(vFilter.Join, vFilter.GetJoinAlias); end; end; end; if (idxWhere >= 0) then begin if vWhereStr <> '' then vWhereStr := 'where ' + vWhereStr; ASQL[idxWhere] := AnsiReplaceText(ASQL[idxWhere], '&WHERE', vWhereStr); end else ASQL[idxWhereValue] := AnsiReplaceText(ASQL[idxWhereValue], '&WHEREVALUE', vWhereStr); end; end; procedure TsprQuery.ProcessOrder(ASQL: TStrings); var I: Integer; vSQL: TStringList; S, vOrderStr: string; vOrderItem: TsprOrderItem; idxOrder: Integer; begin vOrderStr := ''; idxOrder := FindMacro('&ORDER', ASQL); if idxOrder >= 0 then begin for I := 0 to FOrder.Count - 1 do begin vOrderItem := FOrder.Items[I]; S := vOrderItem.GetAsString; if S <> '' then begin vOrderStr := vOrderStr + ', ' + S; if vOrderItem.Join.Table <> '' then ProcessJoin(vOrderItem.Join, vOrderItem.GetJoinAlias); end; end; if vOrderStr <> '' then vOrderStr := 'order by ' + Copy(vOrderStr, 2, Length(vOrderStr) - 1); ASQL[idxOrder] := AnsiReplaceText(ASQL[idxOrder], '&ORDER', vOrderStr); end; end; procedure TsprQuery.ProcessJoins(ASQL: TStrings); var idxJoin: Integer; vJoinStr: string; I: Integer; begin vJoinStr := ''; idxJoin := FindMacro('&JOINS', ASQL); if idxJoin >= 0 then begin for I := 0 to FJoins.Count - 1 do vJoinStr := vJoinStr + FJoins[I] + clrf; ASQL[idxJoin] := AnsiReplaceText(ASQL[idxJoin], '&JOINS', vJoinStr); end; end; procedure TsprQuery.BuildSQL; var I: Integer; vSQL: TStringList; vOrderStr: string; vJoinStr: string; vAlias: string; vOrderItem: TsprOrderItem; idxOrder: Integer; idxJoin: Integer; begin FJoins.Clear; vSQL := TStringList.Create; try vSQL.Assign(FSQLTemplate); Self.ProcessFilters(vSQL); Self.ProcessOrder(vSQL); Self.ProcessJoins(vSQL); if FDebug then ShowMessage(vSQL.Text); SQL.Assign(vSQL); finally vSQL.Free; end; end; function TsprQuery.ParamExists(ParamName: string): Boolean; begin Result := Self.Parameters.FindParam(ParamName) <> nil; end; function TsprQuery.CanFilterDate: Boolean; begin Result := FDateFilterEnabled and ( (ParamExists('StartDate') and ParamExists('EndDate')) or ( Assigned(Self.FindField(FDateFieldName)) //(not isDetail) and (PropertyExists(GetDatePropertyName)) )); end; { function TsprQuery.GetDateFieldName: string; begin Result := 'ReleaseDate'; end;} function TsprQuery.GetDateFormat: TsprDateFormat; begin Result := dfDate; end; procedure TsprQuery.DisableContextParam(AParamName: string); var Param: TParameter; Filter: TsprFilter; begin Param := Parameters.FindParam(AParamName); if Assigned(Param) then Param.Value := Unassigned else begin Filter := Filters.FindByName(AParamName); if Assigned(Filter) then Filter.Enabled := False; end; end; procedure TsprQuery.SetStartDate(const Value: TDateTime); begin if GetDateFormat = dfMonth then FStartDate := StartOfTheMonth(Value) else FStartDate := Value; if CanFilterDate then SetDateFilter else DisableDateFilter; //ContextChanged; end; procedure TsprQuery.SetEndDate(const Value: TDateTime); begin if GetDateFormat = dfMonth then FEndDate := EndOfTheMonth(Value) else FEndDate := Value; if CanFilterDate then SetDateFilter else DisableDateFilter; //ContextChanged; end; procedure TsprQuery.SetContextFilter(FilterName, AExpression: string); var f: TsprFilter; begin f := Filters.GetFilterByName(FilterName); f.GroupName := 'ContextFilters'; f.Expression := AExpression; f.Enabled := AExpression <> sprNoFilter; end; procedure TsprQuery.AddFilter(FilterName, AExpression, AGroupName: string); var f: TsprFilter; begin f := Filters.GetFilterByName(FilterName); f.GroupName := AGroupName; f.Expression := AExpression; f.Enabled := AExpression <> sprNoFilter; end; procedure TsprQuery.DisableFilter(FilterName: string); var Filter: TsprFilter; begin Filter := Filters.FindByName(FilterName); if Assigned(Filter) then Filter.Enabled := False; end; procedure TsprQuery.DisableContextFilter(FilterName: string); var Filter: TsprFilter; begin Filter := Filters.FindByName(FilterName); if Assigned(Filter) then Filter.Enabled := False; end; procedure TsprQuery.SetDateFilter; var StartParam, EndParam: TParameter; vField: TField; vFilterFieldName: string; begin StartParam := Parameters.FindParam('StartDate'); EndParam := Parameters.FindParam('EndDate'); if Assigned(StartParam) and Assigned(EndParam) then begin StartParam.Value := FStartDate; EndParam.Value := FEndDate; end else if Assigned(StartParam) or Assigned(EndParam) then raise Exception.Create( 'Вы должны определить StartDate и EndDate параметры') else begin if CanFilterDate then begin vField := Self.FindField(FDateFieldName); if Assigned(vField) then begin if vField.Origin <> '' then vFilterFieldName := vField.Origin else vFilterFieldName := FDateFieldName; SetContextFilter('ReleaseDate', Format('(%s BETWEEN %s AND %s)', [ vFilterFieldName, SQLStartDateTimeToStr(FStartDate), SQLEndDateTimeToStr(FEndDate)])); end end else DisableDateFilter; end; end; procedure TsprQuery.DisableDateFilter; begin DisableContextParam('StartDate'); DisableContextParam('EndDate'); DisableContextFilter('ReleaseDate'); end; procedure TsprQuery.ReOpen; begin Screen.Cursor := crHourGlass; try Active := False; Active := True; finally Screen.Cursor := crDefault; end; end; procedure TsprQuery.DSOpen; begin Screen.Cursor := crHourGlass; try Active := True; finally Screen.Cursor := crDefault; end; end; function TsprQuery.GetDescription: string; var I: Integer; S, vDirection: string; begin Result := Self.SQL.Text; if Self.Parameters.Count > 0 then begin Result := Result + clrf + '------------------------' + clrf; for I := 0 to Parameters.Count - 1 do begin case Parameters[I].Direction of pdUnknown: vDirection := 'pdUnknown'; pdInput: vDirection := 'pdInput'; pdOutput: vDirection := 'pdOutput'; pdInputOutput: vDirection := 'pdInputOutput'; pdReturnValue: vDirection := 'pdReturnValue'; end; S := Format('%s %s = %s', [vDirection, Parameters[I].Name, VarToStr(Parameters[I].Value)]); Result := Result + clrf + S; end; end; end; procedure TsprQuery.RevertToDefault; begin Active := False; Self.Order.Clear; Self.Filters.Clear; end; procedure SetFieldsFormat(DataSet: TDataSet); var I: Integer; begin for I := 0 to DataSet.Fields.Count - 1 do if DataSet.Fields[I] is TDateTimeField then TDateTimeField(DataSet.Fields[I]).DisplayFormat := sprDateTimeFieldFormat else if DataSet.Fields[I] is TDateField then TDateField(DataSet.Fields[I]).DisplayFormat := sprDateFieldFormat; end; function AsString(DataSet: TDataSet; FieldName: string): string; begin Result := DataSet.FieldByName(FieldName).DisplayText; end; function TQueryActions.IndexOf(const AName: string): Integer; begin for Result := 0 to Count - 1 do if AnsiCompareText(TQueryAction(Items[Result]).Name, AName) = 0 then Exit; Result := -1; end; function TQueryActions.Find(const AName: string): TQueryAction; var I: Integer; begin I := IndexOf(AName); if I < 0 then Result := nil else Result := TQueryAction(Items[I]); end; function TsprQuery.AddAction(Name: string; Caption: string; OnExecute: TActionExecMethod): TQueryAction; begin Result := TQueryAction(FActions.Add); Result.Name := Name; Result.Caption := Caption; Result.OnExecute := OnExecute; end; end.
unit PromoDAO; interface uses ADODb, PromoDTO, db, SysUtils, Classes, contnrs, variants, DateUtils, dialogs, CouponCls; type TPromoDAO = class private fConnection: TADOConnection; stores: TObjectList; function convertPercentRewardValue(arg_amountType: String; arg_value: double): double; function revertPercentRewardValue(arg_amountType: String; arg_value: double): double; function deleteValidOnDays(arg_iddiscount: Integer): boolean; public procedure setConnection(arg_conn: TADOConnection); procedure savePromo(arg_promoDTO: TPromoDTO); procedure removePromo(arg_idDiscount: Integer); procedure saveValidOnDays(arg_promoDTO: TPromoDTO); procedure saveCouponDiscount(arg_promoDTO: TPromoDTO); procedure saveStoreDiscount(arg_promoDTO: TPromoDTO); procedure saveTagDiscount(arg_promoDTO: TPromoDTO); procedure saveUsesDiscount(arg_promoDTO: TPromoDTO); procedure saveRewardsDiscount(arg_promoDTO: TPromoDTO); procedure saveCustomerGroupDiscount(arg_promoDTO: TPromoDTO); function getOnePromo(arg_idDiscount: Integer): TPromoDTO; function getValidOnDays(arg_idDiscount: Integer): TStringList; function getPurchaseTags(): TObjectList; function getRewardTags(idDiscount: integer): TObjectList; function getCustomerGroups(): TObjectList; function getCoupons(arg_idDiscount: Integer): TStringList; function getPurchaseTagsDiscount(arg_idDiscount: Integer): TObjectList; function getRewardTagsDiscount(arg_idDiscount: Integer): TObjectList; function getCustomerGroupsDiscount(arg_idDiscount: Integer): TObjectList; function getCouponsDiscount(arg_idDiscount: Integer): TStringList; function getStoreGroupDiscount(arg_idDiscount: Integer): TObjectList; function IsModelInCurrentPromoCoupon(idModel: integer): TObjectList; // Coupon function GetCurrentCouponPromo(couponCode: string = ''; idPromo: integer = 0): TObjectList; function GetCoupon(select: TDataset): TCoupon; procedure SaveCouponOnSaleToApplyCouponDiscount(coupon: TCoupon); end; var purchaseTagList: TObjectList; rewardTagList: TObjectList; implementation uses StoreCls; { TPromoDAO } function TPromoDAO.convertPercentRewardValue(arg_amountType: String; arg_value: double): double; begin result := arg_value; if ( pos('Percent', arg_amountType) > 0 ) then begin result := arg_value * 0.01; end; end; function TPromoDAO.deleteValidOnDays(arg_iddiscount: Integer): boolean; var delete: TADOQuery; begin try try delete := TADOQuery.Create(nil); delete.Connection := fConnection; delete.SQL.Add('delete from DiscValidOnDays'); delete.SQL.add(' where IDDIScount = :param_idDiscount'); delete.Parameters.ParamByName('param_idDiscount').Value := arg_idDiscount; delete.ExecSQL; except on e: Exception do begin raise Exception.create('Cannot delete DiscValidOnDays: ' + e.Message); end; end; finally freeAndNil(delete); end; end; function TPromoDAO.getCoupons(arg_idDiscount: Integer): TStringList; var select: TADOQuery; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.Add('select * from DiscCoupons'); select.SQL.add(' where IDDIScount = :param_idDiscount'); select.Parameters.ParamByName('param_idDiscount').Value := arg_idDiscount; select.open(); result := TStringList.create(); while ( not select.Eof ) do begin result.Add(select.fieldByName('code').Value); select.Next(); end; except end; finally freeAndNil(select); end; end; function TPromoDAO.getCouponsDiscount(arg_idDiscount: Integer): TStringList; begin result := getCoupons(arg_idDiscount); end; function TPromoDAO.GetCurrentCouponPromo(couponCode: string = ''; idPromo: integer = 0): TObjectList; var select: TADOQuery; coupon: TCoupon; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.sql.add('select distinct d.IdDiscount, d.DiscountName, D.DiscType, D.AmountType, D.RewardAmount, tm.IdModel '); select.sql.add(', m.Model, m.Description, d.CashierShouldWarn, dc.Code, m.SellingPrice'); select.sql.add(' from Discounts d'); select.sql.add(' join DiscQualifyingTags t on d.IDDiscount = t.IdDiscount'); select.sql.add(' join TagModel tm on tm.IdTag = t.IdTag'); select.sql.add(' join Model m on m.IdModel = tm.IdModel'); select.sql.add(' join DiscValidOnDays pd on d.IDDiscount = pd.IDDiscount '); select.sql.add(' join DiscCoupons dc on d.IdDiscount = dc.IdDiscount '); select.sql.add('where tm.Active = 1 '); select.sql.add(' and (d.StartOn <= GetDate() and (d.EndOn >= Cast(GetDate() as Date)))'); select.sql.add(' and d.DiscType like :param_DiscType '); //select.sql.add(' and convert(nvarchar(max), d.DiscType) = N :prm_DiscType '); select.Parameters.ParamByName('param_DiscType').Value := 'Coupon'; if ( idPromo > 0 ) then begin select.sql.add( ' and d.IdDiscount = :param_IdDiscount '); select.Parameters.ParamByName('param_IdDiscount').Value := idPromo; end; if ( Length(Trim(couponCode)) > 0 ) then begin select.sql.add( ' and dc.Code like :param_coupon '); select.Parameters.ParamByName('param_coupon').Value := couponCode; end; select.open(); result := TObjectList.Create(true); while ( not select.Eof ) do begin result.Add(GetCoupon(select)); select.Next; end; except on e: Exception do begin raise e.Create('Cannot retrieve details from the current promo '+ e.Message); end end; finally freeAndNil(select); end; end; function TPromoDAO.getCustomerGroups: TObjectList; var select: TADOQuery; customerGroup: TDiscountCustomerGroup; customerGroupList: TObjectList; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.Add('select tp.IDTipoPessoa, tp.TipoPessoa'); select.SQL.add(' from TipoPessoa tp'); select.open(); customerGroupList := TObjectList.create(); while ( not select.Eof ) do begin customerGroup := TDiscountCustomerGroup.Create(); customerGroup.setIDTipoPessoa(select.fieldByName('IDTipoPessoa').Value); customerGroup.setName(select.fieldByName('TipoPessoa').Value); customerGroupList.add(customerGroup); select.Next(); end; result := customerGroupList; except freeAndNil(select); end; finally end; end; function TPromoDAO.getCustomerGroupsDiscount(arg_idDiscount: Integer): TObjectList; var select: TADOQuery; customerGroup: TDiscountCustomerGroup; customerGroupList: TObjectList; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.Add('select cg.IDTipoPessoa, tp.TipoPessoa'); select.SQL.add(' from DiscAllowedCustGroups cg'); select.sql.Add(' left join TipoPessoa tp on cg.IDTipoPessoa = tp.IDTipoPessoa'); select.SQL.add(' where IDDiscount = :param_idDiscount'); select.Parameters.ParamByName('param_idDiscount').Value := arg_idDiscount; select.open(); customerGroupList := TObjectList.create(); while ( not select.Eof ) do begin customerGroup := TDiscountCustomerGroup.Create(); customerGroup.setIDTipoPessoa(select.fieldByName('IDTipoPessoa').Value); customerGroupList.add(customerGroup); select.Next(); end; result := customerGroupList; except freeAndNil(select); end; finally end; end; function TPromoDAO.getOnePromo(arg_idDiscount: Integer): TPromoDTO; var select: TADOQuery; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.Add('select * from Discounts'); select.sql.add(' where IdDiscount = :param_iddiscount'); select.Parameters.ParamByName('param_iddiscount').Value := arg_idDiscount; select.open(); result := TPromoDTO.create(); result.DiscountName := select.fieldByName('DiscountName').Value; result.DiscountType := select.fieldByName('DiscType').Value; result.AmountType := select.fieldByName('AmountType').Value; if ( not select.fieldByName('MinQuantity').IsNull ) then begin result.MinQuantity := select.fieldByName('MinQuantity').value; end; if ( not select.fieldbyname('MaxUsesInTotal').isnull ) then begin result.MaxUsesInTotal := select.fieldByName('MaxUsesInTotal').value; end; if ( not select.fieldbyname('MinSubTotal').isnull ) then begin result.MaxUsesInTotal := select.fieldByName('MinSubTotal').value; end; if ( not select.fieldbyname('FirstTimeCustomerOnly').isnull ) then begin result.MaxUsesInTotal := select.fieldByName('FirstTimeCustomerOnly').value; end; if ( not select.fieldbyname('MaxUsesPerCustomer').isnull ) then begin result.MaxUsesInTotal := select.fieldByName('MaxUsesPerCustomer').value; end; result.RewardAmount := select.fieldByName('RewardAmount').value; if ( not select.fieldByName('RewardQuantity').IsNull ) then begin result.RewardQuantity := select.fieldByName('RewardQuantity').value; end; // revert reward amount if amount type is "Percent" result.RewardAmount := revertPercentRewardValue(select.fieldByName('AmountType').Value, select.fieldByName('RewardAmount').value); result.StartDate := VarToDateTime(select.fieldByName('StartOn').value); result.EndDate := varToDateTime(select.fieldByName('EndOn').value); result.BeginTimeOfDay := TimeOf(StrToTime(select.fieldByName('BeginTimeOfDay').value)); result.EndTimeOfDay := TimeOf(strToTime(select.fieldByName('EndTimeOfDay').value)); result.CustomerCardRequired := select.fieldByName('CustomerCardRequired').value; result.MinDollarAmount := select.fieldByName('MinDollarAmount').value; result.IsStackable := select.fieldByName('IsStackable').value; if ( not select.fieldByname('IsBogo').IsNull ) then begin result.IsBogo := select.fieldByName('IsBogo').Value; end else begin result.isBogo := false; end; if ( not select.fieldByName('BuyAnd').isNull ) then begin result.BuyAnd := select.fieldByName('BuyAnd').Value; end else begin result.BuyAnd := false; end; if ( not select.fieldByName('CashierShouldWarn').isNull ) then begin result.CashierShouldWarn := select.fieldByName('CashierShouldWarn').Value; end else begin result.CashierShouldWarn := false; end; except on e: exception do begin raise exception.Create(format('can not get Discounts: %s', [e.Message])); end; end; finally freeAndNil(select); end; end; function TPromoDAO.getPurchaseTags: TObjectList; var select: TADOQuery; purchaseTag: TDiscountPurchase; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.Add('select distinct t.IDTag, t.tagName, tm.Active from Tag t '); select.SQL.add('join TagModel tm on t.idtag = tm.idTag '); select.SQL.add('where tm.active = 1 '); select.SQL.add('and t.IdTag not in ( select IdTag from DiscQualifyingTags ) '); select.SQL.Add('order by t.IdTag'); select.Open(); result := TObjectList.Create(); while ( not select.Eof ) do begin purchaseTag := TDiscountPurchase.Create(); purchaseTag.setIDTag(0); purchaseTag.setIDTag(select.fieldByName('idTag').Value); purchaseTag.setName(select.fieldByName('tagName').Value); result.add(purchaseTag); select.Next(); end; except end; finally freeAndNil(select); end; end; function TPromoDAO.getPurchaseTagsDiscount(arg_idDiscount: Integer): TObjectList; var select: TADOQuery; purchaseTag: TDiscountPurchase; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.Add('select dq.IDTag, t.TagName'); select.SQL.add(' from DiscQualifyingTags dq'); select.sql.Add(' join Tag t on dq.IDTag = t.IDTag'); select.SQL.Add( ' where dq.IdDiscount = :param_iddiscount'); select.Parameters.ParamByName('param_iddiscount').Value := arg_idDiscount; select.open(); result := TObjectList.Create(); while ( not select.Eof ) do begin purchaseTag := TDiscountPurchase.Create(); purchaseTag.setIDTag(select.fieldByName('idTag').Value); purchaseTag.setName(select.fieldByName('tagName').Value); result.add(purchaseTag); select.Next(); end; except freeAndNil(select); end; finally end; end; function TPromoDAO.getRewardTags(idDiscount: integer): TObjectList; var select: TADOQuery; rewardTag: TDiscountReward; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.Add('select distinct t.IDTag, t.tagName, tm.Active from Tag t '); select.SQL.add('join TagModel tm on t.idtag = tm.idTag '); select.SQL.add('where tm.active = 1 '); select.SQL.add(' and t.IdTag not in ( select IdTag from DiscRewardTags drt '); select.SQL.add(' union '); select.SQL.add(' select IdTag from DiscQualifyingTags dqt )'); // select.Parameters.ParamByName('prm_idDiscount').Value := idDiscount; select.Open(); result := TObjectList.Create(); while ( not select.Eof ) do begin rewardTag := TDiscountReward.Create(); rewardTag.setIDTag(select.fieldByName('idTag').Value); rewardTag.setName(select.fieldByName('tagName').Value); result.add(rewardTag); select.Next(); end; except end; finally freeAndNil(select); end; // result := //getPurchaseTags; old approach end; function TPromoDAO.getRewardTagsDiscount(arg_idDiscount: Integer): TObjectList; var select: TADOQuery; rewardtag: TDiscountReward; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.Add('select dr.IDTag, t.TagName'); select.SQL.add(' from DiscRewardTags dr'); select.sql.Add(' join Tag t on dr.IDTag = t.IDTag'); select.SQL.Add( ' where dr.IdDiscount = :param_iddiscount'); select.Parameters.ParamByName('param_iddiscount').Value := arg_idDiscount; select.open(); result := TObjectList.Create(); while ( not select.Eof ) do begin rewardtag := TDiscountReward.Create(); rewardtag.setIDTag(select.fieldByName('idTag').Value); rewardtag.setName(select.fieldByName('tagName').Value); result.add(rewardtag); select.Next(); end; except freeAndNil(select); end; finally end; end; function TPromoDAO.getStoreGroupDiscount(arg_idDiscount: Integer): TObjectList; var select: TADOQuery; store: TStoreRegistry; storeDiscountList: TObjectList; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.Add('select s.IDStore, s.name'); select.SQL.add(' from Store s'); select.sql.Add(' join DiscStores ds on ds.IDStore = s.IDStore'); select.sql.add(' where ds.IdDiscount = :param_idDiscount'); select.Parameters.ParamByName('param_idDiscount').value := arg_idDiscount; select.open(); storeDiscountList := TObjectList.Create(); while ( not select.Eof ) do begin store := TStoreRegistry.Create(); store.IdStore := select.fieldByName('IDStore').Value; store.Name := select.fieldByName('Name').Value; storeDiscountList.add(store); select.Next(); end; result := storeDiscountList; except freeAndNil(select); end; finally end; end; function TPromoDAO.getValidOnDays(arg_idDiscount: Integer): TStringList; var select: TADOQuery; i: Integer; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.Add('select * from DiscValidOnDays'); select.sql.add(' where IdDiscount = :param_idDiscount'); select.Parameters.ParamByName('param_idDiscount').Value := arg_idDiscount; select.open(); result := TStringList.Create(); while ( not select.Eof ) do begin result.add(select.fieldByName('DayOfWeek').value); select.Next(); end; except end; finally freeAndNil(select); end; end; function TPromoDAO.IsModelInCurrentPromoCoupon(idModel: integer): TObjectList; var select: TADOQuery; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.sql.add('select d.IdDiscount, d.DiscountName, D.DiscType, D.AmountType, D.RewardAmount, tm.IdModel, m.Model, m.Description'); select.sql.add(' from Discounts d'); select.sql.add(' join DiscQualifyingTags t on d.IDDiscount = t.IdDiscount'); select.sql.add(' join TagModel tm on tm.IdTag = t.IdTag'); select.sql.add(' join Model m on m.IdModel = tm.IdModel'); select.sql.add(' join DiscValidOnDays pd on d.IDDiscount = pd.IDDiscount '); select.sql.add('where (d.EndOn is null) or (d.EndOn >= :param_EndOn)'); select.sql.add(' and tm.Active = 1 '); select.sql.add(' and d.DiscType = :param_DiscType'); except on e: Exception do begin end end; finally freeAndNil(select); end; end; procedure TPromoDAO.removePromo(arg_idDiscount: Integer); var sp: TADOStoredProc; begin try try sp := TADOStoredProc.Create(nil); sp.Connection := fConnection; sp.ProcedureName := 'sp_Discounts_Delete'; sp.Parameters.Refresh(); sp.Parameters.ParamByName('@IDDiscount').value := arg_idDiscount; sp.ExecProc(); except on e: Exception do begin raise; end; end; finally freeAndNil(sp); end; end; function TPromoDAO.revertPercentRewardValue(arg_amountType: String; arg_value: double): double; begin result := arg_value; if ( pos('Percent', arg_amountType) > 0 ) then begin result := arg_value * 100; end; end; function TPromoDAO.GetCoupon(select: TDataset): TCoupon; var coupon: TCoupon; begin coupon := TCoupon.create; coupon.IDPromo := select.fieldByName('IdDiscount').Value; coupon.RewardAmount := select.fieldByName('RewardAmount').Value; coupon.AmountType := select.fieldByName('AmountType').Value; coupon.CashierShouldWarn := select.FieldByName('CashierShouldWarn').Value; coupon.NeedsPhysicalCoupon := true; // needs to create that new field on the database coupon.CouponCode := select.fieldByName('Code').Value; coupon.IdModel := select.fieldByName('IdModel').Value; coupon.SellingPrice := select.fieldByName('SellingPrice').Value; result := coupon; end; procedure TPromoDAO.saveCouponDiscount(arg_promoDTO: TPromoDTO); var sp: TADOStoredProc; couponList: TStringList; i: Integer; begin try try sp := TADOStoredProc.Create(nil); sp.Connection := fConnection; sp.ProcedureName := 'sp_DiscCoupons_Upsert'; sp.Parameters.Refresh(); sp.Parameters.ParamByName('@IDDiscount').value := arg_promoDTO.IDDiscount; couponList := arg_promoDTO.getCouponsDiscount(); for i:= 0 to couponList.Count - 1 do begin sp.Parameters.ParamByName('@Code').Value := couponList.Strings[i]; sp.ExecProc(); end; except on e: Exception do begin raise; end; end; finally freeAndNil(sp); freeAndNil(couponList); end; end; procedure TPromoDAO.saveCustomerGroupDiscount(arg_promoDTO: TPromoDTO); var delete: TADOQuery; sp: TADOStoredProc; customerGroupList: TObjectList; i: Integer; begin try try delete := TADOQuery.Create(nil); delete.Connection := fConnection; delete.SQL.add('delete from DiscAllowedCustGroups '); delete.sql.Add('where idDiscount = :param_idDiscount'); delete.Parameters.ParamByName('param_idDiscount').Value := arg_promoDTO.IDDiscount; delete.ExecSQL(); sp := TADOStoredProc.Create(nil); sp.Connection := fConnection; sp.Name := 'sp_DiscAllowedCustGroups_Upsert'; sp.Parameters.Refresh(); sp.Parameters.ParamByName('@IDDiscount').value := arg_promoDTO.IDDiscount; customerGroupList := arg_promoDTO.getCustomerGroupList(); for i:= 0 to customerGroupList.Count - 1 do begin sp.Parameters.ParamByName('@IDTipoPessoa').Value := TDiscountCustomerGroup(customerGroupList.Items[i]).getIDTipoPessoa; sp.ExecProc(); end; sp.ExecProc(); except on e: Exception do begin end; end; finally freeAndNil(sp); freeAndNil(delete); freeAndNil(customerGroupList); end; end; procedure TPromoDAO.savePromo(arg_promoDTO: TPromoDTO); var sp: TADOStoredProc; begin try fConnection.BeginTrans; try sp := TADOStoredProc.Create(nil); sp.Connection := fConnection; sp.ProcedureName := 'sp_Discounts_Upsert'; sp.Parameters.Refresh(); sp.Parameters.ParamByName('@IDDiscount').Value := arg_promoDTO.IDDiscount; sp.Parameters.ParamByName('@DiscountName').value := arg_promoDTO.DiscountName; sp.Parameters.ParamByName('@StartOn').Value := StrToDateDef(DateToStr(arg_promoDTO.StartDate), 0); sp.Parameters.ParamByName('@EndOn').Value := StrToDateDef(DateToStr(arg_promoDTO.EndDate), 0); sp.Parameters.ParamByName('@BeginTimeOfDay').value := StrToTimeDef(TimeToStr(arg_promoDTO.BeginTimeOfDay), 0); sp.Parameters.ParamByName('@EndTimeOfDay').value := StrToTimeDef(TimeToStr(arg_promoDTO.EndTimeOfDay), 0); sp.Parameters.ParamByName('@DiscType').value := arg_promoDTO.DiscountType; sp.Parameters.ParamByName('@IDStore').value := arg_promoDTO.IDStore; if ( arg_promoDTO.MinSubTotal = 0 ) then begin sp.Parameters.ParamByName('@MinSubTotal').value := null end else begin sp.Parameters.ParamByName('@MinSubtotal').Value := arg_promoDTO.MinSubTotal; end; if ( arg_promoDTO.MaxUsesPerCustomer = 0 ) then begin sp.Parameters.ParamByName('@MaxUsesPerCustomer').value := null; end else begin sp.Parameters.ParamByName('@MaxUsesPerCustomer').value := arg_promoDTO.MaxUsesPerCustomer; end; if ( arg_promoDTO.MaxUsesInTotal = 0 ) then begin sp.Parameters.ParamByName('@MaxUsesInTotal').value := null; end else begin sp.Parameters.ParamByName('@MaxUsesInTotal').value := arg_promoDTO.MaxUsesInTotal; end; sp.Parameters.ParamByName('@MinQuantity').Value := arg_promoDTO.MinQuantity; if ( not arg_promodto.FirstTimeCustomerOnly ) then begin sp.Parameters.ParamByName('@FirstTimeCustomerOnly').value := 0; end else begin sp.Parameters.ParamByName('@FirstTimeCustomerOnly').value := 1; end; sp.Parameters.ParamByName('@CustomerCardRequired').value := arg_promoDTO.CustomerCardRequired; sp.Parameters.ParamByName('@IsStackable').value := arg_promoDTO.IsStackable; // convert rewardAmount to amount type is "Percent" sp.Parameters.ParamByName('@RewardAmount').value := convertPercentRewardValue(arg_promoDTO.AmountType, arg_promoDTO.RewardAmount); sp.Parameters.ParamByName('@AmountType').value := arg_promoDTO.AmountType; sp.Parameters.ParamByName('@RewardQuantity').value := arg_promoDTO.RewardQuantity; sp.Parameters.ParamByName('@MinDollarAmount').value := arg_promoDTO.MinDollarAmount; sp.Parameters.paramByName('@IsBogo').value := arg_promoDTO.IsBogo; sp.Parameters.ParamByName('@BuyAnd').Value := arg_promoDTO.BuyAnd; sp.Parameters.ParamByName('@CashierShouldWarn').Value := arg_promoDTO.CashierShouldWarn; sp.ExecProc(); if ( arg_promoDTO.idDiscount = 0 ) then // stands insert arg_promoDTO.IDDiscount := sp.Parameters.paramByName('@IDDiscount').Value; saveValidOnDays(arg_promoDTO); if ( arg_promoDTO.StoreDefined ) then begin saveStoreDiscount(arg_promoDTO); end; if ( arg_promoDTO.CouponDefined ) then begin saveCouponDiscount(arg_promoDTO); end; if ( arg_promoDTO.IDDiscUses > 0 ) then begin saveUsesDiscount(arg_promoDTO); end; if ( arg_promoDTO.PurchaseTagDefined ) then begin saveTagDiscount(arg_promoDTO); end; if ( arg_promoDTO.RewardTagDefined ) then begin saveRewardsDiscount(arg_promoDTO); end; if ( arg_promoDTO.CustomerGroupDefined ) then begin saveCustomerGroupDiscount(arg_promoDTO); end; fConnection.CommitTrans; except on e: Exception do begin fConnection.RollbackTrans; raise exception.Create(format('save promo error: %s', [e.message])); end; end; finally freeAndNil(sp); end; end; procedure TPromoDAO.saveRewardsDiscount(arg_promoDTO: TPromoDTO); var delete: TADOQuery; sp: TADOStoredProc; // rewardTagList: TObjectList; i: Integer; begin try try delete := TADOQuery.Create(nil); delete.Connection := fConnection; delete.SQL.add('delete from DiscRewardTags '); delete.sql.Add('where idDiscount = :param_idDiscount'); delete.Parameters.ParamByName('param_idDiscount').Value := arg_promoDTO.IDDiscount; delete.ExecSQL(); sp := TADOStoredProc.Create(nil); sp.Connection := fConnection; sp.procedureName := 'sp_DiscRewardTags_Upsert'; sp.Parameters.Refresh(); sp.Parameters.paramByName('@IDDiscount').Value := arg_promoDTO.IDDiscount; rewardTagList := arg_promoDTO.getRewardTagList(); for i:= 0 to rewardTagList.Count - 1 do begin sp.Parameters.ParamByName('@IDTag').Value := TDiscountReward(rewardTagList.Items[i]).getIDTag; // showmessage(format('RewardTag is %d', [TDiscountReward(rewardTagList.Items[i]).getIDTag])); sp.ExecProc(); end; except on e: Exception do begin raise; end; end; finally freeAndNil(sp); freeAndNil(delete); // freeAndNil(rewardTagList); end; end; procedure TPromoDAO.saveStoreDiscount(arg_promoDTO: TPromoDTO); var delete: TADOQuery; sp: TADOStoredProc; i: Integer; begin try try delete := TADOQuery.Create(nil); delete.Connection := fConnection; delete.SQL.add('delete from DiscStores '); delete.sql.Add('where idDiscount = :param_idDiscount'); delete.Parameters.ParamByName('param_idDiscount').Value := arg_promoDTO.IDDiscount; delete.ExecSQL(); sp := TADOStoredProc.Create(nil); sp.Connection := fConnection; sp.procedureName := 'sp_DiscStores_Upsert'; sp.Parameters.Refresh(); sp.Parameters.ParamByName('@IDDiscount').Value := arg_promoDTO.IDDiscount; sp.Parameters.ParamByName('@IsInclude').Value := arg_promoDTO.IsInclude; stores := arg_promoDTO.getStoreList(); for i:= 0 to stores.Count - 1 do begin sp.Parameters.ParamByName('@IDStore').Value := TStoreRegistry(stores.Items[i]).IdStore; sp.ExecProc(); end; except on e: Exception do begin raise; end; end; finally freeAndNil(sp); freeAndNil(delete); end; end; procedure TPromoDAO.saveTagDiscount(arg_promoDTO: TPromoDTO); var sp: TADOStoredProc; delete: TADOQuery; i: Integer; begin try try delete := TADOQuery.Create(nil); delete.Connection := fConnection; delete.SQL.add('delete from DiscQualifyingTags '); delete.sql.Add('where idDiscount = :param_idDiscount'); delete.Parameters.ParamByName('param_idDiscount').Value := arg_promoDTO.IDDiscount; delete.ExecSQL(); sp := TADOStoredProc.Create(nil); sp.Connection := fConnection; sp.procedureName := 'sp_DiscQualifyingTags_Upsert'; sp.Parameters.Refresh(); sp.Parameters.ParamByName('@IDDiscount').value := arg_promoDTO.IDDiscount; purchaseTagList := arg_promoDTO.getPurchaseTagList(); for i:= 0 to purchaseTagList.Count - 1 do begin sp.Parameters.ParamByName('@IDTag').Value := TDiscountPurchase(purchaseTagList.items[i]).getIDTag; //(purchaseTagList.items[i] as TDiscountPurchase).getIdTag;/// // showmessage(format('PurchaseTag is %d', [TDiscountPurchase(purchaseTagList.items[i]).getIDTag])); sp.ExecProc(); end; except on e: Exception do begin raise; end; end; finally // purchaseTagList.Free; freeAndNil(sp); freeAndNil(delete); end; end; procedure TPromoDAO.saveUsesDiscount(arg_promoDTO: TPromoDTO); var sp: TADOStoredProc; begin try try sp := TADOStoredProc.Create(nil); sp.Connection := fConnection; sp.procedureName := 'sp_DiscUses_Upsert'; sp.Parameters.Refresh(); sp.Parameters.ParamByName('@IDDiscount').value := arg_promoDTO.IDDiscount; sp.Parameters.ParamByName('@IDInventoryMov').value := arg_promoDTO.IDDiscUses; sp.ExecProc(); except on e: Exception do begin raise; end; end; finally freeAndNil(sp); end; end; procedure TPromoDAO.saveValidOnDays(arg_promoDTO: TPromoDTO); var sp: TADOStoredProc; discountValidDaysList: TStringList; i: Integer; begin try try deleteValidOnDays(arg_promoDto.IDDiscount); sp := TADOStoredProc.Create(nil); sp.Connection := fConnection; sp.procedureName := 'sp_DiscValidOnDays_Upsert'; sp.Parameters.Refresh(); sp.Parameters.ParamByName('@IDDiscount').value := arg_promoDTO.IDDiscount; discountValidDaysList := arg_promoDTO.getValidOnDaysDiscount(); for i:= 0 to discountValidDaysList.Count - 1 do begin sp.Parameters.ParamByName('@DayOfWeek').Value := strToInt(discountValidDaysList.Strings[i]); sp.ExecProc(); end; except on e: Exception do begin raise; end; end; finally freeAndNil(sp); freeAndNil(discountValidDaysList); end; end; procedure TPromoDAO.setConnection(arg_conn: TADOConnection); begin fConnection := arg_conn; end; procedure TPromoDAO.SaveCouponOnSaleToApplyCouponDiscount( coupon: TCoupon); var cmd: TADOQuery; select: TADOQuery; begin try try select := TADOQuery.Create(nil); select.Connection := fConnection; select.SQL.add('select * from Sal_Coupon '); select.SQL.add(' where DocumentID = :param_DocId and CouponCode like :param_CouponCode '); select.Parameters.ParamByName('param_DocId').Value := coupon.DocumentId; select.Parameters.ParamByName('param_CouponCode').Value := coupon.CouponCode; select.Open(); if ( select.IsEmpty ) then begin cmd := TADOQuery.Create(nil); cmd.Connection := fConnection; cmd.SQL.add('Insert into Sal_Coupon values (:param_DocId, :param_CouponCode)'); cmd.Parameters.ParamByName('param_DocId').Value := coupon.DocumentId; cmd.Parameters.ParamByName('param_CouponCode').Value := coupon.CouponCode; cmd.ExecSQL(); end; except on e: Exception do begin raise e.Create('Error: Cannot insert coupons to sale ' + e.Message); end; end; finally FreeAndNil(select); FreeAndNil(cmd); end; end; end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *) unit ufrmAnimate; interface uses LCLIntf, LCLType, SysUtils, Classes, Graphics, Controls, Forms, uFPG, ExtCtrls, Spin, StdCtrls, uLanguage, uIniFile; const sFPG = 0; sIMG = 1; type { TfrmAnimate } TfrmAnimate = class(TForm) cbStretch: TCheckBox; cbProportional: TCheckBox; Image1: TImage; Panel1: TPanel; seMilliseconds: TSpinEdit; tAnimate: TTimer; procedure cbProportionalChange(Sender: TObject); procedure cbStretchChange(Sender: TObject); procedure FormHide(Sender: TObject); procedure FormShow(Sender: TObject); procedure seMillisecondsChange(Sender: TObject); procedure tAnimateTimer(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } _lng_str : string; procedure _set_lng; public { Public declarations } fpg_animate : Array [1 .. 999] of boolean; img_animate : Array [1 .. 99 ] of TBitmap; num_of_images : integer; source : integer; i : integer; fpg : TFpg; procedure Draw_Image; end; var frmAnimate: TfrmAnimate; implementation {$R *.lfm} procedure TfrmAnimate._set_lng; begin if _lng_str = inifile_language then Exit; _lng_str := inifile_language; end; procedure TfrmAnimate.Draw_Image; begin case source of sFPG : begin while (true) do begin i := i + 1; if fpg_animate[i] then begin Image1.Picture.Bitmap.Assign(Fpg.images[i]); break; end; if i = 999 then i := 0; end; end; sImg: begin i := i + 1; Image1.Picture.Bitmap.Assign(IMG_animate[i]); if i = num_of_images then i := 0; end; end; end; procedure TfrmAnimate.tAnimateTimer(Sender: TObject); begin Draw_Image; end; procedure TfrmAnimate.FormShow(Sender: TObject); begin _set_lng; i := 0; tAnimate.Enabled := true; seMilliseconds.Value:=tAnimate.Interval; end; procedure TfrmAnimate.seMillisecondsChange(Sender: TObject); begin tAnimate.Enabled:=false; tAnimate.Interval:=seMilliseconds.Value; tAnimate.Enabled:=true; end; procedure TfrmAnimate.FormHide(Sender: TObject); begin i := 0; tAnimate.Enabled := false; num_of_images := 0; Hide; ModalResult := mrOK; end; procedure TfrmAnimate.cbStretchChange(Sender: TObject); begin Image1.Stretch:=cbStretch.Checked; end; procedure TfrmAnimate.cbProportionalChange(Sender: TObject); begin image1.Proportional:=cbProportional.Checked; end; procedure TfrmAnimate.FormCreate(Sender: TObject); begin source := sFPG; end; end.
{ publish with BSD Licence. Copyright (c) Terry Lao } unit helpfun; {$MODE Delphi} interface uses iLBC_define,constants,C2Delphi_header; {----------------------------------------------------------------* * calculation of auto correlation *---------------------------------------------------------------} const eps = 0.039; { 50 Hz } eps2 =0.0195; maxlsf=3.14; { 4000 Hz } minlsf=0.01; { 0 Hz } procedure autocorr( r:pareal; { (o) autocorrelation vector } x:pareal; { (i) data vector } N:integer; { (i) length of data vector } order:integer { largest lag for calculated autocorrelations } ); procedure window( z:pareal; { (o) the windowed data } x:pareal; { (i) the original data vector } y:pareal; { (i) the window } N:integer { (i) length of all vectors } ); procedure levdurb( a:pareal; { (o) lpc coefficient vector starting with 1.0 } k:pareal; { (o) reflection coefficients } r:pareal; { (i) autocorrelation vector } order:integer { (i) order of lpc filter } ); procedure interpolate( nout:pareal; { (o) the interpolated vector } in1:pareal; { (i) the first vector for the interpolation } in2:pareal; { (i) the second vector for the interpolation } coef:real; { (i) interpolation weights } length:integer { (i) length of all vectors } ); procedure bwexpand( nout:pareal; { (o) the bandwidth expanded lpc coefficients } nin:pareal; { (i) the lpc coefficients before bandwidth expansion } coef:real; { (i) the bandwidth expansion factor } length:integer { (i) the length of lpc coefficient vectors } ); procedure vq( Xq:pareal; { (o) the quantized vector } index:pinteger; { (o) the quantization index } CB:pareal;{ (i) the vector quantization codebook } X:pareal; { (i) the vector to quantize } n_cb:integer; { (i) the number of vectors in the codebook } dim:integer { (i) the dimension of all vectors } ); procedure SplitVQ( qX:PAreal; { (o) the quantized vector } index:paInteger; { (o) a vector of indexes for all vector codebooks in the split } X:pareal; { (i) the vector to quantize } CB:pareal;{ (i) the quantizer codebook } nsplit:integer; { the number of vector splits } dim:PAInteger; { the dimension of X and qX } cbsize:PAInteger { the number of vectors in the codebook } ); procedure sort_sq( xq:preal; { (o) the quantized value } index:pinteger; { (o) the quantization index } x:real; { (i) the value to quantize } cb:pareal;{ (i) the quantization codebook } cb_size:integer { (i) the size of the quantization codebook } ); function LSF_check( { (o) 1 for stable lsf vectors and 0 for nonstable ones } lsf:pareal; { (i) a table of lsf vectors } dim:integer; { (i) the dimension of each lsf vector } NoAn:integer { (i) the number of lsf vectors in the table } ):integer; implementation procedure autocorr( r:pareal; { (o) autocorrelation vector } x:pareal; { (i) data vector } N:integer; { (i) length of data vector } order:integer { largest lag for calculated autocorrelations } ); var lag, nn:integer; sum:real; begin for lag := 0 to order do begin sum := 0; for nn := 0 to N - lag-1 do begin sum :=sum+ x[nn] * x[nn+lag]; end; r[lag] := sum; end; end; {----------------------------------------------------------------* * window multiplication *---------------------------------------------------------------} procedure window( z:pareal; { (o) the windowed data } x:pareal; { (i) the original data vector } y:pareal; { (i) the window } N:integer { (i) length of all vectors } ); var i:integer; begin for i := 0 to N-1 do begin z[i] := x[i] * y[i]; end; end; {----------------------------------------------------------------* * levinson-durbin solution for lpc coefficients *---------------------------------------------------------------} procedure levdurb( a:pareal; { (o) lpc coefficient vector starting with 1.0 } k:pareal; { (o) reflection coefficients } r:pareal; { (i) autocorrelation vector } order:integer { (i) order of lpc filter } ); var sum, alpha:real; m, m_h, i:integer; begin a[0] := 1.0; if (r[0] < EPS) then begin { if r[0] <:= 0, set LPC coeff. to zero } for i := 0 to order-1 do begin k[i] := 0; a[i+1] := 0; end; end else begin a[1] := -r[1]/r[0]; k[0] := -r[1]/r[0]; alpha := r[0] + r[1] * k[0]; for m := 1 to order-1 do begin sum := r[m + 1]; for i := 0 to m-1 do begin sum :=sum + a[i+1] * r[m - i]; end; k[m] := -sum / alpha; alpha :=alpha + k[m] * sum; m_h := (m + 1) shr 1; for i := 0 to m_h-1 do begin sum := a[i+1] + k[m] * a[m - i]; a[m - i] :=a[m - i] + k[m] * a[i+1]; a[i+1] := sum; end; a[m+1] := k[m]; end; end; end; {----------------------------------------------------------------* * interpolation between vectors *---------------------------------------------------------------} procedure interpolate( nout:pareal; { (o) the interpolated vector } in1:pareal; { (i) the first vector for the interpolation } in2:pareal; { (i) the second vector for the interpolation } coef:real; { (i) interpolation weights } length:integer { (i) length of all vectors } ); var i:integer; invcoef:real; begin invcoef := 1.0 - coef; for i := 0 to length-1 do begin nout[i] := coef * in1[i] + invcoef * in2[i]; end; end; {----------------------------------------------------------------* * lpc bandwidth expansion *---------------------------------------------------------------} procedure bwexpand( nout:pareal; { (o) the bandwidth expanded lpc coefficients } nin:pareal; { (i) the lpc coefficients before bandwidth expansion } coef:real; { (i) the bandwidth expansion factor } length:integer { (i) the length of lpc coefficient vectors } ); var i:integer; chirp:real; begin chirp := coef; nout[0] := nin[0]; for i := 1 to length-1 do begin nout[i] := chirp * nin[i]; chirp :=chirp * coef; end; end; {----------------------------------------------------------------* * vector quantization *---------------------------------------------------------------} procedure vq( Xq:pareal; { (o) the quantized vector } index:pinteger; { (o) the quantization index } CB:pareal;{ (i) the vector quantization codebook } X:pareal; { (i) the vector to quantize } n_cb:integer; { (i) the number of vectors in the codebook } dim:integer { (i) the dimension of all vectors } ); var i, j:integer; pos, minindex:integer; dist, tmp, mindist:real; begin pos := 0; mindist := FLOAT_MAX; minindex := 0; for j := 0 to n_cb-1 do begin dist := X[0] - CB[pos]; dist :=dist * dist; for i := 1 to dim-1 do begin tmp := X[i] - CB[pos + i]; dist:=dist + tmp*tmp; end; if (dist < mindist) then begin mindist := dist; minindex := j; end; pos :=pos + dim; end; for i := 0 to dim-1 do begin Xq[i] := CB[minindex*dim + i]; end; index^ := minindex; end; {----------------------------------------------------------------* * split vector quantization *---------------------------------------------------------------} procedure SplitVQ( qX:PAreal; { (o) the quantized vector } index:paInteger; { (o) a vector of indexes for all vector codebooks in the split } X:pareal; { (i) the vector to quantize } CB:pareal;{ (i) the quantizer codebook } nsplit:integer; { the number of vector splits } dim:PAInteger; { the dimension of X and qX } cbsize:PAInteger { the number of vectors in the codebook } ); var cb_pos, X_pos, i:integer; begin cb_pos := 0; X_pos:= 0; for i := 0 to nsplit-1 do begin vq(@qX[X_pos], @index[ i], @CB[ cb_pos], @X[X_pos], cbsize[i], dim[i]); X_pos :=X_pos+ dim[i]; cb_pos :=cb_pos + dim[i] * cbsize[i]; end; end; {----------------------------------------------------------------* * scalar quantization *---------------------------------------------------------------} procedure sort_sq( xq:preal; { (o) the quantized value } index:pinteger; { (o) the quantization index } x:real; { (i) the value to quantize } cb:pareal;{ (i) the quantization codebook } cb_size:integer { (i) the size of the quantization codebook } ); var i:integer; begin if (x <= cb[0]) then begin index^ := 0; xq^ := cb[0]; end else begin i := 0; while ((x > cb[i]) and (i < cb_size - 1)) do begin inc(i); end; if (x > ((cb[i] + cb[i - 1])/2)) then begin index^ := i; xq^ := cb[i]; end else begin index^ := i - 1; xq^ := cb[i - 1]; end; end; end; {----------------------------------------------------------------* * check for stability of lsf coefficients *---------------------------------------------------------------} function LSF_check( { (o) 1 for stable lsf vectors and 0 for nonstable ones } lsf:pareal; { (i) a table of lsf vectors } dim:integer; { (i) the dimension of each lsf vector } NoAn:integer { (i) the number of lsf vectors in the table } ):integer; var k,n,m, Nit, change,pos:integer; //tmp:real; begin Nit:=2; change:=0; { LSF separation check} for n:=0 to Nit-1 do begin { Run through a couple of times } for m:=0 to NoAn-1 do begin { Number of analyses per frame } for k:=0 to (dim-2) do begin pos:=m*dim+k; if ((lsf[pos+1]-lsf[pos])<eps) then begin if (lsf[pos+1]<lsf[pos]) then begin //tmp:=lsf[pos+1]; lsf[pos+1]:= lsf[pos]+eps2; lsf[pos]:= lsf[pos+1]-eps2; end else begin lsf[pos]:=lsf[pos]-eps2; lsf[pos+1]:=lsf[pos+1]-eps2; end; change:=1; end; if (lsf[pos]<minlsf) then begin lsf[pos]:=minlsf; change:=1; end; if (lsf[pos]>maxlsf) then begin lsf[pos]:=maxlsf; change:=1; end; end; end; end; result:=change; end; end.
unit TpImage; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThTag, ThImage, ThAnchor, TpControls, TpAnchor; type TTpCustomImage = class(TThCustomImage) private FOnGenerate: TTpEvent; FUseAbsoluteUrl: Boolean; protected function GetImageSrc: string; override; procedure SetOnGenerate(const Value: TTpEvent); protected function CreateAnchor: TThAnchor; override; procedure Tag(inTag: TThTag); override; protected property OnGenerate: TTpEvent read FOnGenerate write SetOnGenerate; property UseAbsoluteUrl: Boolean read FUseAbsoluteUrl write FUseAbsoluteUrl; end; // TTpImage = class(TTpCustomImage) published property Align; property AltText; property Anchor; property AutoAspect; property AutoSize; property HAlign; property Picture; property OnGenerate; property Style; property StyleClass; property UseAbsoluteUrl; property VAlign; property Visible; end; implementation uses ThPathUtils{, TpProject, DocumentManager}; { TTpCustomImage } function TTpCustomImage.CreateAnchor: TThAnchor; begin Result := TTpAnchor.Create(Self); end; procedure TTpCustomImage.SetOnGenerate(const Value: TTpEvent); begin FOnGenerate := Value; end; function TTpCustomImage.GetImageSrc: string; begin if Picture.PictureUrl <> '' then Result := Picture.PictureUrl else begin // Result := ExtractRelativePath(CurrentProject.Folder, Picture.PicturePath); // if UseAbsoluteUrl then // Result := CurrentProject.Url + Result; end; { if UseAbsoluteUrl then begin Result := ExtractRelativePath(CurrentProject.Folder, Picture.PicturePath); Result := CurrentProject.Url + Result; end else Result := ExtractRelativePath(DocumentManagerForm.CurrentItem.Path, Picture.PicturePath); } Result := ThPathToUrl(Result); end; procedure TTpCustomImage.Tag(inTag: TThTag); begin inherited; inTag.Add(tpClass, 'TTpImage'); inTag.Add('tpName', Name); inTag.Add('tpOnGenerate', OnGenerate); end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmTaskBar Purpose : To allow window control from a central location. Also has support in it to fix the M$ MDI window bugs. Date : 12-01-1998 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmTaskBar; interface {$I CompilerDefines.INC} uses Windows, Messages, Classes, Graphics, Controls, Forms, extctrls, menus; type TUpdateWindowListEvent = procedure(Sender: TObject; Form: TForm; var AddToList: boolean) of object; TUpdatedWindowListEvent = procedure(Sender: TObject; Form: TForm) of object; {$IFDEF rmDebug} TrmTestEvent = procedure(index: integer; msg: integer) of object; {$ENDIF} TWinType = (wtMDIChild, wtDialog, wtToolWin); TWinTypes = set of TWinType; TrmTaskBar = class(TCustomControl) private { Private declarations } OldWndProc: TFarProc; NewWndProc: Pointer; OldMDIWndProc: TFarProc; NewMDIWndProc: Pointer; OldApplicationWndProc: TFarProc; NewApplicationWndProc: Pointer; FHint: string; FTimer: TTimer; fDelay: integer; FColor: TColor; fBufferBMP: TBitmap; FIconBMP: TBitmap; FLabelBMP: TBitmap; FWindowList: TList; FTempList: TList; fmenuWin: TForm; fAutoHide: boolean; fAutoMinimize: boolean; fLastActiveForm: TForm; fLastActiveMDIChild: TForm; fExcludeWinTypes: TWinTypes; fMinBtnSize: integer; fBtnSpace: integer; fMaxBtnSize: integer; fBtnHeight: integer; fLeftMargin: integer; fRightMargin: integer; FTaskHint: THintWindow; fButtons: array of TRect; fOnAddingWindow: TUpdateWindowListEvent; fOnWindowAdded: TUpdatedWindowListEvent; fOnWindowRemoved: TUpdatedWindowListEvent; {$IFDEF rmDebug} fWinMessage: TrmTestEvent; {$ENDIF} fMDIMenuRefresh: TNotifyEvent; fTopMargin: integer; fMainFormFocused: boolean; fFlat: boolean; procedure SetColor(const Value: TColor); procedure wmCommand(var msg: TMessage); message wm_command; procedure wmEraseBkgnd(var msg: TMessage); message WM_ERASEBKGND; procedure wmDestroy(var msg: TMessage); message wm_destroy; procedure SetAutoHide(const Value: boolean); procedure SetExcludes(const Value: TWinTypes); procedure SetBtnHeight(const Value: integer); procedure SetBtnSpace(const Value: integer); procedure SetMaxBtnSize(const Value: integer); procedure SetMinBtnSize(const Value: integer); procedure SetLeftMargin(const Value: integer); procedure SetRightMargin(const Value: integer); procedure SetTopMargin(const Value: integer); procedure CMMouseLeave(var msg: TMessage); message cm_MouseLeave; procedure HookWin; procedure UnhookWin; procedure HookMDIWin; procedure UnhookMDIWin; function GetActiveForm: TForm; function GetWindowCount: integer; function GetWindowItem(index: integer): TForm; function GetMDIChild(index: integer): TForm; function GetMDIChildCount: integer; function GetActiveMDIChild: TForm; procedure SetFlat(const Value: boolean); protected { Protected declarations } procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure UnRegisterWindow(F: TForm); procedure RegisterWindow(F: TForm); procedure RegisterWindowTemp(F: TForm); procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure DoTimer(Sender: TObject); procedure SetDelay(const Value: integer); procedure MinimizeWindowTypes(WinTypes: TWinTypes); procedure HookWndProc(var AMsg: TMessage); procedure HookMDIWndProc(var AMsg: TMessage); procedure DoDummyForm(ToggleForm: TForm); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Paint; override; procedure HideHint(ClearHint: Boolean); procedure MinimizeAllMDI; procedure MinimizeAll; property ActiveMDIChild: TForm read GetActiveMDIChild; property MDIChildren[index: integer]: TForm read GetMDIChild; property MDIChildCount: integer read GetMDIChildCount; property WindowCount: integer read GetWindowCount; property ActiveWindow: TForm read GetActiveForm; property WindowList[index: integer]: TForm read GetWindowItem; {$IFDEF rmDebug} property OnWinMessage: TrmTestEvent read fWinMessage write fWinMessage; {$ENDIF} published { Published declarations } property LeftMargin: integer read fLeftMargin write SetLeftMargin default 3; property RightMargin: integer read fRightMargin write SetRightMargin default 3; property TopMargin: integer read fTopMargin write SetTopMargin default 3; property BtnSpace: integer read fBtnSpace write SetBtnSpace default 3; property MaxBtnSize: integer read fMaxBtnSize write SetMaxBtnSize default 150; property MinBtnsize: integer read fMinBtnSize write SetMinBtnSize default 5; property BtnHeight: integer read fBtnHeight write SetBtnHeight default 23; property ParentFont; property Font; property HintDelay: integer read fDelay write SetDelay default 2500; property ExcludeWindowTypes: TWinTypes read fExcludeWinTypes write SetExcludes; property Color: TColor read FColor write SetColor default clbtnface; property Flat : boolean read fFlat write SetFlat default false; property AutoHideMDIChildren: boolean read fAutoHide write SetAutoHide default false; property AutoMinimize: boolean read fAutoMinimize write fAutoMinimize default false; property OnAddingWindow: TUpdateWindowListEvent read fOnAddingWindow write fOnAddingWindow; property OnWindowAdded: TUpdatedWindowListEvent read fOnWindowAdded write fOnWindowAdded; property OnWindowRemoved: TUpdatedWindowListEvent read fOnWindowRemoved write fOnWindowRemoved; property OnMDIMenuRefresh: TNotifyEvent read fMDIMenuRefresh write fMDIMenuRefresh; end; implementation { TrmTaskBar } constructor TrmTaskBar.Create(AOwner: TComponent); begin inherited create(AOwner); ControlStyle := ControlStyle + [csAcceptsControls, csOpaque]; NewWndProc := nil; OldWndProc := nil; NewMDIWndProc := nil; OldMDIWndProc := nil; OldApplicationWndProc := nil; NewApplicationWndProc := nil; align := alBottom; height := 28; fColor := clBtnFace; fAutoHide := false; fAutoMinimize := false; fBufferBMP := tbitmap.create; FIconBMP := TBitmap.create; FLabelBMP := TBitmap.create; FWindowList := TList.create; FTempList := TList.create; fLastActiveForm := nil; fLastActiveMDIChild := nil; fExcludeWinTypes := []; LeftMargin := 3; RightMargin := 3; TopMargin := 3; BtnSpace := 3; MaxBtnSize := 150; MinBtnsize := 5; BtnHeight := 23; fFlat := false; SetLength(fButtons, 0); fdelay := 2500; FTaskHint := THintWindow.create(self); FTaskHint.Color := clInfobk; FTaskHint.Canvas.Font.color := clInfoText; FTaskHint.Canvas.Pen.Color := clWindowFrame; FTimer := TTimer.Create(self); FTimer.OnTimer := DoTimer; fMainFormFocused := false; HookWin; end; destructor TrmTaskBar.Destroy; begin SetLength(fButtons, 0); fBufferBMP.free; FIconBMP.free; FLabelBMP.free; FWindowList.free; FTempList.free; FTaskHint.free; FTimer.free; UnHookWin; inherited; end; procedure TrmTaskBar.CMMouseLeave(var msg: TMessage); begin inherited; HideHint(True); if Flat then Invalidate; end; procedure TrmTaskBar.DoTimer(Sender: TObject); begin FTimer.Enabled := false; HideHint(false); end; procedure TrmTaskBar.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var loop, btncount: integer; found: boolean; f: tform; tempmenuhandle: HMENU; newpoint: tpoint; begin fmenuwin := nil; btncount := high(fButtons); loop := 0; newpoint := point(x, y); found := false; while loop <= btncount do begin if ptinrect(fbuttons[loop], newpoint) then begin found := true; break; end; inc(loop); end; if (found) and (loop < fWindowList.count) then begin f := TForm(FWindowList[loop]); try if assigned(f) and isWindow(f.handle) then begin if (button = mbleft) then begin if (screen.ActiveForm <> application.mainform) then begin if (screen.ActiveForm = f) and (fLastActiveForm = f) and (f.WindowState <> wsminimized) then begin if fautominimize then f.WindowState := wsminimized; end else begin if f.windowstate = wsminimized then f.windowstate := wsNormal; f.bringtofront; f.setfocus; if fMainFormFocused then begin fMainFormFocused := false; invalidate; end; end; end else if (screen.activeform = application.mainform) and (fLastActiveMDIChild = f) then begin DoDummyForm(f); end else begin if (fLastActiveForm = f) and (f.WindowState <> wsminimized) then begin if fautominimize then f.WindowState := wsminimized; end else begin if f.windowstate = wsminimized then f.windowstate := wsNormal; f.bringtofront; if assigned(f.activecontrol) then f.activecontrol.SetFocus else begin for loop := 0 to f.ControlCount - 1 do begin if f.Controls[loop] is TWincontrol then begin tWinControl(f.Controls[loop]).setfocus; break; end; end; end; end; end; end; if (button = mbright) then begin newpoint := clienttoscreen(newpoint); fmenuWin := f; tempmenuhandle := Getsystemmenu(f.handle, false); TrackPopupMenu(tempmenuhandle, tpm_leftalign or TPM_LEFTBUTTON, newpoint.x - 1, newpoint.y - 2, 0, self.handle, nil); end; end; except UnRegisterWindow(f); end; end; end; procedure TrmTaskBar.MouseMove(Shift: TShiftState; X, Y: Integer); var tw, th, loop, btncount: integer; found: boolean; f: tform; newpoint: tpoint; wrect: TRect; oldHint: string; begin fmenuwin := nil; btncount := high(fButtons); loop := 0; newpoint := point(x, y); found := false; while loop <= btncount do begin if ptinrect(fbuttons[loop], newpoint) then begin found := true; if Flat then Invalidate; break; end; inc(loop); end; if (found) and (loop < fWindowList.count) then begin f := TForm(FWindowList[loop]); try if assigned(f) and isWindow(f.handle) then begin tw := FLabelBMP.Canvas.TextWidth(f.Caption); wrect := fbuttons[loop]; oldhint := fhint; if tw > (((wrect.right - wrect.left) - 4) - 18) then fhint := f.caption else fhint := ''; if oldhint <> fhint then begin if fhint <> '' then begin newpoint := ClientToScreen(point(wrect.Left, 0)); tw := FTaskHint.Canvas.TextWidth(fhint); th := FTaskHint.Canvas.TextHeight(fhint); WRect := Rect(newpoint.x, newpoint.y - th - 1, newpoint.x + tw + 8, newpoint.y + 2); FTimer.Enabled := false; FTaskHint.Tag := loop; FTaskHint.ActivateHint(Wrect, fHint); FTimer.Interval := fdelay; FTimer.Enabled := true; end else HideHint(true); end; end; except UnRegisterWindow(f); end; end else HideHint(true); end; procedure TrmTaskBar.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if AComponent is TCustomForm then begin if Operation = opRemove then UnRegisterWindow(TForm(AComponent)); if Operation = opInsert then RegisterWindowTemp(TForm(AComponent)); end; end; procedure TrmTaskBar.Paint; var wrect: TRect; btnsize: integer; btncount: integer; loop, xpos: integer; F: TForm; AddToList, BtnDown, updateList: boolean; wCaption: string; wIcon: TIcon; wPt : TPoint; begin inherited; if fTempList.Count > 0 then begin loop := fTempList.Count; while loop > 0 do begin dec(loop); if (TObject(ftemplist[loop]) is tcustomform) then begin f := TForm(ftemplist[loop]); if f.HandleAllocated then begin ftemplist.Delete(loop); AddToList := true; if assigned(fOnAddingWindow) then fOnAddingWindow(self, f, AddtoList); if AddToList then RegisterWindow(f); end; end else begin ftemplist.Delete(loop); end; end; end; if (csdesigning in componentstate) then btncount := 2 else btncount := FWindowList.Count; updateList := high(fButtons) <> btncount; if updatelist then setlength(fButtons, btncount); fBufferBMP.Height := clientheight; fBufferBMP.Width := clientwidth; fBufferBMP.Canvas.Brush.color := fColor; fbufferbmp.canvas.FillRect(ClientRect); btnsize := maxbtnsize; while LeftMargin + (btnsize * btncount) + (btnspace * btncount) + RightMargin > clientwidth do dec(btnsize, 1); if btnsize > maxbtnsize then btnsize := maxbtnsize; if btnsize < minbtnsize then btnsize := minbtnsize; loop := 0; xpos := LeftMargin; fLabelBMP.width := btnsize; flabelbmp.height := btnheight; while loop < btncount do begin if (csdesigning in componentstate) then begin case loop of 0: begin wcaption := 'Button Up'; BtnDown := false; end; 1: begin wcaption := 'Button Down'; BtnDown := true; end; else BtnDown := false; end; end else begin f := TForm(fwindowlist[loop]); if fAutoHide then begin if (f.windowstate = wsminimized) and (f.FormStyle = fsMDIChild) then begin showwindow(f.handle, sw_hide); end; if ((f.windowstate = wsnormal) or (f.Windowstate = wsmaximized)) and (f.FormStyle = fsMDIChild) and (not iswindowvisible(f.handle)) then begin showwindow(f.handle, sw_show); end; end; if not f.icon.Empty then begin FIconBMP.Height := f.Icon.height; FIconBMP.Width := f.Icon.width; FIconBMP.Canvas.brush.color := fcolor; fIconBmp.Canvas.FillRect(rect(0, 0, f.Icon.width, f.Icon.height)); DrawIconEx(FIconBMP.Canvas.handle, 0, 0, f.Icon.handle, 16, 16, 0, 0, DI_NORMAL); fIconBMP.Transparent := true; FIconBMP.TransparentColor := fcolor; end else if (f.FormStyle = fsmdiChild) then begin FIconBMP.Height := 16; FIconBMP.Width := 16; FIconBMP.Canvas.brush.color := fcolor; fIconBmp.Canvas.FillRect(rect(0, 0, 16, 16)); wIcon := TIcon.create; try wIcon.Handle := LoadIcon(hinstance, makeintresource(0)); if wIcon.Handle = 0 then wIcon.Handle := LoadIcon(hinstance, 'MAINICON'); DrawIconEx(FIconBMP.Canvas.handle, 0, 0, wIcon.handle, 16, 16, 0, 0, DI_NORMAL); finally wIcon.free; end; fIconBMP.Transparent := true; FIconBMP.TransparentColor := fcolor; end; wCaption := f.caption; if screen.activeForm <> Application.Mainform then BtnDown := (screen.ActiveForm = f) and (f.windowstate <> wsminimized) else BtnDown := assigned(fLastActiveForm) and (fLastActiveForm = f) and (fLastActiveForm.windowstate <> wsminimized) and not (fMainFormFocused); end; wrect := rect(0, 0, btnsize, btnheight); flabelbmp.Canvas.brush.color := fcolor; flabelbmp.canvas.font := font; flabelbmp.canvas.font.Color := clBtnText; flabelbmp.canvas.fillrect(wrect); if BtnDown then begin FLabelBMP.Canvas.Brush.Bitmap := AllocPatternBitmap(clBtnFace, clBtnHighlight); FLabelBMP.Canvas.FillRect(wrect); inflaterect(wrect, -2, -2); flabelbmp.canvas.StretchDraw(rect(wrect.left + 2, wrect.top + 2, wrect.left + 18, wrect.top + 18), fIconBMP); inflaterect(wrect, 2, 2); if flat then begin frame3d(flabelbmp.canvas, wrect, cl3DDkShadow, clBtnHighlight, 1); inflateRect(wRect, 1, 1); end else begin frame3d(flabelbmp.canvas, wrect, cl3DDkShadow, clBtnHighlight, 1); frame3d(flabelbmp.canvas, wrect, clBtnShadow, cl3DLight, 1); end; wrect.left := wrect.left + 20; wrect.top := wrect.top + 1; wRect.right := wrect.right - 1; FLabelBMP.Canvas.Font.Style := FLabelBMP.Canvas.Font.Style + [fsBold]; FLabelBMP.Canvas.Brush.Style := bsClear; DrawText(flabelbmp.canvas.handle, pchar(wCaption), length(wCaption), wrect, DT_END_ELLIPSIS or dt_VCenter or DT_SingleLine or DT_Left); end else begin inflaterect(wrect, -2, -2); flabelbmp.canvas.StretchDraw(rect(wrect.left + 2, wrect.top + 1, wrect.left + 18, wrect.top + 17), fIconBMP); inflaterect(wrect, 2, 2); if flat then begin wPt := screentoclient(mouse.CursorPos); if PtInRect(rect(xpos, TopMargin, xpos + btnsize, TopMargin + btnheight), wPt) then begin frame3d(flabelbmp.canvas, wrect, clBtnHighlight, cl3DDkShadow, 1); inflateRect(wRect, 1, 1); end; end else begin frame3d(flabelbmp.canvas, wrect, clBtnHighlight, cl3DDkShadow, 1); frame3d(flabelbmp.canvas, wrect, cl3DLight, clBtnShadow, 1); end; wrect.left := wrect.left + 20; wrect.top := wrect.top - 1; wRect.right := wrect.right - 1; FLabelBMP.Canvas.Font.Style := FLabelBMP.Canvas.Font.Style - [fsBold]; DrawText(flabelbmp.canvas.handle, pchar(wCaption), length(wCaption), wrect, DT_END_ELLIPSIS or dt_VCenter or DT_SingleLine or DT_Left); end; if updatelist then fButtons[loop] := rect(xpos, TopMargin, xpos + btnsize, TopMargin + btnheight); fBufferBMP.canvas.Draw(xpos, TopMargin, flabelbmp); inc(xpos, btnsize + btnspace); inc(loop); end; BitBlt(canvas.handle, 0, 0, clientwidth, clientheight, fBufferBMP.canvas.handle, 0, 0, SRCCOPY); if assigned(screen.ActiveForm) then begin fLastActiveForm := screen.ActiveForm; if (screen.ActiveForm.FormStyle = fsMDIChild) then begin try fLastActiveMDIChild := screen.ActiveForm; except fLastActiveMDIChild := nil; end; end; end; end; procedure TrmTaskBar.RegisterWindow(F: TForm); var loop: integer; found: boolean; Added: boolean; begin loop := 0; found := false; while loop < fWindowlist.count do begin if fwindowlist[loop] = f then begin found := true; break; end; inc(loop); end; if not found then begin added := false; if (((f.BorderStyle = bsToolWindow) or (f.BorderStyle = bsSizeToolWin)) and not (wtToolWin in fExcludeWinTypes)) or ((f.BorderStyle = bsDialog) and not (wtDialog in fExcludeWinTypes)) or ((f.FormStyle = fsMDIChild) and not (wtMDIChild in fExcludeWinTypes)) then begin fWindowList.add(f); added := true; end; if added then begin if assigned(fOnWindowAdded) then fOnWindowAdded(self, f); FreeNotification(f); SetLength(fButtons, 0); end; end; end; procedure TrmTaskBar.RegisterWindowTemp(F: TForm); begin FTempList.Add(f); invalidate; end; procedure TrmTaskBar.SetAutoHide(const Value: boolean); var loop: integer; f: TForm; begin fAutoHide := Value; if fAutoHide = false then begin loop := 0; while loop < fwindowlist.count do begin f := TForm(fwindowlist[loop]); if ((f.windowstate = wsnormal) or (f.Windowstate = wsmaximized)) and (f.FormStyle = fsMDIChild) and (not iswindowvisible(f.handle)) then begin showwindow(f.handle, sw_show); end; inc(loop); end; end; end; procedure TrmTaskBar.SetBtnHeight(const Value: integer); begin fBtnHeight := Value; invalidate; end; procedure TrmTaskBar.SetBtnSpace(const Value: integer); begin fBtnSpace := Value; invalidate; end; procedure TrmTaskBar.SetColor(const Value: TColor); begin FColor := Value; Repaint; end; procedure TrmTaskBar.SetExcludes(const Value: TWinTypes); var loop: integer; f: TForm; added, Removed: boolean; begin if fExcludeWinTypes <> Value then begin fExcludeWinTypes := Value; loop := FWindowList.Count; while loop > 0 do begin removed := false; dec(loop); f := FWindowList[loop]; if ((wtToolWin in fExcludeWinTypes) and ((f.BorderStyle = bsToolWindow) or (f.BorderStyle = bsSizeToolWin))) or ((wtDialog in fExcludeWinTypes) and (f.BorderStyle = bsDialog)) or ((wtMDIChild in fExcludeWinTypes) and (f.FormStyle = fsMDIChild)) then begin fWindowList.delete(loop); removed := true; end; if removed then begin if assigned(fOnWindowRemoved) then fOnWindowRemoved(self, f); SetLength(fButtons, 0); end; end; for loop := 0 to screen.CustomFormCount - 1 do begin f := TForm(screen.CustomForms[loop]); if fWindowList.indexof(f) = -1 then begin added := false; if (((f.BorderStyle = bsToolWindow) or (f.BorderStyle = bsSizeToolWin)) and not (wtToolWin in fExcludeWinTypes)) or ((f.BorderStyle = bsDialog) and not (wtDialog in fExcludeWinTypes)) or ((f.FormStyle = fsMDIChild) and not (wtMDIChild in fExcludeWinTypes)) then begin added := true; fWindowList.add(f); end; if added then begin if assigned(fOnWindowAdded) then fOnWindowAdded(self, f); FreeNotification(f); SetLength(fButtons, 0); end; end; end; Invalidate; end; end; procedure TrmTaskBar.SetMaxBtnSize(const Value: integer); begin fMaxBtnSize := Value; invalidate; end; procedure TrmTaskBar.SetMinBtnSize(const Value: integer); begin fMinBtnSize := Value; invalidate; end; procedure TrmTaskBar.UnRegisterWindow(F: TForm); var loop: integer; found: boolean; begin loop := 0; found := false; while loop < fTemplist.count do begin if fTemplist[loop] = f then begin found := true; break; end; inc(loop); end; if found then begin fTemplist.Delete(loop); SetLength(fButtons, 0); //if we found it here then it wont be in FWindowList.... Exit; end; loop := 0; found := false; while loop < fWindowlist.count do begin if fwindowlist[loop] = f then begin found := true; break; end; inc(loop); end; if found then begin fWindowlist.Delete(loop); if assigned(fOnWindowRemoved) then fOnWindowRemoved(self, f); SetLength(fButtons, 0); Repaint; end; end; procedure TrmTaskBar.wmCommand(var msg: TMessage); begin case loword(msg.wparam) of SC_SIZE, SC_MOVE, SC_MINIMIZE, SC_MAXIMIZE, SC_NEXTWINDOW, SC_PREVWINDOW, SC_CLOSE, SC_VSCROLL, SC_HSCROLL, SC_MOUSEMENU, SC_KEYMENU, SC_ARRANGE, SC_RESTORE, SC_TASKLIST, SC_SCREENSAVE, SC_HOTKEY, SC_DEFAULT, SC_MONITORPOWER, SC_CONTEXTHELP, SC_SEPARATOR: begin if assigned(fmenuWin) then postmessage(fmenuwin.handle, wm_syscommand, msg.wparam, msg.lparam); invalidate; end; else if assigned(fmenuWin) then postmessage(fmenuwin.handle, wm_command, msg.wparam, msg.lparam); end; end; procedure TrmTaskBar.SetLeftMargin(const Value: integer); begin fLeftMargin := Value; invalidate; end; procedure TrmTaskBar.SetRightMargin(const Value: integer); begin fRightMargin := Value; invalidate; end; procedure TrmTaskBar.SetTopMargin(const Value: integer); begin fTopMargin := Value; invalidate; end; procedure TrmTaskBar.SetDelay(const Value: integer); begin if fdelay <> value then fdelay := value; end; procedure TrmTaskBar.HideHint(ClearHint: Boolean); begin FTaskHint.ReleaseHandle; FTaskHint.Tag := -1; if ClearHint then fHint := ''; end; { ********** Windows Hooking Procedures ********** } procedure TrmTaskBar.HookWin; begin if csdesigning in componentstate then exit; if not assigned(NewWndProc) then begin OldWndProc := TFarProc(GetWindowLong(TForm(Owner).handle, GWL_WNDPROC)); {$ifdef D6_or_higher} NewWndProc := Classes.MakeObjectInstance(HookWndProc); {$else} NewWndProc := MakeObjectInstance(HookWndProc); {$endif} SetWindowLong(TForm(Owner).handle, GWL_WNDPROC, LongInt(NewWndProc)); if TForm(Owner).formstyle = fsMDIForm then HookMDIWin; end; end; procedure TrmTaskBar.UnhookWin; begin if csdesigning in componentstate then exit; if assigned(NewWndProc) then begin SetWindowLong(TForm(Owner).handle, GWL_WNDPROC, LongInt(OldWndProc)); if assigned(NewWndProc) then {$ifdef D6_or_higher} Classes.FreeObjectInstance(NewWndProc); {$else} FreeObjectInstance(NewWndProc); {$endif} NewWndProc := nil; end; UnHookMDIWin; end; procedure TrmTaskBar.HookWndProc(var AMsg: TMessage); begin case AMsg.msg of WM_PARENTNOTIFY: begin if (AMsg.wParamLo <> wm_create) or (AMsg.wParamLo <> wm_Destroy) then invalidate; end; CM_ACTIVATE: begin fMainFormFocused := true; invalidate; end; end; AMsg.Result := CallWindowProc(OldWndProc, Tform(Owner).handle, AMsg.Msg, AMsg.wParam, AMsg.lParam); {$IFDEF rmDebug} if assigned(fWinMessage) then fWinMessage(1, aMsg.msg); {$ENDIF} end; procedure TrmTaskBar.HookMDIWin; begin if csdesigning in componentstate then exit; if not assigned(NewMDIWndProc) then begin OldMDIWndProc := TFarProc(GetWindowLong(TForm(Owner).ClientHandle, GWL_WNDPROC)); {$ifdef D6_or_higher} NewMDIWndProc := Classes.MakeObjectInstance(HookMDIWndProc); {$else} NewMDIWndProc := MakeObjectInstance(HookMDIWndProc); {$endif} SetWindowLong(TForm(Owner).ClientHandle, GWL_WNDPROC, LongInt(NewMDIWndProc)); end; end; procedure TrmTaskBar.UnhookMDIWin; begin if csdesigning in componentstate then exit; if assigned(NewMDIWndProc) then begin SetWindowLong(TForm(Owner).ClientHandle, GWL_WNDPROC, LongInt(OldMDIWndProc)); if assigned(NewMDIWndProc) then {$ifdef D6_or_higher} Classes.FreeObjectInstance(NewMDIWndProc); {$else} FreeObjectInstance(NewMDIWndProc); {$endif} NewMDIWndProc := nil; OldMDIWndProc := nil; end; end; procedure TrmTaskBar.HookMDIWndProc(var AMsg: TMessage); var loop: integer; begin with AMsg do begin if not ((msg = WM_MDIGETACTIVE) or (msg = WM_NCPaint) or (msg = WM_NCHITTEST)) then Invalidate; if (msg = WM_MDIREFRESHMENU) and assigned(fMDIMenuRefresh) then fMDIMenuRefresh(self); Result := CallWindowProc(OldMDIWndProc, TForm(Owner).ClientHandle, Msg, wParam, lParam); if (msg = wm_parentNotify) then begin if WParamLo = WM_LBUTTONDOWN then begin for loop := WindowCount - 1 downto 0 do begin if PtInRect(WindowList[loop].BoundsRect, Point(LParamLo, LParamHi)) then begin if fMainFormFocused and assigned(fLastActiveMDIChild) and (WindowList[loop] = fLastActiveMDIChild) then DoDummyForm(fLastActiveMDIChild); break; end; end; end; end; end; {$IFDEF rmDebug} if assigned(fWinMessage) then fWinMessage(2, aMsg.msg); {$ENDIF} end; procedure TrmTaskBar.wmEraseBkgnd(var msg: TMessage); begin msg.result := 1; end; function TrmTaskBar.GetActiveForm: TForm; begin Result := fLastActiveForm; end; function TrmTaskBar.GetWindowCount: integer; begin Result := FWindowList.Count; end; function TrmTaskBar.GetWindowItem(index: integer): TForm; begin result := TForm(FWindowList[index]); end; function TrmTaskBar.GetMDIChild(index: integer): TForm; var count: integer; loop: integer; begin loop := 0; count := 0; result := nil; while loop < FWindowList.count do begin if TForm(fWindowList[loop]).FormStyle = fsMDIChild then begin if count = index then begin result := TForm(fWindowList[loop]); break; end; inc(count); end; inc(loop); end; end; function TrmTaskBar.GetMDIChildCount: integer; var count: integer; loop: integer; begin loop := 0; count := 0; while loop < FWindowList.count do begin if TForm(fWindowList[loop]).FormStyle = fsMDIChild then inc(count); inc(loop); end; result := count; end; function TrmTaskBar.GetActiveMDIChild: TForm; begin Result := fLastActiveMDIChild; end; procedure TrmTaskBar.MinimizeAll; begin MinimizeWindowTypes([wtMDIChild, wtDialog, wtToolWin]); end; procedure TrmTaskBar.MinimizeAllMDI; begin MinimizeWindowTypes([wtMDIChild]); end; procedure TrmTaskBar.MinimizeWindowTypes(WinTypes: TWinTypes); var loop: integer; f: TForm; begin loop := 0; while loop < fWindowlist.count do begin f := fwindowlist[loop]; if ((wtToolWin in WinTypes) and ((f.BorderStyle = bsToolWindow) or (f.BorderStyle = bsSizeToolWin))) or ((wtDialog in WinTypes) and (f.BorderStyle = bsDialog)) or ((wtMDIChild in WinTypes) and (f.FormStyle = fsMDIChild)) then begin f.WindowState := wsMinimized; end; inc(loop); end; end; procedure TrmTaskBar.DoDummyForm(ToggleForm: TForm); var wControl : TWinControl; begin if TForm(owner).formstyle = fsMDIForm then begin if ToggleForm.CanFocus then begin ToggleForm.SetFocus; if assigned(ToggleForm.ActiveControl) then begin wControl := ToggleForm.ActiveControl; ToggleForm.DefocusControl(ToggleForm.ActiveControl, False); ToggleForm.SetFocusedControl(wControl); end; fMainFormFocused := false; invalidate; end; end; end; procedure TrmTaskBar.wmDestroy(var msg: TMessage); begin UnhookWin; end; procedure TrmTaskBar.SetFlat(const Value: boolean); begin if fFlat <> value then begin fFlat := Value; Invalidate; end; end; end.
unit Test.Core.ObjectMapping.Order; interface {$M+} uses System.SysUtils, DUnitX.TestFramework, Test.Order.Classes, Nathan.ObjectMapping.Core, Nathan.ObjectMapping.Config; type [TestFixture] TTestObjectMapping = class private FCut: INathanObjectMappingCore<TOrder, TOrderDTO>; function GetConfig(AProc1, AProc2: TProc<TOrder, TOrderDTO>): INathanObjectMappingConfig<TOrder, TOrderDTO>; public [Setup] procedure Setup(); [TearDown] procedure TearDown(); [Test] procedure Test_HasNoMemoryLeaks; [Test] procedure Test_First_MapCallWithEx; [Test] procedure Test_CallMap_TOrder; [Test] procedure Test_Map_TOrder_WithTwoUserAdd; [Test] procedure Test_Map_TOrder_NoExWithUserAddAreNil; [Test] procedure Test_ReverseMap_TOrderDTOToTOrder; end; {$M-} implementation procedure TTestObjectMapping.Setup(); begin TOrderDummyFactory.Init; FCut := nil; end; procedure TTestObjectMapping.TearDown(); begin TOrderDummyFactory.Release; FCut := nil; end; function TTestObjectMapping.GetConfig( AProc1, AProc2: TProc<TOrder, TOrderDTO>): INathanObjectMappingConfig<TOrder, TOrderDTO>; begin Result := TNathanObjectMappingConfig<TOrder, TOrderDTO>.Create; if Assigned(AProc1) then Result.UserMap(AProc1); if Assigned(AProc2) then Result.UserMap(AProc2); Result.CreateMap; end; procedure TTestObjectMapping.Test_HasNoMemoryLeaks; begin // Assert... FCut := TNathanObjectMappingCore<TOrder, TOrderDTO>.Create; Assert.IsNotNull(FCut); end; procedure TTestObjectMapping.Test_First_MapCallWithEx; begin // Arrange... TOrderDummyFactory.InitOrderDummy; FCut := TNathanObjectMappingCore<TOrder, TOrderDTO>.Create; // Act... Assert.WillRaise( procedure begin FCut.Map(TOrderDummyFactory.Order); end, ENoMappingsFoundException); end; procedure TTestObjectMapping.Test_CallMap_TOrder; var Actual: TOrderDTO; begin // Arrange... TOrderDummyFactory.InitOrderDummy; FCut := TNathanObjectMappingCore<TOrder, TOrderDTO>.Create; // Act... Actual := FCut .Config(GetConfig( procedure(ASrc: TOrder; ADest: TOrderDTO) begin ADest.Total := ASrc.Total; end, nil)) .Map(TOrderDummyFactory.Order); try // Assert... Assert.IsNotNull(Actual); Assert.AreEqual(1, Actual.OrderId); Assert.AreEqual('Nathan Thurnreiter', Actual.CustomerName); Assert.AreEqual<Double>(19.9, TOrderDTO(Actual).Total); finally FreeAndNil(Actual); end; end; procedure TTestObjectMapping.Test_Map_TOrder_WithTwoUserAdd; var Cfg: INathanObjectMappingConfig<TOrder, TOrderDTO>; Actual: TOrderDTO; begin // Arrange... TOrderDummyFactory.InitOrderDummy; Cfg := GetConfig( procedure(ASrc: TOrder; ADest: TOrderDTO) begin ADest.Total := ASrc.Total * 2; end, procedure(ASrc: TOrder; ADest: TOrderDTO) begin ADest.InnerValue := ASrc.Extension; end); FCut := TNathanObjectMappingCore<TOrder, TOrderDTO>.Create; // Act... Actual := FCut .Config(Cfg) .Map(TOrderDummyFactory.Order); try // Assert... Assert.IsNotNull(Actual); Assert.AreEqual(1, Actual.OrderId); Assert.AreEqual('Nathan Thurnreiter', Actual.CustomerName); Assert.AreEqual('Chanan', Actual.InnerValue); Assert.AreEqual<Double>(39.8, TOrderDTO(Actual).Total); finally FreeAndNil(Actual); end; end; procedure TTestObjectMapping.Test_Map_TOrder_NoExWithUserAddAreNil; var Cfg: INathanObjectMappingConfig<TOrder, TOrderDTO>; Actual: TOrderDTO; begin // Arrange... TOrderDummyFactory.InitOrderDummy; Cfg := TNathanObjectMappingConfig<TOrder, TOrderDTO>.Create; Cfg .UserMap(nil) .UserMap(nil) .CreateMap; FCut := TNathanObjectMappingCore<TOrder, TOrderDTO>.Create; // Act... Actual := FCut .Config(Cfg) .Map(TOrderDummyFactory.Order); try // Assert... Assert.IsNotNull(Actual); Assert.AreEqual(1, Actual.OrderId); Assert.AreEqual('Nathan Thurnreiter', Actual.CustomerName); Assert.AreEqual('', Actual.InnerValue); Assert.AreEqual<Double>(19.90, TOrderDTO(Actual).Total); finally FreeAndNil(Actual); end; end; procedure TTestObjectMapping.Test_ReverseMap_TOrderDTOToTOrder; var Actual: TOrder; begin // Arrange... TOrderDummyFactory.InitOrderDtoDummy; FCut := TNathanObjectMappingCore<TOrder, TOrderDTO>.Create; // Act... Actual := FCut .Config(TNathanObjectMappingConfig<TOrder, TOrderDTO> .Create .UserMapReverse( procedure(ADest: TOrderDTO; ASrc: TOrder) begin ASrc.Extension := ADest.InnerValue; end) .CreateMap) .MapReverse(TOrderDummyFactory.OrderDTO); try // Assert... Assert.AreEqual(2, TOrderDummyFactory.OrderDTO.OrderId); Assert.AreEqual('Peter Miller', TOrderDummyFactory.OrderDTO.CustomerName); Assert.AreEqual('Chanan', TOrderDummyFactory.OrderDTO.InnerValue); Assert.AreEqual<Double>(47.11, TOrderDummyFactory.OrderDTO.Total); Assert.IsNotNull(Actual); Assert.AreEqual(0, Actual.Id); Assert.AreEqual(2, Actual.OrderId); Assert.AreEqual('Peter Miller', Actual.CustomerName); Assert.AreEqual('Chanan', Actual.Extension); Assert.IsNull(Actual.OrderDetails); Assert.AreEqual<Double>(0.0, Actual.Total); // Because is a function... finally FreeAndNil(Actual); end; end; initialization TDUnitX.RegisterTestFixture(TTestObjectMapping, 'Map.TOrder'); end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clUriUtils; interface {$I clVer.inc} {$IFDEF DELPHI6} {$WARN SYMBOL_PLATFORM OFF} {$ENDIF} uses clWinInet; type TclUrlType = (utUnknown, utFTP, utGOPHER, utHTTP, utHTTPS, utFILE, utNEWS, utMAILTO); TclOnUrlParsing = procedure (Sender: TObject; var URLComponents: TURLComponents) of object; TclUrlParser = class private FUrlpath: string; FUser: string; FExtra: string; FHost: string; FPassword: string; FUrlType: TclUrlType; FOnUrlParsing: TclOnUrlParsing; FPort: Integer; FParsedUrl: string; function InternalParse(const AFullUrl: string): string; function GetAbsolutePath: string; protected procedure DoUrlParsing(var UrlComponents: TURLComponents); virtual; public function Parse(const AFullUrl: string): string; procedure Assign(Source: TclUrlParser); virtual; property Host: string read FHost; property User: string read FUser; property Password: string read FPassword; property Urlpath: string read FUrlpath; property Extra: string read FExtra; property AbsolutePath: string read GetAbsolutePath; property Port: Integer read FPort; property UrlType: TclUrlType read FUrlType; property ParsedUrl: string read FParsedUrl; property OnUrlParsing: TclOnUrlParsing read FOnUrlParsing write FOnUrlParsing; end; TclUrlCorrector = class(TclUrlParser) private FIsByLocalFile: Boolean; FLocalFile: string; protected procedure DoUrlParsing(var UrlComponents: TURLComponents); override; public function GetURLByLocalFile(const AFullUrl, ALocalFile: string): string; function GetLocalFileByURL(const AFullUrl, ALocalFolder: string): string; end; function GetFullUrlByRoot(const AUrl, ARootUrl: string): string; implementation uses SysUtils, Windows, clUtils; function GetFullUrlByRoot(const AUrl, ARootUrl: string): string; var buf: array[0..INTERNET_MAX_URL_LENGTH - 1] of Char; len: DWORD; urlParser: TclUrlParser; begin len := SizeOf(buf); ZeroMemory(buf + 0, len); InternetCombineUrl(PChar(ARootUrl), PChar(AUrl), buf, len, ICU_BROWSER_MODE); Result := buf; urlParser := TclUrlParser.Create(); try Result := urlParser.Parse(Result); finally urlParser.Free(); end; end; { TclUrlParser } procedure TclUrlParser.DoUrlParsing(var UrlComponents: TURLComponents); begin if Assigned(FOnUrlParsing) then begin FOnUrlParsing(Self, UrlComponents); end; end; function TclUrlParser.Parse(const AFullUrl: string): string; begin Result := InternalParse(AFullUrl); if (Result = '') and (AFullUrl <> '') and (GetLastError() = ERROR_INTERNET_UNRECOGNIZED_SCHEME) then begin Result := InternalParse('http://' + AFullUrl); end; FParsedUrl := Result; end; function TclUrlParser.InternalParse(const AFullUrl: string): string; procedure CleanArray(var Arr: array of Char); begin ZeroMemory(Arr + 0, High(Arr) - Low(Arr) + 1); end; var UrlComponents: TURLComponents; scheme: array[0..INTERNET_MAX_SCHEME_LENGTH - 1] of Char; host: array[0..INTERNET_MAX_HOST_NAME_LENGTH - 1] of Char; user: array[0..INTERNET_MAX_USER_NAME_LENGTH - 1] of Char; password: array[0..INTERNET_MAX_PASSWORD_LENGTH - 1] of Char; urlpath: array[0..INTERNET_MAX_PATH_LENGTH - 1] of Char; fullurl: array[0..INTERNET_MAX_URL_LENGTH - 1] of Char; extra: array[0..1024 - 1] of Char; dwLen: DWORD; res: BOOL; begin FUrlType := utUnknown; FHost := ''; FUser := ''; FPassword := ''; FUrlpath := ''; FExtra := ''; FPort := INTERNET_INVALID_PORT_NUMBER; Result := ''; CleanArray(scheme); CleanArray(host); CleanArray(user); CleanArray(password); CleanArray(urlpath); CleanArray(fullurl); CleanArray(extra); ZeroMemory(@UrlComponents, SizeOf(TURLComponents)); UrlComponents.dwStructSize := SizeOf(TURLComponents); UrlComponents.lpszScheme := scheme; UrlComponents.dwSchemeLength := High(scheme) + 1; UrlComponents.lpszHostName := host; UrlComponents.dwHostNameLength := High(host) + 1; UrlComponents.lpszUserName := user; UrlComponents.dwUserNameLength := High(user) + 1; UrlComponents.lpszPassword := password; UrlComponents.dwPasswordLength := High(password) + 1; UrlComponents.lpszUrlPath := urlpath; UrlComponents.dwUrlPathLength := High(urlpath) + 1; UrlComponents.lpszExtraInfo := extra; UrlComponents.dwExtraInfoLength := High(extra) + 1; res := InternetCrackUrl(PChar(AFullUrl), Length(AFullUrl), 0, UrlComponents); if res then begin if (UrlComponents.nScheme in [Integer(Low(TclUrlType))..Integer(High(TclUrlType))]) then begin FUrlType := TclUrlType(UrlComponents.nScheme); end; DoUrlParsing(UrlComponents); if (StrLen(user) = 0) then begin UrlComponents.lpszUserName := nil; UrlComponents.dwUserNameLength := 0; end; if (StrLen(password) = 0) then begin UrlComponents.lpszPassword := nil; UrlComponents.dwPasswordLength := 0; end; FHost := host; FUser := user; FPassword := password; FUrlpath := urlpath; FExtra := extra; FPort := UrlComponents.nPort; dwLen := INTERNET_MAX_URL_LENGTH; fullurl[0] := #0; res := InternetCreateUrl(UrlComponents, 0, fullurl, dwLen); if res then begin Result := system.Copy(fullurl, 1, dwLen); Result := StringReplace(Trim(Result), #32, '%20', [rfReplaceAll]); end; end; end; procedure TclUrlParser.Assign(Source: TclUrlParser); begin FParsedUrl := Source.ParsedUrl; FHost := Source.Host; FUser := Source.User; FPassword := Source.Password; FUrlpath := Source.Urlpath; FExtra := Source.Extra; FPort := Source.Port; FUrlType := Source.UrlType; end; function TclUrlParser.GetAbsolutePath: string; begin if (Host = '*') then begin Result := Host; end else begin Result := Urlpath; if (Extra <> '') then begin if (Extra[1] <> '?') and (Result <> '') and (Result[Length(Result)] <> '?') then begin Result := Result + '?'; end; Result := Result + Extra; end; if (Result = '') then begin Result := '/'; end; end; end; { TclUrlCorrector } function TclUrlCorrector.GetURLByLocalFile(const AFullUrl, ALocalFile: string): string; begin FIsByLocalFile := True; try FLocalFile := ALocalFile; Result := Parse(AFullUrl); finally FIsByLocalFile := False; end; end; function TclUrlCorrector.GetLocalFileByURL(const AFullUrl, ALocalFolder: string): string; var ind: Integer; begin Result := ALocalFolder; if (Parse(AFullUrl) <> '') then begin Result := AddTrailingBackSlash(Result); ind := LastDelimiter('/', Urlpath); Result := Result + system.Copy(Urlpath, ind + 1, MaxInt); end; end; procedure TclUrlCorrector.DoUrlParsing(var UrlComponents: TURLComponents); var ind: Integer; s: string; begin if FIsByLocalFile then begin s := URLComponents.lpszUrlPath; ind := LastDelimiter('/', s); s := system.Copy(s, 1, ind); ind := Length(s); if (ind > 0) and (s[ind] <> '/') then begin s := s + '/'; end; ind := LastDelimiter('\', FLocalFile); s := s + system.Copy(FLocalFile, ind + 1, MaxInt); ZeroMemory(URLComponents.lpszUrlPath + 0, INTERNET_MAX_PATH_LENGTH); CopyMemory(URLComponents.lpszUrlPath + 0, PChar(s), Length(s)); URLComponents.dwUrlPathLength := Length(s); end; inherited DoUrlParsing(UrlComponents); end; end.
unit UnitFormCDMapper; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Imaging.pngimage, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, Vcl.ImgList, Vcl.Menus, Data.DB, UnitCDMappingSupport, uLogger, uDBForm, uMemory, uDBIcons, uDBConnection, uDBContext, uDBEntities, uDBManager, uShellIntegration, uConstants, uFormInterfaces, uCDMappingTypes; type TFormCDMapper = class(TDBForm, ICDMapperForm) Image1: TImage; LabelInfo: TLabel; CDMappingListView: TListView; ButtonOK: TButton; ButtonAddocation: TButton; ButtonRemoveLocation: TButton; CDImageList: TImageList; PopupMenuCDActions: TPopupActionBar; Explorer1: TMenuItem; N1: TMenuItem; Dismount1: TMenuItem; N2: TMenuItem; RefreshDBFilesOnCD1: TMenuItem; procedure FormCreate(Sender: TObject); procedure ButtonOKClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ButtonAddocationClick(Sender: TObject); procedure CDMappingListViewDblClick(Sender: TObject); procedure CDMappingListViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure ButtonRemoveLocationClick(Sender: TObject); procedure PopupMenuCDActionsPopup(Sender: TObject); procedure Explorer1Click(Sender: TObject); procedure RefreshDBFilesOnCD1Click(Sender: TObject); private { Private declarations } FContext: IDBContext; procedure LoadLanguage; protected function GetFormID: string; override; procedure InterfaceDestroyed; override; public { Public declarations } procedure Execute; procedure RefreshCDList; end; procedure DoManageCDMapping; implementation uses UnitFormCDMapInfo, uManagerExplorer, UnitRefreshDBRecordsThread; {$R *.dfm} procedure DoManageCDMapping; var FormCDMapper: TFormCDMapper; begin Application.CreateForm(TFormCDMapper, FormCDMapper); FormCDMapper.Execute; end; procedure TFormCDMapper.Execute; begin ShowModal; end; procedure TFormCDMapper.FormCreate(Sender: TObject); var Icon: TIcon; begin FContext := DBManager.DBContext; PopupMenuCDActions.Images := Icons.ImageList; Icon := TIcon.Create; try Icons.ImageList.GetIcon(DB_IC_CD_IMAGE, Icon); CDImageList.AddIcon(Icon); finally F(Icon); end; LoadLanguage; RefreshCDList; end; procedure TFormCDMapper.ButtonOKClick(Sender: TObject); begin Close; end; procedure TFormCDMapper.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFormCDMapper.LoadLanguage; begin BeginTranslate; try Caption := L('CD mapping'); LabelInfo.Caption := Format(L('In this window you can manage your removable disks with photos. To connect a drive - select the drive or select the file "%s" in the file system'), [C_CD_MAP_FILE]); CDMappingListView.Columns[0].Caption := L('ID'); CDMappingListView.Columns[1].Caption := L('Name'); CDMappingListView.Columns[2].Caption := L('CD location'); CDMappingListView.Columns[3].Caption := L('Mounted'); ButtonRemoveLocation.Caption := L('Unmount disk'); ButtonAddocation.Caption := L('Mount disk'); ButtonOK.Caption := L('Ok'); Explorer1.Caption := L('Explore removable drive'); Dismount1.Caption := L('Unmount disk'); RefreshDBFilesOnCD1.Caption := L('Refresh files in collection for this collection'); finally EndTranslate; end; end; procedure TFormCDMapper.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; function TFormCDMapper.GetFormID: string; begin Result := 'CDMapper'; end; procedure TFormCDMapper.InterfaceDestroyed; begin inherited; Release; end; procedure TFormCDMapper.ButtonAddocationClick(Sender: TObject); begin AddCDLocation(Handle, ''); RefreshCDList; end; procedure TFormCDMapper.RefreshCDList; var I: Integer; List: TList; Item, CDItem: TCDClass; ListItem: TListItem; begin if CDMapper = nil then Exit; CDMappingListView.Items.BeginUpdate; try CDMappingListView.Items.Clear; List := CDMapper.GetFindedCDList; for I := 0 to List.Count - 1 do begin Item := List[I]; ListItem := CDMappingListView.Items.Add; ListItem.ImageIndex := 0; ListItem.Caption := IntToStr(I + 1); ListItem.SubItems.Add(Item.name); ListItem.Data := Item; CDItem := CDMapper.GetCDByName(Item.name); if CDItem <> nil then begin if CDItem.Path <> '' then ListItem.SubItems.Add(CDItem.Path) else ListItem.SubItems.Add(''); end else ListItem.SubItems.Add(''); end; finally CDMappingListView.Items.EndUpdate; end; end; procedure TFormCDMapper.CDMappingListViewDblClick(Sender: TObject); begin if CDMappingListView.Selected <> nil then begin CheckCD(TCDClass(CDMappingListView.Selected.Data).Name); RefreshCDList; end; end; procedure TFormCDMapper.CDMappingListViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin ButtonRemoveLocation.Enabled := Selected; end; procedure TFormCDMapper.ButtonRemoveLocationClick(Sender: TObject); begin if CDMappingListView.Selected <> nil then begin CDMapper.RemoveCDMapping(TCDClass(CDMappingListView.Selected.Data).Name); RefreshCDList; end; end; procedure TFormCDMapper.PopupMenuCDActionsPopup(Sender: TObject); begin Explorer1.Visible := False; Dismount1.Visible := False; RefreshDBFilesOnCD1.Visible := False; if CDMappingListView.Selected <> nil then begin RefreshDBFilesOnCD1.Visible := TCDClass(CDMappingListView.Selected.Data).Path <> ''; Dismount1.Visible := RefreshDBFilesOnCD1.Visible; Explorer1.Visible := Dismount1.Visible; end; end; procedure TFormCDMapper.Explorer1Click(Sender: TObject); begin if CDMappingListView.Selected <> nil then begin with ExplorerManager.NewExplorer(False) do begin SetOldPath(TCDClass(CDMappingListView.Selected.Data).Path); SetPath(ExtractFilePath(TCDClass(CDMappingListView.Selected.Data).Path)); Show; end; end; end; procedure TFormCDMapper.RefreshDBFilesOnCD1Click(Sender: TObject); var Options: TRefreshIDRecordThreadOptions; DS: TDataSet; I: Integer; CD: TCDClass; Info: TMediaItemCollection; InfoRecord: TMediaItem; begin if CDMappingListView.Selected <> nil then if CDMappingListView.Selected.Data <> nil then begin CD := CDMapper.GetCDByName(TCDClass(CDMappingListView.Selected.Data).Name); if CD <> nil then begin DS := FContext.CreateQuery; try SetSQL(DS, 'Select ID,FFileName from $DB$ where FFileName Like "%::' + AnsiLowerCase (TCDClass(CDMappingListView.Selected.Data).name) + '::%"'); try DS.Open; except on E: Exception do begin MessageBoxDB(Handle, Format(L('Unexpected error: %s'), [E.message]), L('Error'), TD_BUTTON_OK, TD_ICON_ERROR); EventLog(':TFormCDMapper::RefreshDBFilesOnCD1Click() throw exception ' + E.message); Exit; end; end; if DS.RecordCount > 0 then begin Info := TMediaItemCollection.Create; try DS.First; for I := 1 to DS.RecordCount do begin InfoRecord := TMediaItem.Create; InfoRecord.FileName := DS.FieldByName('FFileName').AsString; InfoRecord.ID := DS.FieldByName('ID').AsInteger; InfoRecord.Selected := True; info.Add(InfoRecord); DS.Next; end; TRefreshDBRecordsThread.Create(FContext, Self, Options); finally F(Info); end; end; finally FreeDS(DS); end; end; end; end; initialization FormInterfaces.RegisterFormInterface(ICDMapperForm, TFormCDMapper); end.
namespace proholz.xsdparser; interface type XsdAttributeVisitor = public class(XsdAnnotatedElementsVisitor) private // * // * The {@link XsdAttribute} instance which owns this {@link XsdAttributeVisitor} instance. This way this visitor // * instance can perform changes in the {@link XsdAttribute} object. // // var owner: XsdAttribute; public constructor(aowner: XsdAttribute); method visit(element: XsdSimpleType); override; end; implementation constructor XsdAttributeVisitor(aowner: XsdAttribute); begin inherited constructor(aowner); self.owner := aowner; end; method XsdAttributeVisitor.visit(element: XsdSimpleType); begin inherited visit(element); owner.setSimpleType(ReferenceBase.createFromXsd(element)); end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls; type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; LanguageButton: TButton; LoadedLabel: TLabel; Label5: TLabel; procedure FormCreate(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private procedure UpdateStrings; end; var Form1: TForm1; implementation {$R *.fmx} uses NtBase, NtResource, FMX.NtLanguageDlg, FMX.NtTranslator; procedure TForm1.UpdateStrings; var i: Integer; str: String; directories: TStringDynArray; begin Label2.Text := _T('This is a sample'); //loc This is a comment directories := NtResources.ResourceDirectories; str := directories[0]; for i := 1 to Length(directories) - 1 do str := str + sLineBreak + directories[i]; Label3.Text := str; case NtResources.TranslationSource of tsNone: str := _T('None'); tsResource: str := _T('Resource:'); tsFile: str := _T('File:'); tsDirectory: str := _T('Directory:'); end; LoadedLabel.Text := Format('%s %s', [str, NtResources.TranslationSourceValue]); end; procedure TForm1.FormCreate(Sender: TObject); begin NtResources._T('English', 'en'); NtResources._T('Finnish', 'fi'); NtResources._T('German', 'de'); NtResources._T('French', 'fr'); NtResources._T('Japanese', 'ja'); if ParamCount > 0 then NtResources.LanguageId := ParamStr(1); _T(Self); UpdateStrings; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin if TNtLanguageDialog.Select('en', lnBoth) then UpdateStrings; end; initialization // Here you can specify a custom directory where you translation file(s) is located //NtResources.ResourcePath := 'D:\NT\Deploy\Samples\Delphi\FMX\ExternalFile\NtLangRes.ntres'; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Options.Pack; interface uses DPM.Core.Types, DPM.Core.Options.Base; type TPackOptions = class(TOptionsBase) private FSpecFile : string; FOutputFolder : string; FBasePath : string; FVersion : string; FExclude : boolean; FMinClientVer : string; FProperties : string; class var FDefault : TPackOptions; public class constructor CreateDefault; class property Default : TPackOptions read FDefault; constructor Create; override; property SpecFile : string read FSpecFile write FSpecFile; property OutputFolder : string read FOutputFolder write FOutputFolder; property BasePath : string read FBasePath write FBasePath; property Version : string read FVersion write FVersion; property Exclude : boolean read FExclude write FExclude; property MinClientVersion : string read FMinClientVer write FMinClientVer; property Properties : string read FProperties write FProperties; end; implementation uses DPM.Core.Constants; { TPackOptions } constructor TPackOptions.Create; begin inherited; FMinClientVer := cDPMClientVersion; end; class constructor TPackOptions.CreateDefault; begin FDefault := TPackOptions.Create; end; end.
unit UStore; interface type TStore = class private name: string; address: string; end; implementation end.
unit GdiPlusHelpers; {$IFDEF FPC}{$MODE DelphiUnicode}{$ENDIF} { Delphi GDI+ Library for use with Delphi 2009 or later. Copyright (C) 2009 by Erik van Bilsen. Email: erik@bilsen.com Website: www.bilsen.com/gdiplus License in plain English: 1. I don't promise that this software works. (But if you find any bugs, please let me know!) 2. You can use this software for whatever you want. You don't have to pay me. 3. You may not pretend that you wrote this software. If you use it in a program, you must acknowledge somewhere in your documentation that you've used this code. In legalese: The author makes NO WARRANTY or representation, either express or implied, with respect to this software, its quality, accuracy, merchantability, or fitness for a particular purpose. This software is provided "AS IS", and you, its user, assume the entire risk as to its quality and accuracy. Permission is hereby granted to use, copy, modify, and distribute this software (or portions thereof) for any purpose, without fee, subject to these conditions: (1) If any part of the source code for this software is distributed, then the License.txt file must be included, with this copyright and no-warranty notice unaltered; and any additions, deletions, or changes to the original files must be clearly indicated in accompanying documentation. (2) If only executable code is distributed, then the accompanying documentation must state that "this software is based in part on the Delphi GDI+ library by Erik van Bilsen". (3) Permission for use of this software is granted only if the user accepts full responsibility for any undesirable consequences; the author accepts NO LIABILITY for damages of any kind. ------------------------------------ Jacek Pazera https://www,pazera-software.com 2020.09.19 +Lazarus/FPC compatibility } {$IFDEF FPC} {$I GdiPlus_FPC.inc} {$ELSE} {$I GdiPlus_DCC.inc} {$ENDIF} interface uses Windows, {$IFDEF FPC}LCLIntf, LCLType,{$ENDIF} {$IFDEF DCC}{$IFDEF HAS_SYSTEM_UITYPES}System.UITypes,{$ENDIF}{$ENDIF} Graphics, Controls, GdiPlus; type TGPCanvasHelper = class helper for TCanvas public function ToGPGraphics: IGPGraphics; end; type TGPGraphicControlHelper = class helper for TGraphicControl public function ToGPGraphics: IGPGraphics; end; type TGPCustomControlHelper = class helper for TCustomControl public function ToGPGraphics: IGPGraphics; end; type TGPBitmapHelper = class helper for Graphics.TBitmap public function ToGPBitmap: IGPBitmap; procedure FromGPBitmap(const GPBitmap: IGPBitmap); end; // jacek procedure GdipCheck(const Status: TGPStatus); inline; function GPPointF(const ax, ay: Single): TGPPointF; overload; function GPPointF(const apt: TPoint): TGPPointF; overload; function GPPointFMove(const Point: TGPPointF; const dx, dy: Single): TGPPointF; function GPColor(const AColor: TColor; Alpha: Byte = 255): TAlphaColor; function GPTextWidthF(gr: IGPGraphics; Text: {$IFDEF FPC}UnicodeString{$ELSE}string{$ENDIF}; Font: IGPFont; px: Single = 0; py: Single = 0): Single; function GPTextHeightF(gr: IGPGraphics; Text: {$IFDEF FPC}UnicodeString{$ELSE}string{$ENDIF}; Font: IGPFont; px: Single = 0; py: Single = 0): Single; implementation { TGPCanvasHelper } function TGPCanvasHelper.ToGPGraphics: IGPGraphics; begin Result := TGPGraphics.Create(Handle); end; { TGPGraphicControlHelper } function TGPGraphicControlHelper.ToGPGraphics: IGPGraphics; begin Result := TGPGraphics.Create(Canvas.Handle); end; { TGPCustomControlHelper } function TGPCustomControlHelper.ToGPGraphics: IGPGraphics; begin Result := TGPGraphics.Create(Canvas.Handle); end; { TGPBitmapHelper } procedure TGPBitmapHelper.FromGPBitmap(const GPBitmap: IGPBitmap); begin Handle := GPBitmap.GetHBitmap(0); end; function TGPBitmapHelper.ToGPBitmap: IGPBitmap; begin if (PixelFormat in [pf1Bit, pf4Bit, pf8Bit]) then Result := TGPBitmap.Create(Handle, Palette) else Result := TGPBitmap.Create(Handle, 0); end; // jacek procedure GdipCheck(const Status: TGPStatus); inline; begin if (Status <> Ok) then raise EGdipError.Create(Status); end; function GPPointF(const ax, ay: Single): TGPPointF; overload; begin Result.x := ax; Result.y := ay; end; function GPPointF(const apt: TPoint): TGPPointF; overload; begin Result.x := apt.X; Result.y := apt.Y; end; function GPPointFMove(const Point: TGPPointF; const dx, dy: Single): TGPPointF; begin Result.X := Point.X + dx; Result.Y := Point.Y + dy; end; function GPColor(const AColor: TColor; Alpha: Byte = 255): TAlphaColor; begin Result := TGPColor.Create(Alpha, GetRValue(AColor), GetGValue(AColor), GetBValue(AColor)); end; function GPTextWidthF(gr: IGPGraphics; Text: {$IFDEF FPC}UnicodeString{$ELSE}string{$ENDIF}; Font: IGPFont; px: Single = 0; py: Single = 0): Single; var RectF: TGPRectF; Origin: TGPPointF; begin Origin.X := px; Origin.Y := py; RectF := gr.MeasureString(Text, Font, Origin); Result := RectF.Width; end; function GPTextHeightF(gr: IGPGraphics; Text: {$IFDEF FPC}UnicodeString{$ELSE}string{$ENDIF}; Font: IGPFont; px: Single = 0; py: Single = 0): Single; var RectF: TGPRectF; Origin: TGPPointF; begin Origin.X := px; Origin.Y := py; RectF := gr.MeasureString(Text, Font, Origin); Result := RectF.Height; end; end.
unit uNotepad; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus; type TfmMain = class(TForm) MainMenu: TMainMenu; N1: TMenuItem; miNewFile: TMenuItem; miOpenFile: TMenuItem; miSaveFile: TMenuItem; N5: TMenuItem; miSaveTo: TMenuItem; miClose: TMenuItem; moText: TMemo; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; procedure miNewFileClick(Sender: TObject); procedure miOpenFileClick(Sender: TObject); procedure miSaveFileClick(Sender: TObject); procedure miSaveToClick(Sender: TObject); procedure miCloseClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); public { Public declarations } private { Private declarations } FFileName : String; Procedure SetFileName(Value:String); Procedure CheckAndSave; published { published declarations } Property FileName : String read FFileName write SetFileName; end; var fmMain: TfmMain; implementation {$R *.dfm} Procedure TfmMain.CheckAndSave; Var bAskToSave : Boolean; begin If moText.Modified = True then Begin bAskToSave:= MessageDlg( '내용이 변경되었습니다.'#13'변경된 내용을 저장하시겠습니까?', mtInformation, [mbYes, mbNo], 0) = mrYes; If bAskToSave = True then miSaveFileClick(Nil); End; End; procedure TfmMain.miNewFileClick(Sender: TObject); begin CheckAndSave; FileName:= ''; moText.Lines.Clear; moText.Modified:= False; end; procedure TfmMain.miOpenFileClick(Sender: TObject); begin CheckAndSave; If OpenDialog.Execute = True then Begin FileName:= OpenDialog.FileName; moText.Lines.LoadFromFile(OpenDialog.FileName); moText.Modified:= False; End; end; procedure TfmMain.miSaveFileClick(Sender: TObject); begin If FileName = '' then Begin If SaveDialog.Execute = True then Begin FileName:= SaveDialog.FileName; moText.Lines.SaveToFile(FileName); End End Else Begin moText.Lines.SaveToFile(FileName); moText.Modified:= False; End; end; procedure TfmMain.miSaveToClick(Sender: TObject); begin If SaveDialog.Execute = True then Begin FileName:= SaveDialog.FileName; moText.Lines.SaveToFile(FileName); End; end; procedure TfmMain.miCloseClick(Sender: TObject); begin Close; end; procedure TfmMain.FormClose(Sender: TObject; var Action: TCloseAction); Var bAskToSave : Boolean; begin CheckAndSave; end; Procedure TfmMain.SetFileName(Value:String); Begin FFileName:= Value; If Value = '' then Caption:= '제목없음' Else Caption:= ExtractFileName(Value); End; end.
unit uPctMicrochipFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentModalForm, XiButton, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, DBClient; type TPctMicrochipFrm = class(TParentModalForm) grdMicrochipDB: TcxGridDBTableView; grdMicrochipLevel: TcxGridLevel; grdMicrochip: TcxGrid; cdsMicrochip: TClientDataSet; dsMicrochip: TDataSource; grdMicrochipDBMicrochip: TcxGridDBColumn; grdMicrochipDBAmount: TcxGridDBColumn; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FFormRestricted : Boolean; procedure OpenMicrochip; procedure CloseMicrochip; procedure SaveMicrochip; procedure CancelMicrochip; procedure AddMicrochip; function FormRestricted : Boolean; protected procedure ConfirmFrm; override; procedure CancelFrm; override; public { Public declarations } end; implementation uses uDMPet, Math, uClasseFunctions; {$R *.dfm} { TPctMicrochipFrm } procedure TPctMicrochipFrm.CancelFrm; begin inherited; CancelMicrochip; end; procedure TPctMicrochipFrm.CancelMicrochip; begin with cdsMicrochip do if Active then if State in dsEditModes then CancelUpdates; end; procedure TPctMicrochipFrm.CloseMicrochip; begin with cdsMicrochip do if Active then Close; end; procedure TPctMicrochipFrm.ConfirmFrm; begin inherited; SaveMicrochip; end; procedure TPctMicrochipFrm.FormShow(Sender: TObject); begin inherited; OpenMicrochip; FormRestricted; end; procedure TPctMicrochipFrm.OpenMicrochip; begin with cdsMicrochip do if not Active then Open; end; procedure TPctMicrochipFrm.SaveMicrochip; begin with cdsMicrochip do if Active then if State in dsEditModes then ApplyUpdates(0); end; procedure TPctMicrochipFrm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; CloseMicrochip; end; procedure TPctMicrochipFrm.AddMicrochip; var Form : TForm; begin Form := CreateForm(Self, 'TPctMicrochipAddFrm'); try if TParentModalForm(Form).ShowFrm then begin cdsMicrochip.Close; cdsMicrochip.Open; end; finally FreeAndNil(Form); end; end; procedure TPctMicrochipFrm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; case Key of VK_RETURN : begin if (ssCtrl in shift) and (not FFormRestricted) then AddMicrochip; end; end; end; function TPctMicrochipFrm.FormRestricted: Boolean; begin Result := False; if Assigned(DMPet.DataSetControl) then if (Pos(Self.Name, DMPet.DataSetControl.RestrictForms) > 0) then Result := True; FFormRestricted := Result; end; initialization RegisterClass(TPctMicrochipFrm); end.
unit Memory; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, XDebugFile, XDebugItem, ComCtrls, XDebugMemory, stringhash; type TMemoryForm = class(TForm) lvMemory: TListView; procedure lvMemoryCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FFile: XFile; FTotalMemory: Integer; FIncludeMemory: Integer; FIsInclude: Boolean; procedure processItem(AItem: PXItem); public constructor Create(AOwner: TComponent; AFile: XFile); end; var MemoryForm: TMemoryForm; implementation {$R *.dfm} { TMemoryForm } constructor TMemoryForm.Create(AOwner: TComponent; AFile: XFile); var XM: TXMemory; SH: tStrHashIterator; begin inherited Create(AOwner); FFile := AFile; { FTotalMemory := 0; FIncludeMemory := 0; FIsInclude := false; processItem(FFile.Root); txtAnalysis.Lines.Add(Format('Total Memory: %d', [FTotalMemory])); txtAnalysis.Lines.Add(Format('Include Memory: %d', [FIncludeMemory])); } XM := TXMemory.Create(AFile); try SH := XM.List.getIterator; while SH.validEntry do begin with lvMemory.Items.Add do begin Caption := TXMemoryItem(SH.value).FunctionName; Data := Pointer(TXMemoryItem(SH.value).Memory); SubItems.Add(Format('%.0n', [TXMemoryItem(SH.value).Memory * 1.0])); SubItems.Add(Format('%.0n', [TXMemoryItem(SH.value).Count * 1.0])); end; SH.next; end; SH.Free; finally XM.Free; end; lvMemory.SortType := stData; end; procedure TMemoryForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TMemoryForm.lvMemoryCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); var V1, V2: Integer; begin V1 := Integer(Item1.Data); V2 := Integer(Item2.Data); if V1 > V2 then Compare := -1 else if V1 < V2 then Compare := 1 else Compare := 0; end; procedure TMemoryForm.processItem(AItem: PXItem); var I: Integer; includeChanged: Boolean; begin includeChanged := false; if AItem^.Level > 0 then begin if (not FIsInclude) and ((AItem^.FunctionName = 'include') or (AItem^.FunctionName = 'include_once') or (AItem^.FunctionName = 'require') or (AItem^.FunctionName = 'require_once')) then begin FIsInclude := true; includeChanged := true; end; end; if FIsInclude then begin FIncludeMemory := FIncludeMemory + (AItem^.MemoryEnd - AItem^.MemoryStart); end else begin if AItem^.ChildCount > 0 then begin for I := 0 to AItem^.ChildCount - 1 do begin processItem(AItem^.Children[I]); end; end else if AItem^.MemoryEnd > 0 then FTotalMemory := FTotalMemory + (AItem^.MemoryEnd - AItem^.MemoryStart); end; if includeChanged then FIsInclude := false; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [VENDA_CABECALHO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit VendaCabecalhoController; {$MODE Delphi} interface uses Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller, VO, ZDataset, VendaCabecalhoVO; type TVendaCabecalhoController = class(TController) private public class function Consulta(pFiltro: String; pPagina: String): TZQuery; class function ConsultaLista(pFiltro: String): TListaVendaCabecalhoVO; class function ConsultaObjeto(pFiltro: String): TVendaCabecalhoVO; class procedure Insere(pObjeto: TVendaCabecalhoVO); class function Altera(pObjeto: TVendaCabecalhoVO): Boolean; class function Exclui(pId: Integer): Boolean; end; implementation uses UDataModule, T2TiORM, VendaDetalheVO, VendaComissaoVO; var ObjetoLocal: TVendaCabecalhoVO; class function TVendaCabecalhoController.Consulta(pFiltro: String; pPagina: String): TZQuery; begin try ObjetoLocal := TVendaCabecalhoVO.Create; Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina); finally ObjetoLocal.Free; end; end; class function TVendaCabecalhoController.ConsultaLista(pFiltro: String): TListaVendaCabecalhoVO; begin try ObjetoLocal := TVendaCabecalhoVO.Create; Result := TListaVendaCabecalhoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TVendaCabecalhoController.ConsultaObjeto(pFiltro: String): TVendaCabecalhoVO; begin try Result := TVendaCabecalhoVO.Create; Result := TVendaCabecalhoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); Filtro := 'ID_VENDA_CABECALHO = ' + IntToStr(Result.Id); // Objetos Vinculados // Listas Result.ListaVendaDetalheVO := TListaVendaDetalheVO(TT2TiORM.Consultar(TVendaDetalheVO.Create, Filtro, True)); finally end; end; class procedure TVendaCabecalhoController.Insere(pObjeto: TVendaCabecalhoVO); var UltimoID: Integer; VendaComissaoVO: TVendaComissaoVO; Current: TVendaDetalheVO; I: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); // Comissão VendaComissaoVO := TVendaComissaoVO.Create; VendaComissaoVO.IdVendaCabecalho := UltimoID; VendaComissaoVO.IdVendedor := pObjeto.IdVendedor; VendaComissaoVO.ValorVenda := pObjeto.ValorSubtotal - pObjeto.ValorDesconto; VendaComissaoVO.TipoContabil := 'C'; VendaComissaoVO.ValorComissao := pObjeto.ValorComissao; VendaComissaoVO.Situacao := 'A'; VendaComissaoVO.DataLancamento := now; TT2TiORM.Inserir(VendaComissaoVO); // Lista Venda Detalhe for I := 0 to pObjeto.ListaVendaDetalheVO.Count - 1 do begin Current := pObjeto.ListaVendaDetalheVO[I]; Current.IdVendaCabecalho := UltimoID; TT2TiORM.Inserir(Current); end; Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TVendaCabecalhoController.Altera(pObjeto: TVendaCabecalhoVO): Boolean; var Current: TVendaDetalheVO; I: Integer; begin try Result := TT2TiORM.Alterar(pObjeto); // Comissão pObjeto.VendaComissaoVO.IdVendaCabecalho := pObjeto.Id; pObjeto.VendaComissaoVO.IdVendedor := pObjeto.IdVendedor; pObjeto.VendaComissaoVO.ValorVenda := pObjeto.ValorSubtotal - pObjeto.ValorDesconto; pObjeto.VendaComissaoVO.TipoContabil := 'C'; pObjeto.VendaComissaoVO.ValorComissao := pObjeto.ValorComissao; pObjeto.VendaComissaoVO.Situacao := 'A'; pObjeto.VendaComissaoVO.DataLancamento := now; if pObjeto.VendaComissaoVO.Id > 0 then TT2TiORM.Alterar(pObjeto.VendaComissaoVO) else TT2TiORM.Inserir(pObjeto.VendaComissaoVO); // Lista Orçamento Pedido Detalhe for I := 0 to pObjeto.ListaVendaDetalheVO.Count - 1 do begin Current := pObjeto.ListaVendaDetalheVO[I]; if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdVendaCabecalho := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; finally end; end; class function TVendaCabecalhoController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TVendaCabecalhoVO; begin try ObjetoLocal := TVendaCabecalhoVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal) end; end; initialization Classes.RegisterClass(TVendaCabecalhoController); finalization Classes.UnRegisterClass(TVendaCabecalhoController); end.
unit MVVM.Messages.Engine.Interfaces; interface uses System.Generics.Defaults, Spring, MVVM.Types, MVVM.Interfaces; type {$REGION 'IMessage'} IMessage = interface(IObject) ['{8C6AE8E2-B18D-41B4-AAED-88CF3B110F1D}'] function GetCreationDateTime: TDateTime; function GetSender: TObject; procedure Post; procedure Schedule(const AMilisecondsToExecute: Int64); overload; procedure Schedule(const ADateTimeWhenExecute: TDateTime); overload; property CreationDateTime: TDateTime read GetCreationDateTime; property Sender: TObject read GetSender; end; {$ENDREGION} TNotifyMessage = procedure(AMessage: IMessage) of Object; TListenerFilter = reference to function(AMessage: IMessage): Boolean; {$REGION 'IMessageListener'} IMessageListener = interface(IObject) ['{ABC992B0-4CB4-470A-BDCE-EBE6651C84DD}'] function GetIsCodeToExecuteInUIMainThread: Boolean; procedure SetIsCodeToExecuteInUIMainThread(const AValue: Boolean); function GetTypeRestriction: EMessageTypeRestriction; procedure SetTypeRestriction(const ATypeRestriction: EMessageTypeRestriction); function GetListenerFilter: TListenerFilter; procedure SetListenerFilter(const AFilter: TListenerFilter); function GetEnabled: Boolean; procedure SetEnabled(const AValue: Boolean); function GetChannel: String; function GetMessajeClass: TClass; function GetConditionsMatch(AMessage: IMessage): Boolean; procedure Register; procedure UnRegister; procedure DoOnNewMessage(AMessage: IMessage); property FilterCondition: TListenerFilter read GetListenerFilter write SetListenerFilter; property IsCodeToExecuteInUIMainThread: Boolean read GetIsCodeToExecuteInUIMainThread write SetIsCodeToExecuteInUIMainThread; property TypeRestriction: EMessageTypeRestriction read GetTypeRestriction write SetTypeRestriction; property Enabled : Boolean read GetEnabled write SetEnabled; property Channel : String read GetChannel; end; {$ENDREGION} {$REGION 'IMessageListener<T: TMessage>'} IMessageListener<T: IMessage> = interface(IMessageListener) ['{CA3B8245-46E2-4827-B7D4-B3CAA91EE965}'] function GetOnMessage: IEvent<TNotifyMessage>; function GetMessajeClass: TClass; property OnMessage: IEvent<TNotifyMessage> read GetOnMessage; end; {$ENDREGION} {$REGION 'TIMERS'} ISchedulerTask = interface ['{6FFF8050-664B-4AE0-AD2D-2A1CD2F07CDB}'] function GetTaskID: Int64; function GetMilisecondsToAwake: Int64; function IsDone: Boolean; function CheckAndNotify: Boolean; property TaskID: Int64 read GetTaskID; property MilisecondsToAwake: Int64 read GetMilisecondsToAwake; end; {$ENDREGION} TComparerSchedulerTask = class(TComparer<ISchedulerTask>) public function Compare(const Left, Right: ISchedulerTask): Integer; override; end; implementation { TComparerSchedulerTask } function TComparerSchedulerTask.Compare(const Left, Right: ISchedulerTask): Integer; begin Result := 0; if (Left = Right) then Exit; if Left.MilisecondsToAwake < Right.MilisecondsToAwake then Result := -1 else Result := 1; end; end.
unit ThSpacer; interface uses Windows, SysUtils, Types, Classes, Controls, Graphics, ThTag, ThWebControl; type TThSpacer = class(TThWebGraphicControl) private FShowHash: Boolean; procedure SetShowHash(const Value: Boolean); protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; procedure CellTag(inTag: TThTag); override; published property Align; property ShowHash: Boolean read FShowHash write SetShowHash default true; property Style; property StyleClass; property Visible; end; implementation uses ThCssStyle; constructor TThSpacer.Create(AOwner: TComponent); begin inherited; FShowHash := true; DesignOpaque := true; end; procedure TThSpacer.Paint; var c: TColor; begin inherited; if ShowHash then with Canvas do begin c := Brush.Color; Brush.Style := bsBDiagonal; Brush.Color := ColorToRgb(clSilver); Pen.Style := psClear; if ThVisibleColor(c) then SetBkColor(Handle, ColorToRgb(c)) else SetBkMode(Handle, TRANSPARENT); Rectangle(AdjustedClientRect); Brush.Style := bsSolid; Pen.Style := psSolid; SetBkMode(Handle, OPAQUE); end; end; procedure TThSpacer.CellTag(inTag: TThTag); begin inherited; // inTag.Add('height', Height); // StylizeTag(inTag); Tag(inTag); end; procedure TThSpacer.SetShowHash(const Value: Boolean); begin FShowHash := Value; Invalidate; end; end.
// ################################## // ###### IT PAT 2018 ####### // ###### GrowCery ####### // ###### Tiaan van der Riel ####### // ################################## unit frmTransactions_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Grids, DBGrids, Buttons, ExtCtrls, pngimage, Mask, DBCtrls; type TfrmTransactions = class(TForm) dbgAccounts: TDBGrid; dbgTransactions: TDBGrid; redTransactionDetails: TRichEdit; pnlLeft: TPanel; imgDarkLogo: TImage; btnBack: TButton; pnlTop: TPanel; lblSearchTellerName: TLabel; edtSearhTellerID: TEdit; lblAccounts: TLabel; Label2: TLabel; Label3: TLabel; Label5: TLabel; lblTransactionTotal: TEdit; Label6: TLabel; lblNumberOfItemsSold: TEdit; lblNumItemsSold: TLabel; Label8: TLabel; lblNumTrans: TEdit; btnHelp: TButton; lblTransactionInfo: TLabel; Label9: TLabel; lblName: TDBEdit; Label10: TLabel; lblSurname: TDBEdit; lblSelectedTeller: TLabel; lblAccountID: TLabel; DBEdit1: TDBEdit; DBNavigator1: TDBNavigator; procedure btnBackClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure dbgAccountsCellClick(Column: TColumn); procedure dbgTransactionsCellClick(Column: TColumn); procedure edtSearhTellerIDChange(Sender: TObject); procedure btnHelpClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmTransactions: TfrmTransactions; implementation uses frmAdminHomeScreen_u, dmDatabase_u; {$R *.dfm} /// ========================= Click Accounts Grid ============================= procedure TfrmTransactions.dbgAccountsCellClick(Column: TColumn); var sAccountID: string[6]; begin dbgTransactions.DataSource := nil; redTransactionDetails.Clear; lblTransactionTotal.Text := ''; lblNumTrans.Text := ''; lblNumberOfItemsSold.Text := ''; redTransactionDetails.Clear; // To clear the print summary of the previous customer redTransactionDetails.Font.Size := 9; lblTransactionInfo.Caption := ''; Beep; Screen.Cursor := crHourGlass; Sleep(150); with dmDatabase do begin sAccountID := tblAccounts['AccountID']; dbgTransactions.DataSource := dmDatabase.dsrTransactions; tblTransactions.Filtered := False; tblTransactions.Filter := 'AccountID=' + QuotedStr(sAccountID); tblTransactions.Sort := 'TransID DESC'; tblTransactions.Filtered := True; lblTransactionInfo.Caption := IntToStr(tblTransactions.RecordCount) + ' transactions(s) for Teller ' + sAccountID + ': ' + #13 + tblAccounts ['Name'] + ' ' + tblAccounts['Surname'] + '. Click on an order.'; lblNumTrans.Text := IntToStr(tblTransactions.RecordCount); end; Screen.Cursor := crDefault; end; /// ========================= Transaction Gets Chosen ========================= procedure TfrmTransactions.dbgTransactionsCellClick(Column: TColumn); var iNumItems: integer; iQuantity: integer; rUnitPrice: real; rTotal: real; begin redTransactionDetails.Clear; Beep; Screen.Cursor := crHourGlass; iNumItems := 0; rTotal := 0; with dmDatabase do begin dsrTransactions.DataSet := tblTransactions; tblItemTransactions.First; redTransactionDetails.Lines.Add ('Transaction ID: ' + tblTransactions['TransID']); redTransactionDetails.Lines.Add ('Proscessed by: ' + tblTransactions['ProcessedBy']); redTransactionDetails.Lines.Add(' '); redTransactionDetails.Lines.Add( '====================================================================='); redTransactionDetails.Lines.Add ('Product Name:' + #9 + 'QTY:' + #9 + 'Unit Price:'); redTransactionDetails.Lines.Add(' '); /// Search for all the transactions by the selected teller while NOT(tblItemTransactions.Eof) do begin if tblItemTransactions['TransID'] = tblTransactions['TransID'] then begin // Search for all the items sold in that transaction iQuantity := tblItemTransactions['Quantity']; iNumItems := iNumItems + iQuantity; rUnitPrice := StrToFloat(tblItemTransactions['UnitPrice']); rTotal := rTotal + (rUnitPrice * iQuantity); redTransactionDetails.Lines.Add (tblItemTransactions['ItemName'] + #9 + IntToStr(iQuantity) + #9 + FloatToStrF(rUnitPrice, ffCurrency, 6, 2)); end; // if tblItemTransactions.Next; end; // while redTransactionDetails.Lines.Add( '====================================================================='); redTransactionDetails.Lines.Add(''); redTransactionDetails.Lines.Add('Number Of Items Sold: ' + IntToStr (iNumItems)); redTransactionDetails.Lines.Add ('Total for order ' + tblTransactions['TransID'] + ': ' + FloatToStrF (rTotal, ffCurrency, 10, 2)); lblNumberOfItemsSold.Text := IntToStr(iNumItems); lblTransactionTotal.Text := FloatToStrF(rTotal, ffCurrency, 10, 2); end; Screen.Cursor := crDefault; end; /// =================== Search For A Spesific Account ID ====================== procedure TfrmTransactions.edtSearhTellerIDChange(Sender: TObject); { This porcedure is used to search, and filter the table of accounts, to display the smilar usernames, as the user types a username into the edit field } begin if (edtSearhTellerID.Text <> '') then Begin dmDatabase.tblAccounts.Filter := 'AccountID LIKE ''' + (edtSearhTellerID.Text) + '%'' '; dmDatabase.tblAccounts.Filtered := True; End else begin dmDatabase.tblAccounts.Filtered := False; end; end; /// ============================= Form Gets Activated ========================= procedure TfrmTransactions.FormActivate(Sender: TObject); begin pnlLeft.Color := rgb(139, 198, 99); pnlTop.Color := rgb(139, 198, 99); end; /// ======================== Form Gets Created ================================ procedure TfrmTransactions.FormCreate(Sender: TObject); begin with redTransactionDetails do begin Paragraph.TabCount := 3; Paragraph.Tab[0] := 300; Paragraph.Tab[1] := 350; Paragraph.Tab[2] := 375; Font.Name := 'Courier'; Font.Size := 9; end; end; /// =========================== Form Gets Shown =============================== procedure TfrmTransactions.FormShow(Sender: TObject); begin with dmDatabase do begin tblAccounts.Open; tblAccounts.First; tblTransactions.Open; tblItemTransactions.Open; tblAccounts.Filtered := False; tblAccounts.Filter := 'IsAdmin= false'; tblAccounts.Filtered := True; end; dbgTransactions.DataSource := nil; end; /// ================================ Back Button ============================== procedure TfrmTransactions.btnBackClick(Sender: TObject); begin begin if MessageDlg(' Are you sure you want to return to your home page ?', mtConfirmation, [mbYes, mbCancel], 0) = mrYes then begin frmTransactions.Close; end else Exit end; end; /// ============================ Form Gets Closed ============================= procedure TfrmTransactions.FormClose(Sender: TObject; var Action: TCloseAction); begin frmAdminHomeScreen.Show; end; /// ============================ Help Button ================================== procedure TfrmTransactions.btnHelpClick(Sender: TObject); var tHelp: TextFile; sLine: string; sMessage: string; begin sMessage := '========================================'; AssignFile(tHelp, 'Help_Transactions.txt'); try { Code that checks to see if the file about the sponsors can be opened - displays error if not } reset(tHelp); Except ShowMessage('ERROR: The help file could not be opened.'); Exit; end; while NOT Eof(tHelp) do begin Readln(tHelp, sLine); sMessage := sMessage + #13 + sLine; end; sMessage := sMessage + #13 + '========================================'; CloseFile(tHelp); ShowMessage(sMessage); end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_JavaScript.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} {$O-} {$Q-} {$B-} {$R-} unit PAXCOMP_JavaScript; interface {$IFNDEF LINUX} {$IFDEF UNIX} // {just to compile PASCAL ONLY!} function GetVariantValue(Address: Pointer; FinTypeId: Integer): Variant; procedure PutVariantValue(Address: Pointer; FinTypeId: Integer; const value: Variant); implementation Uses Variants, PAXCOMP_SYS, PAXCOMP_CONSTANTS; procedure _VariantFromClass(Dest: PVariant; SourceAddress: Pointer); stdcall; begin VarClear(dest^); with TVarData(dest^) do begin VType := varClass; VInteger := IntPax(SourceAddress^); end; end; procedure _ClassFromVariant(DestAddress: Pointer; Source: PVariant); stdcall; var V: Variant; begin if TVarData(source^).VType = varClass then begin TObject(DestAddress^) := TObject(TVarData(source^).VInteger); (*if TObject(DestAddress^) is TJS_Reference then begin V := TJS_Reference(DestAddress^).GetValue(); if TVarData(V).VType = varClass then TObject(DestAddress^) := TObject(TVarData(V).VInteger) else TObject(DestAddress^) := nil; end; *) end else TObject(DestAddress^) := nil; end; function GetVariantValue(Address: Pointer; FinTypeId: Integer): Variant; begin case FinTypeId of typeBOOLEAN: result := Boolean(Address^); typeBYTE: result := Byte(Address^); typeWORD: result := Word(Address^); typeINTEGER: result := Integer(Address^); typeDOUBLE: result := Double(Address^); typePOINTER: result := Integer(Address^); typeENUM: result := Byte(Address^); typePROC: result := Integer(Address^); {$IFNDEF PAXARM} typeANSICHAR: result := AnsiChar(Address^); typeANSISTRING: result := AnsiString(Address^); typeSHORTSTRING: result := ShortString(Address^); typeWIDESTRING: result := WideString(Address^); {$ENDIF} typeSINGLE: result := Single(Address^); typeEXTENDED: result := Extended(Address^); typeCLASS: begin _VariantFromClass(@result, Address); end; typeCLASSREF: result := Integer(Address^); typeWIDECHAR: result := WideChar(Address^); typeVARIANT: result := Variant(Address^); typeDYNARRAY: result := Integer(Address^); {$IFDEF VARIANTS} typeEVENT: result := Int64(Address^); typeINT64: result := Int64(Address^); {$ELSE} typeINT64: result := Integer(Address^); {$ENDIF} typeINTERFACE: result := Integer(Address^); typeCARDINAL: result := Cardinal(Address^); typeCURRENCY: result := Currency(Address^); typeSMALLINT: result := SmallInt(Address^); typeSHORTINT: result := ShortInt(Address^); typeWORDBOOL: result := WordBool(Address^); typeLONGBOOL: result := LongBool(Address^); typeBYTEBOOL: result := ByteBool(Address^); typeOLEVARIANT: result := OleVariant(Address^); typeUNICSTRING: result := UnicString(Address^); end; end; procedure PutVariantValue(Address: Pointer; FinTypeId: Integer; const value: Variant); var X, Y: TObject; begin case FinTypeId of typeBOOLEAN: Boolean(Address^) := value; typeBYTE: Byte(Address^) := value; typeWORD: Word(Address^) := value; typeINTEGER: Integer(Address^) := value; typeDOUBLE: Double(Address^) := value; typePOINTER: Integer(Address^) := value; typeENUM: Byte(Address^) := value; typePROC: Integer(Address^) := value; {$IFNDEF PAXARM} typeSHORTSTRING: ShortString(Address^) := ShortString(value); typeANSICHAR: AnsiChar(Address^) := AnsiChar(Byte(value)); typeANSISTRING: AnsiString(Address^) := AnsiString(value); typeWIDESTRING: WideString(Address^) := value; {$ENDIF} typeSINGLE: Single(Address^) := value; typeEXTENDED: Extended(Address^) := value; typeCLASS: begin X := TObject(Address^); _ClassFromVariant(@Y, @value); if Y = nil then begin if X = nil then Exit; //if X is TJS_Object then //else TObject(Address^) := nil; Exit; end; //if (X is TJS_Object) and (Y is TGC_Object) then // GC_Assign(PGC_Object(Address), TGC_Object(Y)) //else TObject(Address^) := Y; end; typeCLASSREF: Integer(Address^) := value; typeWIDECHAR: WideChar(Address^) := WideChar(Word(value)); typeVARIANT: Variant(Address^) := value; typeDYNARRAY: Integer(Address^) := value; {$IFDEF VARIANTS} typeINT64: Int64(Address^) := value; typeEVENT: Int64(Address^) := value; {$ELSE} typeINT64: Integer(Address^) := value; {$ENDIF} typeINTERFACE: Integer(Address^) := value; typeCARDINAL: Cardinal(Address^) := value; typeCURRENCY: Currency(Address^) := value; typeSMALLINT: SmallInt(Address^) := value; typeSHORTINT: ShortInt(Address^) := value; typeWORDBOOL: WordBool(Address^) := value; typeLONGBOOL: LongBool(Address^) := value; {$IFDEF FPC} typeBYTEBOOL: if value <> 0 then ByteBool(Address^) := true else ByteBool(Address^) := false; {$ELSE} typeBYTEBOOL: ByteBool(Address^) := value; {$ENDIF} typeOLEVARIANT: OleVariant(Address^) := value; typeUNICSTRING: UnicString(Address^) := value; end; end; end. {$ENDIF} // ndef linux {$ENDIF} // ndef unix uses {$I uses.def} SysUtils, Classes, Math, RegExpr2, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS, PAXCOMP_STDLIB, PAXCOMP_GC, PAXCOMP_BASERUNNER, PAXCOMP_BASESYMBOL_TABLE; const Delta = 100; TYP_JS_OBJECT = 1; TYP_JS_DATE = 2; TYP_JS_ARRAY = 3; TYP_JS_BOOLEAN = 4; TYP_JS_NUMBER = 5; TYP_JS_STRING = 6; TYP_JS_FUNCTION = 7; TYP_JS_MATH = 8; TYP_JS_REGEXP = 9; TYP_JS_ERROR = 10; MaxPrimes = 2; Primes: array[1..MaxPrimes] of Integer = (103, 199); var MaxArgs: Variant; {$IFDEF PAX64} RetAdr_OFFSET: IntPax = 0; ParArr_OFFSET: IntPax = 0; {$ENDIF} type TJS_Object = class; THashFunction = function (S : PChar; TableSize: Integer) : longint; TJS_PropRec = class public Key: PChar; Value: Variant; end; THashTable = class private PrimeIndex: Integer; MaxCard: Integer; A: array of TJS_PropRec; public HashFunction: THashFunction; TableSize: Integer; LastIndex: Integer; Card: Integer; constructor Create; destructor Destroy; override; procedure Clear; function IndexOf(const S: PChar; var I: Integer): Boolean; end; TJS_PropList = class private Owner: TJS_Object; HashTable: THashTable; Arr: array of Variant; AvailArrIndex: array of boolean; CardArr: Integer; LastPropAddress: PVariant; public constructor Create(i_Owner: TJS_Object); destructor Destroy; override; procedure Clear; function IndexOfProperty(PropName: PChar; var I: Integer; var PositiveInt: Boolean): Boolean; procedure SetArrLength(N: Integer); function GetArrProperty(PropName: Integer): PVariant; procedure PutArrProperty(PropName: Integer; const Value: Variant); function GetProperty(PropName: PChar): PVariant; procedure PutProperty(PropName: PChar; const Value: Variant); function HasProperty(PropName: PChar): Boolean; end; TJS_ObjectBase = class(TGC_Object) public function GetGC: TGC; override; end; TJS_Object = class(TJS_ObjectBase) private L: TJS_PropList; fLength: Integer; fDefaultValue: Variant; aconstructor: TJS_Object; Tag: Integer; NextPropIndex: Integer; public typ: Integer; prototype: TJS_Object; prog: TBaseRunner; function GetConstructor: TJS_Object; function HasProperty(PropName: PChar): Boolean; procedure PutProperty(PropName: PChar; const Value: Variant); function GetProperty(PropName: PChar): Variant; function GetPropertyAsObject(PropName: PChar): TJS_Object; procedure PutArrProperty(PropName: Integer; const Value: Variant); function GetArrProperty(PropName: Integer): Variant; function GetVarProperty(const PropName: Variant): Variant; procedure PutVarProperty(const PropName: Variant; const Value: Variant); procedure AddToGC; constructor Create; destructor Destroy; override; function GetGC: TGC; override; function __toString: String; override; property Prop[PropertyName: PChar]: Variant read GetProperty write PutProperty; default; end; TJS_Reference = class(TJS_ObjectBase) public Address: Pointer; FinTypeId: Integer; constructor Create(AFinTypeId: Integer); function GetValue(): Variant; function GetValueAsObject(): TJS_Object; procedure PutValue(const value: Variant); function __toString: String; override; end; TJS_Date = class(TJS_Object) private DelphiDate: TDateTime; function GetValue: Variant; function UTCDelphiDate: TDateTime; function DelphiDateFromUTCDate(D: TDateTime): TDateTime; public property Value: Variant read GetValue; constructor Create(Year: PVariant = nil; Month: PVariant = nil; Day: PVariant = nil; Hours: PVariant = nil; Minutes: PVariant = nil; Seconds: PVariant = nil; Ms: PVariant = nil); function toGMTString: Variant; stdcall; function getTime: Variant; stdcall; function getFullYear: Variant; stdcall; function getUTCFullYear: Variant; stdcall; function getMonth: Variant; stdcall; function getUTCMonth: Variant; stdcall; function getDate: Variant; stdcall; function getUTCDate: Variant; stdcall; function getDay: Variant; stdcall; function getUTCDay: Variant; stdcall; function getHours: Variant; stdcall; function getUTCHours: Variant; stdcall; function getMinutes: Variant; stdcall; function getUTCMinutes: Variant; stdcall; function getSeconds: Variant; stdcall; function getUTCSeconds: Variant; stdcall; function getMilliseconds: Variant; stdcall; function getUTCMilliseconds: Variant; stdcall; function setTime(const P: Variant): Variant; stdcall; function setMilliseconds(const ms: Variant): Variant; stdcall; function setUTCMilliseconds(const ms: Variant): Variant; stdcall; function setSeconds(const sec, ms: Variant): Variant; stdcall; function setUTCSeconds(const sec, ms: Variant): Variant; stdcall; function setMinutes(const min, sec, ms: Variant): Variant; stdcall; function setUTCMinutes(const min, sec, ms: Variant): Variant; stdcall; function setHours(const hour, min, sec, ms: Variant): Variant; stdcall; function setUTCHours(const hour, min, sec, ms: Variant): Variant; stdcall; function setDate(const date: Variant): Variant; stdcall; function _toString: Variant; stdcall; function __toString: String; override; end; TJS_Array = class(TJS_Object) private function GetLength: Integer; procedure SetLength(value: Integer); public constructor Create(const V: array of Variant); destructor Destroy; override; function _toString: Variant; stdcall; function __toString: String; override; function _pop: Variant; stdcall; function _push(P0: PVariant; P1: PVariant = nil; P2: PVariant = nil; P3: PVariant = nil; P4: PVariant = nil; P5: PVariant = nil; P6: PVariant = nil; P7: PVariant = nil; P8: PVariant = nil; P9: PVariant = nil): Variant; stdcall; property Length: Integer read GetLength write SetLength; end; TJS_Boolean = class(TJS_Object) constructor Create(P: PVariant = nil); function _toString: Variant; stdcall; function __toString: String; override; end; TJS_Number = class(TJS_Object) constructor Create(P: PVariant = nil); function _toString(): Variant; stdcall; function __toString: String; override; end; TJS_String = class(TJS_Object) constructor Create(P: PVariant = nil); function _toString: Variant; stdcall; function __toString: String; override; function _valueOf: Variant; stdcall; function _length: Variant; stdcall; function _charAt(const P: Variant): Variant; stdcall; function _charCodeAt(const P: Variant): Variant; stdcall; function _concat(P0: PVariant; P1: PVariant = nil; P2: PVariant = nil; P3: PVariant = nil; P4: PVariant = nil; P5: PVariant = nil; P6: PVariant = nil; P7: PVariant = nil; P8: PVariant = nil; P9: PVariant = nil): Variant; stdcall; function _fromCharCode(P0: PVariant; P1: PVariant = nil; P2: PVariant = nil; P3: PVariant = nil; P4: PVariant = nil; P5: PVariant = nil; P6: PVariant = nil; P7: PVariant = nil; P8: PVariant = nil; P9: PVariant = nil): Variant; stdcall; function _slice(const VStart, VEnd: Variant): Variant; stdcall; function _substr(const VStart, VLength: Variant): Variant; stdcall; function _substring(const VStart, VLength: Variant): Variant; stdcall; function _indexOf(const P: Variant): Variant; stdcall; function _lastIndexOf(const P: Variant): Variant; stdcall; function _anchor(const P: Variant): Variant; stdcall; function _link(const P: Variant): Variant; stdcall; function _big: Variant; stdcall; function _small: Variant; stdcall; function _blink: Variant; stdcall; function _bold: Variant; stdcall; function _italics: Variant; stdcall; function _strike: Variant; stdcall; function _sub: Variant; stdcall; function _sup: Variant; stdcall; function _fixed: Variant; stdcall; function _fontcolor(const P: Variant): Variant; stdcall; function _fontsize(const P: Variant): Variant; stdcall; function _toUpperCase: Variant; stdcall; function _toLowerCase: Variant; stdcall; function _replace(const SearchValue, ReplaceValue: Variant): Variant; stdcall; end; TJS_Function = class(TJS_Object) private // DataPtr: Pointer; // CodePtr: Pointer; CoolCall: Integer; DefaultNP: Integer; public InternalFuncAddr: Pointer; arguments: TJS_Array; InternalLength: Integer; __this: TObject; {$IFDEF PAX64} private ParArr: Pointer; RetAdr: Pointer; procedure InternalCall2(NP: Integer); public {$ENDIF} constructor InternalCreate(i_InternalFuncAddr: Pointer; i_NP: Integer; i_ProgPtr: Pointer); destructor Destroy; override; function InternalCall(NP: Integer): Variant; stdcall; function Invoke(const Params: array of Variant): Variant; stdcall; function _toString: Variant; stdcall; function __toString: String; override; end; TJS_Math = class(TJS_Object) public constructor Create; function _abs(const P: Variant): Variant; stdcall; function _acos(const P: Variant): Variant; stdcall; function _asin(const P: Variant): Variant; stdcall; function _atan(const P: Variant): Variant; stdcall; function _atan2(const X, Y: Variant): Variant; stdcall; function _ceil(const P: Variant): Variant; stdcall; function _cos(const P: Variant): Variant; stdcall; function _exp(const P: Variant): Variant; stdcall; function _floor(const P: Variant): Variant; stdcall; function _log(const P: Variant): Variant; stdcall; function _max(P1, P2, P3, P4, P5: PVariant): Variant; stdcall; function _min(P1, P2, P3, P4, P5: PVariant): Variant; stdcall; function _pow(const X, Y: Variant): Variant; stdcall; function _random: Variant; stdcall; function _round(const P: Variant): Variant; stdcall; function _sin(const P: Variant): Variant; stdcall; function _sqrt(const P: Variant): Variant; stdcall; function _tan(const P: Variant): Variant; stdcall; end; TJS_RegExp = class(TJS_Object) private fLastIndex: Integer; {$IFNDEF PAXARM} fRegExpr: TRegExpr; fZERO_BASED_STRINGS: Boolean; {$ENDIF} function GetMatch(I: Integer): String; function GetMatchLen(I: Integer): Integer; function GetMatchPos(I: Integer): Integer; function GetSource: Variant; procedure SetSource(const Value: Variant); function GetInput: Variant; procedure SetInput(const Value: Variant); function GetGlobal: Boolean; procedure SetGlobal(const Value: Boolean); function GetIgnoreCase: Boolean; procedure SetIgnoreCase(const Value: Boolean); function GetMultiLine: Boolean; procedure SetMultiLine(const Value: Boolean); public constructor Create(Source: PVariant = nil; Modifiers: PVariant = nil); destructor Destroy; override; function Test(const InputString: Variant): Boolean; procedure Compile; function MatchCount: Integer; function Exec(const InputString: Variant): TJS_Array; function Execute(const InputString: Variant): TJS_Array; function Replace(const Expression, ReplaceStr: Variant): String; function _toString: Variant; stdcall; function __toString: String; override; published property global: Boolean read GetGlobal write SetGlobal; property ignoreCase: Boolean read GetIgnoreCase write SetIgnoreCase; property multiLine: Boolean read GetMultiLine write SetMultiLine; property lastIndex: Integer read fLastIndex write fLastIndex; property source: Variant read GetSource write SetSource; property input: Variant read GetInput write SetInput; end; TJS_Error = class(TJS_Object) constructor Create(P: PVariant = nil); function _toString: Variant; stdcall; function __toString: String; override; end; procedure Register_StdJavaScript(st: TBaseSymbolTable); function IsDateObject(const V: Variant): Boolean; function VariantToDateObject(const V: Variant): TJS_Date; function JS_IsObject(const V: Variant): Boolean; function JS_IsPointer(const V: Variant): Boolean; function JS_IsRef(const V: Variant): Boolean; function JS_IsString(const V: Variant): Boolean; function JS_IsBoolean(const V: Variant): Boolean; function JS_IsUndefined(const V: Variant): Boolean; function JS_GetValue(const V: Variant): Variant; procedure JS_PutValue(const V: Variant; const value: Variant); function JS_ToPrimitive(const V: Variant): Variant; function JS_ToString(const V: Variant): Variant; function JS_ToBoolean(const V: Variant): Variant; function JS_ToNumber(const V: Variant): Variant; function JS_ToNumberE(const V: Variant): Extended; function JS_ToInt32(const V: Variant): Variant; function JS_IsSimpleNumber(const V: Variant): Boolean; function JS_IsNumber(const V: Variant): Boolean; function JS_RelationalComparison(const V1, V2: Variant): Variant; //performs x < y comparison function JS_EqualityComparison(const V1, V2: Variant): Boolean; procedure _VariantFromClass(Dest: PVariant; SourceAddress: Pointer); stdcall; procedure _VariantFromPointer(Dest: PVariant; SourceAddress: Pointer); stdcall; procedure _ClassFromVariant(DestAddress: Pointer; Source: PVariant); stdcall; function GetVariantValue(Address: Pointer; FinTypeId: Integer): Variant; procedure PutVariantValue(Address: Pointer; FinTypeId: Integer; const value: Variant); procedure _JS_ToObject(P:TBaseRunner; Address: Pointer; FinTypeId: Integer; result: PVariant); stdcall; procedure _AssignProg(X: TJS_Object; P: TBaseRunner); stdcall; procedure _JS_GetNextProp(VObject: PVariant; Prop: PString; result: PBoolean); stdcall; procedure _ClearReferences(P: TBaseRunner); stdcall; procedure _ClassClr(Address: Pointer); stdcall; procedure _FuncObjFromVariant(source: PVariant; DestAddress: Pointer); stdcall; procedure _JS_TypeOf(V: PVariant; result: PString); stdcall; procedure _PushContext(P: TBaseRunner; value: PVariant); stdcall; procedure _PopContext(P: TBaseRunner); stdcall; procedure _FindContext(P: TBaseRunner; PropName: PChar; AltAddress: Pointer; FinTypeId: Integer; result: PVariant); stdcall; procedure _FindFunc(P: TBaseRunner; PropName: PChar; Alt, result: PVariant); stdcall; {$IFNDEF PAXARM} procedure _VariantFromPAnsiChar(source: PAnsiChar; dest: PVariant); stdcall; procedure _VariantFromAnsiString(Dest: PVariant; Source: PAnsiString); stdcall; procedure _VariantFromWideString(Dest: PVariant; Source: PWideString); stdcall; procedure _VariantFromAnsiChar(source: AnsiChar; dest: PVariant); stdcall; {$ENDIF} procedure _VariantFromPWideChar(source: PWideChar; dest: PVariant); stdcall; procedure _VariantFromInterface(const source: IDispatch; dest: PVariant); stdcall; procedure _VariantFromShortString(Dest: PVariant; Source: PShortString); stdcall; procedure _VariantFromUnicString(Dest: PVariant; Source: PUnicString); stdcall; procedure _VariantFromWideChar(source: WideChar; dest: PVariant); stdcall; procedure _VariantFromInt(source: Integer; dest: PVariant); stdcall; procedure _VariantFromInt64(dest: PVariant; source: PInt64); stdcall; procedure _VariantFromByte(source: Byte; dest: PVariant); stdcall; procedure _VariantFromBool(source: Boolean; dest: PVariant); stdcall; procedure _VariantFromWord(source: Word; dest: PVariant); stdcall; procedure _VariantFromCardinal(source: Cardinal; dest: PVariant); stdcall; procedure _VariantFromSmallInt(source: SmallInt; dest: PVariant); stdcall; procedure _VariantFromShortInt(source: ShortInt; dest: PVariant); stdcall; procedure _VariantFromDouble(dest: PVariant; source: PDouble); stdcall; procedure _VariantFromCurrency(dest: PVariant; source: PCurrency); stdcall; procedure _VariantFromSingle(dest: PVariant; source: PSingle); stdcall; procedure _VariantFromExtended(dest: PVariant; source: PExtended); stdcall; procedure _VariantAssign(dest, source: PVariant); stdcall; procedure _VariantAddition(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantSubtraction(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantMultiplication(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantDivision(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantIDivision(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantModulo(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantLeftShift(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantRightShift(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantAnd(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantOr(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantXor(Language: Integer; v1, v2, dest: PVariant); stdcall; procedure _VariantLessThan(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; procedure _VariantLessThanOrEqual(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; procedure _VariantGreaterThan(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; procedure _VariantGreaterThanOrEqual(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; procedure _VariantEquality(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; procedure _VariantNotEquality(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; procedure _ClassAssign(dest, source: PObject); stdcall; procedure _alert(Prog: TBaseRunner; P1: PVariant; P2: PVariant = nil; P3: PVariant = nil; P4: PVariant = nil; P5: PVariant = nil); stdcall; var VarIntTypes: set of byte; implementation {$IFDEF PAX64} procedure Push_And_Call(NP: Integer; Instance, Params, RetAdr: Pointer); forward; procedure AssignRBX(P: Pointer); forward; {$ENDIF} const varEmpty = $0000; { vt_empty 0 } varNull = $0001; { vt_null 1 } varSmallint = $0002; { vt_i2 2 } varInteger = $0003; { vt_i4 3 } varSingle = $0004; { vt_r4 4 } varDouble = $0005; { vt_r8 5 } varCurrency = $0006; { vt_cy 6 } varDate = $0007; { vt_date 7 } varOleStr = $0008; { vt_bstr 8 } varDispatch = $0009; { vt_dispatch 9 } varError = $000A; { vt_error 10 } varBoolean = $000B; { vt_bool 11 } varVariant = $000C; { vt_variant 12 } varUnknown = $000D; { vt_unknown 13 } //varDecimal = $000E; { vt_decimal 14 } {UNSUPPORTED as of v6.x code base} //varUndef0F = $000F; { undefined 15 } {UNSUPPORTED per Microsoft} varShortInt = $0010; { vt_i1 16 } varByte = $0011; { vt_ui1 17 } varWord = $0012; { vt_ui2 18 } varLongWord = $0013; { vt_ui4 19 } varInt64 = $0014; { vt_i8 20 } //varWord64 = $0015; { vt_ui8 21 } {UNSUPPORTED as of v6.x code base} { if adding new items, update Variants' varLast, BaseTypeMap and OpTypeMap } varStrArg = $0048; { vt_clsid 72 } varString = $0100; { Pascal string 256 } {not OLE compatible } varAny = $0101; { Corba any 257 } {not OLE compatible } varUString = $0102; { Unicode string 258 } {not OLE compatible} // varUndefined = varEmpty; var Undefined: Variant; var EmptyFunction: TJS_Function; procedure RaiseError(const Message: string; params: array of Const); begin raise PaxCompilerException.Create(Format(Message, params)); end; {$IFNDEF VARIANTS} function StrToFloatDef(const S: string; const Default: Extended): Extended; begin if not TextToFloat(PChar(S), Result, fvExtended) then Result := Default; end; function IsNan(const AValue: Single): Boolean; overload; begin Result := ((PLongWord(@AValue)^ and $7F800000) = $7F800000) and ((PLongWord(@AValue)^ and $007FFFFF) <> $00000000); end; function IsNan(const AValue: Double): Boolean; overload; begin Result := ((PInt64(@AValue)^ and $7FF0000000000000) = $7FF0000000000000) and ((PInt64(@AValue)^ and $000FFFFFFFFFFFFF) <> $0000000000000000); end; function IsNan(const AValue: Extended): Boolean; overload; type TExtented = packed record Mantissa: Int64; Exponent: Word; end; PExtended = ^TExtented; begin Result := ((PExtended(@AValue)^.Exponent and $7FFF) = $7FFF) and ((PExtended(@AValue)^.Mantissa and $7FFFFFFFFFFFFFFF) <> 0); end; function IsInfinite(const AValue: Double): Boolean; begin Result := ((PInt64(@AValue)^ and $7FF0000000000000) = $7FF0000000000000) and ((PInt64(@AValue)^ and $000FFFFFFFFFFFFF) = $0000000000000000); end; {$ENDIF} function VarFromClass(Source: TJS_ObjectBase): Variant; begin TVarData(result).VInteger := Integer(Source); TVarData(result).VType := varClass; end; procedure Create_DateObject(P: TBaseRunner; R: TJS_Record); var X: TJS_Object; begin P.JS_Date := TJS_Date.Create; P.SetAddress(P.GetOffset(R.H_JS_Date), @P.JS_Date); X := P.JS_Date as TJS_Object; X.prog := P; X.aconstructor := X; X.Tag := 1; X.AddToGC; X.prototype := TJS_Date.Create; with X.prototype do begin aconstructor := X; prog := P; AddToGC; PutProperty('toString', VarFromClass( TJS_Function.InternalCreate(@TJS_Date._toString, 0, @P))); PutProperty('toGMTString', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.toGMTString, 0, @P))); PutProperty('getTime', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getTime, 0, @P))); PutProperty('getFullYear', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getFullYear, 0, @P))); PutProperty('getUTCFullYear', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getUTCFullYear, 0, @P))); PutProperty('getMonth', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getMonth, 0, @P))); PutProperty('getUTCMonth', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getUTCMonth, 0, @P))); PutProperty('getDate', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getDate, 0, @P))); PutProperty('getUTCDate', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getUTCDate, 0, @P))); PutProperty('getDay', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getDay, 0, @P))); PutProperty('getUTCDay', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getUTCDay, 0, @P))); PutProperty('getHours', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getHours, 0, @P))); PutProperty('getUTCHours', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getUTCHours, 0, @P))); PutProperty('getMinutes', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getMinutes, 0, @P))); PutProperty('getUTCMinutes', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getUTCMinutes, 0, @P))); PutProperty('getSeconds', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getSeconds, 0, @P))); PutProperty('getUTCSeconds', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getUTCSeconds, 0, @P))); PutProperty('getMilliseconds', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getMilliseconds, 0, @P))); PutProperty('getUTCMilliseconds', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.getUTCMilliseconds, 0, @P))); PutProperty('setTime', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.setTime, 1, @P))); PutProperty('setMilliseconds', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.setMilliseconds, 1, @P))); PutProperty('setUTCMilliseconds', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.setUTCMilliseconds, 1, @P))); PutProperty('setSeconds', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.setSeconds, 2, @P))); PutProperty('setUTCSeconds', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.setUTCSeconds, 2, @P))); PutProperty('setMinutes', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.setMinutes, 3, @P))); PutProperty('setUTCMinutes', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.setUTCSeconds, 3, @P))); PutProperty('setHours', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.setHours, 4, @P))); PutProperty('setUTCHours', VarFromClass( TJS_Function.InternalCreate(@TJS_Date.setUTCHours, 4, @P))); end; end; procedure Create_BooleanObject(P: TBaseRunner; R: TJS_Record); var X: TJS_Object; begin P.JS_Boolean := TJS_Boolean.Create; X := P.JS_Boolean as TJS_Object; X.prog := P; X.aconstructor := X; X.Tag := 1; X.AddToGC; X.prototype := TJS_Object.Create; X.prototype.aconstructor := X; X.prototype.prog := P; X.prototype.AddToGC; P.SetAddress(P.GetOffset(R.H_JS_Boolean), @P.JS_Boolean); end; procedure Create_ErrorObject(P: TBaseRunner; R: TJS_Record); var X: TJS_Object; begin P.JS_Error := TJS_Error.Create; X := P.JS_Error as TJS_Object; X.prog := P; X.aconstructor := X; X.Tag := 1; X.AddToGC; X.prototype := TJS_Object.Create; X.prototype.aconstructor := X; X.prototype.prog := P; X.prototype.AddToGC; P.SetAddress(P.GetOffset(R.H_JS_Error), @P.JS_Error); end; procedure Create_NumberObject(P: TBaseRunner; R: TJS_Record); var X: TJS_Object; begin P.JS_Number := TJS_Number.Create; X := P.JS_Number as TJS_Object; X.prog := P; X.aconstructor := X; X.Tag := 1; X.AddToGC; X.prototype := TJS_Object.Create; X.prototype.aconstructor := X; X.prototype.prog := P; X.prototype.AddToGC; P.SetAddress(P.GetOffset(R.H_JS_Number), @P.JS_Number); with X.prototype do begin aconstructor := X; prog := P; PutProperty('toString', VarFromClass( TJS_Function.InternalCreate(@TJS_Function._toString, 0, @P))); end; end; procedure Create_StringObject(P: TBaseRunner; R: TJS_Record); var X: TJS_Object; F: TJS_Function; begin P.JS_String := TJS_String.Create; X := P.JS_String as TJS_Object; X.prog := P; X.aconstructor := X; X.Tag := 1; X.AddToGC; X.prototype := TJS_Object.Create; X.prototype.aconstructor := X; X.prototype.prog := P; X.prototype.AddToGC; P.SetAddress(P.GetOffset(R.H_JS_String), @P.JS_String); with X.prototype do begin aconstructor := X; prog := P; PutProperty('toString', VarFromClass( TJS_Function.InternalCreate(@TJS_String._toString, 0, @P))); PutProperty('valueOf', VarFromClass( TJS_Function.InternalCreate(@TJS_String._valueOf, 0, @P))); PutProperty('charAt', VarFromClass( TJS_Function.InternalCreate(@TJS_String._charAt, 1, @P))); PutProperty('charCodeAt', VarFromClass( TJS_Function.InternalCreate(@TJS_String._charCodeAt, 1, @P))); F := TJS_Function.InternalCreate(@TJS_String._concat, 1, @P); F.DefaultNP := 10; PutProperty('concat', VarFromClass(F)); F := TJS_Function.InternalCreate(@TJS_String._fromCharCode, 1, @P); F.DefaultNP := 10; PutProperty('fromCharCode', VarFromClass(F)); PutProperty('length', VarFromClass( TJS_Function.InternalCreate(@TJS_String._length, 0, @P))); PutProperty('indexOf', VarFromClass( TJS_Function.InternalCreate(@TJS_String._indexOf, 1, @P))); PutProperty('lastIndexOf', VarFromClass( TJS_Function.InternalCreate(@TJS_String._lastIndexOf, 1, @P))); PutProperty('slice', VarFromClass( TJS_Function.InternalCreate(@TJS_String._slice, 2, @P))); PutProperty('substr', VarFromClass( TJS_Function.InternalCreate(@TJS_String._substr, 2, @P))); PutProperty('substring', VarFromClass( TJS_Function.InternalCreate(@TJS_String._substring, 2, @P))); PutProperty('anchor', VarFromClass( TJS_Function.InternalCreate(@TJS_String._anchor, 1, @P))); PutProperty('link', VarFromClass( TJS_Function.InternalCreate(@TJS_String._link, 1, @P))); PutProperty('big', VarFromClass( TJS_Function.InternalCreate(@TJS_String._big, 0, @P))); PutProperty('small', VarFromClass( TJS_Function.InternalCreate(@TJS_String._small, 0, @P))); PutProperty('blink', VarFromClass( TJS_Function.InternalCreate(@TJS_String._blink, 0, @P))); PutProperty('bold', VarFromClass( TJS_Function.InternalCreate(@TJS_String._bold, 0, @P))); PutProperty('italics', VarFromClass( TJS_Function.InternalCreate(@TJS_String._italics, 0, @P))); PutProperty('strike', VarFromClass( TJS_Function.InternalCreate(@TJS_String._strike, 0, @P))); PutProperty('sub', VarFromClass( TJS_Function.InternalCreate(@TJS_String._sub, 0, @P))); PutProperty('sup', VarFromClass( TJS_Function.InternalCreate(@TJS_String._sup, 0, @P))); PutProperty('fixed', VarFromClass( TJS_Function.InternalCreate(@TJS_String._fixed, 0, @P))); PutProperty('fontcolor', VarFromClass( TJS_Function.InternalCreate(@TJS_String._fontcolor, 1, @P))); PutProperty('fontsize', VarFromClass( TJS_Function.InternalCreate(@TJS_String._fontsize, 1, @P))); PutProperty('toUpperCase', VarFromClass( TJS_Function.InternalCreate(@TJS_String._toUpperCase, 0, @P))); PutProperty('toLowerCase', VarFromClass( TJS_Function.InternalCreate(@TJS_String._toLowerCase, 0, @P))); PutProperty('replace', VarFromClass( TJS_Function.InternalCreate(@TJS_String._replace, 2, @P))); end; end; procedure Create_ArrayObject(P: TBaseRunner; R: TJS_Record); var X: TJS_Object; F: TJS_Function; begin P.JS_Array := TJS_Array.Create([]); X := P.JS_Array as TJS_Object; X.prog := P; X.aconstructor := X; X.Tag := 1; X.AddToGC; X.prototype := TJS_Object.Create; X.prototype.aconstructor := X; X.prototype.prog := P; X.prototype.AddToGC; P.SetAddress(P.GetOffset(R.H_JS_Array), @P.JS_Array); with X.prototype do begin aconstructor := X; prog := P; PutProperty('pop', VarFromClass( TJS_Function.InternalCreate(@TJS_Array._pop, 0, @P))); F := TJS_Function.InternalCreate(@TJS_Array._push, 1, @P); F.DefaultNP := 10; PutProperty('push', VarFromClass(F)); end; end; procedure Create_RegExpObject(P: TBaseRunner; R: TJS_Record); var X: TJS_Object; begin P.JS_RegExp := TJS_RegExp.Create; X := P.JS_RegExp as TJS_Object; X.prog := P; X.aconstructor := X; X.Tag := 1; X.AddToGC; X.prototype := TJS_Object.Create; X.prototype.aconstructor := X; X.prototype.prog := P; X.prototype.AddToGC; P.SetAddress(P.GetOffset(R.H_JS_RegExp), @P.JS_RegExp); with X.prototype do begin aconstructor := X; prog := P; PutProperty('toString', VarFromClass( TJS_Function.InternalCreate(@TJS_RegExp._toString, 0, @P))); end; end; procedure Create_FunctionObject(P: TBaseRunner; R: TJS_Record); var X: TJS_Object; begin P.JS_Function := TJS_Function.Create; X := P.JS_Function as TJS_Object; X.prog := P; X.aconstructor := X; X.Tag := 1; X.AddToGC; X.prototype := TJS_Object.Create; X.prototype.aconstructor := X; X.prototype.prog := P; X.prototype.AddToGC; P.SetAddress(P.GetOffset(R.H_JS_Function), @P.JS_Function); end; var JS_MATH_ABS: Integer = -1; JS_MATH_ACOS: Integer = -1; JS_MATH_ASIN: Integer = -1; JS_MATH_ATAN: Integer = -1; JS_MATH_ATAN2: Integer = -1; JS_MATH_CEIL: Integer = -1; JS_MATH_COS: Integer = -1; JS_MATH_EXP: Integer = -1; JS_MATH_FLOOR: Integer = -1; JS_MATH_LOG: Integer = -1; JS_MATH_MAX: Integer = -1; JS_MATH_MIN: Integer = -1; JS_MATH_POW: Integer = -1; JS_MATH_RANDOM: Integer = -1; JS_MATH_ROUND: Integer = -1; JS_MATH_SIN: Integer = -1; JS_MATH_SQRT: Integer = -1; JS_MATH_TAN: Integer = -1; JS_MATH_PI: Integer = -1; JS_MATH_E: Integer = -1; JS_MATH_LN10: Integer = -1; JS_MATH_LN2: Integer = -1; JS_MATH_LOG2E: Integer = -1; JS_MATH_LOG10E: Integer = -1; JS_MATH_SQRT1_2: Integer = -1; JS_MATH_SQRT2: Integer = -1; procedure Create_MathObject(P: TBaseRunner; R: TJS_Record); var X: TJS_Object; F: TJS_Function; begin P.JS_Math := TJS_Math.Create; P.SetAddress(P.GetOffset(R.H_JS_Math), @P.JS_Math); X := P.JS_Math as TJS_Object; X.prog := P; X.aconstructor := X; X.Tag := 1; X.AddToGC; X.prototype := TJS_Object.Create; X.prototype.aconstructor := X; X.prototype.prog := P; X.prototype.AddToGC; with X do begin F := TJS_Function.InternalCreate(@TJS_Math._abs, 1, @P); F.CoolCall := 1; PutProperty('abs', VarFromClass(F)); //0 JS_MATH_ABS := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._acos, 1, @P); F.CoolCall := 1; PutProperty('acos', VarFromClass(F)); //1 JS_MATH_ACOS := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._asin, 1, @P); F.CoolCall := 1; PutProperty('asin', VarFromClass(F)); //2 JS_MATH_ASIN := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._atan, 1, @P); F.CoolCall := 1; PutProperty('atan', VarFromClass(F)); //3 JS_MATH_ATAN := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._atan2, 2, @P); F.CoolCall := 1; PutProperty('atan2', VarFromClass(F)); //4 JS_MATH_ATAN2 := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._ceil, 1, @P); F.CoolCall := 1; PutProperty('ceil', VarFromClass(F)); //5 JS_MATH_CEIL := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._cos, 1, @P); F.CoolCall := 1; PutProperty('cos', VarFromClass(F)); //6 JS_MATH_COS := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._exp, 1, @P); F.CoolCall := 1; PutProperty('exp', VarFromClass(F)); //7 JS_MATH_EXP := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._floor, 1, @P); F.CoolCall := 1; PutProperty('floor', VarFromClass(F)); //8 JS_MATH_FLOOR := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._log, 1, @P); F.CoolCall := 1; PutProperty('log', VarFromClass(F)); //9 JS_MATH_LOG := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._max, 5, @P); F.CoolCall := 1; PutProperty('max', VarFromClass(F)); //10 JS_MATH_MAX := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._min, 5, @P); F.CoolCall := 1; PutProperty('min', VarFromClass(F)); //11 JS_MATH_MIN := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._pow, 2, @P); F.CoolCall := 1; PutProperty('pow', VarFromClass(F)); //12 JS_MATH_POW := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._random, 0, @P); F.CoolCall := 1; PutProperty('random', VarFromClass(F)); //13 JS_MATH_RANDOM := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._round, 1, @P); F.CoolCall := 1; PutProperty('round', VarFromClass(F)); //14 JS_MATH_ROUND := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._sin, 1, @P); F.CoolCall := 1; PutProperty('sin', VarFromClass(F)); //15 JS_MATH_SIN := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._sqrt, 1, @P); F.CoolCall := 1; PutProperty('sqrt', VarFromClass(F)); //16 JS_MATH_SQRT := L.HashTable.LastIndex; F := TJS_Function.InternalCreate(@TJS_Math._tan, 1, @P); F.CoolCall := 1; PutProperty('tan', VarFromClass(F)); //17 JS_MATH_TAN := L.HashTable.LastIndex; PutProperty('PI', PI); //18 JS_MATH_PI := L.HashTable.LastIndex; PutProperty('E', 2.7182818284590452354); //19 JS_MATH_E := L.HashTable.LastIndex; PutProperty('LN10', 2.302585092994046); //20 JS_MATH_LN10 := L.HashTable.LastIndex; PutProperty('LN2', 0.6931471805599453); //21 JS_MATH_LN2 := L.HashTable.LastIndex; PutProperty('LOG2E', 1.4426950408889634); //22 JS_MATH_LOG2E := L.HashTable.LastIndex; PutProperty('LOG10E', 0.434294819032518); //23 JS_MATH_LOG10E := L.HashTable.LastIndex; PutProperty('SQRT1_2', 0.7071067811865476); //24 JS_MATH_SQRT1_2 := L.HashTable.LastIndex; PutProperty('SQRT2', 1.4142135623730951); //25 JS_MATH_SQRT2 := L.HashTable.LastIndex; end; end; procedure Create_JSObjects(Prog: Pointer; R: TJS_Record); var X: TJS_Object; P: TBaseRunner; begin P := TBaseRunner(Prog); P.ProgTag := 1; // global Object object P.JS_Object := TJS_Object.Create; X := P.JS_Object as TJS_Object; X.prog := P; X.aconstructor := X; X.Tag := 1; X.AddToGC; X.prototype := TJS_Object.Create; X.prototype.aconstructor := X; X.prototype.prog := P; X.prototype.AddToGC; P.SetAddress(P.GetOffset(R.H_JS_Object), @P.JS_Object); Create_BooleanObject(P, R); Create_StringObject(P, R); Create_NumberObject(P, R); Create_DateObject(P, R); Create_FunctionObject(P, R); Create_ArrayObject(P, R); Create_RegExpObject(P, R); Create_MathObject(P, R); Create_ErrorObject(P, R); P.RootGC.Mark; // P.ProgTag := 0; end; // VARIANT OPERATORS procedure _FuncObjFromVariant(source: PVariant; DestAddress: Pointer); stdcall; begin with TVarData(source^) do begin if VType <> varClass then begin if VType in [varEmpty, varDispatch] then begin TObject(DestAddress^) := EmptyFunction; Exit; end; RaiseError(errCannotConvertToFunctionObject, []); end; TObject(DestAddress^) := TObject(VInteger); if TObject(DestAddress^).ClassType <> TJS_Function then RaiseError(errCannotConvertToFunctionObject, []); end; end; procedure _VariantAddition(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_ToPrimitive(v1^); w2 := JS_ToPrimitive(v2^); if JS_IsString(w1) or JS_IsString(w2) then begin if not JS_IsString(w1) then w1 := JS_ToString(w1); if not JS_IsString(w2) then w2 := JS_ToString(w2); if JS_IsRef(dest^) then JS_PutValue(dest^, w1 + w2) else dest^ := w1 + w2; end else begin if JS_IsRef(dest^) then JS_PutValue(dest^, JS_ToNumber(w1) + JS_ToNumber(w2)) else dest^ := JS_ToNumber(w1) + JS_ToNumber(w2); end; end else begin dest^ := v1^ + v2^; end; end; procedure _VariantSubtraction(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_GetValue(v1^); w2 := JS_GetValue(v2^); if IsDateObject(w1) and IsDateObject(w2) then begin if JS_IsRef(dest^) then JS_PutValue(dest^, VariantToDateObject(w1).Value - VariantToDateObject(w2).Value) else dest^ := VariantToDateObject(w1).Value - VariantToDateObject(w2).Value; Exit; end else if IsDateObject(w1) then begin if JS_IsRef(dest^) then JS_PutValue(dest^, VariantToDateObject(w1).Value - JS_ToNumber(w2)) else dest^ := VariantToDateObject(w1).Value - JS_ToNumber(w2); Exit; end else if IsDateObject(w2) then begin if JS_IsRef(dest^) then JS_PutValue(dest^, VariantToDateObject(w2).Value - JS_ToNumber(w1)) else dest^ := VariantToDateObject(w2).Value - JS_ToNumber(w1); Exit; end; if JS_IsRef(dest^) then JS_PutValue(dest^, JS_ToNumber(w1) - JS_ToNumber(w2)) else dest^ := JS_ToNumber(w1) - JS_ToNumber(w2); end else begin dest^ := v1^ - v2^; end; end; procedure _VariantMultiplication(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_ToPrimitive(v1^); w2 := JS_ToPrimitive(v2^); if JS_IsRef(dest^) then JS_PutValue(dest^, JS_ToNumber(w1) * JS_ToNumber(w2)) else dest^ := JS_ToNumber(w1) * JS_ToNumber(w2); end else begin dest^ := v1^ * v2^; end; end; procedure _VariantDivision(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_ToPrimitive(v1^); w2 := JS_ToPrimitive(v2^); if JS_IsRef(dest^) then JS_PutValue(dest^, JS_ToNumber(w1) / JS_ToNumber(w2)) else dest^ := JS_ToNumber(w1) - JS_ToNumber(w2); end else begin dest^ := v1^ / v2^; end; end; procedure _VariantIDivision(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_ToPrimitive(v1^); w2 := JS_ToPrimitive(v2^); if JS_IsRef(dest^) then JS_PutValue(dest^, JS_ToInt32(w1) div JS_ToInt32(w2)) else dest^ := JS_ToInt32(w1) div JS_ToInt32(w2); end else dest^ := v1^ div v2^; end; procedure _VariantModulo(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_ToPrimitive(v1^); w2 := JS_ToPrimitive(v2^); if JS_IsRef(dest^) then JS_PutValue(dest^, JS_ToInt32(w1) mod JS_ToInt32(w2)) else dest^ := JS_ToInt32(w1) mod JS_ToInt32(w2); end else dest^ := v1^ mod v2^; end; procedure _VariantLeftShift(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_ToPrimitive(v1^); w2 := JS_ToPrimitive(v2^); w1 := JS_ToInt32(w1); w2 := JS_ToInt32(w2); if JS_IsRef(dest^) then JS_PutValue(dest^, w1 shl w2) else dest^ := w1 shl w2; end else dest^ := v1^ shl v2^; end; procedure _VariantRightShift(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_ToPrimitive(v1^); w2 := JS_ToPrimitive(v2^); w1 := JS_ToInt32(w1); w2 := JS_ToInt32(w2); if JS_IsRef(dest^) then JS_PutValue(dest^, w1 shr w2) else dest^ := w1 shr w2; end else dest^ := v1^ shr v2^; end; procedure _VariantAnd(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_ToPrimitive(v1^); w2 := JS_ToPrimitive(v2^); w1 := JS_ToInt32(w1); w2 := JS_ToInt32(w2); if JS_IsRef(dest^) then JS_PutValue(dest^, w1 and w2) else dest^ := w1 and w2; end else dest^ := v1^ and v2^; end; procedure _VariantOr(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_ToPrimitive(v1^); w2 := JS_ToPrimitive(v2^); w1 := JS_ToInt32(w1); w2 := JS_ToInt32(w2); if JS_IsRef(dest^) then JS_PutValue(dest^, w1 or w2) else dest^ := w1 or w2; end else dest^ := v1^ or v2^; end; procedure _VariantXor(Language: Integer; v1, v2, dest: PVariant); stdcall; var w1, w2: Variant; begin if Language = JS_LANGUAGE then begin w1 := JS_ToPrimitive(v1^); w2 := JS_ToPrimitive(v2^); w1 := JS_ToInt32(w1); w2 := JS_ToInt32(w2); if JS_IsRef(dest^) then JS_PutValue(dest^, w1 xor w2) else dest^ := w1 xor w2; end else dest^ := v1^ xor v2^; end; procedure _VariantLessThan(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; begin if Language = JS_LANGUAGE then begin if JS_IsRef(dest^) then JS_PutValue(dest^, JS_RelationalComparison(v1^, v2^)) else dest^ := JS_RelationalComparison(v1^, v2^); end else dest^ := Boolean(v1^ < v2^); end; procedure _VariantLessThanOrEqual(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; var temp: Variant; begin if Language = JS_LANGUAGE then begin temp := JS_RelationalComparison(v2^, v1^); if JS_IsUndefined(temp) then temp := false else if JS_IsBoolean(temp) then temp := not temp else temp := true; if JS_IsRef(dest^) then JS_PutValue(dest^, temp) else dest^ := temp; end else dest^ := v1^ <= v2^; end; procedure _VariantGreaterThan(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; var temp: Variant; begin if Language = JS_LANGUAGE then begin temp := JS_RelationalComparison(v2^, v1^); if JS_IsUndefined(temp) then temp := false; if JS_IsRef(dest^) then JS_PutValue(dest^, temp) else dest^ := temp; end else dest^ := v1^ > v2^; end; procedure _VariantGreaterThanOrEqual(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; var temp: Variant; begin if Language = JS_LANGUAGE then begin temp := JS_RelationalComparison(v1^, v2^); if JS_IsUndefined(temp) then temp := false else if JS_IsBoolean(dest^) then temp := not temp else temp := true; if JS_IsRef(dest^) then JS_PutValue(dest^, temp) else dest^ := temp; end else dest^ := v1^ >= v2^; end; procedure _VariantEquality(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; begin if Language = JS_LANGUAGE then begin if JS_IsRef(dest^) then JS_PutValue(dest^, JS_EqualityComparison(v1^, v2^)) else dest^ := JS_EqualityComparison(v1^, v2^); end else dest^ := v1^ = v2^; end; procedure _VariantNotEquality(Language: Integer; v1, v2: PVariant; dest: PBoolean); stdcall; begin if Language = JS_LANGUAGE then begin if JS_IsRef(dest^) then JS_PutValue(dest^, not JS_EqualityComparison(v1^, v2^)) else dest^ := not JS_EqualityComparison(v1^, v2^); end else dest^ := v1^ <> v2^; end; function JS_PointerToVariant(P: Pointer): Variant; begin with TVarData(result) do begin VType := varPointer; VInteger := Integer(P); end; end; function JS_VariantToPointer(const V: Variant): Pointer; begin with TVarData(V) do begin result := Pointer(VInteger); end; end; function Empty(P: PVariant): Boolean; begin result := (P = nil) or (VarType(P^) = varEmpty); end; function JS_IsObject(const V: Variant): Boolean; begin result := VarType(V) = varClass; end; function JS_IsPointer(const V: Variant): Boolean; begin result := VarType(V) = varPointer; end; function JS_IsString(const V: Variant): Boolean; var T: Integer; begin T := VarType(V); result := (T = varOleStr) or (T = varString) or (T = varUString); end; function JS_IsBoolean(const V: Variant): Boolean; begin result := VarType(V) = varBoolean; end; function JS_IsUndefined(const V: Variant): Boolean; begin result := VarType(V) = varEmpty; end; function JS_ToPrimitive(const V: Variant): Variant; var X: TJS_ObjectBase; begin if VarType(V) = varClass then begin X := TJS_ObjectBase(TVarData(V).VInteger); if X is TJS_Reference then begin result := (X as TJS_Reference).GetValue(); if VarType(result) = varClass then begin X := TJS_ObjectBase(TVarData(result).VInteger); result := (X as TJS_Object).fDefaultValue; end; end else result := (X as TJS_Object).fDefaultValue; end else result := V; end; function JS_ToString(const V: Variant): Variant; var X: TJS_ObjectBase; begin case VarType(V) of varClass: begin X := TJS_ObjectBase(TVarData(V).VInteger); if X is TJS_Reference then X := (X as TJS_Reference).GetValueAsObject(); result := VarToStr((X as TJS_Object).fDefaultValue); end; else result := VarToStr(V); end; end; function JS_ToNumber(const V: Variant): Variant; var X: TJS_ObjectBase; Code1: Integer; D: Double; begin case VarType(V) of varEmpty: result := NaN; varNull: result := 0; varBoolean: if V then result := 1 else result := 0; varString, varOleStr, varUString: begin Val(V, D, Code1); result := D; // result := StrToFloatDef(StringReplace(V, '.', PAXCOMP_SYS.DecimalSeparator, []), NaN); end; varClass: begin X := TJS_ObjectBase(TVarData(V).VInteger); if X is TJS_Reference then X := (X as TJS_Reference).GetValueAsObject(); result := JS_ToNumber((X as TJS_Object).fDefaultValue); end else result := V; end; end; function JS_ToNumberE(const V: Variant): Extended; var X: TJS_ObjectBase; D: Double; Code1: Integer; begin case VarType(V) of varEmpty: result := NaN; varNull: result := 0; varBoolean: if V then result := 1 else result := 0; varString, varOleStr, varUString: begin Val(V, D, Code1); result := D; // result := StrToFloatDef(StringReplace(V, '.', PAXCOMP_SYS.DecimalSeparator, []), NaN); end; varClass: begin X := TJS_ObjectBase(TVarData(V).VInteger); if X is TJS_Reference then X := (X as TJS_Reference).GetValueAsObject(); result := JS_ToNumber((X as TJS_Object).fDefaultValue); end else result := V; end; end; function JS_ToBoolean(const V: Variant): Variant; begin result := V; end; function JS_ToInt32(const V: Variant): Variant; var N: Variant; D: Double; I: Integer; begin N := JS_ToNumber(V); case VarType(N) of varDouble: begin D := N; if IsNaN(D) or IsInfinite(D) then result := 0 else begin D := N; {$IFDEF VARIANTS} result := Round(D); {$ELSE} I := Round(D); result := I; {$ENDIF} end; end; varInteger, varByte: Result := N; {$IFDEF VARIANTS} varInt64: begin D := N; I := Round(D); result := I; end; {$ENDIF} end; end; function JS_IsSimpleNumber(const V: Variant): Boolean; begin result := VarType(V) in [varSmallint, varInteger, varSingle, varDouble, varCurrency, varShortInt, varByte, varWord, varLongWord, varInt64]; end; function JS_IsNumber(const V: Variant): Boolean; begin result := JS_IsSimpleNumber(V); end; function JS_RelationalComparison(const V1, V2: Variant): Variant; //performs x < y comparison var I, L: Integer; S1, S2: String; P1, P2, N1, N2: Variant; begin P1 := JS_ToPrimitive(V1); P2 := JS_ToPrimitive(V2); if JS_IsString(P1) and JS_IsString(P2) then begin S1 := P1; S2 := P2; if Pos(S1, S2) > 0 then result := true else if Pos(S2, S1) > 0 then result := false else begin L := Length(S1); if Length(S2) < L then L := Length(S2); for I:=1 to L do if S1[I] <> S2[I] then begin if Ord(S1[I]) < Ord(S2[I]) then result := true else result := false; Exit; end; result := false; end; end else begin N1 := JS_ToNumber(P1); N2 := JS_ToNumber(P2); if IsNAN(N1) then Exit; if IsNAN(N2) then Exit; result := N1 < N2; end; end; function JS_EqualityComparison(const V1, V2: Variant): Boolean; var T1, T2: Integer; W1, W2: Variant; begin result := false; if (VarType(V1) = varClass) and (VarType(V2) = varEmpty) then Exit; if (VarType(V2) = varClass) and (VarType(V1) = varEmpty) then Exit; W1 := JS_ToPrimitive(V1); W2 := JS_ToPrimitive(V2); T1 := VarType(W1); T2 := VarType(W2); if T1 = T2 then begin if T1 = varUndefined then begin result := true; Exit; end; if T1 = varNull then begin result := true; Exit; end; if JS_IsNumber(W1) then begin if IsNaN(W1) or IsNaN(W2) then begin result := false; Exit; end; result := W1 = W2; Exit; end; result := W1 = W2; end else begin if (T1 = varNull) and (T2 = varUndefined) then result := true else if (T2 = varNull) and (T1 = varUndefined) then result := true else if JS_IsNumber(W1) and JS_IsString(W2) then result := JS_EqualityComparison(W1, JS_ToNumber(W2)) else if JS_IsNumber(W2) and JS_IsString(W1) then result := JS_EqualityComparison(W2, JS_ToNumber(W1)) else if JS_IsNumber(W1) and JS_IsBoolean(W2) then result := JS_EqualityComparison(W1, JS_ToNumber(W2)) else if JS_IsNumber(W2) and JS_IsBoolean(W1) then result := JS_EqualityComparison(W2, JS_ToNumber(W1)) else if JS_IsObject(W1) and (JS_IsNumber(W2) or JS_IsBoolean(W2) or JS_IsString(W2)) then result := JS_EqualityComparison(JS_ToPrimitive(W1), W2) else if JS_IsObject(W2) and (JS_IsNumber(W1) or JS_IsBoolean(W1) or JS_IsString(W1)) then result := JS_EqualityComparison(JS_ToPrimitive(W2), W1) else if JS_IsNumber(W1) and JS_IsNumber(W2) then result := W1 = W2 else result := false; end; end; //-- THashTable ---------------------------------------------------------------- function HashPJW(S : PChar; TableSize: Integer) : longint; {Note: this hash function is described in "Practical Algorithms For Programmers" by Andrew Binstock and John Rex, Addison Wesley} const BitsInLongint = sizeof(longint) * 8; ThreeQuarters = (BitsInLongint * 3) div 4; OneEighth = BitsInLongint div 8; HighBits : longint = (not longint(0)) shl (BitsInLongint - OneEighth); var Test : longint; c: Char; begin Result := 0; repeat c := S^; if c = #0 then break; Result := (Result shl OneEighth) + ord(c); Test := Result and HighBits; if (Test <> 0) then Result := (Result xor (Test shr ThreeQuarters)) and not HighBits; Inc(S); until false; result := Result mod TableSize; if result < 0 then writeln(123); end; {--------} function HashELF(const S : string; TableSize: Integer) : longint; {Note: this hash function is described in "Practical Algorithms For Programmers" by Andrew Binstock and John Rex, Addison Wesley, with modifications in Dr Dobbs Journal, April 1996} var G : longint; i : integer; begin Result := 0; for i := SLow(S) to SHigh(S) do begin Result := (Result shl 4) + ord(S[i]); G := Result and $F0000000; if (G <> 0) then Result := Result xor (G shr 24); Result := Result and (not G); end; result := Result mod TableSize; end; {--------} function HashBKDR(const S : string; TableSize: Integer) : longint; {Note: this hash function is described in "The C Programming Language" by Brian Kernighan and Donald Ritchie, Prentice Hall} var i : integer; begin Result := 0; for i := SLow(S) to SHigh(S) do begin Result := (Result * 31) + ord(S[i]); end; result := Result mod TableSize; end; constructor THashTable.Create; begin inherited; PrimeIndex := 1; TableSize := Primes[PrimeIndex]; SetLength(A, TableSize + 1); Card := 0; MaxCard := TableSize div 2; HashFunction := HashPJW; end; destructor THashTable.Destroy; begin Clear; inherited; end; function THashTable.IndexOf(const S: PChar; var I: Integer): Boolean; var N: Integer; begin result := false; N := HashFunction(S, TableSize); I := N; while I < TableSize do begin if A[I] = nil then begin LastIndex := I; result := false; Exit; end else if StrComp(A[I].Key, S) = 0 then begin LastIndex := I; result := true; Exit; end; Inc(I); end; I := 0; while I < N do begin if A[I] = nil then begin LastIndex := I; result := false; Exit; end else if StrComp(A[I].Key, S) = 0 then begin LastIndex := I; result := true; Exit; end; Inc(I); end; end; procedure THashTable.Clear; var I: Integer; begin Card := 0; for I:=0 to TableSize - 1 do if A[I] <> nil then begin StrDispose(A[I].Key); FreeAndNil(A[I]); end; end; //-- TJS_PropList -------------------------------------------------------------- constructor TJS_PropList.Create(i_Owner: TJS_Object); begin inherited Create; Owner := i_Owner; HashTable := THashTable.Create; CardArr := 0; end; destructor TJS_PropList.Destroy; begin Clear; FreeAndNil(HashTable); inherited; end; procedure TJS_PropList.Clear; begin HashTable.Clear; end; procedure TJS_PropList.SetArrLength(N: Integer); begin CardArr := N; SetLength(Arr, CardArr); SetLength(AvailArrIndex, CardArr); end; function TJS_PropList.GetArrProperty(PropName: Integer): PVariant; begin if PropName >= 0 then begin if owner.typ = TYP_JS_ARRAY then begin if CardArr <= PropName then SetArrLength(PropName + Delta); result := @ Arr[PropName]; end else begin if CardArr <= PropName then SetArrLength(PropName + Delta); if AvailArrIndex[PropName] then begin result := @ Arr[PropName]; Exit; end; if owner.prototype <> nil then begin if owner.prototype.L.CardArr <= PropName then owner.prototype.L.SetArrLength(PropName + Delta); if owner.prototype.L.AvailArrIndex[PropName] then begin result := @ owner.prototype.L.Arr[PropName]; Exit; end; end; if TJS_Object(owner.prog.JS_Object).prototype.L.CardArr <= PropName then TJS_Object(owner.prog.JS_Object).prototype.L.SetArrLength(PropName + Delta); if TJS_Object(owner.prog.JS_Object).prototype.L.AvailArrIndex[PropName] then begin result := @ TJS_Object(owner.prog.JS_Object).prototype.L.Arr[PropName]; Exit; end; result := @ Arr[PropName]; AvailArrIndex[PropName] := true; end; end else result := GetProperty(PChar(IntToStr(PropName))); end; procedure TJS_PropList.PutArrProperty(PropName: Integer; const Value: Variant); begin if PropName >= 0 then begin if CardArr <= PropName then SetArrLength(PropName + Delta); Arr[PropName] := Value; AvailArrIndex[PropName] := true; end else PutProperty(PChar(IntToStr(PropName)), Value); end; function TJS_PropList.IndexOfProperty(PropName: PChar; var I: Integer; var PositiveInt: Boolean): Boolean; var b: Boolean; begin if PositiveInt then b := true else b := IsPositiveInt(PropName); if b then begin PositiveInt := true; I := StrToInt(PropName); if CardArr <= I then SetArrLength(I + Delta); if Owner.Typ = TYP_JS_ARRAY then result := true else result := AvailArrIndex[I]; Exit; end; PositiveInt := false; result := HashTable.IndexOf(PropName, I); end; procedure TJS_PropList.PutProperty(PropName: PChar; const Value: Variant); var R: TJS_PropRec; I: Integer; PositiveInt: Boolean; begin PositiveInt := false; if IndexOfProperty(PropName, I, PositiveInt) then begin if PositiveInt then Arr[I] := Value else HashTable.A[I].Value := Value; end else begin if PositiveInt then Arr[I] := Value else begin R := TJS_PropRec.Create; R.Key := StrAlloc(StrLen(PropName) + 1); StrCopy(R.Key, PropName); R.Value := Value; HashTable.A[I] := R; Inc(HashTable.Card); end; end; end; function TJS_PropList.GetProperty(PropName: PChar): PVariant; var R: TJS_PropRec; I: Integer; PositiveInt: Boolean; X: TJS_Object; begin { JS_MATH_LN10 = 20; JS_MATH_LN2 = 21; JS_MATH_LOG2E = 22; JS_MATH_LOG10E = 23; JS_MATH_SQRT1_2 = 24; JS_MATH_SQRT2 = 25; } case owner.typ of TYP_JS_MATH: case PropName[0] of 'a': case PropName[1] of 'b': if PropName[2] = 's' then if PropName[3] = #0 then // 'abs' begin result := @ HashTable.A[JS_MATH_ABS].Value; Exit; end; 'c': if PropName[2] = 'o' then if PropName[3] = 's' then if PropName[4] = #0 then // 'acos' begin result := @ HashTable.A[JS_MATH_ACOS].Value; Exit; end; 's': if PropName[2] = 'i' then if PropName[3] = 'n' then if PropName[4] = #0 then // 'asin' begin result := @ HashTable.A[JS_MATH_ASIN].Value; Exit; end; 't': // PropName[1] if PropName[2] = 'a' then if PropName[3] = 'n' then begin if PropName[4] = #0 then // 'atan' begin result := @ HashTable.A[JS_MATH_ATAN].Value; Exit; end else if PropName[4] = '2' then if PropName[5] = #0 then // 'atan2' begin result := @ HashTable.A[JS_MATH_ATAN2].Value; Exit; end; end; end; 'c': case PropName[1] of 'e': if PropName[2] = 'i' then if PropName[3] = 'l' then if PropName[4] = #0 then // 'ceil' begin result := @ HashTable.A[JS_MATH_CEIL].Value; Exit; end; 'o': if PropName[2] = 's' then if PropName[3] = #0 then // 'cos' begin result := @ HashTable.A[JS_MATH_COS].Value; Exit; end; end; 'e': if StrComp(PropName, 'exp') = 0 then begin result := @ HashTable.A[JS_MATH_EXP].Value; Exit; end; 'f': if StrComp(PropName, 'floor') = 0 then begin result := @ HashTable.A[JS_MATH_FLOOR].Value; Exit; end; 'l': if PropName[1] = 'o' then if PropName[2] = 'g' then if PropName[3] = #0 then // 'log' begin result := @ HashTable.A[JS_MATH_LOG].Value; Exit; end; 'm': case PropName[1] of 'a': if StrComp(PropName, 'max') = 0 then begin result := @ HashTable.A[JS_MATH_MAX].Value; Exit; end; 'i': if StrComp(PropName, 'min') = 0 then begin result := @ HashTable.A[JS_MATH_MIN].Value; Exit; end; end; 'p': if StrComp(PropName, 'pow') = 0 then begin result := @ HashTable.A[JS_MATH_POW].Value; Exit; end; 'r': case PropName[1] of 'a': if StrComp(PropName, 'random') = 0 then begin result := @ HashTable.A[JS_MATH_RANDOM].Value; Exit; end; 'o': if StrComp(PropName, 'round') = 0 then begin result := @ HashTable.A[JS_MATH_ROUND].Value; Exit; end; end; 's': case PropName[1] of 'i': if StrComp(PropName, 'sin') = 0 then begin result := @ HashTable.A[JS_MATH_SIN].Value; Exit; end; 'q': if StrComp(PropName, 'sqrt') = 0 then begin result := @ HashTable.A[JS_MATH_SQRT].Value; Exit; end; end; 't': if StrComp(PropName, 'tan') = 0 then begin result := @ HashTable.A[JS_MATH_TAN].Value; Exit; end; 'P': if StrComp(PropName, 'PI') = 0 then begin result := @ HashTable.A[JS_MATH_PI].Value; Exit; end; 'E': if PropName[1] = #0 then begin result := @ HashTable.A[JS_MATH_E].Value; Exit; end; end; // end of math end; PositiveInt := false; if IndexOfProperty(PropName, I, PositiveInt) then begin if PositiveInt then result := @ Arr[I] else result := @ HashTable.A[I].Value; end else begin R := nil; // find property in prototype chain X := owner.prototype; while X <> nil do begin if X.L.IndexOfProperty(PropName, I, PositiveInt) then begin if PositiveInt then begin result := @ X.L.Arr[I]; Exit; end; R := HashTable.A[I]; break; end; X := X.prototype; end; if R = nil then begin case owner.typ of TYP_JS_BOOLEAN: X := TJS_Object(owner.prog.JS_Boolean).prototype; TYP_JS_STRING: X := TJS_Object(owner.prog.JS_String).prototype; TYP_JS_NUMBER: X := TJS_Object(owner.prog.JS_Number).prototype; TYP_JS_DATE: X := TJS_Object(owner.prog.JS_Date).prototype; TYP_JS_FUNCTION: X := TJS_Object(owner.prog.JS_Function).prototype; TYP_JS_ARRAY: X := TJS_Object(owner.prog.JS_Array).prototype; TYP_JS_REGEXP: X := TJS_Object(owner.prog.JS_RegExp).prototype; TYP_JS_ERROR: X := TJS_Object(owner.prog.JS_Error).prototype; else X := nil; end; if X <> nil then if X.L.IndexOfProperty(PropName, I, PositiveInt) then begin if PositiveInt then begin result := @ X.L.Arr[I]; Exit; end; R := X.L.HashTable.A[I]; end; if R = nil then begin X := TJS_Object(owner.prog.JS_Object).prototype; if X.L.IndexOfProperty(PropName, I, PositiveInt) then begin if PositiveInt then begin result := @ X.L.Arr[I]; Exit; end; R := X.L.HashTable.A[I]; end; end; end; if R = nil then result := @ Undefined else result := @ R.Value; end; end; function TJS_PropList.HasProperty(PropName: PChar): Boolean; begin LastPropAddress := GetProperty(PropName); result := LastPropAddress <> (@ Undefined); end; // -- TJS_Reference ------------------------------------------------------------ constructor TJS_Reference.Create(AFinTypeId: Integer); begin inherited Create; FinTypeId := AFinTypeId; end; function TJS_Reference.GetValue(): Variant; begin result := GetVariantValue(Address, FinTypeId); end; function TJS_Reference.GetValueAsObject(): TJS_Object; begin result := TJS_Object(TVarData(Address^).VInteger); end; procedure TJS_Reference.PutValue(const value: Variant); begin PutVariantValue(Address, FinTypeId, value); end; function TJS_Reference.__toString: String; begin result := ''; end; function JS_IsRef(const V: Variant): Boolean; var X: TJS_ObjectBase; VT: Word; begin VT := TVarData(V).VType; if VT = varClass then begin X := TJS_ObjectBase(TVarData(V).VInteger); result := X is TJS_Reference; end else result := false; end; function JS_GetValue(const V: Variant): Variant; begin if JS_IsRef(V) then result := TJS_Reference(TVarData(V).VInteger).GetValue() else result := V; end; procedure JS_PutValue(const V: Variant; const value: Variant); begin if not JS_IsRef(V) then RaiseError(errReferenceError, []); TJS_Reference(TVarData(V).VInteger).PutValue(value); end; //-- TJS_ObjectBase ------------------------------------------------------------ function TJS_ObjectBase.GetGC: TGC; begin result := nil; RaiseError(errInternalError, []); end; //-- TJS_Object ---------------------------------------------------------------- constructor TJS_Object.Create; begin inherited; Typ := TYP_JS_OBJECT; L := TJS_PropList.Create(Self); prototype := nil; Tag := 0; prog := nil; aconstructor := nil; NextPropIndex := -1; end; destructor TJS_Object.Destroy; begin FreeAndNil(L); inherited; end; function TJS_Object.__toString: String; begin result := 'Object[]'; end; function TJS_Object.GetConstructor: TJS_Object; var X: TJS_Object; begin if aconstructor <> nil then begin result := aconstructor; Exit; end; X := Self.prototype; while X <> nil do begin if X.aconstructor <> nil then begin result := X.aconstructor; Exit; end; X := X.prototype; end; result := nil; end; procedure TJS_Object.PutProperty(PropName: PChar; const Value: Variant); begin L.PutProperty(PropName, Value); end; function TJS_Object.HasProperty(PropName: PChar): Boolean; begin result := L.HasProperty(PropName); end; function TJS_Object.GetProperty(PropName: PChar): Variant; var P: Pointer; begin P := L.GetProperty(PropName); if TVarData(P^).VType = varClass then begin TVarData(result).VType := varClass; TVarData(result).VInteger := TVarData(P^).VInteger; end else result := Variant(P^); end; function TJS_Object.GetVarProperty(const PropName: Variant): Variant; var S: String; begin S := JS_ToString(PropName); result := GetProperty(PChar(S)); end; procedure TJS_Object.PutVarProperty(const PropName: Variant; const Value: Variant); var S: String; begin S := JS_ToString(PropName); PutProperty(PChar(S), Value); end; function TJS_Object.GetPropertyAsObject(PropName: PChar): TJS_Object; begin result := TObject(TVarData(L.GetProperty(PropName)^).VInteger) as TJS_Object; if result = nil then RaiseError(errPropertyNotFound, [String(PropName)]); end; procedure TJS_Object.PutArrProperty(PropName: Integer; const Value: Variant); begin if PropName >= fLength then fLength := PropName + 1; L.PutArrProperty(PropName, Value); end; function TJS_Object.GetArrProperty(PropName: Integer): Variant; begin if PropName >= fLength then fLength := PropName + 1; result := L.GetArrProperty(PropName)^; end; procedure TJS_Object.AddToGC; begin if prog = nil then RaiseError(errInternalError, []); prog.RootGC.AddObject(Self); end; function TJS_Object.GetGC: TGC; begin if prog = nil then RaiseError(errInternalError, []); result := TBaseRunner(prog).RootGC; end; //-- TJS_Date ------------------------------------------------------------------ function IsDateObject(const V: Variant): Boolean; begin result := TVarData(V).VType = varClass; if result then result := TObject(TVarData(V).VInteger).ClassType = TJS_Date; end; function VariantToDateObject(const V: Variant): TJS_Date; begin result := TJS_Date(TVarData(V).VInteger); end; function _Floor(X: Extended): Int64; begin result := Trunc(X); if Frac(X) < 0 then Dec(result); end; function DelphiDateTimeToEcmaTime(const AValue: TDateTime): Double; var T: TTimeStamp; D1970: TDateTime; begin D1970 := EncodeDate(1970,1,1); T := DateTimeToTimeStamp(AValue); Result := (_Floor(AValue) - _Floor(D1970)) * MSecsPerDay + T.Time; end; function EcmaTimeToDelphiDateTime(const AValue: Variant): TDateTime; var TimeStamp: TTimeStamp; D1970: TDateTime; begin D1970 := EncodeDate(1970,1,1); TimeStamp := DateTimeToTimeStamp(D1970); TimeStamp.Time := _Floor(AValue) mod MSecsPerDay; TimeStamp.Date := TimeStamp.Date + _Floor(AValue) div MSecsPerDay; result := TimeStampToDateTime(TimeStamp); end; {$IFDEF PAXARM} function GetGMTDifference: Double; begin result := 0; end; {$ELSE} {$IFDEF LINUX} function GetGMTDifference: Double; begin result := 0; end; {$ELSE} {$IFDEF MACOS32} function GetGMTDifference: Double; begin result := 0; end; {$ELSE} function GetGMTDifference: Double; var TZ: TTimeZoneInformation; begin GetTimeZoneInformation(TZ); if TZ.Bias = 0 then Result := 0 else if TZ.Bias < 0 then begin if TZ.Bias mod 60 = 0 then Result := Abs(TZ.Bias) div 60 else Result := Abs(TZ.Bias) / 60; end else begin if TZ.Bias mod 60 = 0 then Result := - TZ.Bias div 60 else Result := - TZ.Bias / 60; end; end; {$ENDIF} {$ENDIF} {$ENDIF} constructor TJS_Date.Create(Year: PVariant = nil; Month: PVariant = nil; Day: PVariant = nil; Hours: PVariant = nil; Minutes: PVariant = nil; Seconds: PVariant = nil; Ms: PVariant = nil); begin inherited Create; Typ := TYP_JS_DATE; DelphiDate := 0; if Empty(Year) then begin DelphiDate := Now; end else if Empty(Month) then begin DelphiDate := EncodeDate(Year^, 1, 1); end else if Empty(Day) then begin DelphiDate := EncodeDate(Year^, Month^, 1); end else if Empty(Hours) then begin DelphiDate := EncodeDate(Year^, Month^, Day^); end else if Empty(Minutes) then begin DelphiDate := EncodeDate(Year^, Month^, Day^); setHours(Hours^, 0, 0 , 0); end else if Empty(Seconds) then begin DelphiDate := EncodeDate(Year^, Month^, Day^); setMinutes(Minutes^, 0 , 0); end else begin DelphiDate := EncodeDate(Year^, Month^, Day^); setSeconds(Seconds^, 0); end; fDefaultValue := DelphiDate; end; function TJS_Date.UTCDelphiDate: TDateTime; var Diff: Integer; begin Diff := Floor(GetGMTDifference); result := EcmaTimeToDelphiDateTime(GetValue - MSecsPerHour * Diff); end; function TJS_Date.DelphiDateFromUTCDate(D: TDateTime): TDateTime; var T: Double; Diff: Integer; begin T := DelphiDateTimeToEcmaTime(D); Diff := Floor(GetGMTDifference); result := EcmaTimeToDelphiDateTime(T + MSecsPerHour * Diff); end; function TJS_Date.GetValue: Variant; begin result := DelphiDateTimeToEcmaTime(DelphiDate); end; function TJS_Date._toString: Variant; stdcall; begin result := JS_ToString(DelphiDate); end; function TJS_Date.__toString: String; begin result := _toString(); end; function TJS_Date.toGMTString: Variant; stdcall; begin result := JS_ToString(UTCDelphiDate); end; function TJS_Date.getTime: Variant; stdcall; begin result := JS_ToNumber(GetValue); end; function TJS_Date.getFullYear: Variant; stdcall; var Year, Month, Day: Word; begin DecodeDate(DelphiDate, Year, Month, Day); result := Integer(Year); end; function TJS_Date.getUTCFullYear: Variant; stdcall; var Year, Month, Day: Word; begin DecodeDate(UTCDelphiDate, Year, Month, Day); result := Integer(Year); end; function TJS_Date.getMonth: Variant; stdcall; var Year, Month, Day: Word; begin DecodeDate(DelphiDate, Year, Month, Day); result := Integer(Month); end; function TJS_Date.getUTCMonth: Variant; stdcall; var Year, Month, Day: Word; begin DecodeDate(UTCDelphiDate, Year, Month, Day); result := Integer(Month); end; function TJS_Date.getDate: Variant; stdcall; var Year, Month, Day: Word; begin DecodeDate(DelphiDate, Year, Month, Day); result := Integer(Day); end; function TJS_Date.getUTCDate: Variant; stdcall; var Year, Month, Day: Word; begin DecodeDate(UTCDelphiDate, Year, Month, Day); result := Integer(Day); end; function TJS_Date.getDay: Variant; stdcall; begin result := DayOfWeek(DelphiDate) - 1; end; function TJS_Date.getUTCDay: Variant; stdcall; begin result := DayOfWeek(UTCDelphiDate) - 1; end; function TJS_Date.getHours: Variant; stdcall; var Hour, Min, Sec, MSec: Word; begin DecodeTime(DelphiDate, Hour, Min, Sec, MSec); result := Integer(Hour); end; function TJS_Date.getUTCHours: Variant; stdcall; var Hour, Min, Sec, MSec: Word; begin DecodeTime(UTCDelphiDate, Hour, Min, Sec, MSec); result := Integer(Hour); end; function TJS_Date.getMinutes: Variant; stdcall; var Hour, Min, Sec, MSec: Word; begin DecodeTime(DelphiDate, Hour, Min, Sec, MSec); result := Integer(Min); end; function TJS_Date.getUTCMinutes: Variant; stdcall; var Hour, Min, Sec, MSec: Word; begin DecodeTime(UTCDelphiDate, Hour, Min, Sec, MSec); result := Integer(Min); end; function TJS_Date.getSeconds: Variant; stdcall; var Hour, Min, Sec, MSec: Word; begin DecodeTime(DelphiDate, Hour, Min, Sec, MSec); result := Integer(Sec); end; function TJS_Date.getUTCSeconds: Variant; stdcall; var Hour, Min, Sec, MSec: Word; begin DecodeTime(UTCDelphiDate, Hour, Min, Sec, MSec); result := Integer(Sec); end; function TJS_Date.getMilliseconds: Variant; stdcall; var Hour, Min, Sec, MSec: Word; begin DecodeTime(DelphiDate, Hour, Min, Sec, MSec); result := Integer(MSec); end; function TJS_Date.getUTCMilliseconds: Variant; stdcall; var Hour, Min, Sec, MSec: Word; begin DecodeTime(DelphiDate, Hour, Min, Sec, MSec); result := Integer(MSec); end; function TJS_Date.setTime(const P: Variant): Variant; stdcall; begin result := JS_ToNumber(P); DelphiDate := EcmaTimeToDelphiDateTime(result); end; function TJS_Date.setMilliseconds(const ms: Variant): Variant; stdcall; var aHour, aMin, aSec, aMsec: Word; begin DecodeTime(DelphiDate, aHour, aMin, aSec, aMsec); if VarType(ms) <> varEmpty then aMsec := JS_ToInt32(ms); DelphiDate := EncodeTime(aHour, aMin, aSec, aMsec); result := GetValue; end; function TJS_Date.setUTCMilliseconds(const ms: Variant): Variant; stdcall; var aHour, aMin, aSec, aMsec: Word; begin DecodeTime(UTCDelphiDate, aHour, aMin, aSec, aMsec); if VarType(ms) <> varEmpty then aMsec := JS_ToInt32(ms); DelphiDate := EncodeTime(aHour, aMin, aSec, aMsec); DelphiDate := DelphiDateFromUTCDate(DelphiDate); result := GetValue; end; function TJS_Date.setSeconds(const sec, ms: Variant): Variant; stdcall; var aHour, aMin, aSec, aMsec: Word; begin DecodeTime(DelphiDate, aHour, aMin, aSec, aMsec); if VarType(sec) <> varEmpty then aSec := JS_ToInt32(sec); if VarType(ms) <> varEmpty then aMsec := JS_ToInt32(ms); DelphiDate := EncodeTime(aHour, aMin, aSec, aMsec); result := GetValue; end; function TJS_Date.setUTCSeconds(const sec, ms: Variant): Variant; stdcall; var aHour, aMin, aSec, aMsec: Word; begin DecodeTime(UTCDelphiDate, aHour, aMin, aSec, aMsec); if VarType(sec) <> varEmpty then aSec := JS_ToInt32(sec); if VarType(ms) <> varEmpty then aMsec := JS_ToInt32(ms); DelphiDate := EncodeTime(aHour, aMin, aSec, aMsec); DelphiDate := DelphiDateFromUTCDate(DelphiDate); result := GetValue; end; function TJS_Date.setMinutes(const min, sec, ms: Variant): Variant; stdcall; var aHour, aMin, aSec, aMsec: Word; begin DecodeTime(DelphiDate, aHour, aMin, aSec, aMsec); if VarType(min) <> varEmpty then aMin := JS_ToInt32(min); if VarType(sec) <> varEmpty then aSec := JS_ToInt32(sec); if VarType(ms) <> varEmpty then aMsec := JS_ToInt32(ms); DelphiDate := EncodeTime(aHour, aMin, aSec, aMsec); result := GetValue; end; function TJS_Date.setUTCMinutes(const min, sec, ms: Variant): Variant; stdcall; var aHour, aMin, aSec, aMsec: Word; begin DecodeTime(UTCDelphiDate, aHour, aMin, aSec, aMsec); if VarType(min) <> varEmpty then aMin := JS_ToInt32(min); if VarType(sec) <> varEmpty then aSec := JS_ToInt32(sec); if VarType(ms) <> varEmpty then aMsec := JS_ToInt32(ms); DelphiDate := EncodeTime(aHour, aMin, aSec, aMsec); DelphiDate := DelphiDateFromUTCDate(DelphiDate); result := GetValue; end; function TJS_Date.setHours(const hour, min, sec, ms: Variant): Variant; stdcall; var aHour, aMin, aSec, aMsec: Word; begin DecodeTime(DelphiDate, aHour, aMin, aSec, aMsec); if VarType(hour) <> varEmpty then aHour := JS_ToInt32(hour); if VarType(min) <> varEmpty then aMin := JS_ToInt32(min); if VarType(sec) <> varEmpty then aSec := JS_ToInt32(sec); if VarType(ms) <> varEmpty then aMsec := JS_ToInt32(ms); DelphiDate := EncodeTime(aHour, aMin, aSec, aMsec); result := GetValue; end; function TJS_Date.setUTCHours(const hour, min, sec, ms: Variant): Variant; stdcall; var aHour, aMin, aSec, aMsec: Word; begin DecodeTime(UTCDelphiDate, aHour, aMin, aSec, aMsec); if VarType(hour) <> varEmpty then aHour := JS_ToInt32(hour); if VarType(min) <> varEmpty then aMin := JS_ToInt32(min); if VarType(sec) <> varEmpty then aSec := JS_ToInt32(sec); if VarType(ms) <> varEmpty then aMsec := JS_ToInt32(ms); DelphiDate := EncodeTime(aHour, aMin, aSec, aMsec); DelphiDate := DelphiDateFromUTCDate(DelphiDate); result := GetValue; end; function TJS_Date.setDate(const date: Variant): Variant; stdcall; var aYear, aMonth, aDay: Word; begin DecodeDate(DelphiDate, aYear, aMonth, aDay); result := GetValue; end; //-- TJS_Array ----------------------------------------------------------------- constructor TJS_Array.Create(const V: array of Variant); var I, L: Integer; begin inherited Create; Typ := TYP_JS_ARRAY; L := System.Length(V); if L = 0 then Length := 0 else if L = 1 then Length := V[0] else for I := 0 to L - 1 do PutArrProperty(I, V[I]); end; destructor TJS_Array.Destroy; begin inherited; end; function TJS_Array.GetLength: Integer; begin result := fLength; end; procedure TJS_Array.SetLength(value: Integer); begin L.SetArrLength(value); fLength := value; end; function TJS_Array._toString: Variant; stdcall; var I: Integer; V: Variant; begin result := '['; for I := 0 to fLength - 1 do begin V := GetArrProperty(I); result := result + JS_ToString(V); if I < fLength - 1 then result := result + ','; end; result := result + ']'; end; function TJS_Array.__toString: String; begin result := _toString(); end; function TJS_Array._pop: Variant; stdcall; begin result := GetArrProperty(fLength - 1); SetLength(fLength - 1); end; function TJS_Array._push(P0: PVariant; P1: PVariant = nil; P2: PVariant = nil; P3: PVariant = nil; P4: PVariant = nil; P5: PVariant = nil; P6: PVariant = nil; P7: PVariant = nil; P8: PVariant = nil; P9: PVariant = nil): Variant; stdcall; begin SetLength(fLength + 1); PutArrProperty(fLength - 1, P0^); if Empty(P1) then begin result := fLength; Exit; end; SetLength(fLength + 1); PutArrProperty(fLength - 1, P1^); if Empty(P2) then begin result := fLength; Exit; end; SetLength(fLength + 1); PutArrProperty(fLength - 1, P2^); if Empty(P3) then begin result := fLength; Exit; end; SetLength(fLength + 1); PutArrProperty(fLength - 1, P3^); if Empty(P4) then begin result := fLength; Exit; end; SetLength(fLength + 1); PutArrProperty(fLength - 1, P4^); if Empty(P5) then begin result := fLength; Exit; end; SetLength(fLength + 1); PutArrProperty(fLength - 1, P5^); if Empty(P6) then begin result := fLength; Exit; end; SetLength(fLength + 1); PutArrProperty(fLength - 1, P6^); if Empty(P7) then begin result := fLength; Exit; end; SetLength(fLength + 1); PutArrProperty(fLength - 1, P7^); if Empty(P8) then begin result := fLength; Exit; end; SetLength(fLength + 1); PutArrProperty(fLength - 1, P8^); if Empty(P9) then begin result := fLength; Exit; end; SetLength(fLength + 1); PutArrProperty(fLength - 1, P9^); end; //-- TJS_Error ----------------------------------------------------------------- constructor TJS_Error.Create(P: PVariant = nil); begin inherited Create; Typ := TYP_JS_ERROR; if Empty(P) then fDefaultValue := '' else fDefaultValue := JS_ToString(P^); end; function TJS_Error._toString: Variant; stdcall; begin result := fDefaultValue; end; function TJS_Error.__toString: String; begin result := _toString(); end; //-- TJS_Boolean --------------------------------------------------------------- constructor TJS_Boolean.Create(P: PVariant = nil); begin inherited Create; Typ := TYP_JS_BOOLEAN; if Empty(P) then fDefaultValue := false else fDefaultValue := JS_ToBoolean(P^); end; function TJS_Boolean._toString: Variant; stdcall; begin if fDefaultValue then result := 'true' else result := 'false'; end; function TJS_Boolean.__toString: String; begin result := _toString(); end; //-- TJS_Number ---------------------------------------------------------------- constructor TJS_Number.Create(P: PVariant = nil); begin inherited Create; Typ := TYP_JS_NUMBER; if Empty(P) then fDefaultValue := Undefined else fDefaultValue := JS_ToNumber(P^); end; function TJS_Number._toString(): Variant; stdcall; begin result := JS_ToString(fDefaultValue); end; function TJS_Number.__toString(): String; begin result := _toString(); end; //-- TJS_String ---------------------------------------------------------------- constructor TJS_String.Create(P: PVariant = nil); begin inherited Create; Typ := TYP_JS_STRING; if Empty(P) then fDefaultValue := '' else fDefaultValue := JS_ToString(P^); end; function TJS_String._toString: Variant; stdcall; begin result := fDefaultValue; end; function TJS_String.__toString: String; begin result := _toString(); end; function TJS_String._valueOf: Variant; stdcall; begin result := fDefaultValue; end; function TJS_String._length: Variant; stdcall; begin result := Length(fDefaultValue); end; function TJS_String._charAt(const P: Variant): Variant; stdcall; var I: Integer; begin result := ''; I := JS_ToInt32(P); if I < 0 then Exit; if I >= Length(fDefaultValue) then Exit; result := fDefaultValue[I + 1]; end; function TJS_String._charCodeAt(const P: Variant): Variant; stdcall; var I: Integer; begin result := -1; I := JS_ToInt32(P); if I < 0 then Exit; if I >= Length(fDefaultValue) then Exit; result := ord(String(fDefaultValue)[I + 1]); end; function TJS_String._concat(P0: PVariant; P1: PVariant = nil; P2: PVariant = nil; P3: PVariant = nil; P4: PVariant = nil; P5: PVariant = nil; P6: PVariant = nil; P7: PVariant = nil; P8: PVariant = nil; P9: PVariant = nil): Variant; stdcall; begin result := fDefaultValue; if Empty(P0) then Exit; result := result + JS_ToString(P0^); if Empty(P1) then Exit; result := result + JS_ToString(P1^); if Empty(P2) then Exit; result := result + JS_ToString(P2^); if Empty(P3) then Exit; result := result + JS_ToString(P3^); if Empty(P4) then Exit; result := result + JS_ToString(P4^); if Empty(P5) then Exit; result := result + JS_ToString(P5^); if Empty(P6) then Exit; result := result + JS_ToString(P6^); if Empty(P7) then Exit; result := result + JS_ToString(P7^); if Empty(P8) then Exit; result := result + JS_ToString(P8^); if Empty(P9) then Exit; result := result + JS_ToString(P9^); end; function TJS_String._fromCharCode(P0: PVariant; P1: PVariant = nil; P2: PVariant = nil; P3: PVariant = nil; P4: PVariant = nil; P5: PVariant = nil; P6: PVariant = nil; P7: PVariant = nil; P8: PVariant = nil; P9: PVariant = nil): Variant; stdcall; var B: Byte; begin result := ''; if Empty(P0) then Exit; B := JS_ToInt32(P0^); result := result + Chr(B); if Empty(P1) then Exit; B := JS_ToInt32(P1^); result := result + Chr(B); if Empty(P2) then Exit; B := JS_ToInt32(P2^); result := result + Chr(B); if Empty(P3) then Exit; B := JS_ToInt32(P3^); result := result + Chr(B); if Empty(P4) then Exit; B := JS_ToInt32(P4^); result := result + Chr(B); if Empty(P5) then Exit; B := JS_ToInt32(P5^); result := result + Chr(B); if Empty(P6) then Exit; B := JS_ToInt32(P6^); result := result + Chr(B); if Empty(P7) then Exit; B := JS_ToInt32(P7^); result := result + Chr(B); if Empty(P8) then Exit; B := JS_ToInt32(P8^); result := result + Chr(B); if Empty(P9) then Exit; B := JS_ToInt32(P9^); result := result + Chr(B); end; function TJS_String._slice(const VStart, VEnd: Variant): Variant; stdcall; var S: String; IStart, IEnd, L: Integer; begin S := fDefaultValue; L := Length(S); if Empty(@VStart) then begin IStart := 0; IEnd := L - 1; end else if Empty(@VEnd) then begin IStart := JS_ToInt32(VStart); if IStart < 0 then IStart := IStart + L; IEnd := L - 1; end else begin IStart := JS_ToInt32(VStart); IEnd := JS_ToInt32(VEnd); if IStart < 0 then IStart := IStart + L; if IEnd < 0 then IEnd := IEnd + L; end; L := IEnd - IStart + 1; if L > 0 then result := Copy(S, IStart, L); end; function TJS_String._substr(const VStart, VLength: Variant): Variant; stdcall; var S: String; I, L: Integer; begin S := fDefaultValue; I := 1; L := Length(S); if not Empty(@VStart) then I := JS_ToInt32(VStart); if not Empty(@VLength) then L := JS_ToInt32(VLength); result := Copy(S, I + 1, L); end; function TJS_String._substring(const VStart, VLength: Variant): Variant; stdcall; var S: String; I, L: Integer; begin S := fDefaultValue; I := 1; L := Length(S); if not Empty(@VStart) then I := JS_ToInt32(VStart); if not Empty(@VLength) then L := JS_ToInt32(VLength); result := Copy(S, I + 1, L); end; function TJS_String._indexOf(const P: Variant): Variant; stdcall; var I: Integer; S, Q: String; begin result := Integer(-1); S := fDefaultValue; Q := JS_ToString(P); I := Pos(Q, S); if I = 0 then Exit; result := I - 1; end; function TJS_String._lastIndexOf(const P: Variant): Variant; stdcall; var I, L: Integer; S, Q: String; begin result := Integer(-1); S := fDefaultValue; Q := JS_ToString(P); L := Length(Q); for I:=Length(S) - L downto 1 do if Copy(S, I, L) = Q then begin result := I - 1; Exit; end; end; function TJS_String._anchor(const P: Variant): Variant; stdcall; begin result := '<A NAME="' + JS_ToString(P) + '">' + fDefaultValue + '</A>'; end; function TJS_String._link(const P: Variant): Variant; stdcall; begin result := '<A HREF="' + JS_ToString(P) + '">' + fDefaultValue + '</A>'; end; function TJS_String._big: Variant; stdcall; begin result := '<BIG>' + fDefaultValue + '</BIG>'; end; function TJS_String._small: Variant; stdcall; begin result := '<SMALL>' + fDefaultValue + '</SMALL>'; end; function TJS_String._blink: Variant; stdcall; begin result := '<BLINK>' + fDefaultValue + '</BLINK>'; end; function TJS_String._bold: Variant; stdcall; begin result := '<BOLD>' + fDefaultValue + '</BOLD>'; end; function TJS_String._italics: Variant; stdcall; begin result := '<I>' + fDefaultValue + '</I>'; end; function TJS_String._strike: Variant; stdcall; begin result := '<STRIKE>' + fDefaultValue + '</STRIKE>'; end; function TJS_String._sub: Variant; stdcall; begin result := '<SUB>' + fDefaultValue + '</SUB>'; end; function TJS_String._sup: Variant; stdcall; begin result := '<SUP>' + fDefaultValue + '</SUP>'; end; function TJS_String._fixed: Variant; stdcall; begin result := '<TT>' + fDefaultValue + '</TT>'; end; function TJS_String._fontcolor(const P: Variant): Variant; stdcall; begin result := '<FONT COLOR="' + JS_ToString(P) + '">' + fDefaultValue + '</A>'; end; function TJS_String._fontsize(const P: Variant): Variant; stdcall; begin result := '<FONT SIZE="' + JS_ToString(P) + '">' + fDefaultValue + '</A>'; end; function TJS_String._toUpperCase: Variant; stdcall; begin result := UpperCase(fDefaultValue); end; function TJS_String._toLowerCase: Variant; stdcall; begin result := LowerCase(fDefaultValue); end; function TJS_String._Replace(const SearchValue, ReplaceValue: Variant): Variant; stdcall; var SearchStr, ReplaceStr: Variant; X: TJS_ObjectBase; begin ReplaceStr := JS_ToString(ReplaceValue); if JS_IsObject(SearchValue) then begin X := TJS_ObjectBase(TVarData(SearchValue).VInteger); if X is TJS_Reference then X := (X as TJS_Reference).GetValueAsObject(); if X is TJS_RegExp then begin result := TJS_RegExp(X).Replace(fDefaultValue, ReplaceStr); end else begin SearchStr := VarToStr((X as TJS_Object).fDefaultValue); result := StringReplace(fDefaultValue, SearchStr, ReplaceStr, [rfReplaceAll]); end; end else begin SearchStr := VarToStr(SearchValue); result := StringReplace(fDefaultValue, SearchStr, ReplaceStr, [rfReplaceAll]); end; end; //-- TJS_Function -------------------------------------------------------------- constructor TJS_Function.InternalCreate(i_InternalFuncAddr: Pointer; i_NP: Integer; i_ProgPtr: Pointer); begin inherited Create; Typ := TYP_JS_FUNCTION; arguments := TJS_Array.Create([]); arguments.Length := MaxArgs; InternalFuncAddr := i_InternalFuncAddr; InternalLength := i_NP; if i_ProgPtr <> nil then begin Prog := TBaseRunner(i_ProgPtr^); if Prog.ProgTag = 1 then // adding global objects Prog.RootGC.AddObject(Self); end; __this := nil; CoolCall := 0; DefaultNP := 0; end; destructor TJS_Function.Destroy; begin FreeAndNil(arguments); inherited; end; function TJS_Function._toString: Variant; stdcall; begin result := 'Function[]'; end; function TJS_Function.__toString: String; begin result := _toString(); end; {$IFDEF PAXARM} function TJS_Function.Invoke(const Params: array of Variant): Variant; stdcall; begin end; {$ELSE} {$IFDEF PAX64} function TJS_Function.Invoke(const Params: array of Variant): Variant; stdcall; var I, NP: Integer; A: array of Pointer; begin NP := Length(Params); SetLength(A, NP); for I := 0 to NP - 1 do A[I] := @Params[I]; AssignRBX(InternalFuncAddr); Push_And_Call(NP, Self, Pointer(A), @result); end; {$ELSE} function TJS_Function.Invoke(const Params: array of Variant): Variant; stdcall; var NP: Integer; P, _Self, Res: Pointer; begin NP := Length(Params); _Self := Self; Res := @result; P := @Params; Inc(Integer(P), (NP - 1) * VARIANT_SIZE); if NP > 0 then asm // push parameters mov edx, P mov ecx, NP @@loop: push edx sub edx, VARIANT_SIZE sub ecx, 1 cmp ecx, 0 jnz @@loop end; asm push NP push _Self push Res call InternalCall end; end; {$ENDIF} {$ENDIF} {$IFDEF PAX64} procedure Push_And_Call(NP: Integer; Instance, Params, RetAdr: Pointer); assembler; asm // Address = rbx // np = rcx // instance = rdx // params = r8 // RetAddr = r9 push rbp sub rsp, $100 mov rbp, rsp cmp rcx, 0 jnz @@Par1 jmp @@Ret @@Par1: cmp rcx, 1 jnz @@Par2 mov rcx, rdx mov rdx, r9 mov r10, r8 mov r8, [r10] call rbx jmp @@Ret @@Par2: cmp rcx, 2 jnz @@Par3_or_More mov rcx, rdx mov rdx, r9 mov r10, r8 mov r8, [r10] add r10, 8 mov r9, [r10] call rbx jmp @@Ret @@Par3_or_More: mov r15, rcx mov rcx, rdx mov rdx, r9 mov r10, r8 mov r8, [r10] add r10, 8 mov r9, [r10] sub r15, 1 mov r11, $20 @@loop: add r10, 8 mov r14, [r10] mov [rsp + r11], r14 add r11, 8 sub r15, 1 jz @@Call jmp @@loop @@Call: call rbx @@Ret: mov rsp, rbp add rsp, $100 pop rbp ret end; procedure Push_And_Call2(NP: Integer; Instance, Params, RetAdr: Pointer); assembler; asm // Address = rbx // np = rcx // instance = rdx // params = r8 // RetAddr = r9 push rbp sub rsp, $100 mov rbp, rsp cmp rcx, 0 jnz @@Par1 jmp @@Ret @@Par1: cmp rcx, 1 jnz @@Par2 mov rcx, rdx mov rdx, r9 mov r10, r8 mov r8, r10 call rbx jmp @@Ret @@Par2: cmp rcx, 2 jnz @@Par3_or_More mov rcx, rdx mov rdx, r9 mov r10, r8 mov r8, r10 add r10, VARIANT_SIZE mov r9, r10 call rbx jmp @@Ret @@Par3_or_More: mov r15, rcx mov rcx, rdx mov rdx, r9 mov r10, r8 mov r8, r10 add r10, VARIANT_SIZE mov r9, r10 sub r15, 1 mov r11, $20 @@loop: add r10, VARIANT_SIZE mov r14, r10 mov [rsp + r11], r14 add r11, 8 sub r15, 1 jz @@Call jmp @@loop @@Call: call rbx @@Ret: mov rsp, rbp add rsp, $100 pop rbp ret end; procedure AssignRBX(P: Pointer); assembler; asm mov rbx, P end; procedure TJS_Function.InternalCall2(NP: Integer); var P, SelfPtr: Pointer; I: Integer; A: array[0..IntMaxArgs] of Variant; temp: Pointer; Q: PVariant; begin arguments.fLength := NP; temp := Pointer(Arguments.L.Arr); Pointer(Arguments.L.Arr) := @A; P := ParArr; for I:=0 to NP - 1 do begin Q := Pointer(P^); A[I] := Variant(Q^); Inc(IntPax(P), SizeOf(Pointer)); end; P := InternalFuncAddr; if __this <> nil then begin SelfPtr := __this; __this := nil; end else SelfPtr := Self; AssignRBX(P); Push_And_Call2(NP, Self, @ A, RetAdr); Pointer(Arguments.L.Arr) := temp; end; function TJS_Function.InternalCall(NP: Integer): Variant; stdcall; asm push rbp sub rsp, $100 mov rbp, rsp mov [rbp + $110], rcx // instance mov [rbp + $118], rdx // ret addr mov [rbp + $120], r8 // number of params mov [rbp + $128], r9 // first param mov r10, rcx add r10, RetAdr_OFFSET mov [r10], rdx mov r10, rcx add r10, ParArr_OFFSET mov r11, rbp add r11, $128 mov [r10], r11 mov rdx, r8 call TJS_Function.InternalCall2 lea rsp, [rbp + $100] pop rbp ret end; {$ELSE} {$IFDEF PAXARM} function TJS_Function.InternalCall(NP: Integer): Variant; stdcall; begin end; {$ELSE} function TJS_Function.InternalCall(NP: Integer): Variant; stdcall; var Params: Pointer; procedure Nested; var P, Q, ResPtr, arg_ptr, SelfPtr, temp: Pointer; I, NA: Integer; A: array[0..IntMaxArgs] of Variant; begin arguments.fLength := NP; temp := Pointer(Arguments.L.Arr); Pointer(Arguments.L.Arr) := @A; for I:=0 to NP - 1 do begin Inc(Integer(Params), 4); Q := Pointer(Params^); A[I] := Variant(Q^); end; // make call P := InternalFuncAddr; if __this <> nil then begin SelfPtr := __this; __this := nil; end else SelfPtr := Self; ResPtr := @Result; NA := InternalLength; if DefaultNP > 0 then NA := DefaultNP; arg_ptr := @A; Inc(Integer(arg_ptr), (NA - 1) * 16); if NA > 0 then asm // push parameters mov edx, arg_ptr mov ecx, NA @@loop: push edx sub edx, 16 sub ecx, 1 cmp ecx, 0 jnz @@loop end; asm // push self ptr push SelfPtr // push result ptr push ResPtr call P end; Pointer(Arguments.L.Arr) := temp; end; var RetSize: Integer; P: Pointer; begin if InternalFuncAddr = nil then Exit; case CoolCall of 1:if NP = InternalLength then // project2.dpr begin P := InternalFuncAddr; asm mov esp, ebp; pop esi // old ebp pop edi // ret addr pop ecx // result ptr pop edx // self pop eax // np push edx push ecx call P mov ebp, esi; jmp edi; end; end; // CoolCall = 1 end; asm mov Params, ebp; end; Inc(Integer(Params), 16); Nested; RetSize := 12 + NP * 4; asm // emulate ret RetSize mov ecx, RetSize mov esp, ebp pop ebp mov ebx, [esp] @@loop: pop edx sub ecx, 4 jnz @@loop pop edx jmp ebx end; end; {$ENDIF} {$ENDIF} //-- Math ---------------------------------------------------------------------- constructor TJS_Math.Create; begin inherited; Typ := TYP_JS_MATH; end; function TJS_Math._abs(const P: Variant): Variant; stdcall; var V: Variant; begin V := JS_ToNumber(P); if IsNaN(V) then result := NaN else if V >= 0 then result := V else result := - V; end; function TJS_Math._acos(const P: Variant): Variant; stdcall; var E: Extended; begin E := JS_ToNumberE(P); if IsNaN(E) then result := NaN else if E > 1 then result := NaN else if E < -1 then result := NaN else result := Math.ArcCos(E); end; function TJS_Math._asin(const P: Variant): Variant; stdcall; var E: Extended; begin E := JS_ToNumberE(P); if IsNaN(E) then result := NaN else if E > 1 then result := NaN else if E < -1 then result := NaN else result := Math.ArcSin(E); end; function TJS_Math._atan(const P: Variant): Variant; stdcall; var E: Extended; begin E := JS_ToNumberE(P); if IsNaN(E) then result := NaN else result := ArcTan(E); end; function TJS_Math._atan2(const X, Y: Variant): Variant; stdcall; var VX, VY: Extended; begin VX := JS_ToNumberE(X); VY := JS_ToNumberE(Y); if IsNaN(VX) then result := NaN else if IsNaN(VY) then result := NaN else result := Math.ArcTan2(VX, VY); end; function TJS_Math._ceil(const P: Variant): Variant; stdcall; var E: Extended; begin E := JS_ToNumberE(P); if IsNaN(E) then result := NaN else result := Math.Ceil(E); end; function TJS_Math._cos(const P: Variant): Variant; stdcall; var E: Extended; begin E := JS_ToNumberE(P); if IsNaN(E) then result := NaN else result := Cos(E); end; function TJS_Math._exp(const P: Variant): Variant; stdcall; var E: Extended; begin E := JS_ToNumberE(P); if IsNaN(E) then result := NaN else result := Exp(E); end; function TJS_Math._floor(const P: Variant): Variant; stdcall; var E: Extended; begin E := JS_ToNumberE(P); if IsNaN(E) then result := NaN else result := Math.Floor(E); end; function TJS_Math._log(const P: Variant): Variant; stdcall; var E: Extended; begin E := JS_ToNumberE(P); if IsNaN(E) then result := NaN else if E < 0 then result := NaN else if E = 0 then result := NegInfinity else result := ln(E); end; function TJS_Math._max(P1, P2, P3, P4, P5: PVariant): Variant; stdcall; var V: Extended; begin result := NegInfinity; if Empty(P1) then Exit; V := JS_ToNumber(P1^); if IsNan(V) then begin result := NaN; Exit; end; result := V; if Empty(P2) then Exit; V := JS_ToNumber(P2^); if IsNan(V) then begin result := NaN; Exit; end; if V > result then result := V; if Empty(P3) then Exit; V := JS_ToNumber(P3^); if IsNan(V) then begin result := NaN; Exit; end; if V > result then result := V; if Empty(P4) then Exit; V := JS_ToNumber(P4^); if IsNan(V) then begin result := NaN; Exit; end; if V > result then result := V; if Empty(P5) then Exit; V := JS_ToNumber(P5^); if IsNan(V) then begin result := NaN; Exit; end; if V > result then result := V; end; function TJS_Math._min(P1, P2, P3, P4, P5: PVariant): Variant; stdcall; var V: Extended; begin result := Infinity; if Empty(P1) then Exit; V := JS_ToNumber(P1^); if IsNan(V) then begin result := NaN; Exit; end; result := V; if Empty(P2) then Exit; V := JS_ToNumber(P2^); if IsNan(V) then begin result := NaN; Exit; end; if V < result then result := V; if Empty(P3) then Exit; V := JS_ToNumber(P3^); if IsNan(V) then begin result := NaN; Exit; end; if V < result then result := V; if Empty(P4) then Exit; V := JS_ToNumber(P4^); if IsNan(V) then begin result := NaN; Exit; end; if V < result then result := V; if Empty(P5) then Exit; V := JS_ToNumber(P5^); if IsNan(V) then begin result := NaN; Exit; end; if V < result then result := V; end; function TJS_Math._pow(const X, Y: Variant): Variant; stdcall; var VX, VY: Extended; begin VX := JS_ToNumberE(X); VY := JS_ToNumberE(Y); if IsNaN(VX) then result := NaN else if IsNaN(VY) then result := NaN else result := Math.Power(VX, VY); end; function TJS_Math._random: Variant; stdcall; begin result := Random(10000)/10000; end; function TJS_Math._round(const P: Variant): Variant; stdcall; var V: Extended; begin V := JS_ToNumberE(P); if IsNaN(V) then result := NaN else {$IFDEF VARIANTS} result := round(V); {$ELSE} result := Integer(round(V)); {$ENDIF} end; function TJS_Math._sin(const P: Variant): Variant; stdcall; var V: Extended; begin V := JS_ToNumberE(P); if IsNaN(V) then result := NaN else result := Sin(V); end; function TJS_Math._sqrt(const P: Variant): Variant; stdcall; var V: Extended; begin V := JS_ToNumberE(P); if IsNaN(P) then result := NaN else result := Sqrt(V); end; function TJS_Math._tan(const P: Variant): Variant; stdcall; var V: Extended; begin V := JS_ToNumberE(P); if IsNaN(V) then result := NaN else result := Math.tan(V); end; // TJS_RegExp ------------------------------------------------------------------ {$IFDEF PAXARM} constructor TJS_RegExp.Create(Source: PVariant = nil; Modifiers: PVariant = nil); begin inherited Create; Typ := TYP_JS_REGEXP; end; destructor TJS_RegExp.Destroy; begin inherited; end; function TJS_RegExp.GetMatch(I: Integer): String; begin result := ''; RIE; end; function TJS_RegExp.GetMatchLen(I: Integer): Integer; begin result := 0; RIE; end; function TJS_RegExp.GetMatchPos(I: Integer): Integer; begin result := 0; RIE; end; function TJS_RegExp.GetSource: Variant; begin RIE; end; procedure TJS_RegExp.SetSource(const Value: Variant); begin RIE; end; function TJS_RegExp.GetInput: Variant; begin RIE; end; procedure TJS_RegExp.SetInput(const Value: Variant); begin RIE; end; function TJS_RegExp.GetGlobal: Boolean; begin result := false; RIE; end; procedure TJS_RegExp.SetGlobal(const Value: Boolean); begin RIE; end; function TJS_RegExp.GetIgnoreCase: Boolean; begin result := false; RIE; end; procedure TJS_RegExp.SetIgnoreCase(const Value: Boolean); begin RIE; end; function TJS_RegExp.GetMultiLine: Boolean; begin result := false; RIE; end; procedure TJS_RegExp.SetMultiLine(const Value: Boolean); begin RIE; end; function TJS_RegExp.Test(const InputString: Variant): Boolean; begin result := false; RIE; end; procedure TJS_RegExp.Compile; begin RIE; end; function TJS_RegExp.Exec(const InputString: Variant): TJS_Array; begin RIE; result := nil; end; function TJS_RegExp.Execute(const InputString: Variant): TJS_Array; begin RIE; result := nil; end; function TJS_RegExp.MatchCount: Integer; begin result := 0; RIE; end; function TJS_RegExp.Replace(const Expression, ReplaceStr: Variant): String; begin RIE; end; function TJS_RegExp._toString: Variant; begin result := '/' + Source + '/'; if Global then result := result + 'g'; if IgnoreCase then result := result + 'i'; if MultiLine then result := result + 'm'; end; function TJS_RegExp.__toString: String; begin result := _toString(); end; {$ELSE} constructor TJS_RegExp.Create(Source: PVariant = nil; Modifiers: PVariant = nil); begin inherited Create; Typ := TYP_JS_REGEXP; fRegExpr := TRegExpr.Create; if Source <> nil then SetSource(Source^); fLastIndex := 1; if Modifiers = nil then Exit; if Length(Modifiers^) = 0 then begin Global := false; IgnoreCase := false; MultiLine := false; end else begin Global := PosCh('g', UpperCase(Modifiers^)) > 0; IgnoreCase := PosCh('i', UpperCase(Modifiers^)) > 0; MultiLine := PosCh('m', UpperCase(Modifiers^)) > 0; end; end; destructor TJS_RegExp.Destroy; begin FreeAndNil(fRegExpr); inherited; end; function TJS_RegExp.GetMatch(I: Integer): String; begin result := fRegExpr.Match[I]; end; function TJS_RegExp.GetMatchLen(I: Integer): Integer; begin result := fRegExpr.MatchLen[I]; end; function TJS_RegExp.GetMatchPos(I: Integer): Integer; begin if fZERO_BASED_STRINGS then result := fRegExpr.MatchPos[I] - 1 else result := fRegExpr.MatchPos[I]; end; function TJS_RegExp.GetSource: Variant; begin result := fRegExpr.Expression; end; procedure TJS_RegExp.SetSource(const Value: Variant); begin fRegExpr.Expression := Value; end; function TJS_RegExp.GetInput: Variant; begin result := fRegExpr.InputString; end; procedure TJS_RegExp.SetInput(const Value: Variant); begin fRegExpr.InputString := Value; end; function TJS_RegExp.GetGlobal: Boolean; begin result := fRegExpr.ModifierG; end; procedure TJS_RegExp.SetGlobal(const Value: Boolean); begin fRegExpr.ModifierG := Value; end; function TJS_RegExp.GetIgnoreCase: Boolean; begin result := fRegExpr.ModifierI; end; procedure TJS_RegExp.SetIgnoreCase(const Value: Boolean); begin fRegExpr.ModifierI := Value; end; function TJS_RegExp.GetMultiLine: Boolean; begin result := fRegExpr.ModifierM; end; procedure TJS_RegExp.SetMultiLine(const Value: Boolean); begin fRegExpr.ModifierM := Value; end; function TJS_RegExp.Test(const InputString: Variant): Boolean; begin result := fRegExpr.Exec(InputString); end; procedure TJS_RegExp.Compile; begin fRegExpr.Compile; end; function TJS_RegExp.Exec(const InputString: Variant): TJS_Array; var I, L: Integer; _InputString: String; begin _InputString := InputString; fRegExpr.InputString := _InputString; L := Length(_InputString); if LastIndex >= L then begin LastIndex := 1; result := TJS_Array.Create([]); result.prog := prog; result.AddToGC; result.length := 0; result.PutProperty('lastIndex', LastIndex); result.PutProperty('inputString', InputString); Exit; end; if fRegExpr.ExecPos(LastIndex) then begin result := TJS_Array.Create([]); result.prog := prog; result.AddToGC; for I:=0 to fRegExpr.SubExprMatchCount do result.PutArrProperty(I, fRegExpr.Match[I]); if fZERO_BASED_STRINGS then begin with fRegExpr do if MatchLen[0] = 0 then LastIndex := MatchPos[0] else LastIndex := MatchPos[0] + MatchLen[0]; result.PutProperty('index', fRegExpr.MatchPos[0] - 1); result.PutProperty('lastIndex', LastIndex - 1); end else begin with fRegExpr do if MatchLen[0] = 0 then LastIndex := MatchPos[0] + 1 else LastIndex := MatchPos[0] + MatchLen[0] + 1; result.PutProperty('index', fRegExpr.MatchPos[0]); result.PutProperty('lastIndex', LastIndex); end; result.PutProperty('inputString', InputString); end else begin result := TJS_Array.Create([]); result.prog := prog; result.AddToGC; result.length := 0; result.PutProperty('lastIndex', LastIndex); result.PutProperty('lnputString', InputString); end; end; function TJS_RegExp.Execute(const InputString: Variant): TJS_Array; var I: Integer; P: TIntegerList; begin fRegExpr.InputString := InputString; P := TIntegerList.Create; try if fRegExpr.Exec(InputString) then begin repeat P.Add(fRegExpr.MatchPos[0]); until not fRegExpr.ExecNext; end; result := TJS_Array.Create([]); result.prog := prog; result.AddToGC; for I:=0 to P.Count - 1 do result.PutArrProperty(I, P[I]); finally FreeAndNil(P); end; end; function TJS_RegExp.MatchCount: Integer; begin result := fRegExpr.SubExprMatchCount; end; function TJS_RegExp.Replace(const Expression, ReplaceStr: Variant): String; begin result := fRegExpr.Replace(Expression, ReplaceStr); end; function TJS_RegExp._toString: Variant; begin result := '/' + Source + '/'; if Global then result := result + 'g'; if IgnoreCase then result := result + 'i'; if MultiLine then result := result + 'm'; end; function TJS_RegExp.__toString: String; begin result := _toString(); end; {$ENDIF} //------------------------------------------------------------------------------ procedure _alert(Prog: TBaseRunner; P1: PVariant; P2: PVariant = nil; P3: PVariant = nil; P4: PVariant = nil; P5: PVariant = nil); stdcall; function Show(P: PVariant): Boolean; begin result := P <> nil; if result then result := VarType(P^) <> varEmpty; if result then ErrMessageBox(JS_ToString(P^)); end; begin if Assigned(Prog.OnPrint) then Prog.OnPrint(Prog.Owner, JS_ToString(P1^)) else ErrMessageBox(JS_ToString(P1^)); if not Show(P2) then Exit; if not Show(P3) then Exit; if not Show(P4) then Exit; if not Show(P5) then Exit; end; procedure _WriteObject(const value: TObject); var S: String; begin if value = nil then begin write('undefined'); end else if value is TJS_Object then begin S := value.ClassName; S := 'object ' + Copy(S, 5, Length(S) - 4); write('[' + S + ']'); end else begin S := 'object ' + value.ClassName; write('[' + S + ']'); end; end; {$IFDEF PAX64} procedure _GetGenericPropertyEx(Prog: TBaseRunner; var VObject: Variant; PropName: PChar; NP: Integer; var Result: Variant; Params: Pointer); var b: Boolean; I, VT: Integer; S: String; E: Extended; X, Y: TJS_Object; result_addr: Pointer; Q: Pointer; begin b := JS_IsObject(VObject); if not b then begin VT := VarType(VObject); case VT of varUString, varString, varOleStr: begin S := VObject; _JS_ToObject(Prog, @S, typeSTRING, @VObject); b := JS_IsObject(VObject); end; varSmallInt, varInteger, varByte, varShortInt, varWord, varLongWord: begin I := VObject; _JS_ToObject(Prog, @I, typeINTEGER, @VObject); b := JS_IsObject(VObject); end; varSingle, varDouble, varCurrency: begin E:= VObject; _JS_ToObject(Prog, @E, typeEXTENDED, @VObject); b := JS_IsObject(VObject); end; end; end; if b then begin case NP of 0: begin X := TJS_Object(TVarData(VObject).VInteger); result := X.L.GetProperty(PropName)^; if JS_IsObject(result) then begin Y := TJS_Object(TVarData(result).VInteger); if Y is TJS_Function then begin (Y as TJS_Function).__this := X; end; end; Exit; end; 1: begin X := TJS_Object(TVarData(VObject).VInteger); Y := X.GetPropertyAsObject(PropName); if Y is TJS_Function then begin (Y as TJS_Function).__this := X; result_addr := @result; // asm // jmp TJS_Function.InternalCall // end; end; Q := Pointer(Params^); VT := TVarData(Q^).VType; if VT = varString then result := Y.L.GetProperty(PChar(TVarData(Q^).VString))^ else if VT in VarIntTypes then result := Y.L.GetArrProperty(TVarData(Q^).VInteger)^ else result := Y.GetVarProperty(JS_ToString(Variant(Q^))); end; else begin X := TJS_Object(TVarData(VObject).VInteger); Y := X.GetPropertyAsObject(PropName); if Y is TJS_Function then begin (Y as TJS_Function).__this := X; result_addr := @result; // asm // jmp TJS_Function.InternalCall // end; end; result := Undefined; end; end; // case NP end else if Assigned(GetOlePropProc) then begin RaiseNotImpl; end else result := Undefined; end; procedure _GetGenericProperty(Prog: TBaseRunner; var VObject: Variant; PropName: PChar; NP: Integer); assembler; // r10 = result asm push rbp sub rsp, $40 mov rbp, rsp mov [rsp + $20], r10 // result mov [rsp + $28], rax // address of params call _GetGenericPropertyEx mov rsp, rbp add rsp, $40 pop rbp ret end; {$ELSE} {$IFNDEF PAXARM} procedure _GetGenericProperty(Prog: TBaseRunner; var VObject: Variant; PropName: PChar; NP: Integer; var Result: Variant); stdcall; var X, Y: TJS_Object; P, Q: Pointer; VT, RetSize: Integer; b: Boolean; S: String; I: Integer; E: Extended; result_addr: Pointer; begin asm mov P, ebp end; b := JS_IsObject(VObject); if not b then begin VT := VarType(VObject); case VT of varUString, varString, varOleStr: begin S := VObject; _JS_ToObject(Prog, @S, typeSTRING, @VObject); b := JS_IsObject(VObject); end; varSmallInt, varInteger, varByte, varShortInt, varWord, varLongWord: begin I := VObject; _JS_ToObject(Prog, @I, typeINTEGER, @VObject); b := JS_IsObject(VObject); end; varSingle, varDouble, varCurrency: begin E:= VObject; _JS_ToObject(Prog, @E, typeEXTENDED, @VObject); b := JS_IsObject(VObject); end; end; end; if b then begin case NP of 0: begin X := TJS_Object(TVarData(VObject).VInteger); result := X.L.GetProperty(PropName)^; if JS_IsObject(result) then begin Y := TJS_Object(TVarData(result).VInteger); if Y is TJS_Function then begin (Y as TJS_Function).__this := X; end; end; Exit; end; 1: begin X := TJS_Object(TVarData(VObject).VInteger); Y := X.GetPropertyAsObject(PropName); if Y is TJS_Function then begin (Y as TJS_Function).__this := X; result_addr := @result; asm mov eax, NP mov edx, Y mov ecx, result_addr mov esp, ebp pop ebp // restore old ebp pop ebx // pop ret addr mov [ebp - 512], ebx // save ret address pop ebx // pop 5 parametes pop ebx pop ebx pop ebx pop ebx push eax // np push edx // instance push ecx // result mov ebx, [ebp - 512] push ebx jmp TJS_Function.InternalCall end; end; Inc(Integer(P), 28); Q := Pointer(P^); VT := TVarData(Q^).VType; if VT = varString then result := Y.L.GetProperty(PChar(TVarData(Q^).VString))^ else if VT in VarIntTypes then result := Y.L.GetArrProperty(TVarData(Q^).VInteger)^ else result := Y.GetVarProperty(JS_ToString(Variant(Q^))); asm mov esp, ebp pop ebp ret 24 end; end; else begin X := TJS_Object(TVarData(VObject).VInteger); Y := X.GetPropertyAsObject(PropName); if Y is TJS_Function then begin (Y as TJS_Function).__this := X; result_addr := @result; asm mov eax, NP mov edx, Y mov ecx, result_addr mov esp, ebp pop ebp // restore old ebp pop ebx // pop ret addr mov [ebp - 512], ebx // save ret address pop ebx // pop 5 parametes pop ebx pop ebx pop ebx pop ebx push eax // np push edx // instance push ecx // result mov ebx, [ebp - 512] push ebx jmp TJS_Function.InternalCall end; end; result := Undefined; end; end; // case NP end else if Assigned(GetOlePropProc) then begin Inc(Integer(P), 28); if NP > 0 then asm mov edx, P mov ecx, NP @@loop: mov eax, [edx] push eax add edx, 4 sub ecx, 1 cmp ecx, 0 jnz @@loop end; GetOlePropProc(VObject, PropName, result, NP); end else result := Undefined; RetSize := 20 + NP * 4; asm // emulate ret RetSize mov ecx, RetSize mov esp, ebp pop ebp mov ebx, [esp] @@loop: pop edx sub ecx, 4 jnz @@loop pop edx jmp ebx end; end; {$ENDIF} {$ENDIF} {$IFDEF PAX64} procedure _PutGenericPropertyEx(const VObject: Variant; PropName: PChar; NP: Integer; const Value: Variant; Params: Pointer); var X: TJS_Object; Q: Pointer; VT: Integer; begin if JS_IsObject(VObject) then begin case NP of 0: begin X := TJS_Object(TVarData(VObject).VInteger); X.L.PutProperty(PropName, Value); Exit; end; 1: begin Q := Pointer(Params^); X := TJS_Object(TVarData(VObject).VInteger); X := X.GetPropertyAsObject(PropName); VT := TVarData(Q^).VType; if VT = varString then X.L.PutProperty(PChar(TVarData(Q^).VString), Value) else if VT in VarIntTypes then X.L.PutArrProperty(TVarData(Q^).VInteger, Value) else X.PutVarProperty(JS_ToString(Variant(Q^)), Value); end; end; // case NP end else RaiseNotImpl; end; procedure _PutGenericProperty(const VObject: Variant; PropName: PChar; NP: Integer; const Value: Variant); assembler; asm push rbp sub rsp, $30 mov rbp, rsp mov [rsp + $20], rax // address of params call _PutGenericPropertyEx mov rsp, rbp add rsp, $30 pop rbp ret end; {$ELSE} {$IFNDEF PAXARM} procedure _PutGenericProperty(const VObject: Variant; PropName: PChar; NP: Integer; const Value: Variant); stdcall; var X: TJS_Object; P, Q: Pointer; RetSize, VT: Integer; begin asm mov P, ebp end; if JS_IsObject(VObject) then begin case NP of 0: begin X := TJS_Object(TVarData(VObject).VInteger); X.L.PutProperty(PropName, Value); Exit; end; 1: begin Inc(Integer(P), 24); Q := Pointer(P^); X := TJS_Object(TVarData(VObject).VInteger); X := X.GetPropertyAsObject(PropName); VT := TVarData(Q^).VType; if VT = varString then X.L.PutProperty(PChar(TVarData(Q^).VString), Value) else if VT in VarIntTypes then X.L.PutArrProperty(TVarData(Q^).VInteger, Value) else X.PutVarProperty(JS_ToString(Variant(Q^)), Value); asm mov esp, ebp pop ebp ret 20 end; end; end; // case NP end else begin Inc(Integer(P), 24); if NP > 0 then asm mov edx, P mov ecx, NP @@loop: mov eax, [edx] push eax add edx, 4 sub ecx, 1 cmp ecx, 0 jnz @@loop end; PutOlePropProc(VObject, PropName, Value, NP); end; RetSize := 16 + NP * 4; asm // emulate ret RetSize mov ecx, RetSize mov esp, ebp pop ebp mov ebx, [esp] @@loop: pop edx sub ecx, 4 jnz @@loop pop edx jmp ebx end; end; {$ENDIF} {$ENDIF} procedure _JS_TypeOf(V: PVariant; result: PString); stdcall; var JS_Object: TJS_Object; begin if JS_IsString(V^) then result^ := 'string' else if JS_IsBoolean(V^) then result^ := 'boolean' else if JS_IsNumber(V^) then result^ := 'number' else if JS_IsObject(V^) then begin JS_Object := TJS_Object(TVarData(V^).VInteger); if JS_Object is TJS_Function then result^ := 'function' else result^ := 'object'; end else result^ := 'undefined'; end; procedure _JS_Void(var V: Variant; var result: Variant); stdcall; begin VarClear(result); end; procedure _JS_Delete(VObject: PVariant; Prop: PString); stdcall; begin end; procedure _JS_GetNextProp(VObject: PVariant; Prop: PString; result: PBoolean); stdcall; var I: Integer; JS_Array: TJS_Array; JS_Object: TJS_Object; LA: Integer; begin JS_Object := TJS_Object(TVarData(VObject^).VInteger); I := JS_Object.NextPropIndex; Inc(I); if JS_Object is TJS_Array then begin JS_Array := TJS_Array(JS_Object); if I > JS_Array.Length then begin JS_Object.NextPropIndex := -1; result^ := false; end else begin Prop^ := IntToStr(I); JS_Object.NextPropIndex := I; result^ := true; end; end else begin LA := System.Length(JS_Object.L.HashTable.A); with JS_Object.L.HashTable do repeat if I >= LA then begin JS_Object.NextPropIndex := -1; result^ := false; Exit; end; if A[I] = nil then begin Inc(I); continue; end else begin Prop^ := A[I].Key; JS_Object.NextPropIndex := I; result^ := true; Exit; end; until false; end; end; procedure _JS_ToObject(P:TBaseRunner; Address: Pointer; FinTypeId: Integer; result: PVariant); stdcall; var V: Variant; XS: TJS_String; XN: TJS_Number; XB: TJS_Boolean; I: Integer; VT: Word; begin case FinTypeId of typeCLASS: begin result^ := VarFromClass(TJS_ObjectBase(Address^)); end; typePOINTER: begin V := String(PChar(Address^)); XS := TJS_String.Create(@ V); XS.prog := P; XS.prototype := P.JS_String as TJS_Object; result^ := VarFromClass(XS); end; {$IFNDEF PAXARM} typeANSISTRING: begin V := String(Address^); XS := TJS_String.Create(@ V); XS.prog := P; XS.prototype := P.JS_String as TJS_Object; result^ := VarFromClass(XS); end; typeWIDESTRING: begin V := WideString(Address^); XS := TJS_String.Create(@ V); XS.prog := P; XS.prototype := P.JS_String as TJS_Object; result^ := VarFromClass(XS); end; {$ENDIF} typeUNICSTRING: begin V := String(Address^); XS := TJS_String.Create(@ V); XS.prog := P; XS.prototype := P.JS_String as TJS_Object; result^ := VarFromClass(XS); end; typeINTEGER: begin V := Integer(Address^); XN := TJS_Number.Create(@ V); XN.prog := P; XN.prototype := P.JS_Number as TJS_Object; result^ := VarFromClass(XN); end; typeBYTE: begin V := Byte(Address^); XN := TJS_Number.Create(@ V); XN.prog := P; XN.prototype := P.JS_Number as TJS_Object; result^ := VarFromClass(XN); end; typeWORD: begin V := Word(Address^); XN := TJS_Number.Create(@ V); XN.prog := P; XN.prototype := P.JS_Number as TJS_Object; result^ := VarFromClass(XN); end; typeCARDINAL: begin {$IFDEF VARIANTS} V := Cardinal(Address^); {$ELSE} V := Integer(Address^); {$ENDIF} XN := TJS_Number.Create(@ V); XN.prog := P; XN.prototype := P.JS_Number as TJS_Object; result^ := VarFromClass(XN); end; typeINT64: begin I := Int64(Address^); V := I; XN := TJS_Number.Create(@ V); XN.prog := P; XN.prototype := P.JS_Number as TJS_Object; result^ := VarFromClass(XN); end; typeDOUBLE: begin V := Double(Address^); XN := TJS_Number.Create(@ V); XN.prog := P; XN.prototype := P.JS_Number as TJS_Object; result^ := VarFromClass(XN); end; typeSINGLE: begin V := Single(Address^); XN := TJS_Number.Create(@ V); XN.prog := P; XN.prototype := P.JS_Number as TJS_Object; result^ := VarFromClass(XN); end; typeCURRENCY: begin V := Currency(Address^); XN := TJS_Number.Create(@ V); XN.prog := P; XN.prototype := P.JS_Number as TJS_Object; result^ := VarFromClass(XN); end; typeEXTENDED: begin V := Extended(Address^); XN := TJS_Number.Create(@ V); XN.prog := P; XN.prototype := P.JS_Number as TJS_Object; result^ := VarFromClass(XN); end; typeBOOLEAN: begin V := Boolean(Address^); XB := TJS_Boolean.Create(@ V); XB.prog := P; XB.prototype := P.JS_Boolean as TJS_Object; result^ := VarFromClass(XB); end; typeVARIANT: begin VT := TVarData(Address^).VType; case VT of varInteger, varSmallInt, varShortInt, varByte, varWord, varLongWord, varInt64, varSingle, varDouble, varCurrency, varDate: begin XN := TJS_Number.Create(PVariant(Address)); XN.prog := P; XN.prototype := P.JS_Number as TJS_Object; result^ := VarFromClass(XN); end; varBoolean: begin XB := TJS_Boolean.Create(PVariant(Address)); XB.prog := P; XB.prototype := P.JS_Boolean as TJS_Object; result^ := VarFromClass(XB); end; varString, varOleStr, varUString: begin XS := TJS_String.Create(PVariant(Address)); XS.prog := P; XS.prototype := P.JS_String as TJS_Object; result^ := VarFromClass(XS); end; varClass: begin result^ := Variant(Address^); end; else RaiseError(errCannotConvertToJS_Object, []); end; end; else RaiseError(errCannotConvertToJS_Object, []); end; end; procedure _VariantClr(var V: Variant); stdcall; //var // X: TJS_Object; begin { if JS_IsObject(V) then begin X := TJS_Object(TVarData(V).VInteger); if X <> nil then begin X.Free; TVarData(V).VInteger := 0; end; end; } VarClear(V); end; procedure _PushContext(P: TBaseRunner; value: PVariant); stdcall; var X: TObject; begin X := TObject(TVarData(value^).VInteger); if X is TJS_Reference then X := TJS_Reference(X).GetValueAsObject(); P.ContextList.Add(X); end; procedure _PopContext(P: TBaseRunner); stdcall; begin P.ContextList.Delete(P.ContextList.Count - 1); end; procedure _FindContext(P: TBaseRunner; PropName: PChar; AltAddress: Pointer; FinTypeId: Integer; result: PVariant); stdcall; var I: Integer; X: TJS_Object; {$IFDEF ARC} L: TList<TObject>; {$ELSE} L: TList; {$ENDIF} R: TJS_Reference; begin L := P.ContextList; for I := L.Count - 1 downto 0 do if TObject(L[I]) is TJS_Object then begin X := TJS_Object(L[I]); if X.HasProperty(PropName) then begin R := TJS_Reference.Create(typeVARIANT); R.Address := X.L.LastPropAddress; P.RootGC.AddReference(R); // R.Base := X; // R.PropName := PropName; result^ := VarFromClass(R); Exit; end; end; R := TJS_Reference.Create(FinTypeId); R.Address := AltAddress; P.RootGC.AddReference(R); result^ := VarFromClass(R); end; procedure _FindFunc(P: TBaseRunner; PropName: PChar; Alt, result: PVariant); stdcall; var I: Integer; X: TJS_Object; {$IFDEF ARC} L: TList<TObject>; {$ELSE} L: TList; {$ENDIF} begin L := P.ContextList; for I := L.Count - 1 downto 0 do begin if TObject(L[I]) is TJS_Object then begin X := TJS_Object(L[I]); if X.HasProperty(PropName) then begin result^ := X.GetProperty(PropName); if TVarData(result^).VInteger <> 0 then {$IFDEF PAX64} TJS_Function(TVarData(result^).VInt64).__this := X; {$ELSE} TJS_Function(TVarData(result^).VInteger).__this := X; {$ENDIF} Exit; end; end; end; result^ := Alt^; end; // overriden routines - begin procedure _VarArrayPut1(var V: Variant; var value: Variant; const I1: Variant); stdcall; var X: TJS_Object; S: String; begin if JS_IsObject(V) then begin X := TJS_Object(TVarData(V).VInteger); if VarType(I1) in VarIntTypes then X.PutArrProperty(I1, Value) else begin S := JS_ToString(I1); X.PutProperty(PChar(S), Value); end; end else V[I1] := value; end; procedure _VarArrayGet1(var V: Variant; var result: Variant; const I1: Variant); stdcall; var X: TJS_Object; S: String; begin if JS_IsObject(V) then begin X := TJS_Object(TVarData(V).VInteger); if VarType(I1) in VarIntTypes then result := X.GetArrProperty(I1) else begin S := JS_ToString(I1); result := X.GetProperty(PChar(S)); end; end else result := V[I1]; end; procedure _VarArrayPut2(var V: Variant; var value: Variant; const I2, I1: Variant); stdcall; begin V[I1, I2] := value; end; procedure _VarArrayGet2(var V: Variant; var result: Variant; const I2, I1: Variant); stdcall; begin result := V[I1, I2]; end; procedure _VarArrayPut3(var V: Variant; var value: Variant; const I3, I2, I1: Variant); stdcall; begin V[I1, I2, I3] := value; end; procedure _VarArrayGet3(var V: Variant; var result: Variant; const I3, I2, I1: Variant); stdcall; begin result := V[I1, I2, I3]; end; procedure _VariantFromPWideChar(source: PWideChar; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, UnicString(Source)) else dest^ := UnicString(Source); end; {$IFNDEF PAXARM} procedure _VariantFromPAnsiChar(source: PAnsiChar; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, AnsiString(Source)) else dest^ := AnsiString(Source); end; procedure _VariantFromAnsiString(Dest: PVariant; Source: PAnsiString); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source^) else Dest^ := Source^; end; procedure _VariantFromWideString(Dest: PVariant; Source: PWideString); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source^) else Dest^ := Source^; end; procedure _VariantFromAnsiChar(source: AnsiChar; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source) else dest^ := source; end; {$ENDIF} procedure _VariantFromInterface(const source: IDispatch; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source) else dest^ := Source; end; procedure _VariantFromShortString(Dest: PVariant; Source: PShortString); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, StringFromPShortString(Source)) else Dest^ := StringFromPShortString(Source); end; procedure _VariantFromUnicString(Dest: PVariant; Source: PUnicString); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source^) else Dest^ := Source^; end; procedure _VariantFromWideChar(source: WideChar; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source) else dest^ := source; end; procedure _VariantFromInt(source: Integer; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source) else dest^ := source; end; {$IFDEF VARIANTS} procedure _VariantFromInt64(dest: PVariant; source: PInt64); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source^) else dest^ := source^; end; {$ELSE} procedure _VariantFromInt64(dest: PVariant; source: PInt64); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Integer(Source^)) else dest^ := Integer(source^); end; {$ENDIF} procedure _VariantFromByte(source: Byte; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source) else dest^ := source; end; procedure _VariantFromBool(source: Boolean; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source) else dest^ := source; end; procedure _VariantFromWord(source: Word; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source) else dest^ := source; end; procedure _VariantFromCardinal(source: Cardinal; dest: PVariant); stdcall; begin {$IFDEF VARIANTS} if JS_IsRef(dest^) then JS_PutValue(dest^, Source) else dest^ := source; {$ELSE} if JS_IsRef(dest^) then JS_PutValue(dest^, Integer(Source)) else dest^ := Integer(source); {$ENDIF} end; procedure _VariantFromSmallInt(source: SmallInt; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source) else dest^ := source; end; procedure _VariantFromShortInt(source: ShortInt; dest: PVariant); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source) else dest^ := source; end; procedure _VariantFromDouble(dest: PVariant; source: PDouble); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source^) else dest^ := source^; end; procedure _VariantFromCurrency(dest: PVariant; source: PCurrency); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source^) else dest^ := source^; end; procedure _VariantFromSingle(dest: PVariant; source: PSingle); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source^) else dest^ := source^; end; procedure _VariantFromExtended(dest: PVariant; source: PExtended); stdcall; begin if JS_IsRef(dest^) then JS_PutValue(dest^, Source^) else dest^ := source^; end; procedure _VariantAssign(dest, source: PVariant); stdcall; var IsRefSource, IsRefDest, IsObjectDest, IsObjectSource: Boolean; Y: TJS_Object; temp: Variant; begin if VarIsNull(source^) then begin VarClear(dest^); end; IsRefSource := JS_IsRef(source^); IsRefDest := JS_IsRef(dest^); if IsRefSource and IsRefDest then JS_PutValue(dest^, JS_GetValue(Source^)) else if IsRefDest then JS_PutValue(dest^, Source^) else if IsRefSource then begin temp := JS_GetValue(Source^); IsObjectDest := JS_IsObject(dest^); IsObjectSource := JS_IsObject(temp); if IsObjectDest and IsObjectSource then GC_Assign(PGC_Object(@TVarData(Dest^).VInteger), TJS_Object(TVarData(temp).VInteger)) else if IsObjectDest then begin _ClassFromVariant(@Y, @temp); GC_Assign(PGC_Object(@TVarData(Dest^).VInteger), TGC_Object(Y)); if TVarData(Dest^).VInteger <> 0 then TVarData(Dest^).VType := varClass; end else if IsObjectSource then begin Y := TJS_Object(TVarData(temp).VInteger); GC_Assign(PGC_Object(@TVarData(Dest^).VInteger), TGC_Object(Y)); if TVarData(Dest^).VInteger <> 0 then TVarData(Dest^).VType := varClass; end else dest^ := temp; end else begin IsObjectDest := JS_IsObject(dest^); IsObjectSource := JS_IsObject(source^); if IsObjectDest and IsObjectSource then GC_Assign(PGC_Object(@TVarData(Dest^).VInteger), TJS_Object(TVarData(Source^).VInteger)) else if IsObjectDest then begin _ClassFromVariant(@Y, @Source); GC_Assign(PGC_Object(@TVarData(Dest^).VInteger), TGC_Object(Y)); if TVarData(Dest^).VInteger <> 0 then TVarData(Dest^).VType := varClass end else if IsObjectSource then begin Y := TJS_Object(TVarData(Source^).VInteger); GC_Assign(PGC_Object(@TVarData(Dest^).VInteger), Y); if TVarData(Dest^).VInteger <> 0 then TVarData(Dest^).VType := varClass; end else dest^ := source^; end; end; procedure _ClassAssign(dest, source: PObject); stdcall; var IsGCSource, IsGCDest: Boolean; begin if source^ = nil then begin if dest^ = nil then Exit; if dest^ is TGC_Object then GC_Assign(PGC_Object(dest), nil) else begin FreeAndNil(dest^); end; Exit; end; if dest^ = nil then begin if source^ = nil then Exit; if source^ is TGC_Object then begin TGC_Object(source^).AddRef; dest^ := source^; end else dest^ := source^; Exit; end; IsGCSource := source^ is TGC_Object; IsGCDest := dest^ is TGC_Object; if IsGCSource and IsGCDest then GC_Assign(PGC_Object(dest), TGC_Object(source)) else dest^ := source^; end; // overriden routines - end procedure _AssignProg(X: TJS_Object; P: TBaseRunner); stdcall; begin X.prog := P; X.AddToGC; end; procedure _VariantFromClass(Dest: PVariant; SourceAddress: Pointer); stdcall; begin VarClear(dest^); with TVarData(dest^) do begin VType := varClass; VInteger := IntPax(SourceAddress^); end; end; procedure _ClassFromVariant(DestAddress: Pointer; Source: PVariant); stdcall; var V: Variant; begin if TVarData(source^).VType = varClass then begin TObject(DestAddress^) := TObject(TVarData(source^).VInteger); if TObject(DestAddress^) is TJS_Reference then begin V := TJS_Reference(DestAddress^).GetValue(); if TVarData(V).VType = varClass then TObject(DestAddress^) := TObject(TVarData(V).VInteger) else TObject(DestAddress^) := nil; end; end else TObject(DestAddress^) := nil; end; function GetVariantValue(Address: Pointer; FinTypeId: Integer): Variant; begin case FinTypeId of typeBOOLEAN: result := Boolean(Address^); typeBYTE: result := Byte(Address^); typeWORD: result := Word(Address^); typeINTEGER: result := Integer(Address^); typeDOUBLE: result := Double(Address^); typePOINTER: result := Integer(Address^); typeENUM: result := Byte(Address^); typePROC: result := Integer(Address^); {$IFNDEF PAXARM} typeANSICHAR: result := AnsiChar(Address^); typeANSISTRING: result := AnsiString(Address^); typeSHORTSTRING: result := ShortString(Address^); typeWIDESTRING: result := WideString(Address^); {$ENDIF} typeSINGLE: result := Single(Address^); typeEXTENDED: result := Extended(Address^); typeCLASS: begin _VariantFromClass(@result, Address); end; typeCLASSREF: result := Integer(Address^); typeWIDECHAR: result := WideChar(Address^); typeVARIANT: result := Variant(Address^); typeDYNARRAY: result := Integer(Address^); {$IFDEF VARIANTS} typeEVENT: result := Int64(Address^); typeINT64: result := Int64(Address^); {$ELSE} typeINT64: result := Integer(Address^); {$ENDIF} typeINTERFACE: result := Integer(Address^); typeCARDINAL: result := Cardinal(Address^); typeCURRENCY: result := Currency(Address^); typeSMALLINT: result := SmallInt(Address^); typeSHORTINT: result := ShortInt(Address^); typeWORDBOOL: result := WordBool(Address^); typeLONGBOOL: result := LongBool(Address^); typeBYTEBOOL: result := ByteBool(Address^); typeOLEVARIANT: result := OleVariant(Address^); typeUNICSTRING: result := UnicString(Address^); end; end; procedure PutVariantValue(Address: Pointer; FinTypeId: Integer; const value: Variant); var X, Y: TObject; begin case FinTypeId of typeBOOLEAN: Boolean(Address^) := value; typeBYTE: Byte(Address^) := value; typeWORD: Word(Address^) := value; typeINTEGER: Integer(Address^) := value; typeDOUBLE: Double(Address^) := value; typePOINTER: Integer(Address^) := value; typeENUM: Byte(Address^) := value; typePROC: Integer(Address^) := value; {$IFNDEF PAXARM} typeSHORTSTRING: ShortString(Address^) := ShortString(value); typeANSICHAR: AnsiChar(Address^) := AnsiChar(Byte(value)); typeANSISTRING: AnsiString(Address^) := AnsiString(value); typeWIDESTRING: WideString(Address^) := value; {$ENDIF} typeSINGLE: Single(Address^) := value; typeEXTENDED: Extended(Address^) := value; typeCLASS: begin X := TObject(Address^); _ClassFromVariant(@Y, @value); if Y = nil then begin if X = nil then Exit; if X is TJS_Object then else TObject(Address^) := nil; Exit; end; if (X is TJS_Object) and (Y is TGC_Object) then GC_Assign(PGC_Object(Address), TGC_Object(Y)) else TObject(Address^) := Y; end; typeCLASSREF: Integer(Address^) := value; typeWIDECHAR: WideChar(Address^) := WideChar(Word(value)); typeVARIANT: Variant(Address^) := value; typeDYNARRAY: Integer(Address^) := value; {$IFDEF VARIANTS} typeINT64: Int64(Address^) := value; typeEVENT: Int64(Address^) := value; {$ELSE} typeINT64: Integer(Address^) := value; {$ENDIF} typeINTERFACE: Integer(Address^) := value; typeCARDINAL: Cardinal(Address^) := value; typeCURRENCY: Currency(Address^) := value; typeSMALLINT: SmallInt(Address^) := value; typeSHORTINT: ShortInt(Address^) := value; typeWORDBOOL: WordBool(Address^) := value; typeLONGBOOL: LongBool(Address^) := value; {$IFDEF FPC} typeBYTEBOOL: if value <> 0 then ByteBool(Address^) := true else ByteBool(Address^) := false; {$ELSE} typeBYTEBOOL: ByteBool(Address^) := value; {$ENDIF} typeOLEVARIANT: OleVariant(Address^) := value; typeUNICSTRING: UnicString(Address^) := value; end; end; procedure _VariantFromPointer(Dest: PVariant; SourceAddress: Pointer); stdcall; begin Dest^ := IntPax(SourceAddress^); TVarData(Dest^).VType := varPointer; end; procedure _ClearReferences(P: TBaseRunner); stdcall; begin P.RootGC.ClearRef; end; procedure _ClassClr(Address: Pointer); stdcall; begin if not (PObject(Address)^ is TGC_Object) then begin PObject(Address)^ := nil; Exit; end; GC_Assign(Address, nil); end; function _IsJSType(T: Integer; P: Pointer): Boolean; var SymbolTable: TBaseSymbolTable; begin result := (T = JS_ObjectClassId) or (T = JS_DateClassId) or (T = JS_ArrayClassId) or (T = JS_FunctionClassId) or (T = JS_MathClassId) or (T = JS_NumberClassId) or (T = JS_StringClassId) or (T = JS_ErrorClassId) or (T = JS_RegExpClassId) or (T = JS_BooleanClassId); if not result then if P <> nil then begin SymbolTable := TBaseSymbolTable(P); if SymbolTable[T].FinalTypeId <> typeCLASS then Exit; result := SymbolTable.Inherits(T, JS_ObjectClassId); end; end; const ByRef = true; procedure Register_StdJavaScript(st: TBaseSymbolTable); var H, G, H_Sub: Integer; begin IsJSType := _IsJSType; with st do begin {$IFNDEF PAXARM} RegisterRoutine(0, '', typeVARIANT, ccSTDCALL, @_GetGenericProperty); JS_GetGenericPropertyId := LastSubId; {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVARIANT, ccSTDCALL, @_AssignProg); JS_AssignProgId := LastSubId; RegisterParameter(H_Sub, typeCLASS, Unassigned); RegisterParameter(H_Sub, typeCLASS, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromClass); Id_VariantFromClass := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromPointer); Id_VariantFromPointer := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ClassFromVariant); Id_ClassFromVariant := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ClassAssign); Id_ClassAssign := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef); RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ClearReferences); JS_ClearReferencesId := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ClassClr); Id_ClassClr := LastSubId; RegisterParameter(H_Sub, typeCLASS, Unassigned, ByRef); // overriden routines - begin H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantClr); Id_VariantClr := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromPAnsiChar); Id_VariantFromPAnsiChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromAnsiString); Id_VariantFromAnsiString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromWideString); Id_VariantFromWideString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromAnsiChar); Id_VariantFromAnsiChar := LastSubId; RegisterParameter(H_Sub, typeANSICHAR, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromPWideChar); Id_VariantFromPWideChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromInterface); Id_VariantFromInterface := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromShortString); Id_VariantFromShortString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromUnicString); Id_VariantFromUnicString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromWideChar); Id_VariantFromWideChar := LastSubId; RegisterParameter(H_Sub, typeWIDECHAR, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromInt); Id_VariantFromInt := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromInt64); Id_VariantFromInt64 := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromByte); Id_VariantFromByte := LastSubId; RegisterParameter(H_Sub, typeBYTE, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromBool); Id_VariantFromBool := LastSubId; RegisterParameter(H_Sub, typeBOOLEAN, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromWord); Id_VariantFromWord := LastSubId; RegisterParameter(H_Sub, typeWORD, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromCardinal); Id_VariantFromCardinal := LastSubId; RegisterParameter(H_Sub, typeCARDINAL, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromSmallInt); Id_VariantFromSmallInt := LastSubId; RegisterParameter(H_Sub, typeSMALLINT, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromShortInt); Id_VariantFromShortInt := LastSubId; RegisterParameter(H_Sub, typeSHORTINT, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromDouble); Id_VariantFromDouble := LastSubId; RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromCurrency); Id_VariantFromCurrency := LastSubId; RegisterParameter(H_Sub, typeCURRENCY, Unassigned, ByRef); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromSingle); Id_VariantFromSingle := LastSubId; RegisterParameter(H_Sub, typeSINGLE, Unassigned, ByRef); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromExtended); Id_VariantFromExtended := LastSubId; RegisterParameter(H_Sub, typeEXTENDED, Unassigned, ByRef); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantAssign); Id_VariantAssign := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); {$IFNDEF PAXARM} RegisterRoutine(0, '', typeVARIANT, ccSTDCALL, @_PutGenericProperty); JS_PutGenericPropertyId := LastSubId; {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayGet1); Id_VarArrayGet1 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayPut1); Id_VarArrayPut1 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayGet2); Id_VarArrayGet2 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayPut2); Id_VarArrayPut2 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayGet3); Id_VarArrayGet3 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayPut3); Id_VarArrayPut3 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); // overriden routines - end H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteObject); Id_WriteObject := LastSubId; RegisterParameter(H_Sub, typeCLASS, Unassigned); H_WriteObject := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _FuncObjFromVariant); Id_FuncObjFromVariant := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _JS_ToObject); JS_ToObjectId := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _JS_GetNextProp); JS_GetNextPropId := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _JS_TypeOf); JS_TypeOfId := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _JS_Void); JS_VoidId := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _JS_Delete); JS_Delete := LastSubId; JS_TempNamespaceId := RegisterNamespace(0, StrJavaScriptTempNamespace); H := RegisterNamespace(0, StrJavaScriptNamespace); JS_JavaScriptNamespace := H; RegisterConstant(H, 'Undefined', Undefined); RegisterHeader(H, 'procedure alert(const P1: Variant; const P2, P3, P4, P5: Variant = Undefined); stdcall;', @ _alert); Records[LastSubId].PushProgRequired := true; JS_AlertId := LastSubId; H_Sub := RegisterRoutine(0, '', typeVARIANT, ccSTDCALL, @_PushContext); Id_PushContext := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVARIANT, ccSTDCALL, @_PopContext); Id_PopContext := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVARIANT, ccSTDCALL, @_FindContext); Id_FindContext := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVARIANT, ccSTDCALL, @_FindFunc); JS_FindFuncId := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterConstant(H, 'null', typeVARIANT, Undefined); // Object ---------------------------------------------------------------------- G := RegisterClassType(H, TJS_Object); JS_ObjectClassId := G; Records[G].Name := 'Object'; Records[G].IsJavaScriptClass := true; RegisterHeader(G, 'constructor Create;, @TJS_Object.Create);', @TJS_Object.Create); RegisterHeader(G, 'procedure PutProperty(PropName: PChar; const Value: Variant);', @TJS_Object.PutProperty); JS_PutPropertyId := LastSubId; RegisterHeader(G, 'function GetProperty(PropName: PChar): Variant;', @TJS_Object.GetProperty); JS_GetPropertyId := LastSubId; RegisterHeader(G, 'property ___prop[PropertyName: PChar]: Variant read GetProperty write PutProperty; default;', nil); RegisterHeader(G, 'function GetPropertyAsObject(PropName: PChar): TObject;', @ TJS_Object.GetPropertyAsObject); JS_GetPropertyAsObjectId := LastSubId; RegisterHeader(G, 'procedure PutArrProperty(PropName: Integer; const Value: Variant);', @TJS_Object.PutArrProperty); JS_PutArrPropertyId := LastSubId; RegisterHeader(G, 'function GetArrProperty(PropName: Integer): Variant;', @TJS_Object.GetArrProperty); JS_GetArrPropertyId := LastSubId; RegisterTypeField(G, 'prototype', JS_ObjectClassId, Integer(@TJS_Object(nil).prototype)); RegisterTypeField(G, strInternalConstructor, JS_ObjectClassId, Integer(@TJS_Object(nil).aconstructor)); RegisterTypeField(G, strProgram, typePOINTER, Integer(@TJS_Object(nil).prog)); RegisterHeader(G, 'function GetConstructor: Object;', @TJS_Object.GetConstructor); RegisterHeader(G, 'property constructor: Object read GetConstructor write ' + strInternalConstructor + ';', nil); //-- Date ---------------------------------------------------------------------- G := RegisterClassType(H, TJS_Date); JS_DateClassId := G; Records[G].Name := 'Date'; Records[G].IsJavaScriptClass := true; RegisterHeader(G, 'constructor Create(const Year, Month, Date, Hours, Minutes, Seconds, Ms: Variant = Undefined);', @TJS_Date.Create); // Array ----------------------------------------------------------------------- G := RegisterClassType(H, TJS_Array); JS_ArrayClassId := G; Records[G].Name := 'Array'; Records[G].IsJavaScriptClass := true; RegisterHeader(G, 'constructor Create(const V: array of Variant);', @TJS_Array.Create); RegisterHeader(G, 'function GetLength: Integer;', @TJS_Array.GetLength); RegisterHeader(G, 'procedure SetLength(value: Integer);', @TJS_Array.SetLength); RegisterHeader(G, 'property length: Integer read GetLength write SetLength;', nil); // Boolean --------------------------------------------------------------------- G := RegisterClassType(H, TJS_Boolean); JS_BooleanClassId := G; Records[G].Name := 'Boolean'; Records[G].IsJavaScriptClass := true; RegisterHeader(G, 'constructor Create(const P: Variant = Undefined);', @TJS_Boolean.Create); // Number ---------------------------------------------------------------------- G := RegisterClassType(H, TJS_Number); JS_NumberClassId := G; Records[G].Name := 'Number'; Records[G].IsJavaScriptClass := true; RegisterHeader(G, 'constructor Create(const P: Variant = Undefined);', @TJS_Number.Create); // String ---------------------------------------------------------------------- G := RegisterClassType(H, TJS_String); JS_StringClassId := G; Records[G].Name := 'String'; Records[G].IsJavaScriptClass := true; RegisterHeader(G, 'constructor Create(const P: Variant = Undefined);', @TJS_String.Create); // Function -------------------------------------------------------------------- G := RegisterClassType(H, TJS_Function); JS_FunctionClassId := G; Records[G].Name := 'Function'; Records[G].IsJavaScriptClass := true; RegisterHeader(G, 'constructor ' + strInternalCreate + '(i_InternalFuncAddr: Pointer; i_NP: Integer; i_ProgPtr: Pointer);', @TJS_Function.InternalCreate); RegisterHeader(G, 'function ' + strInternalCall + '(NP: Integer): Variant; stdcall;', @TJS_Function.InternalCall); JS_FunctionCallId := LastSubId; RegisterTypeField(G, 'arguments', JS_ArrayClassId, Integer(@TJS_Function(nil).arguments)); RegisterTypeField(G, 'length', typeINTEGER, Integer(@TJS_Function(nil).InternalLength)); RegisterTypeField(G, strInternalLength, typeINTEGER, Integer(@TJS_Function(nil).InternalLength)); RegisterTypeField(G, strInternalFuncAddr, typePOINTER, Integer(@TJS_Function(nil).InternalFuncAddr)); RegisterTypeField(G, str__this, typePOINTER, Integer(@TJS_Function(nil).__this)); {$IFDEF PAX64} ParArr_OFFSET := IntPax(@TJS_Function(nil).ParArr); RetAdr_OFFSET := IntPax(@TJS_Function(nil).RetAdr); {$ENDIF} //-- Math ---------------------------------------------------------------------- G := RegisterClassType(H, TJS_Math); JS_MathClassId := G; Records[G].Name := 'Math'; Records[G].IsJavaScriptClass := true; //-- RegExp -------------------------------------------------------------------- G := RegisterClassType(H, TJS_RegExp); JS_RegExpClassId := G; Records[G].Name := 'RegExp'; Records[G].IsJavaScriptClass := true; RegisterHeader(G, 'constructor Create(const Source: Variant = Undefined; const Modifiers: Variant = Undefined);', @TJS_RegExp.Create); RegisterHeader(G, 'destructor Destroy; override;', @TJS_RegExp.Destroy); RegisterHeader(G, 'function test(const InputString: Variant): Boolean;', @TJS_RegExp.Test); RegisterHeader(G, 'procedure compile;', @TJS_RegExp.Compile); RegisterHeader(G, 'function matchCount: Integer;', @TJS_RegExp.MatchCount); RegisterHeader(G, 'function exec(const InputString: Variant): Array;', @TJS_RegExp.Exec); RegisterHeader(G, 'function execute(const InputString: Variant): Array;', @TJS_RegExp.Execute); RegisterHeader(G, 'function replace(const Expression, ReplaceStr: Variant): String;', @TJS_RegExp.Replace); RegisterHeader(G, 'function __GetMatch(I: Integer): String;', @TJS_RegExp.GetMatch); RegisterHeader(G, 'function __GetMatchLen(I: Integer): Integer;', @TJS_RegExp.GetMatchLen); RegisterHeader(G, 'function __GetMatchPos(I: Integer): Integer;', @TJS_RegExp.GetMatchPos); RegisterHeader(G, 'property match[I: Integer]: Integer read __GetMatch;', nil); RegisterHeader(G, 'property matchPos[I: Integer]: Integer read __GetMatchPos;', nil); RegisterHeader(G, 'property matchLen[I: Integer]: Integer read __GetMatchLen;', nil); // Error --------------------------------------------------------------------- G := RegisterClassType(H, TJS_Error); JS_ErrorClassId := G; Records[G].Name := 'Error'; Records[G].IsJavaScriptClass := true; RegisterHeader(G, 'constructor Create(const P: Variant = Undefined);', @TJS_Error.Create); end; end; initialization VarIntTypes := [varSmallint, varInteger, varShortInt, varByte, varWord, varLongWord]; Randomize; MaxArgs := IntMaxArgs; CrtJSObjects := Create_JSObjects; EmptyFunction := TJS_Function.InternalCreate(nil, 0, nil); finalization EmptyFunction.Free; end.
unit uAssociativeArray; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type PAssocArrayItem = ^TAssocArrayItem; TAssocArrayItem = packed record Name : AnsiString; Value: Variant; Next : PAssocArrayItem; end; { TAssociativeArray } TAssociativeArray = class private ffirst : PAssocArrayItem; function GetItem(S: AnsiString): Variant; procedure SetItem(S: AnsiString; V: Variant); public constructor Create; destructor Destroy; override; property Values[Index: AnsiString]: Variant read GetItem write SetItem; default; end; implementation uses Variants; { TAssociativeArray } function TAssociativeArray.GetItem(S: AnsiString): Variant; var itm : PAssocArrayItem; begin result := NULL; itm := ffirst; while (result = NULL) and (assigned(itm)) do begin if AnsiCompareText(S, itm^.Name) = 0 then result := itm^.Value; itm := itm^.Next; end; end; procedure TAssociativeArray.SetItem(S: AnsiString; V: Variant); var workingitm, itm : PAssocArrayItem; begin itm := nil; workingitm := ffirst; while (assigned(workingitm)) do begin itm := workingitm; if AnsiCompareText(S, workingitm^.Name) = 0 then begin workingitm^.Value := V; exit; end; workingitm := workingitm^.Next; end; // if itm isn't assigned we can't have a first pointer yet, so create it if not assigned(itm) then begin new(ffirst); ffirst^.Next := nil; itm := ffirst; end else begin new(itm^.Next); // create a new working node itm := itm^.Next; itm^.Next := nil; end; itm^.Name := S; itm^.Value := V; end; constructor TAssociativeArray.Create; begin ffirst := nil; end; destructor TAssociativeArray.Destroy; var itm : PAssocArrayItem; begin while assigned(ffirst) do begin itm := ffirst; ffirst := ffirst^.Next; Freemem(itm); end; inherited Destroy; end; end.
unit ModflowCfpFixedUnit; interface uses Classes, RbwParser, GoPhastTypes, ModflowBoundaryUnit, SubscriptionUnit, FormulaManagerUnit, Contnrs, SysUtils; type // @name is used to control data set 27 in the CFP process via the // @link(TDataArray) "CfpFixedHeads." TCfpFixedBoundary = class(TModflowSteadyBoundary) private FFixedHead: TFormulaObject; FDiameterObserver: TObserver; function GetFixedHead: string; procedure SetFixedHead(const Value: string); function GetFixedHeadObserver: TObserver; protected procedure HandleChangedValue(Observer: TObserver); override; procedure GetPropertyObserver(Sender: TObject; List: TList); override; function GetUsedObserver: TObserver; override; procedure CreateFormulaObjects; override; function BoundaryObserverPrefix: string; override; procedure CreateObservers; override; property FixedHeadObserver: TObserver read GetFixedHeadObserver; public Procedure Assign(Source: TPersistent); override; Constructor Create(Model: TBaseModel; ScreenObject: TObject); destructor Destroy; override; published property FixedHead: string read GetFixedHead write SetFixedHead; end; implementation uses PhastModelUnit, frmGoPhastUnit, ScreenObjectUnit, DataSetUnit; const FixedHeadPosition = 0; { TCfpFixedBoundary } procedure TCfpFixedBoundary.Assign(Source: TPersistent); var SourceCfp: TCfpFixedBoundary; begin if Source is TCfpFixedBoundary then begin SourceCfp := TCfpFixedBoundary(Source); FixedHead := SourceCfp.FixedHead; end; inherited; end; function TCfpFixedBoundary.BoundaryObserverPrefix: string; begin result := 'CfpFixedBoundary_'; end; constructor TCfpFixedBoundary.Create(Model: TBaseModel; ScreenObject: TObject); begin inherited; FixedHead := '0'; end; procedure TCfpFixedBoundary.CreateFormulaObjects; begin FFixedHead := CreateFormulaObject(dso3D); end; procedure TCfpFixedBoundary.CreateObservers; begin if ScreenObject <> nil then begin FObserverList.Add(FixedHeadObserver); end; end; destructor TCfpFixedBoundary.Destroy; begin FixedHead := '0'; inherited; end; function TCfpFixedBoundary.GetFixedHead: string; begin Result := FFixedHead.Formula; if ScreenObject <> nil then begin ResetItemObserver(FixedHeadPosition); end; end; function TCfpFixedBoundary.GetFixedHeadObserver: TObserver; var Model: TPhastModel; DataArray: TDataArray; begin if FDiameterObserver = nil then begin if ParentModel <> nil then begin Model := ParentModel as TPhastModel; DataArray := Model.DataArrayManager.GetDataSetByName(KCfpFixedHeads); end else begin DataArray := nil; end; CreateObserver('Cfp_FixedHead_', FDiameterObserver, DataArray); end; result := FDiameterObserver; end; procedure TCfpFixedBoundary.GetPropertyObserver(Sender: TObject; List: TList); begin if Sender = FFixedHead then begin List.Add(FObserverList[FixedHeadPosition]); end; end; function TCfpFixedBoundary.GetUsedObserver: TObserver; var Model: TPhastModel; DataArray: TDataArray; begin if FUsedObserver = nil then begin if ParentModel <> nil then begin Model := ParentModel as TPhastModel; DataArray := Model.DataArrayManager.GetDataSetByName(KCfpFixedHeads); end else begin DataArray := nil; end; CreateObserver('CFP_Fixed_Used_', FUsedObserver, DataArray); end; result := FUsedObserver; end; procedure TCfpFixedBoundary.HandleChangedValue(Observer: TObserver); begin // invalidate display here. { TODO -cCFP : Does this need to be finished?} end; procedure TCfpFixedBoundary.SetFixedHead(const Value: string); begin UpdateFormula(Value, FixedHeadPosition, FFixedHead); end; end.
namespace com.example.android.wiktionary; {* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *} interface uses android.app, android.content, android.graphics, android.net, android.os, android.text, android.text.format, android.util, android.view, android.view.animation, android.webkit, android.widget, java.util; type /// <summary> /// Activity that lets users browse through Wiktionary content. This is just the /// user interface, and all API communication and parsing is handled in /// ExtendedWikiHelper. /// </summary> LookupActivity = public class(Activity, Animation.AnimationListener) private const TAG = 'LookupActivity'; var mTitleBar: View; var mTitle: TextView; var mProgress: ProgressBar; var mWebView: WebView; var mSlideIn: Animation; var mSlideOut: Animation; // History stack of previous words browsed in this session. This is // referenced when the user taps the "back" key, to possibly intercept and // show the last-visited entry, instead of closing the activity. var mHistory: Stack<String> := new Stack<String>; var mEntryTitle: String; // Keep track of last time user tapped "back" hard key. When pressed more // than once within BACK_THRESHOLD, we let the back key fall // through and close the app. var mLastPress: Int64 := - 1; var BACK_THRESHOLD: Int64 := DateUtils.SECOND_IN_MILLIS div 2; readonly; method startNavigating(aWord: String; pushHistory: Boolean); protected method showAbout; method setEntryTitle(entryText: String); method setEntryContent(entryContent: String); public method onCreate(savedInstanceState: Bundle); override; method onCreateOptionsMenu(mnu: Menu): Boolean; override; method onOptionsItemSelected(itm: MenuItem): Boolean; override; method onKeyDown(keyCode: Integer; &event: KeyEvent): Boolean; override; method onNewIntent(int: Intent); override; method onAnimationEnd(animation: Animation); method onAnimationRepeat(animation: Animation); method onAnimationStart(animation: Animation); end; /// <summary> /// Background task to handle Wiktionary lookups. This correctly shows and /// hides the loading animation from the GUI thread before starting a /// background query to the Wiktionary API. When finished, it transitions /// back to the GUI thread where it updates with the newly-found entry. /// </summary> LookupTask nested in LookupActivity = private class(AsyncTask<String, String, String>) private mContext: LookupActivity; protected method onPreExecute; override; method doInBackground(params args: array of String): String; override; method onProgressUpdate(params args: array of String); override; method onPostExecute(parsedText: String); override; public constructor (aContext: LookupActivity); end; implementation method LookupActivity.onCreate(savedInstanceState: Bundle); begin inherited; ContentView := R.layout.lookup; // Load animations used to show/hide progress bar mSlideIn := AnimationUtils.loadAnimation(self, R.anim.slide_in); mSlideOut := AnimationUtils.loadAnimation(self, R.anim.slide_out); // Listen for the "in" animation so we make the progress bar visible // only after the sliding has finished. mSlideIn.AnimationListener := self; mTitleBar := findViewById(R.id.title_bar); mTitle := TextView(findViewById(R.id.title)); mProgress := ProgressBar(findViewById(R.id.progress)); mWebView := WebView(findViewById(R.id.webview)); // Make the view transparent to show background mWebView.BackgroundColor := 0;//Color.TRANSPARENT; // Handle incoming intents as possible searches or links onNewIntent(Intent) end; method LookupActivity.onCreateOptionsMenu(mnu: Menu): Boolean; begin var inflater := MenuInflater; inflater.inflate(R.menu.lookup, mnu); exit true end; method LookupActivity.onOptionsItemSelected(itm: MenuItem): Boolean; begin case itm.ItemId of R.id.lookup_search: begin onSearchRequested; exit true end; R.id.lookup_random: begin startNavigating(nil, true); exit true end; R.id.lookup_about: begin showAbout; exit true end; end; exit false end; /// <summary> /// Intercept the back-key to try walking backwards along our word history /// stack. If we don't have any remaining history, the key behaves normally /// and closes this activity. /// </summary> /// <param name="keyCode"></param> /// <param name="event"></param> /// <returns></returns> method LookupActivity.onKeyDown(keyCode: Integer; &event: KeyEvent): Boolean; begin // Handle back key as long we have a history stack if (keyCode = KeyEvent.KEYCODE_BACK) and not mHistory.empty then begin // Compare against last pressed time, and if user hit multiple times // in quick succession, we should consider bailing out early. var currentPress: Int64 := SystemClock.uptimeMillis; if currentPress - mLastPress < BACK_THRESHOLD then exit inherited; mLastPress := currentPress; // Pop last entry off stack and start loading var lastEntry: String := mHistory.pop; startNavigating(lastEntry, false); exit true end; // Otherwise fall through to parent exit inherited end; /// <summary> /// Start navigating to the given word, pushing any current word onto the /// history stack if requested. The navigation happens on a background thread /// and updates the GUI when finished. /// </summary> /// <param name="word">The dictionary word to navigate to.</param> /// <param name="pushHistory">If true, push the current word onto history stack.</param> method LookupActivity.startNavigating(aWord: String; pushHistory: Boolean); begin // Push any current word onto the history stack if not TextUtils.isEmpty(mEntryTitle) and pushHistory then mHistory.add(mEntryTitle); // Start lookup for new word in background new LookupTask(self).execute(aWord) end; /// <summary> /// Show an about dialog that cites data sources. /// </summary> method LookupActivity.showAbout; begin // Inflate the about message contents var messageView: View := LayoutInflater.inflate(R.layout.about, nil, false); // When linking text, force to always use default color. This works // around a pressed color state bug. var txtView: TextView := TextView(messageView.findViewById(R.id.about_credits)); var defaultColor: Integer := txtView.TextColors.DefaultColor; txtView.TextColor := defaultColor; var builder: AlertDialog.Builder := new AlertDialog.Builder(self); builder.Icon := R.drawable.app_icon; builder.Title := R.string.app_name; builder.View := messageView; builder.&create; builder.show end; /// <summary> /// Because we're singleTop, we handle our own new intents. These usually /// come from the SearchManager when a search is requested, or from /// internal links the user clicks on. /// </summary> method LookupActivity.onNewIntent(int: Intent); begin var action: String := int.Action; if Intent.ACTION_SEARCH.&equals(action) then begin // Start query for incoming search request var query: String := int.StringExtra[SearchManager.QUERY]; startNavigating(query, true) end else if Intent.ACTION_VIEW.&equals(action) then begin // Treat as internal link only if valid Uri and host matches var data: Uri := int.Data; if (data <> nil) and ExtendedWikiHelper.WIKI_LOOKUP_HOST.&equals(data.Host) then begin var query: String := data.PathSegments.get(0); startNavigating(query, true) end end else begin // If not recognized, then start showing random word startNavigating(nil, true) end end; /// <summary> /// Set the title for the current entry. /// </summary> method LookupActivity.setEntryTitle(entryText: String); begin mEntryTitle := entryText; mTitle.Text := mEntryTitle end; /// <summary> /// Set the content for the current entry. This will update our /// WebView to show the requested content. /// </summary> method LookupActivity.setEntryContent(entryContent: String); begin mWebView.loadDataWithBaseURL(ExtendedWikiHelper.WIKI_AUTHORITY, entryContent, ExtendedWikiHelper.MIME_TYPE, ExtendedWikiHelper.ENCODING, nil) end; method LookupActivity.onAnimationEnd(animation: Animation); begin mProgress.Visibility := View.VISIBLE end; method LookupActivity.onAnimationRepeat(animation: Animation); // Not interested if the animation repeats begin end; method LookupActivity.onAnimationStart(animation: Animation); // Not interested when the animation starts begin end; constructor LookupActivity.LookupTask(aContext: LookupActivity); begin inherited constructor; mContext := aContext end; /// <summary> /// Perform the background query using ExtendedWikiHelper, which /// may return an error message as the result. /// </summary> method LookupActivity.LookupTask.onPreExecute; begin mContext.mTitleBar.startAnimation(mContext.mSlideIn) end; /// <summary> /// Our progress update pushes a title bar update. /// </summary> method LookupActivity.LookupTask.doInBackground(params args: array of String): String; begin var query: String := args[0]; var parsedText: String := nil; try // If query word is null, assume request for random word if query = nil then query := ExtendedWikiHelper.getRandomWord; if query <> nil then begin // Push our requested word to the title bar publishProgress(query); var wikiText: String := ExtendedWikiHelper.getPageContent(query, true); parsedText := ExtendedWikiHelper.formatWikiText(wikiText) end; except on e: SimpleWikiHelper.ApiException do Log.e(TAG, 'Problem making wiktionary request', e); on e: SimpleWikiHelper.ParseException do Log.e(TAG, 'Problem making wiktionary request', e); end; if parsedText = nil then parsedText := mContext.String[R.string.empty_result]; exit parsedText end; /// <summary> /// When finished, push the newly-found entry content into our /// WebView and hide the ProgressBar. /// </summary> method LookupActivity.LookupTask.onProgressUpdate(params args: array of String); begin var searchWord: String := args[0]; mContext.setEntryTitle(searchWord) end; method LookupActivity.LookupTask.onPostExecute(parsedText: String); begin mContext.mTitleBar.startAnimation(mContext.mSlideOut); mContext.mProgress.Visibility := View.INVISIBLE; mContext.setEntryContent(parsedText) end; end.
unit ibSHDBObjectActions; interface uses SysUtils, Classes, Controls, StrUtils, DesignIntf, TypInfo, Dialogs, Menus, SHDesignIntf, ibSHDesignIntf; type TibSHDDLObjectPaletteAction = class(TSHAction) private function GetClassIID: TGUID; public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; property ClassIID: TGUID read GetClassIID; end; TibSHDDLObjectFormAction = class(TSHAction) private function GetCallString: string; function GetComponentFormClass: TSHComponentFormClass; procedure RegisterComponentForm(const AClassIID: TGUID); public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; property CallString: string read GetCallString; property ComponentFormClass: TSHComponentFormClass read GetComponentFormClass; end; TibSHDDLObjectEditorAction = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; // Component Palette TibSHDomainPaletteAction = class(TibSHDDLObjectPaletteAction) end; TibSHTablePaletteAction = class(TibSHDDLObjectPaletteAction) end; TibSHIndexPaletteAction = class(TibSHDDLObjectPaletteAction) end; TibSHViewPaletteAction = class(TibSHDDLObjectPaletteAction) end; TibSHProcedurePaletteAction = class(TibSHDDLObjectPaletteAction) end; TibSHTriggerPaletteAction = class(TibSHDDLObjectPaletteAction) end; TibSHGeneratorPaletteAction = class(TibSHDDLObjectPaletteAction) end; TibSHExceptionPaletteAction = class(TibSHDDLObjectPaletteAction) end; TibSHFunctionPaletteAction = class(TibSHDDLObjectPaletteAction) end; TibSHFilterPaletteAction = class(TibSHDDLObjectPaletteAction) end; TibSHRolePaletteAction = class(TibSHDDLObjectPaletteAction) end; // Forms TibSHDDLObjectFormAction_CreateDDL = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_SourceDDL = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_AlterDDL = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_DropDDL = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_RecreateDDL = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_Description = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_Dependencies = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_Fields = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_Constraints = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_Indices = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_Triggers = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_Data = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_DataBLOB = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_DataForm = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_FieldDescr = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_FieldOrder = class(TibSHDDLObjectFormAction) end; TibSHDDLObjectFormAction_ParamDescr = class(TibSHDDLObjectFormAction) end; // Editors TibSHDDLObjectEditorAction_FindInScheme = class(TibSHDDLObjectEditorAction) end; TibSHDDLObjectEditorAction_CreateNew = class(TibSHDDLObjectEditorAction) end; TibSHDDLObjectEditorAction_RecordCount = class(TibSHDDLObjectEditorAction) end; TibSHDDLObjectEditorAction_ChangeCount = class(TibSHDDLObjectEditorAction) end; TibSHDDLObjectEditorAction_SetSatatistics = class(TibSHDDLObjectEditorAction) end; implementation uses ibSHConsts, ibSHDDLFrm, ibSHDataGridFrm, ibSHDataBlobFrm, ibSHDataVCLFrm, {ibSHDDLGeneratorFrm,} ibSHFieldsFrm, ibSHConstraintsFrm, ibSHIndicesFrm, ibSHTriggersFrm, ibSHDependenciesFrm, ibSHDescriptionFrm, ibSHFieldOrderFrm, ibSHFieldDescrFrm, ibSHDDLGenerator, ibSHDDLCompiler, ibSHDependencies, ibSHQuery; { TibSHDDLObjectPaletteAction } constructor TibSHDDLObjectPaletteAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallPalette; Caption := '-'; // separator Category := Format('%s', ['Meta']); if IsEqualGUID(ClassIID, IibSHDomain) then Caption := Format('%s', ['Domain']) else if IsEqualGUID(ClassIID, IibSHTable) then Caption := Format('%s', ['Table']) else if IsEqualGUID(ClassIID, IibSHIndex) then Caption := Format('%s', ['Index']) else if IsEqualGUID(ClassIID, IibSHView) then Caption := Format('%s', ['View']) else if IsEqualGUID(ClassIID, IibSHProcedure) then Caption := Format('%s', ['Procedure']) else if IsEqualGUID(ClassIID, IibSHTrigger) then Caption := Format('%s', ['Trigger']) else if IsEqualGUID(ClassIID, IibSHGenerator) then Caption := Format('%s', ['Generator']) else if IsEqualGUID(ClassIID, IibSHException) then Caption := Format('%s', ['Exception']) else if IsEqualGUID(ClassIID, IibSHFunction) then Caption := Format('%s', ['Function']) else if IsEqualGUID(ClassIID, IibSHFilter) then Caption := Format('%s', ['Filter']) else if IsEqualGUID(ClassIID, IibSHRole) then Caption := Format('%s', ['Role']); if IsEqualGUID(ClassIID, IibSHDomain) then ShortCut := TextToShortCut('Shift+Alt+D'); if IsEqualGUID(ClassIID, IibSHTable) then ShortCut := TextToShortCut('Shift+Alt+T'); if IsEqualGUID(ClassIID, IibSHIndex) then ShortCut := TextToShortCut('Shift+Alt+I'); if IsEqualGUID(ClassIID, IibSHView) then ShortCut := TextToShortCut('Shift+Alt+V'); if IsEqualGUID(ClassIID, IibSHProcedure) then ShortCut := TextToShortCut('Shift+Alt+P'); if IsEqualGUID(ClassIID, IibSHTrigger) then ShortCut := TextToShortCut('Shift+Alt+M'); if IsEqualGUID(ClassIID, IibSHGenerator) then ShortCut := TextToShortCut('Shift+Alt+G'); if IsEqualGUID(ClassIID, IibSHException) then ShortCut := TextToShortCut('Shift+Alt+E'); if IsEqualGUID(ClassIID, IibSHFunction) then ShortCut := TextToShortCut('Shift+Alt+F'); if IsEqualGUID(ClassIID, IibSHFilter) then ShortCut := TextToShortCut('Shift+Alt+L'); if IsEqualGUID(ClassIID, IibSHRole) then ShortCut := TextToShortCut('Shift+Alt+R'); end; function TibSHDDLObjectPaletteAction.GetClassIID: TGUID; begin Result := IUnknown; if Self is TibSHDomainPaletteAction then Result := IibSHDomain else if Self is TibSHTablePaletteAction then Result := IibSHTable else if Self is TibSHIndexPaletteAction then Result := IibSHIndex else if Self is TibSHViewPaletteAction then Result := IibSHView else if Self is TibSHProcedurePaletteAction then Result := IibSHProcedure else if Self is TibSHTriggerPaletteAction then Result := IibSHTrigger else if Self is TibSHGeneratorPaletteAction then Result := IibSHGenerator else if Self is TibSHExceptionPaletteAction then Result := IibSHException else if Self is TibSHFunctionPaletteAction then Result := IibSHFunction else if Self is TibSHFilterPaletteAction then Result := IibSHFilter else if Self is TibSHRolePaletteAction then Result := IibSHRole; end; function TibSHDDLObjectPaletteAction.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(IibSHBranch, AClassIID) or IsEqualGUID(IfbSHBranch, AClassIID); end; procedure TibSHDDLObjectPaletteAction.EventExecute(Sender: TObject); //var // vComponent: TSHComponent; begin Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, ClassIID, EmptyStr); // vComponent := Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, ClassIID, EmptyStr); // if Assigned(vComponent) then // Designer.ShowModal(vComponent, Format('DDL_WIZARD.%s', [AnsiUpperCase(vComponent.Association)])); end; procedure TibSHDDLObjectPaletteAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHDDLObjectPaletteAction.EventUpdate(Sender: TObject); begin Enabled := Assigned(Designer.CurrentDatabase) and (Designer.CurrentDatabase as ISHRegistration).Connected and SupportComponent(Designer.CurrentDatabase.BranchIID); end; { TibSHDDLObjectFormAction } constructor TibSHDDLObjectFormAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallForm; Caption := '-'; // separator Caption := CallString; RegisterComponentForm(IibSHDomain); RegisterComponentForm(IibSHTable); RegisterComponentForm(IibSHConstraint); RegisterComponentForm(IibSHIndex); RegisterComponentForm(IibSHView); RegisterComponentForm(IibSHProcedure); RegisterComponentForm(IibSHTrigger); RegisterComponentForm(IibSHGenerator); RegisterComponentForm(IibSHException); RegisterComponentForm(IibSHFunction); RegisterComponentForm(IibSHFilter); RegisterComponentForm(IibSHRole); RegisterComponentForm(IibSHSystemDomain); RegisterComponentForm(IibSHSystemTable); RegisterComponentForm(IibSHSystemTableTmp); if Self is TibSHDDLObjectFormAction_CreateDDL then ShortCut := TextToShortCut(''); if Self is TibSHDDLObjectFormAction_SourceDDL then ShortCut := TextToShortCut(''); if Self is TibSHDDLObjectFormAction_AlterDDL then ShortCut := TextToShortCut('F4'); if Self is TibSHDDLObjectFormAction_DropDDL then ShortCut := TextToShortCut('Shift+Alt+Del'); if Self is TibSHDDLObjectFormAction_RecreateDDL then ShortCut := TextToShortCut('Shift+Alt+F4'); end; function TibSHDDLObjectFormAction.GetCallString: string; begin Result := EmptyStr; if Self is TibSHDDLObjectFormAction_CreateDDL then Result := SCallCreateDDL else if Self is TibSHDDLObjectFormAction_SourceDDL then Result := SCallSourceDDL else if Self is TibSHDDLObjectFormAction_AlterDDL then Result := SCallAlterDDL else if Self is TibSHDDLObjectFormAction_DropDDL then Result := SCallDropDDL else if Self is TibSHDDLObjectFormAction_RecreateDDL then Result := SCallRecreateDDL else if Self is TibSHDDLObjectFormAction_Description then Result := SCallDescription else if Self is TibSHDDLObjectFormAction_Dependencies then Result := SCallDependencies else if Self is TibSHDDLObjectFormAction_Fields then Result := SCallFields else if Self is TibSHDDLObjectFormAction_Constraints then Result := SCallConstraints else if Self is TibSHDDLObjectFormAction_Indices then Result := SCallIndices else if Self is TibSHDDLObjectFormAction_Triggers then Result := SCallTriggers else if Self is TibSHDDLObjectFormAction_Data then Result := SCallData else if Self is TibSHDDLObjectFormAction_DataBLOB then Result := SCallDataBLOB else if Self is TibSHDDLObjectFormAction_DataForm then Result := SCallDataForm else if Self is TibSHDDLObjectFormAction_FieldDescr then Result := SCallFieldDescr else if Self is TibSHDDLObjectFormAction_FieldOrder then Result := SCallFieldOrder else if Self is TibSHDDLObjectFormAction_ParamDescr then Result := SCallParamDescr; end; function TibSHDDLObjectFormAction.GetComponentFormClass: TSHComponentFormClass; begin Result := nil; if AnsiSameText(CallString, SCallCreateDDL) then Result := TibBTDDLForm else if AnsiSameText(CallString, SCallSourceDDL) then Result := TibBTDDLForm else if AnsiSameText(CallString, SCallAlterDDL) then Result := TibBTDDLForm else if AnsiSameText(CallString, SCallDropDDL) then Result := TibBTDDLForm else if AnsiSameText(CallString, SCallRecreateDDL) then Result := TibBTDDLForm else if AnsiSameText(CallString, SCallDescription) then Result := TibBTDescriptionForm else if AnsiSameText(CallString, SCallDependencies) then Result := TibBTDependenciesForm else if AnsiSameText(CallString, SCallFields) then Result := TibSHFieldsForm else if AnsiSameText(CallString, SCallConstraints) then Result := TibBTConstraintsForm else if AnsiSameText(CallString, SCallIndices) then Result := TibBTIndicesForm else if AnsiSameText(CallString, SCallTriggers) then Result := TibBTTriggersForm else if AnsiSameText(CallString, SCallData) then Result := TibSHDataGridForm else if AnsiSameText(CallString, SCallDataBLOB) then Result := TibSHDataBlobForm else if AnsiSameText(CallString, SCallDataForm) then Result := TibSHDataVCLForm else if AnsiSameText(CallString, SCallFieldDescr) then Result := TibSHFieldDescrForm else if AnsiSameText(CallString, SCallFieldOrder) then Result := TibSHFieldOrderForm else if AnsiSameText(CallString, SCallParamDescr) then Result := TibSHFieldDescrForm; end; procedure TibSHDDLObjectFormAction.RegisterComponentForm(const AClassIID: TGUID); begin if SupportComponent(AClassIID) then SHRegisterComponentForm(AClassIID, CallString, ComponentFormClass); end; function TibSHDDLObjectFormAction.SupportComponent(const AClassIID: TGUID): Boolean; begin { Идем по порядку CallString и выдаем ГУИДы, на которые регистрится форма } Result := False; if AnsiSameText(CallString, SCallCreateDDL) then begin Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or //IsEqualGUID(AClassIID, IibSHConstraint) or IsEqualGUID(AClassIID, IibSHIndex) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException) or IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or IsEqualGUID(AClassIID, IibSHRole);// or //IsEqualGUID(AClassIID, IibSHSystemDomain) or //IsEqualGUID(AClassIID, IibSHSystemTable) or //IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallSourceDDL) then begin Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHConstraint) or IsEqualGUID(AClassIID, IibSHIndex) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException) or IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or IsEqualGUID(AClassIID, IibSHRole) or IsEqualGUID(AClassIID, IibSHSystemDomain) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallAlterDDL) then begin Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or //IsEqualGUID(AClassIID, IibSHConstraint) or IsEqualGUID(AClassIID, IibSHIndex) or //IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException);// or //IsEqualGUID(AClassIID, IibSHFunction) or //IsEqualGUID(AClassIID, IibSHFilter) or //IsEqualGUID(AClassIID, IibSHRole) or //IsEqualGUID(AClassIID, IibSHSystemDomain) or //IsEqualGUID(AClassIID, IibSHSystemTable) or //IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallDropDDL) then begin Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or //IsEqualGUID(AClassIID, IibSHConstraint) or IsEqualGUID(AClassIID, IibSHIndex) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException) or IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or IsEqualGUID(AClassIID, IibSHRole);// or //IsEqualGUID(AClassIID, IibSHSystemDomain) or //IsEqualGUID(AClassIID, IibSHSystemTable) or //IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallRecreateDDL) then begin Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or //IsEqualGUID(AClassIID, IibSHConstraint) or IsEqualGUID(AClassIID, IibSHIndex) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException) or IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or IsEqualGUID(AClassIID, IibSHRole);// or //IsEqualGUID(AClassIID, IibSHSystemDomain) or //IsEqualGUID(AClassIID, IibSHSystemTable) or //IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallDescription) then begin Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or //IsEqualGUID(AClassIID, IibSHConstraint) or IsEqualGUID(AClassIID, IibSHIndex) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or //IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException) or IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or IsEqualGUID(AClassIID, IibSHRole) or //IsEqualGUID(AClassIID, IibSHSystemDomain) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallDependencies) then begin Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or //IsEqualGUID(AClassIID, IibSHConstraint) or //IsEqualGUID(AClassIID, IibSHIndex) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException) or IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or //IsEqualGUID(AClassIID, IibSHRole) or IsEqualGUID(AClassIID, IibSHSystemDomain) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallFields) then begin Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallConstraints) then begin Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallIndices) then begin Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallTriggers) then begin Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallData) then begin Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallDataBLOB) then begin Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallDataForm) then begin Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallFieldDescr) then begin Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); end else if AnsiSameText(CallString, SCallFieldOrder) then begin Result := IsEqualGUID(AClassIID, IibSHTable); end else if AnsiSameText(CallString, SCallParamDescr) then begin Result := IsEqualGUID(AClassIID, IibSHProcedure); end; end; procedure TibSHDDLObjectFormAction.EventExecute(Sender: TObject); begin Designer.ChangeNotification(Designer.CurrentComponent, CallString, opInsert); end; procedure TibSHDDLObjectFormAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHDDLObjectFormAction.EventUpdate(Sender: TObject); begin Visible := Assigned(Designer.CurrentComponent) and Supports(Designer.CurrentComponent, ISHDBComponent) and not ((Designer.CurrentComponent as ISHDBComponent).State = csCreate); if AnsiSameText(CallString, SCallCreateDDL) then Visible := Assigned(Designer.CurrentComponent) and Supports(Designer.CurrentComponent, ISHDBComponent) and ((Designer.CurrentComponent as ISHDBComponent).State = csCreate); FDefault := Assigned(Designer.CurrentComponentForm) and AnsiSameText(CallString, Designer.CurrentComponentForm.CallString); Enabled := True; end; { TibSHDDLObjectEditorAction } constructor TibSHDDLObjectEditorAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallEditor; if Self is TibSHDDLObjectEditorAction_FindInScheme then Tag := 1; if Self is TibSHDDLObjectEditorAction_CreateNew then Tag := 2; if Self is TibSHDDLObjectEditorAction_RecordCount then Tag := 3; if Self is TibSHDDLObjectEditorAction_ChangeCount then Tag := 4; if Self is TibSHDDLObjectEditorAction_SetSatatistics then Tag := 5; case Tag of 0: Caption := '-'; // separator 1: Caption := SCallFindInScheme; 2: begin Caption := SCallCreateNew; ShortCut := TextToShortCut('Shift+F4'); end; 3: Caption := SCallRecordCount; 4: Caption := SCallChangeCount; 5: Caption := SCallSetSatatistics; end; end; function TibSHDDLObjectEditorAction.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := False; case Tag of // SCallFindInScheme 1: Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or //IsEqualGUID(AClassIID, IibSHConstraint) or IsEqualGUID(AClassIID, IibSHIndex) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException) or IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or IsEqualGUID(AClassIID, IibSHRole);// or //IsEqualGUID(AClassIID, IibSHSystemDomain) or //IsEqualGUID(AClassIID, IibSHSystemTable) or //IsEqualGUID(AClassIID, IibSHSystemTableTmp); // SCallCreateNew 2: Result := IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHTable) or //IsEqualGUID(AClassIID, IibSHConstraint) or IsEqualGUID(AClassIID, IibSHIndex) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) or IsEqualGUID(AClassIID, IibSHGenerator) or IsEqualGUID(AClassIID, IibSHException) or IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or IsEqualGUID(AClassIID, IibSHRole);// or //IsEqualGUID(AClassIID, IibSHSystemDomain) or //IsEqualGUID(AClassIID, IibSHSystemTable) or //IsEqualGUID(AClassIID, IibSHSystemTableTmp); // SCallRecordCount 3: Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); // SCallChangeCount 4: Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp); // SCallSetSatatistics 5: Result := IsEqualGUID(AClassIID, IibSHIndex); end; end; procedure TibSHDDLObjectEditorAction.EventExecute(Sender: TObject); var vComponent: TSHComponent; begin case Tag of // SCallFindInScheme 1: begin Designer.SynchronizeConnection( Designer.FindComponent(Designer.CurrentComponent.OwnerIID), Designer.CurrentComponent.ClassIID, Designer.CurrentComponent.Caption, opInsert); end; // SCallCreateNew 2: begin vComponent := Designer.CreateComponent( Designer.CurrentComponent.OwnerIID, Designer.CurrentComponent.ClassIID, EmptyStr); if Assigned(vComponent) then ; // Designer.ShowModal(vComponent, Format('DDL_WIZARD.%s', [AnsiUpperCase(vComponent.Association)])); end; // SCallRecordCount 3: begin if Supports(Designer.CurrentComponent, IibSHTable) then (Designer.CurrentComponent as IibSHTable).SetRecordCount; if Supports(Designer.CurrentComponent, IibSHView) then (Designer.CurrentComponent as IibSHView).SetRecordCount; if Supports(Designer.CurrentComponent, IibSHTable) and (Length((Designer.CurrentComponent as IibSHTable).RecordCountFrmt) > 0) then Designer.ShowMsg(Format('%s Record Count: %s', [Designer.CurrentComponent.Caption, (Designer.CurrentComponent as IibSHTable).RecordCountFrmt]), mtInformation); if Supports(Designer.CurrentComponent, IibSHView) and (Length((Designer.CurrentComponent as IibSHView).RecordCountFrmt) > 0) then Designer.ShowMsg(Format('%s Record Count: %s', [Designer.CurrentComponent.Caption, (Designer.CurrentComponent as IibSHView).RecordCountFrmt]), mtInformation); end; // SCallChangeCount 4: begin if Supports(Designer.CurrentComponent, IibSHTable) then (Designer.CurrentComponent as IibSHTable).SetChangeCount; if Supports(Designer.CurrentComponent, IibSHTable) and (Length((Designer.CurrentComponent as IibSHTable).ChangeCountFrmt) > 0) then Designer.ShowMsg(Format('%s Change Count: %s', [Designer.CurrentComponent.Caption, (Designer.CurrentComponent as IibSHTable).ChangeCountFrmt]), mtInformation); end; // SCallSetSatatistics 5: begin if Supports(Designer.CurrentComponent, IibSHIndex) then (Designer.CurrentComponent as IibSHIndex).RecountStatistics; end; end; end; procedure TibSHDDLObjectEditorAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHDDLObjectEditorAction.EventUpdate(Sender: TObject); begin Visible := Assigned(Designer.CurrentComponent) and Supports(Designer.CurrentComponent, ISHDBComponent) and not ((Designer.CurrentComponent as ISHDBComponent).State = csCreate); case Tag of // SCallFindInScheme 1: begin Enabled := True; end; // SCallCreateNew 2: begin Visible := True; Enabled := True; if Assigned(Designer.CurrentComponent) then Caption := Format('%s %s...', [SCallCreateNew, Designer.CurrentComponent.Association]); end; // SCallRecordCount 3: begin Enabled := True; end; // SCallChangeCount 4: begin Enabled := True; end; // SCallSetSatatistics 5: begin Enabled := True; end; end; end; end.
namespace RemObjects.Elements.Linq; interface uses java.util; type Predicate<T> = public delegate (aItem: T): Boolean; &Selector<T, R> = public delegate (aItem: T): R; Comparer<T> = public delegate(aItem1, aItem2: T): Integer; ForSelector<T> = public delegate(aIndex: Integer): T; extension method sequence of T.Where<T>(aBlock: Predicate<T>): sequence of T; iterator; extension method sequence of T.Any<T>(aBlock: Predicate<T>): Boolean; extension method sequence of T.Take<T>(aCount: Integer): sequence of T; iterator; extension method sequence of T.Skip<T>(aCount: Integer): sequence of T; iterator; extension method sequence of T.TakeWhile<T>(aBlock: Predicate<T>): sequence of T; iterator; extension method sequence of T.SkipWhile<T>(aBlock: Predicate<T>): sequence of T; iterator; extension method sequence of T.Select<T, R>(aBlock: &Selector<T, R>): sequence of R; iterator; extension method sequence of T.Concat<T>(aSecond: sequence of T): sequence of T; iterator; extension method sequence of T.Reverse<T>: sequence of T; extension method sequence of T.Cast<T, U>: sequence of U; iterator; extension method sequence of T.FirstOrDefault<T>: T; extension method sequence of T.Count<T>: Integer; extension method sequence of T.Any<T>: Boolean; extension method sequence of T.ToArray<T>: array of T; inline; // must be inline extension method sequence of T.ToList<T>: ArrayList<T>; extension method sequence of T.ToDictionary<T, K, V>(aKeyBlock: &Selector<T, K>; aValueBlock: &Selector<K, V>): Hashtable<K, V>; extension method sequence of T.OrderBy<T, C>(aBlock: &Selector<T, C>): sequence of T; where C is Comparable<C>; extension method sequence of T.OrderByDescending<T, C>(aBlock: &Selector<T, C>): sequence of T; where C is Comparable<C>; extension method sequence of T.Distinct<T>(aComparator: Comparer<T> := nil): sequence of T; extension method sequence of T.Intersect<T>(aSecond: sequence of T; aComparator: Comparer<T> := nil): sequence of T; iterator; extension method sequence of T.Except<T>(aSecond: sequence of T; aComparator: Comparer<T> := nil): sequence of T; iterator; extension method List<T>.Contains<T>(aElement: T; aComparator: Comparer<T>): Boolean; extension method sequence of T.Contains<T>(aElement: T): Boolean; type Helpers = public static class public class method ForHelper<T>(aStart, aEnd, aStep: Integer; aBackward: Boolean; aMethod: ForSelector<T>): sequence of T; iterator; end; implementation extension method sequence of T.Where<T>(aBlock: Predicate<T>): sequence of T; begin for each el in self do if aBlock(el) then yield el; end; extension method sequence of T.Any<T>(aBlock: Predicate<T>): Boolean; begin for each el in self do if aBlock(el) then exit true; end; extension method sequence of T.Take<T>(aCount: Integer): sequence of T; begin if aCount > 0 then begin for each el in self do begin yield el; dec(aCount); if aCount <= 0 then break; end; end; end; extension method sequence of T.Skip<T>(aCount: Integer): sequence of T; begin for each el in self do begin if aCount > 0 then dec(aCount) else yield el; end; end; extension method sequence of T.TakeWhile<T>(aBlock: Predicate<T>): sequence of T; begin for each el in self do begin if not aBlock(el) then break; yield el; end; end; extension method sequence of T.SkipWhile<T>(aBlock: Predicate<T>): sequence of T; begin var lFound := true; for each el in self do begin if not lFound and not aBlock(el) then lFound := true; if lFound then yield el; end; end; extension method sequence of T.Select<T, R>(aBlock: &Selector<T, R>): sequence of R; begin for each el in self do yield aBlock(el); end; extension method sequence of T.Concat<T>(aSecond: sequence of T): sequence of T; begin for each el in self do yield el; for each el in aSecond do yield el; end; extension method sequence of T.Reverse<T>: sequence of T; begin var lList := self.ToList(); Collections.reverse(lList); exit lList; end; extension method sequence of T.Cast<T, U>: sequence of U; begin for each el in self do yield el as U; end; extension method sequence of T.FirstOrDefault<T>: T; begin var lItem := &iterator; if lItem.hasNext then exit lItem.next; exit nil; end; extension method sequence of T.Any<T>: Boolean; begin var lItem := &iterator; result := lItem.hasNext; end; extension method sequence of T.Count<T>: Integer; begin if self is List then exit List(self).size(); result := 0; for each el in self do inc(result); end; extension method sequence of T.ToArray<T>: array of T; begin var lList := self.ToList(); result := new T[lList.Count]; result := lList.toArray(result); end; extension method sequence of T.ToList<T>: ArrayList<T>; begin result := new ArrayList<T>(); for each el in self do result.add(el); end; extension method sequence of T.ToDictionary<T, K, V>(aKeyBlock: &Selector<T, K>; aValueBlock: &Selector<K, V>): Hashtable<K, V>; begin result := new Hashtable<K, V>(); for each el in self do result.put(aKeyBlock(el), aValueBlock(el)); end; extension method sequence of T.OrderBy<T, C>(aBlock: &Selector<T, C>): sequence of T; begin var lList := self.ToList(); Collections.sort(lList, new interface Comparator<T>( compare := (a, b) -> aBlock(a).compareTo(aBlock(b)) )); exit lList; end; extension method sequence of T.OrderByDescending<T, C>(aBlock: &Selector<T, C>): sequence of T; begin var lList := self.ToList(); Collections.sort(lList, new interface Comparator<T>( compare := (a, b) -> 0 - aBlock(a).compareTo(aBlock(b)) )); exit lList; end; extension method sequence of T.Distinct<T>(aComparator: Comparer<T> := nil): sequence of T; begin var lHS := new ArrayList<T>; if aComparator = nil then begin for each el in self do begin if not lHS.contains(el) then lHS.add(el); end; end else begin for each el in self do begin var lFound := false; if lHS.Contains(el, aComparator) then lFound := true; if not lFound then lHS.add(el); end; end; exit lHS; end; extension method sequence of T.Intersect<T>(aSecond: sequence of T; aComparator: Comparer<T> := nil): sequence of T; begin var lSecond := aSecond.ToList(); for each i in self do if lSecond.Contains(i, aComparator) then yield i; end; extension method sequence of T.Except<T>(aSecond: sequence of T; aComparator: Comparer<T> := nil): sequence of T; begin var lFirst := self.ToList(); var lSecond := aSecond.ToList(); for each i in lFirst do if not lSecond.Contains(i, aComparator) then yield i; for each i in lSecond do if not lFirst.Contains(i, aComparator) then yield i; end; extension method List<T>.Contains<T>(aElement: T; aComparator: Comparer<T>): Boolean; begin if aComparator = nil then exit self.contains(aElement); for j: Integer := 0 to Count -1 do begin if 0 = aComparator(self[j], aElement) then exit true; end; exit false; end; extension method sequence of T.Contains<T>(aElement: T): Boolean; begin if self is java.util.ArrayList<T> then exit (self as java.util.ArrayList<T>).contains(aElement); for each i in self do begin if (i = nil) then begin if (aElement = nil) then exit true; end else begin if i.equals(aElement) then exit true; end; end; end; class method Helpers.ForHelper<T>(aStart: Integer; aEnd: Integer; aStep: Integer; aBackward: Boolean; aMethod: ForSelector<T>): sequence of T; begin if aBackward then for i: Integer := aStart downto aEnd step aStep do yield aMethod(i) else for i: Integer := aStart to aEnd step aStep do yield aMethod(i) end; end.
unit LessOpTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, uIntXLibTypes, uIntX; type { TTestLessOp } TTestLessOp = class(TTestCase) published procedure Simple(); procedure SimpleFail(); procedure Big(); procedure BigFail(); procedure EqualValues(); procedure Neg(); end; implementation procedure TTestLessOp.Simple(); var int1, int2: TIntX; begin int1 := TIntX.Create(7); int2 := TIntX.Create(8); AssertTrue(int1 < int2); end; procedure TTestLessOp.SimpleFail(); var int1: TIntX; begin int1 := TIntX.Create(8); AssertFalse(int1 < 7); end; procedure TTestLessOp.Big(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 2); temp1[0] := 1; temp1[1] := 2; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, True); AssertTrue(int2 < int1); end; procedure TTestLessOp.BigFail(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 2); temp1[0] := 1; temp1[1] := 2; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, True); AssertFalse(int1 < int2); end; procedure TTestLessOp.EqualValues(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 3); temp1[0] := 1; temp1[1] := 2; temp1[2] := 3; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, True); int2 := TIntX.Create(temp2, True); AssertFalse(int1 < int2); end; procedure TTestLessOp.Neg(); var int1, int2: TIntX; begin int1 := TIntX.Create(-10); int2 := TIntX.Create(-2); AssertTrue(int1 < int2); end; initialization RegisterTest(TTestLessOp); end.
PROGRAM storygen; USES Crt, sysutils; (* sysutils for filesexits *) CONST EF = CHR(0); (*END of file character*) maxWordLen = 30; (*max. number of characters per word*) chars = ['a' .. 'z', 'ä', 'ö', 'ü', 'ß', 'A' .. 'Z', 'Ä', 'Ö', 'Ü']; size = 100; TYPE Word = STRING[maxWordLen]; NodePtr = ^Node; Node = RECORD key: STRING; replacement : STRING; next: NodePtr; END; (*Record*) ListPtr = NodePtr; HashTable = ARRAY[0..size-1] OF ListPtr; VAR curLine : STRING; (*current line from file txt*) curCh: CHAR; (*current character*) curLineNr: INTEGER; (*current line number*) curColNr: INTEGER; (*current column number*) mode : (fillHashTableMode, replaceMode); replTXTFile, inTXTFile, outTXTFile : TEXT; (* text files *) newLine : BOOLEAN; (* Sets everything in the ht to NIL *) PROCEDURE InitHashTable(VAR ht: HashTable); VAR h: Integer; BEGIN FOR h := 0 TO size - 1 DO BEGIN ht[h] := NIL; END; END; (* Create a new Node *) FUNCTION NewNode(w, wr : Word; next: NodePtr) : NodePtr; VAR n: NodePtr; BEGIN New(n); n^.key := w; n^.replacement := wr; n^.next := next; NewNode := n; END; (* compiler hashcode returns hashcode of string *) FUNCTION HashCode(key: String): Integer; BEGIN IF Length(key) = 1 THEN HashCode := (Ord(key[1]) * 7 + 1) * 17 MOD size ELSE HashCode := (Ord(key[1]) * 7 + Ord(key[2]) + Length(key)) * 17 MOD size END; (* Lookup combines search and prepend *) FUNCTION Lookup(w, wr : Word; VAR ht: HashTable) : NodePtr; VAR i: Integer; n: NodePtr; BEGIN i := HashCode(w); n := ht[i]; WHILE (n <> NIL) AND (n^.key <> w) DO BEGIN n := n^.next; END; IF n = NIL THEN BEGIN n := NewNode(w, wr, ht[i]); ht[i] := n; END; Lookup := n; END; (* Searches for a string in the hashtable returns NIL if not found *) FUNCTION Search(key: String; ht: HashTable) : NodePtr; VAR i: Integer; n: NodePtr; BEGIN i := HashCode(key); n := ht[i]; WHILE (n <> NIL) AND (n^.key <> key) DO BEGIN n := n^.next; END; Search := n; END; (* updates curChar *) PROCEDURE GetNextChar(VAR txt: TEXT); BEGIN IF curColNr < Length(curLine) THEN BEGIN curColNr := curColNr + 1; curCh := curLine[curColNr]; END ELSE IF (curColNr = 0) AND (curColNr >= Length(curLine)) THEN BEGIN CASE mode OF replaceMode: BEGIN WriteLn(outTXTFile); ReadLn(txt, curLine); curLineNr:= curLineNr + 1; curColNr := 0; curCh := ' '; (* separate lines by ' ' *) END; END; END ELSE BEGIN (* curColNr >= Length(curLine) *) IF NOT Eof(txt) THEN BEGIN CASE mode OF replaceMode: BEGIN newLine := TRUE; END; END; ReadLn(txt, curLine); curLineNr:= curLineNr + 1; curColNr := 0; curCh := ' '; (* separate lines by ' ' *) END ELSE curCh := EF; END; END; (* GetNextChar *) (* Creates word from char - mode decides if between reading or writing returns the next word in a string *) PROCEDURE GetNextWord(VAR w: Word; VAR lnr: INTEGER; VAR txt: TEXT); BEGIN WHILE (curCh <> EF) AND NOT (curCh IN chars) DO BEGIN CASE mode OF replaceMode: BEGIN IF NOT (curCh IN chars) THEN Write(outTXTFile, curCh); END; END; GetNextChar(txt); END; lnr := curLineNr; IF curCh <> EF THEN BEGIN w := curCh; GetNextChar(txt); WHILE (curCh <> EF) AND (curCh IN chars) DO BEGIN w := Concat(w, curCh); GetNextChar(txt); END; END ELSE w := ''; END; (* GetNextWord *) (* Fills the HashTable with the replacements *) PROCEDURE FillHashTable(VAR ht: HashTable; VAR txt: TEXT); VAR w, wr: Word; (*current word*) lnr: INTEGER; (*line number of current word*) n: LONGINT; (*number of words*) BEGIN curLine := ''; curLineNr := 0; curColNr := 1; (*curColNr > Length(curLine) FORces reading of first line*) GetNextChar(txt); (*curCh now holds first character*) n := 0; mode := fillHashTableMode; w := ''; GetNextWord(w, lnr, txt); GetNextWord(wr, lnr, txt); WHILE Length(w) > 0 DO BEGIN IF (w <> '') AND (wr <> '') THEN Lookup(w, wr, ht); n := n + 1; GetNextWord(w, lnr, txt); GetNextWord(wr, lnr, txt); END; WriteLn('Found ',n ,' replacements'); END; (* Replaces a word if there is a replacement *) PROCEDURE Replace(ht: HashTable); VAR w : Word; (*current word*) lnr: INTEGER; (*line number of current word*) n: LONGINT; (*number of words*) temp : NodePtr; BEGIN curLine := ''; curLineNr := 0; curColNr := 1; (*curColNr > Length(curLine) forces reading of first line*) GetNextChar(inTXTFile); (*curCh now holds first character*) n := 0; mode := replaceMode; w := ' '; WriteLn('Replacing... '); GetNextWord(w, lnr, inTXTFile); WHILE Length(w) > 0 DO BEGIN (* Check if word is the word from the ht, and not just a word with the same hashcode *) temp := Search(w, ht); IF newLine THEN BEGIN WriteLn(outTXTFile); newLine := FALSE; END; IF temp <> NIL THEN BEGIN //WriteLn('w: ', w, ' temp: ', temp^.key, ' temp repl.: ', temp^.replacement, ' '); IF (temp^.key = w) THEN Write(outTXTFile, temp^.replacement) ELSE Write(outTXTFile, w); END ELSE Write(outTXTFile, w); n := n + 1; GetNextWord(w, lnr, inTXTFile); END; WriteLn('Finished!'); END; (* check for command line args calls Decompress or Compress *) PROCEDURE ParamCheck(); VAR replaceFileName, inFileName, outFileName : STRING; ht : HashTable; BEGIN IF (ParamCount < 3) OR (NOT FileExists(ParamStr(2))) OR (NOT FileExists(ParamStr(3))) THEN BEGIN WriteLn('Wrong input, try again: '); Write('replaceFile > '); ReadLn(replaceFileName); Write('inFile > '); ReadLn(inFileName); Write('outFile > '); ReadLn(outFileName); END ELSE BEGIN replaceFileName := ParamStr(1); inFileName := ParamStr(2); outFileName := ParamStr(3); END; InitHashTable(ht); (*$I-*) (* File initialization *) Assign(replTXTFile, replaceFileName); Reset(replTXTFile); (* read file *) Assign(inTXTFile, inFileName); Reset(inTXTFile); (* read file *) Assign(outTXTFile, outFileName); Rewrite(outTXTFile); (* Rewrite new file or write*) (* Check IOResult for opening errors *) IF IOResult <> 0 THEN BEGIN WriteLn('Error opening file!'); Exit; END; (* closing repl. cause we dont need it anymore *) FillHashTable(ht, replTXTFile); Close(replTXTFile); Replace(ht); (* close files *) Close(inTXTFile); Close(outTXTFile); END; BEGIN ParamCheck(); END.
unit LookAt; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, aiOGL; type TLookAtForm = class(TForm) Panel1: TPanel; OKBtn: TBitBtn; ApplyBtn: TButton; EyeBox: TGroupBox; Label3: TLabel; Label1: TLabel; EyeYEdit: TEdit; Label2: TLabel; EyeZEdit: TEdit; EyeXEdit: TEdit; GroupBox1: TGroupBox; Label4: TLabel; Label5: TLabel; Label6: TLabel; RefYEdit: TEdit; RefZEdit: TEdit; RefXEdit: TEdit; GroupBox2: TGroupBox; Label7: TLabel; Label8: TLabel; Label9: TLabel; UpYEdit: TEdit; UpZEdit: TEdit; UpXEdit: TEdit; CancelBtn: TBitBtn; procedure ApplyBtnClick(Sender: TObject); procedure OKBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CancelBtnClick(Sender: TObject); private EyePointSave, RefPointSave, UpVectorSave: TVector; end; var LookAtForm: TLookAtForm; implementation uses Data; {$R *.DFM} procedure TLookAtForm.FormCreate(Sender: TObject); begin with CurScene do begin EyePointSave:= EyePoint; RefPointSave:= RefPoint; UpVectorSave:= UpVector; ShowVector(EyePoint, EyeXEdit, EyeYEdit, EyeZEdit); ShowVector(RefPoint, RefXEdit, RefYEdit, RefZEdit); ShowVector(UpVector, UpXEdit, UpYEdit, UpZEdit); end; end; procedure TLookAtForm.ApplyBtnClick(Sender: TObject); begin with CurScene do begin EyePoint:= GetVector(EyeXEdit, EyeYEdit, EyeZEdit); RefPoint:= GetVector(RefXEdit, RefYEdit, RefZEdit); UpVector:= GetVector(UpXEdit, UpYEdit, UpZEdit); LookAt; Paint; end; end; procedure TLookAtForm.OKBtnClick(Sender: TObject); begin ApplyBtnClick(Sender); end; procedure TLookAtForm.CancelBtnClick(Sender: TObject); begin with CurScene do begin EyePoint:= EyePointSave; RefPoint:= RefPointSave; UpVector:= UpVectorSave; LookAt; Paint; end; end; end.
unit IsoSurfaceFile; interface uses Voxel; type CIsosurfaceFile = class public // I/O procedure SaveToFile(const _Filename: string; const _Voxel: TVoxelSection); end; implementation uses VoxelMap, BasicConstants, SysUtils, Dialogs, BasicDataTypes; // http://www.matmidia.mat.puc-rio.br/tomlew/publication_page.php?pubkey=marching_cubes_jgt // It saves .iso files used by Thomas Lewiner's marching cubes program. I need // to test it with VXLSE III's entries. -- Banshee procedure CIsosurfaceFile.SaveToFile(const _Filename: string; const _Voxel: TVoxelSection); var F: File; x,y,z,maxx,maxy,maxz: integer; NegValue,PosValue : single; Value : longword; Map: TVoxelMap; begin try AssignFile(F,_Filename); FileMode := fmOpenWrite; // we save file, so write mode [VK] Rewrite(F,1); // file of byte Value := _Voxel.Tailer.XSize + 2; BlockWrite(F,Value, sizeof(longword)); Value := _Voxel.Tailer.ZSize + 2; BlockWrite(F,Value, sizeof(longword)); Value := _Voxel.Tailer.YSize + 2; BlockWrite(F,Value, sizeof(longword)); NegValue := -1.0; PosValue := 1.0; BlockWrite(F,NegValue, sizeof(single)); BlockWrite(F,PosValue, sizeof(single)); BlockWrite(F,NegValue, sizeof(single)); BlockWrite(F,PosValue, sizeof(single)); BlockWrite(F,NegValue, sizeof(single)); BlockWrite(F,PosValue, sizeof(single)); Map := TVoxelMap.CreateQuick(_Voxel,1); Map.GenerateVolumeMap; maxx := High(_Voxel.Data) +2; maxy := High(_Voxel.Data[0]) + 2; maxz := High(_Voxel.Data[0,0]) + 2; for x := 0 to maxx do for z := 0 to maxz do for y := 0 to maxy do begin if Map.MapSafe[x,y,z] = C_INSIDE_VOLUME then BlockWrite(F,NegValue, sizeof(single)) else BlockWrite(F,PosValue, sizeof(single)); end; CloseFile(F); except on E : EInOutError do // VK 1.36 U MessageDlg('Error: ' + E.Message + Char($0A) + _Filename, mtError, [mbOK], 0); end; end; end.
unit uImageLoader; interface uses System.SysUtils, System.Classes, System.DateUtils, System.Math, Winapi.Windows, Vcl.Graphics, Vcl.Imaging.PngImage, CCR.Exif, CCR.Exif.XMPUtils, Dmitry.Utils.System, GraphicEx, GraphicCrypt, UnitDBDeclare, uTiffImage, uConstants, uMemory, uLogger, uRawExif, uExifUtils, uICCProfile, uAssociations, uGraphicUtils, uPortableDeviceUtils, uSettings, uRAWImage, uBitmapUtils, uJpegUtils, uTranslate, uDBEntities, uFormInterfaces, uSessionPasswords, uPNGUtils; type TImageLoadFlag = (ilfGraphic, ilfICCProfile, ilfEXIF, ilfFullRAW, ilfHalfRawSize, ilfPassword, ilfAskUserPassword, ilfThrowError, ilfDontUpdateInfo, ilfUseCache); TImageLoadFlags = set of TImageLoadFlag; TImageLoadBitmapFlag = (ilboFreeGraphic, ilboFullBitmap, ilboAddShadow, ilboRotate, ilboApplyICCProfile, ilboDrawAttributes, ilboQualityResize); TImageLoadBitmapFlags = set of TImageLoadBitmapFlag; TLoadImageProgressState = (lipsReading); TLoadImageProgress = procedure(ProgressState: TLoadImageProgressState; BytesTotal, BytesComplete: Int64; var Break: Boolean) of object; ILoadImageInfo = interface ['{8FA3C77A-70D6-4873-9F50-DA1F450A5FF9}'] function ExtractGraphic: TGraphic; function ExtractFullBitmap: TBitmap; function GetImageTotalPages: Integer; function GetRotation: Integer; function AppllyICCProfile(Bitmap: TBitmap): Boolean; function UpdateImageGeoInfo(Info: TMediaItem): Boolean; function UpdateImageInfo(Info: TMediaItem; IsDBValues: Boolean = True; LoadGroups: Boolean = False): Boolean; function GenerateBitmap(Info: TMediaItem; Width, Height: Integer; PixelFormat: TPixelFormat; BackgroundColor: TColor; Flags: TImageLoadBitmapFlags): TBitmap; function SaveWithExif(Graphic: TGraphic; FileName: string): Boolean; function TryUpdateExif(MS: TMemoryStream; Graphic: TGraphic): Boolean; function GetGraphicWidth: Integer; function GetGraphicHeight: Integer; function GetIsImageEncrypted: Boolean; function GetPassword: string; function GetHasExifHeader: Boolean; function GetExifData: TExifData; function GetRawExif: TRAWExif; property ImageTotalPages: Integer read GetImageTotalPages; property Rotation: Integer read GetRotation; property GraphicWidth: Integer read GetGraphicWidth; property GraphicHeight: Integer read GetGraphicHeight; property IsImageEncrypted: Boolean read GetIsImageEncrypted; property Password: string read GetPassword; property HasExifHeader: Boolean read GetHasExifHeader; property ExifData: TExifData read GetExifData; property RawExif: TRAWExif read GetRawExif; end; TLoadImageInfo = class(TInterfacedObject, ILoadImageInfo) private FGraphic: TGraphic; FFullBitmap: TBitmap; FImageTotalPages: Integer; FRotation: Integer; FICCProfileName: string; FIsImageEncrypted: Boolean; FPassword: string; FMSICC: TMemoryStream; FExifData: TExifData; FRawExif: TRAWExif; FGraphicWidth: Integer; FGraphicHeight: Integer; public constructor Create(AGraphic: TGraphic; AImageTotalPages: Integer; ARotation: Integer; AICCProfileName: string; MSICC: TMemoryStream; AExifData: TExifData; ARawExif: TRAWExif; AIsImageEncrypted: Boolean; APassword: string); destructor Destroy; override; function ExtractGraphic: TGraphic; function ExtractFullBitmap: TBitmap; function GetImageTotalPages: Integer; function GetRotation: Integer; function GetGraphicWidth: Integer; function GetGraphicHeight: Integer; function GetIsImageEncrypted: Boolean; function GetPassword: string; function GetHasExifHeader: Boolean; function GetExifData: TExifData; function GetRawExif: TRAWExif; function AppllyICCProfile(Bitmap: TBitmap): Boolean; function UpdateImageGeoInfo(Info: TMediaItem): Boolean; function UpdateImageInfo(Info: TMediaItem; IsDBValues: Boolean = True; LoadGroups: Boolean = False): Boolean; function GenerateBitmap(Info: TMediaItem; Width, Height: Integer; PixelFormat: TPixelFormat; BackgroundColor: TColor; Flags: TImageLoadBitmapFlags): TBitmap; function SaveWithExif(Graphic: TGraphic; FileName: string): Boolean; function TryUpdateExif(MS: TMemoryStream; Graphic: TGraphic): Boolean; end; type TStreamHelper = class helper for TStream public function CopyFromEx(Source: TStream; Count: Int64; MaxBufSize: Integer; Progress: TLoadImageProgress): Int64; end; function LoadImageFromPath(Info: TMediaItem; LoadPage: Integer; Password: string; Flags: TImageLoadFlags; out ImageInfo: ILoadImageInfo; Width: Integer = 0; Height: Integer = 0; Progress: TLoadImageProgress = nil): Boolean; implementation function DisplayProfileName: string; begin Result := AppSettings.ReadString('Options', 'DisplayICCProfileName', DEFAULT_ICC_DISPLAY_PROFILE); if Result = '-' then Result := ''; end; function LoadImageFromPath(Info: TMediaItem; LoadPage: Integer; Password: string; Flags: TImageLoadFlags; out ImageInfo: ILoadImageInfo; Width: Integer = 0; Height: Integer = 0; Progress: TLoadImageProgress = nil): Boolean; var FS: TFileStream; S: TStream; GraphicClass: TGraphicClass; TiffImage: TTiffImage; PngImage: TPngImage; Graphic: TGraphic; EXIFRotation, ImageTotalPages, I, J: Integer; ExifData: TExifData; RawExif: TRAWExif; MSICC: TMemoryStream; XMPICCProperty: TXMPProperty; XMPICCPrifile: string; IsImageEncrypted: Boolean; LoadToMemory, LoadOnlyExif: Boolean; OldMode: Cardinal; begin Result := False; ImageInfo := nil; RawExif := nil; ImageTotalPages := 0; EXIFRotation := DB_IMAGE_ROTATE_0; IsImageEncrypted := False; try OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try GraphicClass := TFileAssociations.Instance.GetGraphicClass(ExtractFileExt(Info.FileName)); if GraphicClass = nil then Exit(False); MSICC := nil; LoadToMemory := not (GraphicClass = TRAWImage) and (ilfEXIF in Flags); if (GraphicClass = TPSDGraphic) then LoadToMemory := False; if IsDevicePath(Info.FileName) then LoadToMemory := True; if not LoadToMemory then S := nil else S := TMemoryStream.Create; try if (ilfGraphic in Flags) then begin if not IsDevicePath(Info.FileName) then begin FS := TFileStream.Create(Info.FileName, fmOpenRead or fmShareDenyWrite); try IsImageEncrypted := ValidCryptGraphicStream(FS); Info.Encrypted := IsImageEncrypted; if Info.Encrypted then begin if ilfPassword in Flags then Password := SessionPasswords.FindForFile(Info.FileName); if (Password = '') and (ilfAskUserPassword in flags) then TThread.Synchronize(nil, procedure begin Password := RequestPasswordForm.ForImage(Info.FileName); end ); if (Password = '') and (ilfThrowError in Flags) then raise Exception.Create(FormatEx(TA('Can''t decrypt image "{0}"', 'Image'), [Info.FileName])); if S = nil then S := TMemoryStream.Create; DecryptStreamToStream(FS, S, Password); end else begin if not LoadToMemory then begin S := FS; FS := nil; end else S.CopyFromEx(FS, FS.Size, 1024 * 1024, Progress); end; finally F(FS); end; end else begin if S = nil then S := TMemoryStream.Create; ReadStreamFromDevice(Info.FileName, S); end; end; LoadOnlyExif := (ilfEXIF in Flags) and not (ilfGraphic in Flags); if (S <> nil) or LoadOnlyExif then begin if Flags * [ilfICCProfile, ilfEXIF, ilfGraphic] <> [] then begin if not LoadOnlyExif then S.Seek(0, soFromBeginning); ExifData := TExifData.Create(nil); if IsRAWImageFile(Info.FileName) then RawExif := TRAWExif.Create; try try if Flags * [ilfEXIF] <> [] then begin if LoadOnlyExif then begin ExifData.LoadFromFileEx(Info.FileName, False); if RawExif <> nil then RawExif.LoadFromFile(Info.FileName); end else begin ExifData.LoadFromGraphic(S); if RawExif <> nil then begin S.Seek(0, soFromBeginning); RawExif.LoadFromStream(S); end; end; if not ExifData.Empty then begin if not (ilfDontUpdateInfo in Flags) then begin Info.HasExifHeader := True; if (ExifData.ImageDateTime > 0) and (YearOf(ExifData.ImageDateTime) >= cMinEXIFYear) then begin Info.Date := DateOf(ExifData.ImageDateTime); Info.Time := TimeOf(ExifData.ImageDateTime); end; end; if (ilfEXIF in Flags) then EXIFRotation := ExifOrientationToRatation(Ord(ExifData.Orientation)); if (ilfICCProfile in Flags) then begin if (ExifData.ColorSpace = csTagMissing) or (ExifData.ColorSpace = csUncalibrated) or (ExifData.ColorSpace = csICCProfile) then begin if ExifData.HasICCProfile then begin MSICC := TMemoryStream.Create; ExifData.ExtractICCProfile(MSICC); end; if MSICC = nil then begin XMPICCProperty := ExifData.XMPPacket.Schemas[xsPhotoshop].Properties['ICCProfile']; if XMPICCProperty <> nil then XMPICCPrifile := XMPICCProperty.ReadValue(); end; end; end; end; end; except //EXIF loading errors should't affect image loading, ignore possible errors on e: Exception do EventLog(e); end; if (ilfGraphic in Flags) then begin Graphic := GraphicClass.Create; try InitGraphic(Graphic); if (Graphic is TRAWImage) then begin TRAWImage(Graphic).IsPreview := not (ilfFullRAW in Flags); if TRAWImage(Graphic).IsPreview then TRAWImage(Graphic).PreviewSize := Max(Width, Height); if (ilfHalfRawSize in Flags) then TRAWImage(Graphic).HalfSizeLoad := True; end; if not (ilfDontUpdateInfo in flags) and (Info.ID = 0) {and not IsDevicePath(Info.FileName)} then Info.Rotation := EXIFRotation or DB_IMAGE_ROTATE_NO_DB; S.Seek(0, soFromBeginning); if (Graphic is TTiffImage) then begin TiffImage := TTiffImage(Graphic); TiffImage.LoadFromStreamEx(S, LoadPage); ImageTotalPages := TiffImage.Pages; end else Graphic.LoadFromStream(S); if not Graphic.Empty then begin //load ICC profile from PNG image if (Graphic is TPngImage) and (ilfICCProfile in Flags) and (MSICC = nil) then ApplyPNGIccProfile(TPngImage(Graphic), DisplayProfileName); ImageInfo := TLoadImageInfo.Create( Graphic, ImageTotalPages, EXIFRotation, XMPICCPrifile, MSICC, ExifData, RawExif, IsImageEncrypted, Password); ExifData := nil; MSICC := nil; Graphic := nil; RawExif := nil; Result := True; end else begin if (Graphic = nil) and (ilfThrowError in Flags) then raise Exception.Create(FormatEx(TA('Can''t load image "{0}"', 'Image'), [Info.FileName])); if (Graphic.Empty) and (ilfThrowError in Flags) then raise Exception.Create(FormatEx(TA('Image "{0}" is empty!', 'Image'), [Info.FileName])); end; finally F(Graphic); end; end else begin ImageInfo := TLoadImageInfo.Create( nil, ImageTotalPages, EXIFRotation, XMPICCPrifile, MSICC, ExifData, RawExif, IsImageEncrypted, Password); ExifData := nil; RawExif := nil; MSICC := nil; Result := True; end; finally F(ExifData); end; end; end; finally F(S); F(MSICC); F(RawExif); end; finally SetErrorMode(OldMode); end; except on e: Exception do begin EventLog(e); if (ilfThrowError in Flags) then raise; end; end; end; { TLoadImageInfo } function TLoadImageInfo.AppllyICCProfile(Bitmap: TBitmap): Boolean; begin Result := False; if (Bitmap <> nil) and not Bitmap.Empty and (Bitmap.PixelFormat = pf24Bit) then begin if (FMSICC <> nil) and (FMSICC.Size > 0) then Result := ConvertBitmapToDisplayICCProfile(Self, Bitmap, FMSICC.Memory, FMSICC.Size, '', DisplayProfileName); if not Result and (FICCProfileName <> '') then Result := ConvertBitmapToDisplayICCProfile(Self, Bitmap, nil, 0, FICCProfileName, DisplayProfileName); end; end; constructor TLoadImageInfo.Create(AGraphic: TGraphic; AImageTotalPages, ARotation: Integer; AICCProfileName: string; MSICC: TMemoryStream; AExifData: TExifData; ARawExif: TRAWExif; AIsImageEncrypted: Boolean; APassword: string); begin FGraphic := AGraphic; FFullBitmap := nil; FImageTotalPages := AImageTotalPages; FRotation := ARotation; FICCProfileName := AICCProfileName; FMSICC := MSICC; FExifData := AExifData; FRawExif := ARawExif; FGraphicWidth := 0; FGraphicHeight := 0; FIsImageEncrypted := AIsImageEncrypted; FPassword := APassword; if FGraphic <> nil then begin FGraphicWidth := FGraphic.Width; FGraphicHeight := FGraphic.Height; end; end; destructor TLoadImageInfo.Destroy; begin F(FExifData); F(FRawExif); F(FMSICC); F(FGraphic); F(FFullBitmap); inherited; end; function TLoadImageInfo.ExtractFullBitmap: TBitmap; begin Result := FFullBitmap; FFullBitmap := nil; end; function TLoadImageInfo.ExtractGraphic: TGraphic; begin Result := FGraphic; FGraphic := nil; end; function TLoadImageInfo.GenerateBitmap(Info: TMediaItem; Width, Height: Integer; PixelFormat: TPixelFormat; BackgroundColor: TColor; Flags: TImageLoadBitmapFlags): TBitmap; var B, B32: TBitmap; W, H: Integer; begin Result := nil; if FGraphic = nil then Exit(nil); B := TBitmap.Create; try if (Width > 0) and (Height > 0) and not (ilboFullBitmap in Flags) then JPEGScale(FGraphic, Width, Height); AssignGraphic(B, FGraphic); if ilboFreeGraphic in Flags then F(FGraphic); Exchange(B, Result); finally F(B); end; if (Result <> nil) and (PixelFormat = pf24bit) then begin if Result.PixelFormat = pf32bit then begin B := TBitmap.Create; try LoadBMPImage32bit(Result, B, BackgroundColor); Exchange(B, Result); finally F(B); end; end else Result.PixelFormat := pf24Bit; end; if (Result <> nil) and (PixelFormat <> pf24bit) and (PixelFormat <> pf32bit) then Result.PixelFormat := pf24Bit; if (Result <> nil) and (Width > 0) and (Height > 0) then begin B := TBitmap.Create; try B.PixelFormat := Result.PixelFormat; W := Result.Width; H := Result.Height; ProportionalSize(Width, Height, W, H); if ilboQualityResize in Flags then StretchEx(W, H, sfLanczos3, 0, Result, B) else DoResize(W, H, Result, B); if ilboFullBitmap in Flags then begin FFullBitmap := Result; Result := nil; end; Exchange(B, Result); finally F(B); end; end; if ilboRotate in Flags then ApplyRotate(Result, Info.Rotation); if ilboApplyICCProfile in Flags then AppllyICCProfile(Result); if (ilboAddShadow in Flags) then begin B32 := TBitmap.Create; try DrawShadowToImage(B32, Result); B32.AlphaFormat := afDefined; if (Result.PixelFormat = pf24bit) then LoadBMPImage32bit(B32, Result, BackgroundColor) else Exchange(B32, Result); finally F(B32); end; end; end; function TLoadImageInfo.GetExifData: TExifData; begin Result := FExifData; end; function TLoadImageInfo.GetGraphicHeight: Integer; begin Result := FGraphicHeight; end; function TLoadImageInfo.GetGraphicWidth: Integer; begin Result := FGraphicWidth; end; function TLoadImageInfo.GetHasExifHeader: Boolean; begin Result := not FExifData.Empty; end; function TLoadImageInfo.GetImageTotalPages: Integer; begin Result := FImageTotalPages; end; function TLoadImageInfo.GetIsImageEncrypted: Boolean; begin Result := FIsImageEncrypted; end; function TLoadImageInfo.GetPassword: string; begin Result := FPassword; end; function TLoadImageInfo.GetRawExif: TRAWExif; begin Result := FRawExif; end; function TLoadImageInfo.GetRotation: Integer; begin Result := FRotation; end; function TLoadImageInfo.SaveWithExif(Graphic: TGraphic; FileName: string): Boolean; begin if not FExifData.Empty then begin FExifData.BeginUpdate; try FExifData.Orientation := toTopLeft; FExifData.ExifImageWidth := Graphic.Width; FExifData.ExifImageHeight := Graphic.Height; FExifData.Thumbnail := nil; Graphic.SaveToFile(FileName); FExifData.SaveToGraphic(FileName); finally FExifData.EndUpdate; end; end else Graphic.SaveToFile(FileName); Result := True; end; function TLoadImageInfo.TryUpdateExif(MS: TMemoryStream; Graphic: TGraphic): Boolean; begin Result := False; if (FExifData <> nil) and not FExifData.Empty then begin FixEXIFForJpegStream(FExifData, MS, Graphic.Width, Graphic.Height); Result := True; end; end; function TLoadImageInfo.UpdateImageGeoInfo(Info: TMediaItem): Boolean; begin Result := False; if FExifData <> nil then Result := UpdateImageGeoInfoFromExif(Info, FExifData); end; function TLoadImageInfo.UpdateImageInfo(Info: TMediaItem; IsDBValues: Boolean = True; LoadGroups: Boolean = False): Boolean; begin Result := False; try if FExifData <> nil then Result := UpdateImageRecordFromExifData(Info, FExifData, IsDBValues, LoadGroups); except on e: Exception do EventLog(e); end; end; { TStreamHelper } function TStreamHelper.CopyFromEx(Source: TStream; Count: Int64; MaxBufSize: Integer; Progress: TLoadImageProgress): Int64; var BufSize, N: Integer; Buffer: PByte; IsBreak: Boolean; begin if Count = 0 then begin Source.Position := 0; Count := Source.Size; end; IsBreak := False; Result := Count; if Count > MaxBufSize then BufSize := MaxBufSize else BufSize := Count; GetMem(Buffer, BufSize); try while Count <> 0 do begin if Count > BufSize then N := BufSize else N := Count; Source.ReadBuffer(Buffer^, N); WriteBuffer(Buffer^, N); Dec(Count, N); if Assigned(Progress) then Progress(lipsReading, Result, Size, IsBreak); if IsBreak then Break; end; finally FreeMem(Buffer, BufSize); end; end; end.
unit FmImInfo; interface uses WinProcs, WinTypes, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Spin, GifUnit, FmSubImg; type TGifImageInfoDialog = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; V87a: TRadioButton; V89a: TRadioButton; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; WidthEdit: TSpinEdit; HeightEdit: TSpinEdit; PackedFieldsEdit: TSpinEdit; BgColorIndexEdit: TSpinEdit; AspectRatioEdit: TSpinEdit; HasGlobalColormapBox: TCheckBox; BitsPerPixelEdit: TSpinEdit; Label6: TLabel; NoSubImagesEdit: TSpinEdit; Label7: TLabel; Button1: TButton; NoColorsEdit: TSpinEdit; Label8: TLabel; procedure Button1Click(Sender: TObject); private { Private declarations } SubImageDialog: TSubImageDialog; public { Public declarations } constructor Create(GifImage: TGifFile); end; var GifImageInfoDialog: TGifImageInfoDialog; implementation {$R *.DFM} constructor TGifImageInfoDialog.Create(GifImage: TGifFile); begin { TGifImageInfoDialog.Create } inherited Create(nil); with GifImage do begin if Header.Version[1] = '7' then V87a.Checked := True else V89a.Checked := True; WidthEdit.Value := ScreenDescriptor.ScreenWidth; HeightEdit.Value := ScreenDescriptor.ScreenHeight; PackedFieldsEdit.Value := ScreenDescriptor.PackedFields; BgColorIndexEdit.Value := ScreenDescriptor.BackgroundColorIndex; AspectRatioEdit.Value := ScreenDescriptor.AspectRatio; HasGlobalColormapBox.Checked := HasGlobalColormap; BitsPerPixelEdit.Value := BitsPerPixel; NoSubImagesEdit.value := SubImages.Count; if HasGlobalColormap then NoColorsEdit.Value := GlobalColormap.Count; SubImageDialog := TSubImageDialog.Create(SubImages); end; end; { TGifImageInfoDialog.Create } procedure TGifImageInfoDialog.Button1Click(Sender: TObject); begin SubImageDialog.Show; end; end.
unit HS4Bind.Get; interface uses System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, Vcl.ExtCtrls, Vcl.Imaging.jpeg, Vcl.Graphics, HS4Bind.Interfaces; type THS4bindGet = class(TInterfacedObject, iHS4BindGet) private FParent : iHS4Bind; FFileName : string; procedure GetImageByUrl(URL: string; APicture: TPicture); public constructor Create(Parent : iHS4Bind); destructor Destroy; override; class function New (aParent : iHS4Bind): iHS4BindGet; function Get(var aImage : TImage) : iHS4BindGet; function FileName(aName : string) : iHS4BindGet; end; implementation uses System.Classes; { THS4bindGet } constructor THS4bindGet.Create(Parent: iHS4Bind); begin FParent:= Parent; end; destructor THS4bindGet.Destroy; begin inherited; end; function THS4bindGet.FileName(aName: string): iHS4BindGet; begin Result:= Self; FFileName:= aName; end; function THS4bindGet.Get(var aImage : TImage) : iHS4BindGet; begin result:= self; if pos('http', FFileName) > 0 then begin GetImageByUrl(FFileName, aImage.Picture); end else begin aImage.Picture.LoadFromFile(FFileName); end; end; procedure THS4bindGet.GetImageByUrl(URL: string; APicture: TPicture); var Jpeg: TJPEGImage; Strm: TMemoryStream; vIdHTTP : TIdHTTP; begin Jpeg := TJPEGImage.Create; Strm := TMemoryStream.Create; vIdHTTP := TIdHTTP.Create(nil); try vIdHTTP.Get(URL, Strm); if (Strm.Size > 0) then begin Strm.Position := 0; Jpeg.LoadFromStream(Strm); APicture.Assign(Jpeg); end; finally Strm.Free; Jpeg.Free; vIdHTTP.Free; end; end; class function THS4bindGet.New(aParent : iHS4Bind): iHS4BindGet; begin result:= Self.Create(aParent); end; end.
unit UnitViewerCommon.FMX; // ------------------------------------------------------------------------------ // // SVG Control 2.0 // Copyright (c) 2015 Bruno Verhue // // ------------------------------------------------------------------------------ // [The "BSD licence"] // // Copyright (c) 2013 Bruno Verhue // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ----------------------------------------------------------------------------- /// <summary> /// /// This unit contains the core functionality of the "SVG Viewer demo". /// /// Add the following paths to the project search path or library path: /// /// 1. In case of demo: /// <Root folder>\<Delphi version>\Dcu /// /// 2. In case of full version with source code: /// <Root folder>\Common /// <Root folder>\Common\Fmx /// <Root folder>\Common\Platform /// /// </summary> {$IFDEF ANDROID} {$DEFINE SVGIMAGE} {$ENDIF} {-$DEFINE SVGLINKEDIMAGE} {$Include 'DemoAppCompilerSettings.inc'} interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, {$IFDEF ANDROID} FMX.Platform.Android, Androidapi.JNI.JavaTypes, Androidapi.JNI.App, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Net, AndroidApi.Helpers, {$ENDIF} FMX.Platform, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Objects, FMX.Layouts, FMX.StdCtrls, FMX.ListBox, FMX.EditBox, FMX.SpinBox, FMX.Dialogs, FMX.ActnList, BVE.SVG2Intf, BVE.SVG2Types, BVE.SVG2Doc, BVE.SVG2Control.FMX, BVE.SVG2Image.FMX, BVE.SVG2ImageList.FMX; type TSVGSelection = class; ISVGViewer = interface ['{50CEF706-3E81-45D1-AD79-3D8F0F0D3DFC}'] function GetForm: TForm; function GetScrollbox: TScrollbox; function GetSelection: TSVGSelection; procedure SetSelection(const Value: TSVGSelection); procedure AlignControls; procedure ShowInfo(const aValue: string); property Form: TForm read GetForm; property Scrollbox: TScrollbox read GetScrollbox; property Selection: TSVGSelection read GetSelection write SetSelection; end; TSVGZoomBox = class(TComponent) private FForm: TForm; FLayoutSize: TLayout; FLayoutZoom: TLayout; FScrollbox: TScrollbox; FZoom: Single; procedure SetZoom(const Value: Single); public constructor Create(aForm: TForm; aLayoutSize, aLayoutZoom: TLayout; aScrollbox: TScrollbox); reintroduce; destructor Destroy; override; procedure CalcLayoutDimensions; property Zoom: Single read FZoom write SetZoom; end; TSVGSelection = class(TSelection) private FViewer: ISVGViewer; FSelected: Boolean; FHasEvents: Boolean; FAnimationTimer: TSVG2AnimationTimer; FLastLocation: TPointF; FLastDistance: Single; FTimerUpdate: TTimer; {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage: TSVG2LinkedImage; {$ELSE} {$IFDEF SVGIMAGE} FSVGImage: TSVG2Image; {$ELSE} FSVGControl: TSVG2Control; {$ENDIF} {$ENDIF} function GetAnimationFPS: TSVGFloat; function GetAnimationIsPaused: Boolean; function GetAnimationIsStarted: Boolean; function GetAnimationTime: Cardinal; function GetAspectRatioAlign: TSVGAspectRatioAlign; function GetAspectRatioMeetOrSlice: TSVGAspectRatioMeetOrSlice; function GetAutoViewbox: boolean; function GetFilename: string; function GetImageIndex: integer; function GetImages: TSVG2ImageList; function GetOnAnimationSample: TNotifyEvent; function GetOnSVGEvent: TSVGEvent; function GetOpacity: Single; function GetRenderOptions: TSVGRenderOptions; procedure SetAnimationIsPaused(const Value: Boolean); procedure SetAnimationIsStarted(const Value: Boolean); procedure SetAnimationTime(const Value: Cardinal); procedure SetAspectRatioAlign(const Value: TSVGAspectRatioAlign); procedure SetAspectRatioMeetOrSlice( const Value: TSVGAspectRatioMeetOrSlice); procedure SetAutoViewbox(const Value: boolean); procedure SetImageIndex(const Value: integer); procedure SetImages(const Value: TSVG2ImageList); procedure SetFileName(const Value: string); procedure SetOnAnimationSample(const Value: TNotifyEvent); procedure SetOnSVGEvent(const Value: TSVGEvent); procedure SetOpacity(const Value: Single); procedure SetSelected(const Value: boolean); procedure SetRenderOptions(const Value: TSVGRenderOptions); function GetHasAnimations: Boolean; protected function GetSVG: string; procedure SetSVG(const Value: string); {$IFDEF Ver270Down} function GetAbsoluteRect: TRectF; override; {$ELSE} function DoGetUpdateRect: TRectF; override; {$ENDIF} procedure DoGesture(const EventInfo: TGestureEventInfo; var Handled: Boolean); override; procedure UpdateContent(Sender: TObject); public constructor Create(aViewer: ISVGViewer); reintroduce; destructor Destroy; override; function CreateCopy: TSVGSelection; procedure Assign(aObject: TPersistent); override; function GetSVGContent: string; procedure ContentMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure ContentMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); procedure ContentMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure ContentGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; property AnimationFPS: TSVGFloat read GetAnimationFPS; property AnimationIsStarted: Boolean read GetAnimationIsStarted write SetAnimationIsStarted; property AnimationIsPaused: Boolean read GetAnimationIsPaused write SetAnimationIsPaused; property AnimationTime: Cardinal read GetAnimationTime write SetAnimationTime; property AspectRatioAlign: TSVGAspectRatioAlign read GetAspectRatioAlign write SetAspectRatioAlign; property AspectRatioMeetOrSlice: TSVGAspectRatioMeetOrSlice read GetAspectRatioMeetOrSlice write SetAspectRatioMeetOrSlice; property AutoViewbox: boolean read GetAutoViewbox write SetAutoViewbox; property Filename: string read GetFilename write SetFileName; property Images: TSVG2ImageList read GetImages write SetImages; property ImageIndex: Integer read GetImageIndex write SetImageIndex; property HasAnimations: Boolean read GetHasAnimations; property Opacity: Single read GetOpacity write SetOpacity; property RenderOptions: TSVGRenderOptions read GetRenderOptions write SetRenderOptions; property Selected: boolean read FSelected write SetSelected; property SVG: string read GetSVG write SetSVG; property OnAnimationSample: TNotifyEvent read GetOnAnimationSample write SetOnAnimationSample; property OnSVGEvent: TSVGEvent read GetOnSVGEvent write SetOnSVGEvent; end; TSVGViewerInfoForm = class; TSVGViewerForm = class(TForm, ISVGViewer) private {$IFDEF ANDROID} const FileRequestCode = 0; var FMessageSubscriptionID: Integer; FFileName: string; {$ENDIF} FTimerZoom: TTimer; FTimerAndroidLoad: TTimer; FSelection: TSVGSelection; FActionAddOk: TAction; FActionAddCancel: TAction; FActionAdd: TAction; FActionCopy: TAction; FActionCopyDirect: TAction; FActionInfo: TAction; FActionLoad: TAction; FActionPaste: TAction; FActionRemove: TAction; FActionZoomReset: TAction; FActionZoomDec: TAction; FActionZoomInc: TAction; FActionAnimationPause: TButton; FActionAnimationStart: TButton; FAnimationTrackBar: TTrackBar; FLabelTime: TLabel; FCheckboxAutoViewbox: TCheckBox; FCheckboxClippath: TCheckBox; FCheckboxFilters: TCheckBox; FCheckboxMouseEvents: TCheckBox; FComboboxAspectRatio: TComboBox; FComboboxMeetOrSlice: TComboBox; FSpinboxRotate: TSpinBox; FSpinboxOpacity: TSpinBox; FScrollbox: TScrollbox; FLayoutSide: TLayout; FLayoutSize: TLayout; FLayoutZoom: TLayout; FListbox: TListbox; FImageList1: TSVG2ImageList; FImageList2: TSVG2ImageList; FLabelInfo: TLabel; FOpenDialog: TOpenDialog; FZoomTrackBar: TTrackBar; FZoomBox: TSVGZoomBox; FFormInfo: TSVGViewerInfoForm; protected function GetForm: TForm; function GetScrollbox: TScrollbox; function GetSelection: TSVGSelection; procedure SetSelection(const Value: TSVGSelection); procedure SetFormInfo(const Value: TSVGViewerInfoForm); procedure ActionAddOkExecute(Sender: TObject); procedure ActionAddCancelExecute(Sender: TObject); procedure ActionAddExecute(Sender: TObject); procedure ActionCopyExecute(Sender: TObject); procedure ActionCopyDirectExecute(Sender: TObject); procedure ActionInfoExecute(Sender: TObject); procedure ActionLoadExecute(Sender: TObject); procedure ActionPasteExecute(Sender: TObject); procedure ActionRemoveExecute(Sender: TObject); procedure ActionZoomResetExecute(Sender: TObject); procedure ActionZoomDecExecute(Sender: TObject); procedure ActionZoomIncExecute(Sender: TObject); procedure ActionAnimationStartExecute(Sender: TObject); procedure ActionAnimationPauseExecute(Sender: TObject); procedure ScrollBoxDragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Operation: TDragOperation); procedure ScrollBoxDragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); procedure CheckboxAutoViewboxChange(Sender: TObject); procedure CheckboxClippathChange(Sender: TObject); procedure CheckboxFiltersChange(Sender: TObject); procedure CheckboxMouseEventsChange(Sender: TObject); procedure ComboboxAspectRatioChange(Sender: TObject); procedure ComboboxMeetOrSliceChange(Sender: TObject); procedure SpinboxRotateChange(Sender: TObject); procedure SpinboxOpacityChange(Sender: TObject); procedure TimerAndroidLoadTimer(Sender: TObject); procedure TimerZoomTimer(Sender: TObject); procedure TrackBarChange(Sender: TObject); procedure AnimationTrackbarChange(aSender: TObject); procedure DoTimer(aSender: TObject); procedure DoShow; override; procedure SVGEvent(Sender: TObject; aSVGRoot: ISVGRoot; aEvent: ISVGEvent; const aValue: string); procedure AlignControls; procedure Resize; override; procedure ShowInfo(const aValue: string); {$IFDEF ANDROID} function LaunchActivityForResult(const Intent: JIntent; RequestCode: Integer): Boolean; procedure LaunchLoadFile; procedure HandleActivityMessage(const Sender: TObject; const M: TMessage); function OnActivityResult(RequestCode, ResultCode: Integer; Data: JIntent): Boolean; {$ENDIF} public constructor Create(AOwnder: TComponent); override; destructor Destroy; override; procedure ConnectControls( aActionAddOk: TAction; aActionAddCancel: TAction; aActionAdd: TAction; aActionCopy: TAction; aActionCopyDirect: TAction; aActionInfo: TAction; aActionLoad: TAction; aActionPaste: TAction; aActionRemove: TAction; aActionZoomReset: TAction; aActionZoomDec: TAction; aActionZoomInc: TAction; aActionAnimationStart: TButton; aActionAnimationPause: TButton; aCheckboxAutoViewbox: TCheckBox; aCheckboxClippath: TCheckBox; aCheckboxFilters: TCheckBox; aCheckboxMouseEvents: TCheckBox; aComboboxAspectRatio: TComboBox; aComboboxMeetOrSlice: TComboBox; aSpinboxRotate: TSpinBox; aSpinboxOpacity: TSpinBox; aScrollbox: TScrollbox; aLayoutSide: TLayout; aLayoutSize: TLayout; aLayoutZoom: TLayout; aListbox: TListbox; aImageList1: TSVG2ImageList; aImageList2: TSVG2ImageList; aOpenDialog: TOpenDialog; aZoomTrackBar: TTrackBar; aLabelInfo: TLabel; aAnimationTrackbar: TTrackbar; aLabelTime: TLabel); procedure UpdateControls; procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override; function AddSVG(const aFilename: string): Boolean; procedure AddSVGSelection; property Form: TForm read GetForm; property FormInfo: TSVGViewerInfoForm read FFormInfo write SetFormInfo; property Scrollbox: TScrollbox read GetScrollbox; property Selection: TSVGSelection read GetSelection write SetSelection; end; TSVGViewerInfoForm = class(TForm) private FButton: TButton; FSVGImage: TSVG2Image; protected procedure ButtonClick(Sender: TObject); procedure SVGEvent(Sender: TObject; aSVGRoot: ISVGRoot; aEvent: ISVGEvent; const aValue: string); public constructor Create(AOwnder: TComponent); override; destructor Destroy; override; procedure ConnectControls(aButton: TButton; aSVGImage: TSVG2Image); procedure Open(const FilePath: string); end; function MaxZoom(aControl: TFmxObject): Single; implementation uses System.Math, System.Rtti, System.IOUtils, {$IFDEF MSWINDOWS} Winapi.ShellAPI, Winapi.Windows, {$ENDIF MSWINDOWS} {$IFDEF MACOS} Posix.Stdlib, {$ENDIF MACOS} {$IFDEF ANDROID} Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Net, Androidapi.JNI.App, Androidapi.helpers, {$ENDIF} {$IFDEF IOS} macapi.helpers, iOSapi.Foundation, FMX.helpers.iOS, {$ENDIF} BVE.SVG2GeomUtility; function ChildrenRect(aControl: TFmxObject): TRectF; var i: integer; Control: TControl; begin // Calc max size of a parent control Result.Left := 100000; Result.Right := 0; Result.Top := 100000; Result.Bottom := 0; for i := 0 to aControl.ChildrenCount - 1 do begin if aControl.Children[i] is TControl then begin Control := (aControl.Children[i] as TControl); if Control.Position.X < Result.Left then Result.Left := Control.Position.X; if Control.Position.Y < Result.Top then Result.Top := Control.Position.Y; if Control.Position.X + Control.Width > Result.Right then Result.Right := Control.Position.X + Control.Width; if Control.Position.Y + Control.Height > Result.Bottom then Result.Bottom := Control.Position.Y + Control.Height; end; end; end; function ChildrenMaxSize(aControl: TFmxObject): TRectF; var i: integer; Control: TControl; begin // Calc max size of a parent control Result.Left := 0; Result.Right := 0; Result.Top := 0; Result.Bottom := 0; for i := 0 to aControl.ChildrenCount - 1 do begin if aControl.Children[i] is TControl then begin Control := (aControl.Children[i] as TControl); if (Control.Width * Control.Height) > (Result.Width * Result.Height) then Result := Control.BoundsRect; end; end; end; function MaxZoom(aControl: TFmxObject): Single; var R: TRectF; Size, MaxSize: integer; begin R := ChildrenMaxSize(aControl); if (R.Width <> 0) and (R.Height <> 0) then begin Size := Max(Round(R.Width), Round(R.Height)); MaxSize := TCanvasManager.DefaultCanvas.GetAttribute( TCanvasAttribute.MaxBitmapSize); Result := MaxSize / Size; end else Result := 10; if Result > 10 then Result := 10; end; // ----------------------------------------------------------------------------- // // TSVGSelection // // ----------------------------------------------------------------------------- procedure TSVGSelection.Assign(aObject: TPersistent); var Srce: TSVGSelection; begin if aObject is TSVGSelection then begin Srce := (aObject as TSVGSelection); BeginUpdate; try Size := Srce.Size; Scale := Srce.Scale; RotationAngle := Srce.RotationAngle; Position := Srce.Position; Position.X := Position.X + 10; Position.Y := Position.Y + 10; {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.Assign(Srce.FSVGLinkedImage); {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.Assign(Srce.FSVGImage); {$ELSE} FSVGControl.Assign(Srce.FSVGControl); {$ENDIF} {$ENDIF} finally Endupdate; end; end else inherited; end; procedure TSVGSelection.ContentGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); begin DoGesture(EventInfo, Handled); end; procedure TSVGSelection.ContentMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin MouseDown(Button, Shift, X, Y); end; procedure TSVGSelection.ContentMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); begin MouseMove(Shift, X, Y); end; procedure TSVGSelection.ContentMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin MouseUp(Button, Shift, X, Y); end; constructor TSVGSelection.Create(aViewer: ISVGViewer); begin inherited Create(aViewer.Form); FViewer := aViewer; FAnimationTimer := TSVG2AnimationTimer.Create(nil); {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage := TSVG2LinkedImage.Create(Self); FSVGLinkedImage.Parent := Self; FSVGLinkedImage.HitTest := False; FSVGLinkedImage.Position.X := 0.0; FSVGLinkedImage.Position.Y := 0.0; FSVGLinkedImage.Scale.X := 1.0; FSVGLinkedImage.Scale.Y := 1.0; FSVGLinkedImage.AnimationTimer := FAnimationTimer; FSVGLinkedImage.OnMouseDown := ContentMouseDown; FSVGLinkedImage.OnMouseMove := ContentMouseMove; FSVGLinkedImage.OnMouseUp := ContentMouseUp; FSVGLinkedImage.OnGesture := ContentGesture; {$ELSE} {$IFDEF SVGIMAGE} FSVGImage := TSVG2Image.Create(Self); FSVGImage.Parent := Self; FSVGImage.HitTest := False; FSVGImage.Position.X := 0.0; FSVGImage.Position.Y := 0.0; FSVGImage.AutoViewbox := True; FSVGImage.AnimationTimer := FAnimationTimer; FSVGImage.OnMouseDown := ContentMouseDown; FSVGImage.OnMouseMove := ContentMouseMove; FSVGImage.OnMouseUp := ContentMouseUp; FSVGImage.OnGesture := ContentGesture; {$ELSE} FSVGControl := TSVG2Control.Create(Self); FSVGControl.Parent := Self; FSVGControl.HitTest := True; FSVGControl.Position.X := 0.0; FSVGControl.Position.Y := 0.0; FSVGControl.AutoViewbox := True; FSVGControl.RenderOptions := [sroFilters, sroClippath, sroEvents]; FSVGControl.Opacity := 1.0; FSVGControl.AnimationTimer := FAnimationTimer; FSVGControl.OnMouseDown := ContentMouseDown; FSVGControl.OnMouseMove := ContentMouseMove; FSVGControl.OnMouseUp := ContentMouseUp; FSVGControl.OnGesture := ContentGesture; {$ENDIF} {$ENDIF} Touch.InteractiveGestures := [TInteractiveGesture.Zoom, TInteractiveGesture.Pan]; Width := 105; Height := 105; FLastLocation := PointF(0, 0); FLastDistance := 0; FTimerUpdate := TTimer.Create(Self); FTimerUpdate.Enabled := False; FTimerUpdate.Interval := 200; FTimerUpdate.OnTimer := UpdateContent; FViewer.AlignControls; end; function TSVGSelection.CreateCopy: TSVGSelection; begin Result := TSVGSelection.Create(FViewer); Result.Assign(Self); end; destructor TSVGSelection.Destroy; begin FAnimationTimer.Free; inherited; end; procedure TSVGSelection.DoGesture(const EventInfo: TGestureEventInfo; var Handled: Boolean); var D, L, Vpx, Vpy: Single; R: TRectF; begin if EventInfo.GestureID = igiZoom then begin if (TInteractiveGestureFlag.gfBegin in EventInfo.Flags) then begin if assigned(FViewer.Scrollbox) then FViewer.Scrollbox.AniCalculations.TouchTracking := []; end; if (not(TInteractiveGestureFlag.gfBegin in EventInfo.Flags)) and (not(TInteractiveGestureFlag.gfEnd in EventInfo.Flags)) then begin BeginUpdate; try D := (EventInfo.Distance - FLastDistance); Vpx := EventInfo.Location.X - FLastLocation.X; Vpy := EventInfo.Location.Y - FLastLocation.Y; //Text1.Text := Format('%0:3.1f %1:3.1f %2:3d', [ Vpx, Vpy, EventInfo.Distance]); R.Left := Position.X; R.Top := Position.Y; R.Width := Width; R.Height := Height; L := 2 * Sqrt(R.Width * R.Width + R.Height * R.Height); R.Left := R.Left - (R.Right - Vpx) / L * D; R.Top := R.Top - (R.Bottom - Vpy) / L * D; R.Right := R.Right + (R.Right - Vpx) / L * D; R.Bottom := R.Bottom + (R.Bottom - Vpy) / L * D; if (R.Width < 10) or (R.Height < 10) then Exit; Position.X := R.Left; Position.Y := R.Top; Width := R.Width; Height := R.Height; FTimerUpdate.Enabled := False; finally EndUpdate; end; Repaint; end; FLastLocation := EventInfo.Location; FLastDistance := EventInfo.Distance; if (TInteractiveGestureFlag.gfEnd in EventInfo.Flags) then begin if assigned(FViewer.Scrollbox) then FViewer.Scrollbox.AniCalculations.TouchTracking := [ttVertical, ttHorizontal]; FTimerUpdate.Enabled := True; end; end; if EventInfo.GestureID = igiPan then begin if (not(TInteractiveGestureFlag.gfBegin in EventInfo.Flags)) and (not(TInteractiveGestureFlag.gfEnd in EventInfo.Flags)) then begin BeginUpdate; try Position.X := Position.X + (EventInfo.Location.X - FLastLocation.X); Position.Y := Position.Y + (EventInfo.Location.Y - FLastLocation.Y); finally EndUpdate; end; Repaint; end; FLastLocation := EventInfo.Location; end; end; {$IFDEF Ver270Down} function TSVGSelection.GetAbsoluteRect: TRectF; {$ELSE} function TSVGSelection.DoGetUpdateRect: TRectF; {$ENDIF} begin // Bug in Delphi Scale should be AbsoluteScale Result := inherited; Result.Inflate((GripSize + 1) * AbsoluteScale.X, (GripSize + 1) * AbsoluteScale.Y); end; function TSVGSelection.GetAnimationFPS: TSVGFloat; begin Result := FAnimationTimer.FPS; end; function TSVGSelection.GetAnimationIsPaused: Boolean; begin Result := FAnimationTimer.IsPaused; end; function TSVGSelection.GetAnimationIsStarted: Boolean; begin Result := FAnimationTimer.IsStarted; end; function TSVGSelection.GetAnimationTime: Cardinal; begin {$IFDEF SVGLINKEDIMAGE} Result := FSVGLinkedImage.AnimationTime; {$ELSE} {$IFDEF SVGIMAGE} Result := FSVGImage.AnimationTime; {$ELSE} Result := FSVGControl.AnimationTime; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetAspectRatioAlign: TSVGAspectRatioAlign; begin {$IFDEF SVGLINKEDIMAGE} Result := FSVGLinkedImage.AspectRatioAlign; {$ELSE} {$IFDEF SVGIMAGE} Result := FSVGImage.AspectRatioAlign; {$ELSE} Result := FSVGControl.AspectRatioAlign; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetAspectRatioMeetOrSlice: TSVGAspectRatioMeetOrSlice; begin {$IFDEF SVGLINKEDIMAGE} Result := FSVGLinkedImage.AspectRatioMeetOrSlice; {$ELSE} {$IFDEF SVGIMAGE} Result := FSVGImage.AspectRatioMeetOrSlice; {$ELSE} Result := FSVGControl.AspectRatioMeetOrSlice; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetAutoViewbox: boolean; begin {$IFDEF SVGLINKEDIMAGE} Result := FSVGLinkedImage.AutoViewbox; {$ELSE} {$IFDEF SVGIMAGE} Result := FSVGImage.AutoViewbox; {$ELSE} Result := FSVGControl.AutoViewbox; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetFilename: string; begin {$IFDEF SVGLINKEDIMAGE} Result := ''; {$ELSE} {$IFDEF SVGIMAGE} Result := FSVGImage.Filename; {$ELSE} Result := FSVGControl.Filename; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetHasAnimations: Boolean; begin {$IFDEF SVGLINKEDIMAGE} Result := FSVGLinkedImage.HasAnimations; {$ELSE} {$IFDEF SVGIMAGE} Result := FSVGImage.HasAnimations; {$ELSE} Result := FSVGControl.HasAnimations; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetImageIndex: integer; begin {$IFDEF SVGLINKEDIMAGE} Result := FSVGLinkedImage.ImageIndex; {$ELSE} {$IFDEF SVGIMAGE} Result := 0; {$ELSE} Result := 0; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetImages: TSVG2ImageList; begin {$IFDEF SVGLINKEDIMAGE} Result := FSVGLinkedImage.Images as TSVG2ImageList; {$ELSE} {$IFDEF SVGIMAGE} Result := nil; {$ELSE} Result := nil; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetOnAnimationSample: TNotifyEvent; begin Result := FAnimationTimer.OnSample; end; function TSVGSelection.GetOnSVGEvent: TSVGEvent; begin {$IFDEF SVGLINKEDIMAGE} Result := FSVGLinkedImage.OnSVGEvent; {$ELSE} {$IFDEF SVGIMAGE} Result := FSVGImage.OnSVGEvent; {$ELSE} Result := FSVGControl.OnSVGEvent; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetOpacity: Single; begin {$IFDEF SVGLINKEDIMAGE} Result := FSVGLinkedImage.Opacity; {$ELSE} {$IFDEF SVGIMAGE} Result := FSVGImage.Opacity; {$ELSE} Result := FSVGControl.Opacity; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetRenderOptions: TSVGRenderOptions; begin {$IFDEF SVGLINKEDIMAGE} Result := FSVGLinkedImage.RenderOptions; {$ELSE} {$IFDEF SVGIMAGE} Result := FSVGImage.RenderOptions; {$ELSE} Result := FSVGControl.RenderOptions; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetSVG: string; begin {$IFDEF SVGLINKEDIMAGE} Result := ''; {$ELSE} {$IFDEF SVGIMAGE} Result := FSVGImage.SVG.Text; {$ELSE} Result := FSVGControl.SVG.Text; {$ENDIF} {$ENDIF} end; function TSVGSelection.GetSVGContent: string; var HasSVG: boolean; sl: TStringList; StrStream: TStringStream; begin {$IFDEF SVGLINKEDIMAGE} HasSVG := False; {$ELSE} {$IFDEF SVGIMAGE} HasSVG := FSVGImage.SVG.Count > 0; {$ELSE} HasSVG := FSVGControl.SVG.Count > 0; {$ENDIF} {$ENDIF} if HasSVG then begin Result := SVG; end else if Filename <> '' then begin sl := TStringList.Create; try sl.LoadFromFile(FileName); Result := sl.Text; finally sl.Free; end; end else begin if assigned(Images) and (ImageIndex >= 0) and (ImageIndex < Images.Count) then begin StrStream := TStringStream.Create; try Images.SaveSVGToStream(ImageIndex, StrStream); Result := StrStream.DataString; finally StrStream.Free; end; end; end; end; procedure TSVGSelection.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin if assigned(FViewer.Scrollbox) then FViewer.Scrollbox.AniCalculations.TouchTracking := []; FViewer.Selection := Self; inherited; end; procedure TSVGSelection.MouseMove(Shift: TShiftState; X, Y: Single); var Obj: ISVGObject; begin if ssTouch in Shift then Exit; inherited; if (not FHasEvents) and (sroEvents in RenderOptions) then begin {$IFDEF SVGLINKEDIMAGE} Obj := FSVGLinkedImage.ObjectAtPt(PointF(X, Y), False); {$ELSE} {$IFDEF SVGIMAGE} Obj := FSVGImage.ObjectAtPt(PointF(X, Y), False); {$ELSE} Obj := FSVGControl.ObjectAtPt(PointF(X, Y), False); FSVGControl.SVGRoot.CheckEventTypes; {$ENDIF} {$ENDIF} if assigned(Obj) then FViewer.ShowInfo(Obj.ID) else FViewer.ShowInfo('No object'); end; end; procedure TSVGSelection.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; if assigned(FViewer.Scrollbox) then FViewer.Scrollbox.AniCalculations.TouchTracking := [ttVertical, ttHorizontal]; FTimerUpdate.Enabled := True; end; procedure TSVGSelection.SetAnimationIsPaused(const Value: Boolean); begin FAnimationTimer.IsPaused := Value; end; procedure TSVGSelection.SetAnimationIsStarted(const Value: Boolean); begin FAnimationTimer.IsStarted := Value; end; procedure TSVGSelection.SetAnimationTime(const Value: Cardinal); begin {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.AnimationTime := Value; {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.AnimationTime := Value; {$ELSE} FSVGControl.AnimationTime := Value; {$ENDIF} {$ENDIF} end; procedure TSVGSelection.SetAspectRatioAlign(const Value: TSVGAspectRatioAlign); begin {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.AspectRatioAlign := Value; {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.AspectRatioAlign := Value; {$ELSE} FSVGControl.AspectRatioAlign := Value; {$ENDIF} {$ENDIF} end; procedure TSVGSelection.SetAspectRatioMeetOrSlice( const Value: TSVGAspectRatioMeetOrSlice); begin {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.AspectRatioMeetOrSlice := Value; {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.AspectRatioMeetOrSlice := Value; {$ELSE} FSVGControl.AspectRatioMeetOrSlice := Value; {$ENDIF} {$ENDIF} end; procedure TSVGSelection.SetAutoViewbox(const Value: boolean); begin {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.AutoViewbox := Value; {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.AutoViewbox := Value; {$ELSE} FSVGControl.AutoViewbox := Value; {$ENDIF} {$ENDIF} end; procedure TSVGSelection.SetFileName(const Value: string); begin {$IFDEF SVGLINKEDIMAGE} {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.Filename := Value; FSVGImage.ParseSVG; FSVGImage.CalcSize; Width := FSVGImage.Width; Height := FSVGImage.Height; FViewer.AlignControls; FHasEvents := (FSVGImage.SVGRoot.EventTypeSet <> []); {$ELSE} FSVGControl.Filename := Value; FSVGControl.ParseSVG; FSVGControl.CalcSize; Width := FSVGControl.Width; Height := FSVGControl.Height; FViewer.AlignControls; FHasEvents := (FSVGControl.SVGRoot.EventTypeSet <> []); {$ENDIF} {$ENDIF} end; procedure TSVGSelection.SetImageIndex(const Value: integer); begin {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.ImageIndex := Value; {$ELSE} {$IFDEF SVGIMAGE} {$ELSE} {$ENDIF} {$ENDIF} end; procedure TSVGSelection.SetImages(const Value: TSVG2ImageList); begin {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.Images := Value; {$ELSE} {$IFDEF SVGIMAGE} {$ELSE} {$ENDIF} {$ENDIF} end; procedure TSVGSelection.SetOnAnimationSample(const Value: TNotifyEvent); begin FAnimationTimer.OnSample := Value; end; procedure TSVGSelection.SetOnSVGEvent(const Value: TSVGEvent); begin {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.OnSVGEvent := Value;; {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.OnSVGEvent := Value;; {$ELSE} FSVGControl.OnSVGEvent := Value; {$ENDIF} {$ENDIF} end; procedure TSVGSelection.SetOpacity(const Value: Single); begin {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.Opacity := Value; {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.Opacity := Value; {$ELSE} FSVGControl.Opacity := Value; {$ENDIF} {$ENDIF} end; procedure TSVGSelection.SetRenderOptions(const Value: TSVGRenderOptions); begin {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.RenderOptions := Value; {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.RenderOptions := Value; {$ELSE} FSVGControl.RenderOptions := Value; {$ENDIF} {$ENDIF} end; procedure TSVGSelection.SetSelected(const Value: boolean); begin FSelected := Value; HideSelection := not FSelected; end; procedure TSVGSelection.SetSVG(const Value: string); begin {$IFDEF SVGLINKEDIMAGE} {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.SVG.Text := Value; FSVGImage.ParseSVG; FSVGImage.CalcSize; Width := FSVGImage.Width; Height := FSVGImage.Height; FViewer.AlignControls; FHasEvents := (FSVGImage.SVGRoot.EventTypeSet <> []); FSVGImage.Repaint; {$ELSE} FSVGControl.SVG.Text := Value; FSVGControl.ParseSVG; FSVGControl.CalcSize; Width := FSVGControl.Width; Height := FSVGControl.Height; FViewer.AlignControls; FHasEvents := (FSVGControl.SVGRoot.EventTypeSet <> []); FSVGControl.Repaint; {$ENDIF} {$ENDIF} end; procedure TSVGSelection.UpdateContent(Sender: TObject); begin FTimerUpdate.Enabled := False; {$IFDEF SVGLINKEDIMAGE} FSVGLinkedImage.SetBounds(0, 0, Width, Height); {$ELSE} {$IFDEF SVGIMAGE} FSVGImage.SetBounds(0, 0, Width, Height); {$ELSE} FSVGControl.SetBounds(0, 0, Width, Height); {$ENDIF} {$ENDIF} end; // ----------------------------------------------------------------------------- // // TSVGZoomBox // // ----------------------------------------------------------------------------- constructor TSVGZoomBox.Create(aForm: TForm; aLayoutSize, aLayoutZoom: TLayout; aScrollbox: TScrollbox); begin inherited Create(aForm); FForm := aForm; FLayoutSize := aLayoutSize; FLayoutZoom := aLayoutZoom; FScrollbox := aScrollbox; FZoom := 1.0; end; destructor TSVGZoomBox.Destroy; begin inherited; end; procedure TSVGZoomBox.CalcLayoutDimensions; var CR, WR, R: TRectF; Z: Single; begin // Calc max size of lZoom layout CR := ChildrenRect(FLayoutZoom); CR.Right := CR.Right * 2; CR.Bottom := CR.Bottom * 2; if FZoom < 0 then Z := 1.2 / FZoom else Z := 1.2; WR := RectF( 0.0, 0.0, FScrollbox.Width * Z, FScrollbox.Height * Z); R := MaxRect(CR, WR); FLayoutZoom.Position.X := 0.0; FLayoutZoom.Position.Y := 0.0; FLayoutZoom.Width := R.Right; FLayoutZoom.Height := R.Bottom; FLayoutSize.Position.X := 0.0; FLayoutSize.Position.Y := 0.0; FLayoutSize.Width := FLayoutZoom.Width * FZoom; FLayoutSize.Height := FLayoutZoom.Height * FZoom; end; procedure TSVGZoomBox.SetZoom(const Value: Single); var Mx, My: Single; begin if FZoom <> Value then begin // Calc middle of currently visible rectangle of scrollbox Mx := (FScrollbox.ViewportPosition.X + FScrollbox.Width / 2) / FLayoutSize.Width; My := (FScrollbox.ViewportPosition.Y + FScrollbox.Height / 2) / FLayoutSize.Height; FZoom := Value; // Set zoom of lZoom layout FScrollbox.BeginUpdate; try FLayoutZoom.Scale.X := FZoom; FLayoutZoom.Scale.Y := FZoom; CalcLayoutDimensions; FScrollbox.ViewportPosition := PointF( Mx * FLayoutSize.Width - (FScrollbox.Width / 2), My * FLayoutSize.Height - (FScrollbox.Height / 2)); finally FScrollbox.EndUpdate; FScrollbox.Repaint; end; end; end; // ----------------------------------------------------------------------------- // // TSVGViewerForm // // ----------------------------------------------------------------------------- procedure TSVGViewerForm.ActionAddCancelExecute(Sender: TObject); begin FLayoutSide.Visible := False; end; procedure TSVGViewerForm.ActionAddExecute(Sender: TObject); begin FLayoutSide.Visible := False; AddSVGSelection; end; procedure TSVGViewerForm.ActionAddOkExecute(Sender: TObject); begin // end; procedure TSVGViewerForm.ActionAnimationPauseExecute(Sender: TObject); begin if assigned(FSelection) then FSelection.AnimationIsPaused := FActionAnimationPause.IsPressed; UpdateControls; end; procedure TSVGViewerForm.ActionAnimationStartExecute(Sender: TObject); begin if assigned(FSelection) then FSelection.AnimationIsStarted := FActionAnimationStart.IsPressed; UpdateControls; end; procedure TSVGViewerForm.ActionCopyDirectExecute(Sender: TObject); begin if assigned(Selection) then begin Selection := Selection.CreateCopy; Selection.Parent := FlayoutZoom; Selection.Images := FImageList2; Selection.ImageIndex := FListBox.ItemIndex; Selection.OnSVGEvent := SVGEvent; end; end; procedure TSVGViewerForm.ActionCopyExecute(Sender: TObject); var Svc: IFMXClipboardService; begin if assigned(Selection) then begin if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, Svc) then Svc.SetClipboard(Selection.GetSVGContent); end; end; procedure TSVGViewerForm.ActionInfoExecute(Sender: TObject); begin {$IFDEF MSWINDOWS} FFormInfo.ShowModal; {$ENDIF} {$IFDEF MACOS} FFormInfo.ShowModal; {$ENDIF} {$IFDEF IOS} FFormInfo.Show; {$ENDIF} {$IFDEF ANDROID} FFormInfo.Show; {$ENDIF} end; procedure TSVGViewerForm.ActionLoadExecute(Sender: TObject); {$IFDEF IOS} var sr: TSearchRec; {$ENDIF} begin {$IFDEF ANDROID} LaunchLoadFile {$ELSE} {$IFDEF IOS} // Load all files in the documents folder, these need to be "deployed" first if FindFirst(TPath.GetDocumentsPath + PathDelim + '*.svg', faArchive, sr) = 0 then begin repeat AddSVG(TPath.GetDocumentsPath + PathDelim + sr.Name); until FindNext(sr) <> 0; FindClose(sr); end; {$ELSE} if FOpenDialog.Execute then begin AddSVG(FOpenDialog.FileName); end; {$ENDIF} {$ENDIF} end; procedure TSVGViewerForm.ActionPasteExecute(Sender: TObject); var Svc: IFMXClipboardService; Value: TValue; begin if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, Svc) then begin Value := Svc.GetClipboard; if not Value.IsEmpty then begin if Value.IsType<string> then begin Selection := TSVGSelection.Create(Self); Selection.Parent := FLayoutZoom; Selection.Images := FImageList2; Selection.ImageIndex := FListBox.ItemIndex; Selection.SVG := Value.ToString; Selection.OnSVGEvent := SVGEvent; FZoomTrackBar.Max := MaxZoom(FLayoutZoom); end end; end; end; procedure TSVGViewerForm.ActionRemoveExecute(Sender: TObject); begin if assigned(Selection) then begin Selection.Parent := nil; Selection.Free; Selection := nil; FZoomTrackBar.Max := MaxZoom(FLayoutZoom); end; end; procedure TSVGViewerForm.ActionZoomDecExecute(Sender: TObject); var NewValue: Single; begin NewValue := FZoomTrackBar.Value / 1.2; if NewValue < FZoomTrackBar.Min then FZoomTrackBar.Value := FZoomTrackBar.Min else FZoomTrackBar.Value := NewValue; end; procedure TSVGViewerForm.ActionZoomIncExecute(Sender: TObject); var NewValue: Single; begin NewValue := FZoomTrackBar.Value * 1.2; if NewValue > FZoomTrackBar.Max then FZoomTrackBar.Value := FZoomTrackBar.Max else FZoomTrackBar.Value := NewValue; end; procedure TSVGViewerForm.ActionZoomResetExecute(Sender: TObject); begin FZoomTrackBar.Value := 1.0; end; function TSVGViewerForm.AddSVG(const aFilename: string): boolean; var Ext: string; Item: TListBoxItem; begin Result := False; Ext := Lowercase(ExtractFileExt(aFileName)); if Ext = '.svg' then begin Result := True; FImageList2.AddSVG(aFilename); Item := TListBoxItem.Create(FListBox); Item.Text := ExtractFilename(aFileName); Item.ImageIndex := FImageList2.Count - 1; FListBox.AddObject(Item); FListBox.ItemIndex := FListBox.Items.Count - 1; Selection := TSVGSelection.Create(Self); Selection.Parent := FLayoutZoom; Selection.Images := FImageList2; Selection.Filename := aFilename; Selection.OnSVGEvent := SVGEvent; FZoomTrackBar.Max := MaxZoom(FLayoutZoom); end; end; procedure TSVGViewerForm.AddSVGSelection; var StrStream: TStringStream; begin Selection := TSVGSelection.Create(Self); Selection.Parent := FLayoutZoom; Selection.Images := FImageList2; Selection.ImageIndex := FListBox.ItemIndex; StrStream := TStringStream.Create; try FImageList2.SaveSVGToStream(FListBox.ItemIndex, StrStream); Selection.SVG := StrStream.DataString; finally StrStream.Free; end; Selection.OnSVGEvent := SVGEvent; FZoomTrackBar.Max := MaxZoom(FLayoutZoom); end; procedure TSVGViewerForm.AlignControls; begin FZoomBox.CalcLayoutDimensions; end; procedure TSVGViewerForm.AnimationTrackbarChange(aSender: TObject); begin if assigned(FSelection) then begin if FSelection.AnimationIsPaused then begin FSelection.AnimationTime := Round(FAnimationTrackbar.Value); DoTimer(Self); end; end; end; procedure TSVGViewerForm.CheckboxAutoViewboxChange(Sender: TObject); begin if assigned(FSelection) then FSelection.AutoViewbox := FCheckboxAutoViewbox.IsChecked; end; procedure TSVGViewerForm.CheckboxClippathChange(Sender: TObject); begin if assigned(FSelection) then begin if FCheckboxClippath.IsChecked then FSelection.RenderOptions := FSelection.RenderOptions + [sroClippath] else FSelection.RenderOptions := FSelection.RenderOptions - [sroClippath]; end; end; procedure TSVGViewerForm.CheckboxFiltersChange(Sender: TObject); begin if assigned(FSelection) then begin if FCheckboxFilters.IsChecked then FSelection.RenderOptions := FSelection.RenderOptions + [sroFilters] else FSelection.RenderOptions := FSelection.RenderOptions - [sroFilters]; end; end; procedure TSVGViewerForm.CheckboxMouseEventsChange(Sender: TObject); begin if assigned(FSelection) then begin if FCheckboxMouseEvents.IsChecked then FSelection.RenderOptions := FSelection.RenderOptions + [sroEvents] else FSelection.RenderOptions := FSelection.RenderOptions - [sroEvents]; end; end; procedure TSVGViewerForm.ComboboxAspectRatioChange(Sender: TObject); begin if assigned(FSelection) then FSelection.AspectRatioAlign := TSVGAspectRatioAlign(FComboboxAspectRatio.ItemIndex); end; procedure TSVGViewerForm.ComboboxMeetOrSliceChange(Sender: TObject); begin if assigned(FSelection) then FSelection.AspectRatioMeetOrSlice := TSVGAspectRatioMeetOrSlice(FComboboxMeetOrSlice.ItemIndex); end; procedure TSVGViewerForm.ConnectControls( aActionAddOk, aActionAddCancel, aActionAdd, aActionCopy, aActionCopyDirect, aActionInfo, aActionLoad, aActionPaste, aActionRemove, aActionZoomReset, aActionZoomDec, aActionZoomInc: TAction; aActionAnimationStart, aActionAnimationPause: TButton; aCheckboxAutoViewbox, aCheckboxClippath, aCheckboxFilters, aCheckboxMouseEvents: TCheckBox; aComboboxAspectRatio, aComboboxMeetOrSlice: TComboBox; aSpinboxRotate, aSpinboxOpacity: TSpinBox; aScrollbox: TScrollbox; aLayoutSide, aLayoutSize, aLayoutZoom: TLayout; aListbox: TListbox; aImageList1, aImageList2: TSVG2ImageList; aOpenDialog: TOpenDialog; aZoomTrackBar: TTrackBar; aLabelInfo: TLabel; aAnimationTrackbar: TTrackbar; aLabelTime: TLabel); begin FActionAddOk := aActionAddOk; FActionAddCancel := aActionAddCancel; FActionAdd := aActionAdd; FActionCopy := aActionCopy; FActionCopyDirect := aActionCopyDirect; FActionInfo := aActionInfo; FActionLoad := aActionLoad; FActionPaste := aActionPaste; FActionRemove := aActionRemove; FActionZoomReset := aActionZoomReset; FActionZoomDec := aActionZoomDec; FActionZoomInc := aActionZoomInc; FActionAnimationPause := aActionAnimationPause; FActionAnimationStart := aActionAnimationStart; FCheckboxAutoViewbox := aCheckboxAutoViewbox; FCheckboxClippath := aCheckboxClippath; FCheckboxFilters := aCheckboxFilters; FCheckboxMouseEvents := aCheckboxMouseEvents; FComboboxAspectRatio := aComboboxAspectRatio; FComboboxMeetOrSlice := aComboboxMeetOrSlice; FSpinboxRotate := aSpinboxRotate; FSpinboxOpacity := aSpinboxOpacity; FScrollbox := aScrollbox; FLayoutSide := aLayoutSide; FLayoutSize := aLayoutSize; FLayoutZoom := aLayoutZoom; FListbox := aListbox; FImageList1 := aImageList1; FImageList2 := aImageList2; FOpenDialog := aOpenDialog; FZoomTrackBar := aZoomTrackBar; FLabelInfo := aLabelInfo; FAnimationTrackBar := aAnimationTrackbar; FLabelTime := aLabelTime; // If the cachesize is too small, images in the list might have to be // rerendered wich can make the application slow down. FImageList1.CacheSize := 20; FImageList2.CacheSize := 20; FComboboxMeetOrSlice.Items.Add('Meet'); FComboboxMeetOrSlice.Items.Add('Slice'); FComboboxAspectRatio.Items.Add('None'); FComboboxAspectRatio.Items.Add('XMin YMin'); FComboboxAspectRatio.Items.Add('XMid YMin'); FComboboxAspectRatio.Items.Add('XMax YMin'); FComboboxAspectRatio.Items.Add('XMin YMid'); FComboboxAspectRatio.Items.Add('XMid YMid'); FComboboxAspectRatio.Items.Add('XMax YMid'); FComboboxAspectRatio.Items.Add('XMin YMax'); FComboboxAspectRatio.Items.Add('XMid YMax'); FComboboxAspectRatio.Items.Add('XMax YMax'); FActionAddOk.OnExecute := ActionAddOkExecute; FActionAddCancel.OnExecute := ActionAddCancelExecute; FActionAdd.OnExecute := ActionAddExecute; FActionCopy.OnExecute := ActionCopyExecute; FActionCopyDirect.OnExecute := ActionCopyDirectExecute; FActionInfo.OnExecute := ActionInfoExecute; FActionLoad.OnExecute := ActionLoadExecute; FActionPaste.OnExecute := ActionPasteExecute; FActionRemove.OnExecute := ActionRemoveExecute; FActionZoomReset.OnExecute := ActionZoomResetExecute; FActionZoomDec.OnExecute := ActionZoomDecExecute; FActionZoomInc.OnExecute := ActionZoomIncExecute; FActionAnimationPause.OnClick := ActionAnimationPauseExecute; FActionAnimationStart.OnClick := ActionAnimationStartExecute; FCheckboxAutoViewbox.OnChange := CheckboxAutoViewboxChange; FCheckboxClippath.OnChange := CheckboxClippathChange; FCheckboxFilters.OnChange := CheckboxFiltersChange; FCheckboxMouseEvents.OnChange := CheckboxMouseEventsChange; FComboboxAspectRatio.OnChange := ComboboxAspectRatioChange; FComboboxMeetOrSlice.OnChange := ComboboxMeetOrSliceChange; FSpinboxRotate.OnChange := SpinboxRotateChange; FSpinboxOpacity.OnChange := SpinboxOpacityChange; FZoomTrackBar.OnChange := TrackBarChange; FScrollbox.OnDragDrop := ScrollBoxDragDrop; FScrollbox.OnDragOver := ScrollBoxDragOver; FAnimationTrackBar.OnChange := AnimationTrackbarChange; FZoomBox := TSVGZoomBox.Create(Self, FLayoutSize, FLayoutZoom, FScrollbox); end; constructor TSVGViewerForm.Create(AOwnder: TComponent); begin inherited; FTimerAndroidLoad := TTimer.Create(Self); FTimerAndroidLoad.Enabled := False; FTimerAndroidLoad.Interval := 100; FTimerAndroidLoad.OnTimer := TimerAndroidLoadTimer; FTimerZoom := TTimer.Create(Self); FTimerZoom.Enabled := False; FTimerZoom.OnTimer := TimerZoomTimer; {$IFDEF MSWINDOWS} FTimerZoom.Interval := 0; {$ENDIF} {$IFDEF MACOS} FTimerZoom.Interval := 0; {$ENDIF} {$IFDEF IOS} FTimerZoom.Interval := 250; {$ENDIF} {$IFDEF ANDROID} FTimerZoom.Interval := 250; {$ENDIF} end; destructor TSVGViewerForm.Destroy; begin inherited; end; procedure TSVGViewerForm.DoShow; begin inherited; UpdateControls; end; procedure TSVGViewerForm.DoTimer(aSender: TObject); begin if not assigned(FSelection) then Exit; FLabelTime.Text := Format(' Time: %5.1f FPS: %3.0f ', [FSelection.AnimationTime / 1000, FSelection.AnimationFPS]); if FSelection.AnimationTime > FAnimationTrackbar.Max then FAnimationTrackbar.Max := FAnimationTrackbar.Max + 5000; if not FSelection.AnimationIsPaused then FAnimationTrackbar.Value := FSelection.AnimationTime; end; function TSVGViewerForm.GetForm: TForm; begin Result := Self; end; function TSVGViewerForm.GetScrollbox: TScrollbox; begin Result := FScrollbox; end; function TSVGViewerForm.GetSelection: TSVGSelection; begin Result := FSelection; end; procedure TSVGViewerForm.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); begin inherited; if Key = vkDelete then begin ActionRemoveExecute(Self) end; end; procedure TSVGViewerForm.Resize; begin FZoomBox.CalcLayoutDimensions; end; procedure TSVGViewerForm.ScrollBoxDragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); var i: integer; begin for i := 0 to Length(Data.Files) - 1 do begin if AddSVG(Data.Files[i]) then FSelection.Position.Point := Point; end; end; procedure TSVGViewerForm.ScrollBoxDragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Operation: TDragOperation); begin if Length(Data.Files) > 0 then Operation := TDragOperation.Copy else Operation := TDragOperation.None; end; procedure TSVGViewerForm.SetFormInfo(const Value: TSVGViewerInfoForm); begin FFormInfo := Value; end; procedure TSVGViewerForm.SetSelection(const Value: TSVGSelection); begin if assigned(FSelection) then begin FSelection.Selected := False; FSelection.OnAnimationSample := nil; end; FSelection := Value; if assigned(FSelection) then begin FSelection.Selected := True; FSelection.OnAnimationSample := DoTimer; FCheckboxAutoViewbox.IsChecked := FSelection.AutoViewbox; FCheckboxClippath.IsChecked := sroClippath in FSelection.RenderOptions; FCheckboxFilters.IsChecked := sroFilters in FSelection.RenderOptions; FCheckboxMouseEvents.IsChecked := sroEvents in FSelection.RenderOptions; FSpinboxOpacity.Value := FSelection.Opacity; FSpinboxRotate.Value := FSelection.RotationAngle; FComboboxAspectRatio.ItemIndex := Ord(FSelection.AspectRatioAlign); FComboboxMeetOrSlice.ItemIndex := Ord(FSelection.AspectRatioMeetOrSlice); end; UpdateControls; end; procedure TSVGViewerForm.ShowInfo(const aValue: string); begin FLabelInfo.Text := aValue; end; procedure TSVGViewerForm.SpinboxOpacityChange(Sender: TObject); begin if assigned(FSelection) then FSelection.Opacity := FSpinboxOpacity.Value; end; procedure TSVGViewerForm.SpinboxRotateChange(Sender: TObject); begin if assigned(FSelection) then FSelection.RotationAngle := FSpinboxRotate.Value; end; procedure TSVGViewerForm.SVGEvent(Sender: TObject; aSVGRoot: ISVGRoot; aEvent: ISVGEvent; const aValue: string); begin FLabelInfo.Text := aValue; end; {$IFDEF ANDROID} // http://blong.com/articles/DelphiXE6AndroidActivityResult/ActivityResult.htm function TSVGViewerForm.LaunchActivityForResult(const Intent: JIntent; RequestCode: Integer): Boolean; var ResolveInfo: JResolveInfo; begin ResolveInfo := SharedActivity.getPackageManager.resolveActivity(Intent, 0); Result := ResolveInfo <> nil; if Result then SharedActivity.startActivityForResult(Intent, RequestCode); end; procedure TSVGViewerForm.LaunchLoadFile; var Intent: JIntent; begin FFileName := ''; FMessageSubscriptionID := TMessageManager.DefaultManager.SubscribeToMessage( TMessageResultNotification, HandleActivityMessage); Intent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_PICK); Intent.setType(StringToJString('image/svg+xml')); Intent.setAction(TjIntent.JavaClass.ACTION_GET_CONTENT); //Intent.putExtra(TJIntent.JavaClass.EXTRA_ALLOW_MULTIPLE,true); if not LaunchActivityForResult(Intent, FileRequestCode) then ShowMessage('Cannot display file picker'); end; procedure TSVGViewerForm.HandleActivityMessage(const Sender: TObject; const M: TMessage); begin if M is TMessageResultNotification then OnActivityResult(TMessageResultNotification(M).RequestCode, TMessageResultNotification(M).ResultCode, TMessageResultNotification(M).Value); end; function TSVGViewerForm.OnActivityResult(RequestCode, ResultCode: Integer; Data: JIntent): Boolean; var Uri: Jnet_Uri; begin Result := False; TMessageManager.DefaultManager.Unsubscribe(TMessageResultNotification, FMessageSubscriptionID); FMessageSubscriptionID := 0; if RequestCode = FileRequestCode then begin if ResultCode = TJActivity.JavaClass.RESULT_OK then begin if assigned(Data) then begin Uri := Data.getData; if assigned(Uri) then begin FFileName := JStringToString(Uri.getPath); FTimerAndroidLoad.Enabled := True; end; end; end; Result := True; end; end; {$ENDIF} procedure TSVGViewerForm.TimerAndroidLoadTimer(Sender: TObject); begin FTimerAndroidLoad.Enabled := False; {$IFDEF ANDROID} // Work around for the Bitmap size too big error, bitmap must be created in // the main thread AddSVG(FFilename); {$ENDIF} end; procedure TSVGViewerForm.TimerZoomTimer(Sender: TObject); begin FTimerZoom.Enabled := False; FZoomBox.Zoom := FZoomTrackbar.Value; end; procedure TSVGViewerForm.TrackBarChange(Sender: TObject); begin if FTimerZoom.Interval <> 0 then begin FTimerZoom.Enabled := False; FTimerZoom.Enabled := True; end else FZoomBox.Zoom := FZoomTrackbar.Value; end; procedure TSVGViewerForm.UpdateControls; var HasAnimations: Boolean; begin HasAnimations := False; FActionCopy.Enabled := True; FActionCopyDirect.Enabled := True; FCheckboxFilters.Enabled := True; FCheckboxClippath.Enabled := True; FCheckboxMouseEvents.Enabled := True; FCheckboxAutoViewbox.Enabled := True; FActionRemove.Enabled := True; FActionAnimationStart.Enabled := True; FActionAnimationPause.Enabled := True; FAnimationTrackbar.Enabled := True; if assigned(FSelection) then begin FCheckboxFilters.IsChecked := sroFilters in FSelection.RenderOptions; FCheckboxClippath.IsChecked := sroClippath in FSelection.RenderOptions; FCheckboxMouseEvents.IsChecked := sroEvents in FSelection.RenderOptions; FCheckboxAutoViewbox.IsChecked := FSelection.AutoViewbox; HasAnimations := FSelection.HasAnimations; if HasAnimations then begin FActionAnimationStart.IsPressed := FSelection.AnimationIsStarted; FActionAnimationPause.IsPressed := FSelection.AnimationIsPaused; end else begin FActionAnimationStart.IsPressed := False; FActionAnimationPause.IsPressed := False; end; end else begin FCheckboxFilters.IsChecked := False; FCheckboxClippath.IsChecked := False; FCheckboxMouseEvents.IsChecked := False; FCheckboxAutoViewbox.IsChecked := False; FActionAnimationStart.IsPressed := False; FActionAnimationPause.IsPressed := False; FActionCopy.Enabled := False; FActionCopyDirect.Enabled := False; FCheckboxFilters.Enabled := False; FCheckboxClippath.Enabled := False; FCheckboxMouseEvents.Enabled := False; FCheckboxAutoViewbox.Enabled := False; FActionRemove.Enabled := False; end; FActionAnimationStart.Enabled := HasAnimations; FActionAnimationPause.Enabled := HasAnimations; FAnimationTrackbar.Enabled := HasAnimations; end; // ----------------------------------------------------------------------------- // // TSVGViewerInfoForm // // ----------------------------------------------------------------------------- procedure TSVGViewerInfoForm.ButtonClick(Sender: TObject); begin ModalResult := mrOk; Close; end; procedure TSVGViewerInfoForm.ConnectControls(aButton: TButton; aSVGImage: TSVG2Image); begin FButton := aButton; FSVGImage := aSVGImage; FButton.OnClick := ButtonClick; FSVGImage.OnSVGEvent := SVGEvent; end; constructor TSVGViewerInfoForm.Create(AOwnder: TComponent); begin inherited; end; destructor TSVGViewerInfoForm.Destroy; begin inherited; end; procedure TSVGViewerInfoForm.Open(const FilePath: string); {$IFDEF ANDROID} var Intent: JIntent; {$ENDIF} begin {$IFDEF MSWINDOWS} ShellExecute(0, nil, pchar(FilePath), nil, nil, sw_restore); {$ENDIF MSWINDOWS} {$IFDEF MACOS} {$IFNDEF IOS} _system(PAnsiChar('open '+'"'+AnsiString(FilePath)+'"')); {$ELSE} SharedApplication.OpenURL(StrToNSUrl(FilePath)); {$ENDIF} {$ENDIF MACOS} {$IFDEF ANDROID} Intent := TJIntent.Create; Intent.setAction(TJIntent.JavaClass.ACTION_VIEW); Intent.setData(StrToJURI(FilePath)); SharedActivity.startActivity(Intent); {$ENDIF} end; procedure TSVGViewerInfoForm.SVGEvent(Sender: TObject; aSVGRoot: ISVGRoot; aEvent: ISVGEvent; const aValue: string); var ImageElement: ISVGImage; begin case aEvent.EventType of etClick: begin if aEvent.Target.ID = 'link' then Open('http://www.bverhue.nl/delphisvg/'); end; etMouseOut: begin if assigned(aEvent.Target) and (aEvent.Target.ID = 'link') then begin aEvent.Target.Attributes['fill'] := 'black'; aEvent.Target.Attributes['font-size'] := '16'; FSVGImage.Repaint; end; end; etMouseOver: begin if assigned(aEvent.Target) and (aEvent.Target.ID = 'link') then begin aEvent.Target.Attributes['fill'] := 'blue'; aEvent.Target.Attributes['font-size'] := '18'; FSVGImage.Repaint; end; end; etMouseDown: begin if aEvent.CurrentTarget.ID = 'img_svg_logo' then begin if Supports(aEvent.CurrentTarget, ISVGImage, ImageElement) then begin ImageElement.X := TSVGDimension.Init(284); ImageElement.Y := TSVGDimension.Init(14); FSVGImage.Repaint; end; end; end; etMouseUp: begin if aEvent.CurrentTarget.ID = 'img_svg_logo' then begin if Supports(aEvent.CurrentTarget, ISVGImage, ImageElement) then begin ImageElement.X := TSVGDimension.Init(280); ImageElement.Y := TSVGDimension.Init(10); FSVGImage.Repaint; Open('https://www.w3.org/TR/SVG11/'); end; end; end; end; end; end.
unit AST.Parser.Messages; interface {$I compilers.inc} uses SysUtils, Generics.Collections, AST.Lexer; type IUnit = interface ['{80A26C85-754B-4D35-BFA4-5FFFBA78322B}'] end; TCompilerMessageType = (cmtHint, cmtWarning, cmtError, cmtInteranlError); { TCompilerMessage } TCompilerMessage = record strict private FUnit: TObject; FUnitName: string; FMessageType: TCompilerMessageType; FMessageText: string; FSourcePosition: TTextPosition; function GetMessageTypeName: string; function GetAsString: string; public //property DeclUnit: TObject read FUnit write FUnit; property UnitName: string read FUnitName write FUnitName; property MessageType: TCompilerMessageType read FMessageType; property MessageTypeName: string read GetMessageTypeName; property MessageText: string read FMessageText; property Row: Integer read FSourcePosition.Row write FSourcePosition.Row; property Col: Integer read FSourcePosition.Col write FSourcePosition.Col; property AsString: string read GetAsString; constructor Create(DeclUnit: TObject; MessageType: TCompilerMessageType; const MessageText: string; const SourcePosition: TTextPosition); {$IFDEF FPC} class operator Equal(const Left, Right: TCompilerMessage): boolean; {$ENDIF} end; PCompilerMessage = ^TCompilerMessage; ICompilerMessages = interface ['{0F47607D-E9F5-41F2-BB05-B539743EC65A}'] procedure Add(const Message: TCompilerMessage); procedure Clear; procedure CopyFrom(const Messages: ICompilerMessages); function GetHasErrors: Boolean; function GetAsString: string; function GetCount: Integer; function GetItem(Index: Integer): TCompilerMessage; property Count: Integer read GetCount; property Items[Index: Integer]: TCompilerMessage read GetItem; default; property Text: string read GetAsString; property HasErrors: Boolean read GetHasErrors; end; TCompilerMessages = class(TInterfacedObject, ICompilerMessages) private FMessages: TList<TCompilerMessage>; function GetCount: Integer; public constructor Create; destructor Destroy; override; procedure Add(const Message: TCompilerMessage); procedure CopyFrom(const Messages: ICompilerMessages); procedure Clear; property Count: Integer read GetCount; function GetHasErrors: Boolean; function GetAsString: string; function GetItem(Index: Integer): TCompilerMessage; end; implementation uses AST.Pascal.Parser, AST.Delphi.Errors, AST.Parser.Utils; { TCompilerMessage } constructor TCompilerMessage.Create(DeclUnit: TObject; MessageType: TCompilerMessageType; const MessageText: string; const SourcePosition: TTextPosition); begin FUnit := DeclUnit; FMessageType := MessageType; FMessageText := MessageText; FSourcePosition := SourcePosition; end; {$IFDEF FPC} class operator TCompilerMessage.Equal(const Left, Right: TCompilerMessage): boolean; begin end; {$ENDIF} function TCompilerMessage.GetAsString: string; begin Result := Format('%s [%s(%d, %d)]: %s', [GetMessageTypeName, Self.UnitName, Row, Col, MessageText]); end; function TCompilerMessage.GetMessageTypeName: string; begin case FMessageType of cmtHint: Result := sHintWord; cmtWarning: Result := sWarningWord; cmtError: Result := sErrorWord; cmtInteranlError: Result := sInternalErrorWord; end; end; { TCompilerMessages } procedure TCompilerMessages.Add(const Message: TCompilerMessage); begin FMessages.Add(Message); end; procedure TCompilerMessages.Clear; begin FMessages.Clear; end; procedure TCompilerMessages.CopyFrom(const Messages: ICompilerMessages); var i: Integer; begin for i := 0 to Messages.Count - 1 do FMessages.Add(Messages[i]); end; constructor TCompilerMessages.Create; begin FMessages := TList<TCompilerMessage>.Create; end; destructor TCompilerMessages.Destroy; begin FMessages.Free; end; function TCompilerMessages.GetAsString: string; var i: Integer; SrcCoords: string; begin for i := 0 to FMessages.Count - 1 do with FMessages[i] do begin if Row <> -1 then begin if Col <> -1 then SrcCoords := format('(%d,%d)', [Row, Col]) else SrcCoords := format('(%d)', [Row]); end; Result := AddStringSegment(Result, Format('[%s] %s%s: %s', [MessageTypeName, UnitName, SrcCoords, MessageText]), #13#10); end; end; function TCompilerMessages.GetCount: Integer; begin Result := FMessages.Count; end; function TCompilerMessages.GetHasErrors: Boolean; var i: Integer; begin for i := 0 to FMessages.Count - 1 do if FMessages[i].MessageType in [cmtError, cmtInteranlError] then Exit(True); Result := False; end; function TCompilerMessages.GetItem(Index: Integer): TCompilerMessage; begin Result := FMessages[Index]; end; end.
(* ABSBUFF.PAS - Copyright (c) 1995-1996, Eminent Domain Software *) unit AbsBuff; {-Abstract buffer manager for EDSSpell component} {-also includes native Delphi CustomEdit buffer manager} interface uses Classes, Controls, Graphics, SysUtils, Forms, Dialogs, StdCtrls, WinProcs, WinTypes, {$IFDEF Win32} {$IFDEF Ver100} LexDCTD3, {$ELSE} LexDCT32, {$ENDIF} {$ELSE} LexDCT, {$ENDIF} MemoUtil, SpellGbl, Words; type TAbsBuffer = class (TObject) {abstract buffer manager} private { Private declarations } FSize: Longint; {size of buffer} FCurPosPtr: PChar; {points to current character in buffer} FBeginPos: Longint; {beginning position of word in buffer} FEndPos: Longint; {ending position of word in buffer} FParent: TControl; {parent control, if any} FAllNums: Boolean; {TRUE if the current word is all numbers} FSupportHTML: Boolean; {set to TRUE to support HTML} protected { Protected declarations } public { Public declarations } Buffer: PBigBuffer; {pointer to the buffer} BufferSize: integer; {size of the above buffer} CurPos: Longint; {current location in the buffer} constructor Create (AParent: TControl); dynamic; destructor Destroy; override; procedure InitParms; {-initializes buffer parameters} function IsModified: Boolean; virtual; abstract; {-returns TRUE if parent had been modified} procedure SetModified (NowModified: Boolean); virtual; abstract; {-sets parents modified flag} function GetYPos: integer; virtual; {-gets the current y location of the highlighted word (absolute screen)} function GetTextBufferSize: integer; dynamic; {-returns the maximum size of the buffer} function GetNextWord: string; dynamic; abstract; {-returns the next word in the buffer} procedure MoveBackOneWord; dynamic; abstract; {-moves back to the beginning of the current word} procedure UpdateBuffer; dynamic; abstract; {-updates the buffer from the parent component, if any} procedure SetSelectedText; dynamic; {-highlights the current word using FBeginPos & FEndPos} procedure ReplaceWord (WithWord: string); dynamic; abstract; {-replaces the current word with the word provided} procedure WordCount (var NumWords, UniqueWords: Longint); dynamic; {-returns the number of words in buffer} { Property declarations } property BufSize: Longint read FSize write FSize; property PCurPos: PChar read FCurPosPtr write FCurPosPtr; property BeginPos: Longint read FBeginPos write FBeginPos; property EndPos: Longint read FEndPos write FEndPos; property Parent: TControl read FParent write FParent; property Modified: Boolean read IsModified write SetModified; property YPos: Integer read GetYPos; property AllNumbers: Boolean read FAllNums write FAllNums; property SupportHTML: Boolean read FSupportHTML write FSupportHTML; end; { TAbsBuffer } TPCharBuffer = class (TAbsBuffer) {PChar buffer manager} private { Private declarations } FModified: Boolean; {Internal modified flag} FPChar: PChar; {Parent Buffer} protected { Protected declarations } public { Public declarations } constructor Create (AParent: TControl); override; constructor CreateSpecial (ParentBuffer: PChar); dynamic; function IsModified: Boolean; override; {-returns TRUE if parent had been modified} procedure SetModified (NowModified: Boolean); override; {-sets parents modified flag} function GetNextWord: string; override; {-returns the next word in the buffer} procedure MoveBackOneWord; override; {-moves back to the beginning of the current word} procedure UpdateBuffer; override; {-updates the buffer from the parent component, if any} procedure ReplaceWord (WithWord: string); override; {-replaces the current word with the word provided} end; { TPCharBuffer } PString = ^String; TStringBuffer = class (TAbsBuffer) {pascal string buffer manager} private { Private declarations } // FModified: Boolean; {Internal modified flag} FString: PString; {string being spell checked} protected { Protected declarations } public { Public declarations } constructor Create (CheckString: PString); procedure UpdateBuffer; override; {-updates the buffer from the parent component, if any} procedure ReplaceWord (WithWord: string); override; {-replaces the current word with the word provided} end; { TStringBuffer } TCEBuffer = class (TPCharBuffer) {TCustomEdit buffer manager} private {works for TMemo & TEdit} { Private declarations } protected { Protected declarations } public { Public declarations } constructor Create (AParent: TControl); function IsModified: Boolean; override; {-returns TRUE if parent had been modified} procedure SetModified (NowModified: Boolean); override; {-sets parents modified flag} function GetYPos: integer; override; {-gets the current y location of the highlighted word (absolute screen)} function GetTextBufferSize: integer; override; {-returns the maximum size of the buffer} procedure SetSelectedText; override; {-highlights the current word using BeginPos & EndPos} procedure UpdateBuffer; override; {-updates the buffer from the parent component, if any} procedure ReplaceWord (WithWord: string); override; {-replaces the current word with the word provided} end; { TCEBuffer } implementation {Abstract Buffer Manager} constructor TAbsBuffer.Create (AParent: TControl); var TestSize: Longint; begin inherited Create; FParent := AParent; TestSize := GetTextBufferSize + AddBufferSize; if TestSize > MaxBuffer then BufferSize := MaxBuffer else BufferSize := TestSize; GetMem (Buffer, BufferSize); InitParms; UpdateBuffer; end; { TAbsBuffer.Create } procedure TAbsBuffer.InitParms; {-initializes buffer parameters} begin FSize := 0; CurPos := 1; PCurPos := @Buffer^[1]; end; { TAbsBuffer.InitParms } function TAbsBuffer.GetYPos: integer; {-gets the current y location of the highlighted word (absolute screen)} begin Result := 0; end; { TAbsBuffer.GetYPos } function TAbsBuffer.GetTextBufferSize: integer; {-returns the maximum size of the buffer} begin Result := 32767 - AddBufferSize; {-default maximum buffer is 32K} end; { TAbsBuffer.GetTextBufferSize } procedure TAbsBuffer.WordCount (var NumWords, UniqueWords: Longint); {-returns the number of words in buffer} var UniqueList: TStringList; WordSt: String; Words: String; UniqueSt: String; begin InitParms; NumWords := 0; UniqueWords := 0; UniqueList := TStringList.Create; UpdateBuffer; if WordForm = nil then WordForm := TWordForm.Create (Application); if not WordForm.Visible then WordForm.Show; repeat WordSt := UpperCase (GetNextWord); {Note: If using an older version of WPTools, uncomment the next lines;} {the next two lines were used as a patch for earlier versions - 10-30-97.} {From version 1.98 on, WPTools does not now need this patch} { if WordSt = '' then WordSt := UpperCase (GetNextWord); } if WordSt <> '' then begin Inc (NumWords); if UniqueList.IndexOf (WordSt) = (-1) then UniqueList.Add (WordSt); end; { if... } Str (NumWords, Words); Str (UniqueList.Count, UniqueSt); WordForm.lblWords.Caption := Words; WordForm.lblUniqueWords.Caption := UniqueSt; Application.ProcessMessages; if not WordForm.Visible then {form was closed} begin NumWords := 0; UniqueList.Clear; Break; end; { if... } until WordSt = ''; UniqueWords := UniqueList.Count; UniqueList.Free; end; { TAbsBuffer.WordCount } procedure TAbsBuffer.SetSelectedText; begin {do nothing} end; { TabsBuffer.SetSelectedText } destructor TAbsBuffer.Destroy; begin if Buffer <> nil then FreeMem (Buffer, BufferSize); inherited Destroy; end; { TAbsBuffer.Destroy } {PChar Buffer Manager} constructor TPCharBuffer.Create (AParent: TControl); begin inherited Create (AParent); FModified := FALSE; end; { TPCharBuffer.Create } constructor TPCharBuffer.CreateSpecial (ParentBuffer: PChar); begin FPChar := ParentBuffer; FModified := FALSE; inherited Create (nil); end; { TPCharBuffer.CreateSpecial } function TPCharBuffer.IsModified: Boolean; {-returns TRUE if parent had been modified} begin Result := FModified; end; { TPCharBuffer.IsModified } procedure TPCharBuffer.SetModified (NowModified: Boolean); {-sets parents modified flag} begin FModified := NowModified; end; { TPCharBuffer.SetModified } function TPCharBuffer.GetNextWord: string; {-returns the next word in the buffer} var S: string; {string being constructed} InHTML: Boolean; {TRUE if '<' has been encountered} Ch: Char; begin BeginPos := CurPos; EndPos := CurPos; S := ''; FAllNums := TRUE; InHTML := FALSE; {find the first letter of the next word} while (not (Char (PCurPos^) in ValidChars)) and (CurPos<BufSize) or InHTML do begin if SupportHTML then begin Ch := PCurPos^; if InHTML and (Ch = '>') then InHTML := FALSE else if Ch = '<' then InHTML := TRUE; end; { if... } Inc (CurPos, 1); PCurPos := @Buffer^[CurPos]; end; { while } if CurPos<BufSize then begin BeginPos := CurPos; {goto the end of the word} while ((Char (PCurPos^) in ValidChars) and (CurPos<BufSize)) do begin S := ConCat (S, Char (PCurPos^)); Inc (CurPos, 1); if FAllNums and (not (Char (PCurPos^) in NumberSet)) then FAllNums := FALSE; PCurPos := @Buffer^[CurPos]; EndPos := CurPos; if EndPos - BeginPos = MaxWordLength then begin MessageDlg ('Aborting spell check (Invalid word): ' + #13 + S, mtError, [mbOk], 0); S := ''; Break; end; { if... } end; { while } Result := S; end {:} else Result := ''; end; { TPCharBuffer.GetNextword } procedure TPCharBuffer.MoveBackOneWord; {-moves back to the beginning of the current word} begin while (Char (PCurPos^) in ValidChars) and (CurPos > 1) do begin Dec (CurPos, 1); PCurPos := @Buffer^[CurPos]; end; { while } end; { TPCharBuffer.MoveBackOneWord } procedure TPCharBuffer.UpdateBuffer; {-updates the buffer from the parent component, if any} begin BufSize := StrLen (FPChar) + 1; Move (FPChar^, Buffer^, BufSize); PCurPos := @Buffer^[CurPos]; end; { TPCharBuffer.UpdateBuffer } procedure TPCharBuffer.ReplaceWord (WithWord: string); {-replaces the current word with the word provided} begin {Delete the current word} {Insert the new one} UpdateBuffer; end; { TPCharBuffer.ReplaceWord } constructor TStringBuffer.Create (CheckString: PString); begin inherited Create (nil); FString := CheckString; end; { TStringBuffer.Create } procedure TStringBuffer.UpdateBuffer; {-updates the buffer from the parent component, if any} begin {do nothing}; end; { TStringBuffer.UpdateBuffer } procedure TStringBuffer.ReplaceWord (WithWord: string); {-replaces the current word with the word provided} begin Delete (FString^, BeginPos, Length (WithWord)); Insert (WithWord, FString^, BeginPos); end; { TStringBuffer.ReplaceWord } {TCustomEdit Buffer Manager} constructor TCEBuffer.Create (AParent: TControl); begin inherited Create (AParent); end; { TCEBuffer.Create } function TCEBuffer.IsModified: Boolean; {-returns TRUE if parent had been modified} begin Result := TCustomEdit (Parent).Modified; end; { TCEBuffer.IsModified } procedure TCEBuffer.SetModified (NowModified: Boolean); {-sets parents modified flag} begin TCustomEdit (Parent).Modified := Modified; end; { TCEBuffer.SetModified } function TCEBuffer.GetYPos: integer; {-gets the current y location of the highlighted word (absolute screen)} var AbsMemoXY: TPoint; begin if Parent is TMemo then begin Result := Memo_WhereY (TMemo (Parent)); end {:} else begin AbsMemoXY := Parent.ClientToScreen (Point (0, 0)); Result := AbsMemoXY.Y; end; { else } end; { TCEBuffer.GetYPos } function TCEBuffer.GetTextBufferSize: integer; {-returns the maximum size of the buffer} begin Result := TCustomEdit (Parent).GetTextLen + 1; end; { TCEBuffer.GetTextBufferSize } procedure TCEBuffer.SetSelectedText; {-highlights the current word using BeginPos & EndPos} begin with Parent as TCustomEdit do begin SelStart := BeginPos - 1; SelLength := EndPos - BeginPos; Update; end; { with } end; { TCEBuffer.SetSelectedText } procedure TCEBuffer.UpdateBuffer; {-updates the buffer from the parent component, if any} begin BufSize := GetTextBufferSize; TCustomEdit (Parent).GetTextBuf (pChar(Buffer), BufSize); {support international characters} AnsiToOemBuff (pChar (Buffer), pChar (Buffer), BufSize); PCurPos := @Buffer^[CurPos]; end; { TCEBuffer.UpdateBuffer } procedure TCEBuffer.ReplaceWord (WithWord: string); {-replaces the current word with the word provided} begin with Parent as TCustomEdit do begin SetFocus; SetSelectedText; CurPos := CurPos - (EndPos - BeginPos); SelText := WithWord; CurPos := CurPos + Length (WithWord); UpdateBuffer; end; { with } end; { TCEBuffer.ReplaceWord } end. { AbsBuff }
unit uModJurnal; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uModApp, uModCostCenter, uModUnit, uModRekening, System.Generics.Collections; type TModJurnalItem = class; TModJurnal = class(TModApp) private FJUR_CREDIT: Double; FJUR_DATE: TDatetime; FJUR_DEBET: Double; FJUR_DESCRIPTION: string; FJUR_FISCAL_YEAR: string; FJUR_JURNALITEMS: TObjectList<TModJurnalItem>; FJUR_NO: string; FJUR_PERIOD: string; FJUR_POSTED_DATE: Double; FJUR_REF_NO: string; FJUR_IS_POSTED: Integer; function GetJUR_JURNALITEMS: TObjectList<TModJurnalItem>; public property JUR_JURNALITEMS: TObjectList<TModJurnalItem> read GetJUR_JURNALITEMS write FJUR_JURNALITEMS; published property JUR_CREDIT: Double read FJUR_CREDIT write FJUR_CREDIT; property JUR_DATE: TDatetime read FJUR_DATE write FJUR_DATE; property JUR_DEBET: Double read FJUR_DEBET write FJUR_DEBET; property JUR_DESCRIPTION: string read FJUR_DESCRIPTION write FJUR_DESCRIPTION; property JUR_FISCAL_YEAR: string read FJUR_FISCAL_YEAR write FJUR_FISCAL_YEAR; [AttributeOfCode] property JUR_NO: string read FJUR_NO write FJUR_NO; property JUR_PERIOD: string read FJUR_PERIOD write FJUR_PERIOD; property JUR_POSTED_DATE: Double read FJUR_POSTED_DATE write FJUR_POSTED_DATE; property JUR_REF_NO: string read FJUR_REF_NO write FJUR_REF_NO; property JUR_IS_POSTED: Integer read FJUR_IS_POSTED write FJUR_IS_POSTED; end; TModJurnalItem = class(TModApp) private FJURD_COCENTER: TModCostCenter; FJURD_CREDIT: Double; FJURD_DEBET: Double; FJURD_DESCRIPTION: string; FJURD_JURNAL: TModJurnal; FJURD_REKENING: TModRekening; public class function GetTableName: String; override; published [AttributeOfForeign('COST_CENTER_ID')] property JURD_COCENTER: TModCostCenter read FJURD_COCENTER write FJURD_COCENTER; property JURD_CREDIT: Double read FJURD_CREDIT write FJURD_CREDIT; property JURD_DEBET: Double read FJURD_DEBET write FJURD_DEBET; property JURD_DESCRIPTION: string read FJURD_DESCRIPTION write FJURD_DESCRIPTION; [AttributeOfHeader('JURNAL_ID')] property JURD_JURNAL: TModJurnal read FJURD_JURNAL write FJURD_JURNAL; [AttributeOfForeign('REKENING_ID')] property JURD_REKENING: TModRekening read FJURD_REKENING write FJURD_REKENING; end; implementation function TModJurnal.GetJUR_JURNALITEMS: TObjectList<TModJurnalItem>; begin if FJUR_JURNALITEMS = nil then FJUR_JURNALITEMS := TObjectList<TModJurnalItem>.Create(); Result := FJUR_JURNALITEMS; end; class function TModJurnalItem.GetTableName: String; begin Result := 'JURNAL_DETIL'; end; initialization TModJurnal.RegisterRTTI; end.
unit Classes.Player; interface uses Interfaces.Player, Vcl.ExtCtrls, System.Classes, System.Types, Vcl.Imaging.pngimage, Vcl.Controls; type TPlayer = class(TInterfacedObject, IPlayer) strict private var FPosition: TPoint; FImage: TImage; FOwner: TGridPanel; FDirection: TPlayerDirection; png: TPngImage; public class function New(const AOwner: TGridPanel): IPlayer; destructor Destroy; override; function Position(const Value: TPoint): IPlayer; overload; function Position: TPoint; overload; function Owner(const Value: TGridPanel): IPlayer; overload; function Owner: TGridPanel; overload; function Direction(const Value: TPlayerDirection): IPlayer; overload; function Direction: TPlayerDirection; overload; function CreateImages: IPlayer; function ChangeImage: IPlayer; function ChangeParent: IPlayer; end; implementation uses System.SysUtils; { TPlayer } function TPlayer.ChangeImage: IPlayer; begin Result := Self; if Assigned(png) then FreeAndNil(png); png := TPngImage.Create; case FDirection of tpdUP: png.LoadFromResourceName(HInstance, 'up'); tpdDOWN: png.LoadFromResourceName(HInstance, 'down'); tpdLEFT: png.LoadFromResourceName(HInstance, 'left'); tpdRIGHT: png.LoadFromResourceName(HInstance, 'right'); end; FImage.Picture.Graphic := png; end; function TPlayer.ChangeParent: IPlayer; var Panel: TWinControl; begin Result := Self; Panel := TWinControl(FOwner.ControlCollection.Controls[FPosition.X - 1, FPosition.Y - 1]); FImage.Parent := Panel; end; function TPlayer.CreateImages: IPlayer; var Panel: TWinControl; begin Result := Self; Panel := TWinControl(FOwner.ControlCollection.Controls[FPosition.X - 1, FPosition.Y - 1]); FImage := TImage.Create(Panel); FImage.Parent := Panel; FImage.Align := alClient; if Assigned(png) then FreeAndNil(png); png := TPngImage.Create; png.LoadFromResourceName(HInstance, 'down'); FImage.Picture.Graphic := png; end; destructor TPlayer.Destroy; begin FOwner.ControlCollection.RemoveControl(FImage); FreeAndNil(FImage); if Assigned(png) then FreeAndNil(png); inherited; end; function TPlayer.Direction: TPlayerDirection; begin Result := FDirection; end; function TPlayer.Direction(const Value: TPlayerDirection): IPlayer; begin Result := Self; FDirection := Value; end; class function TPlayer.New(const AOwner: TGridPanel): IPlayer; begin Result := Self.Create; Result.Owner(AOwner); end; function TPlayer.Owner: TGridPanel; begin Result := FOwner; end; function TPlayer.Owner(const Value: TGridPanel): IPlayer; begin Result := Self; FOwner := Value; end; function TPlayer.Position(const Value: TPoint): IPlayer; begin Result := Self; FPosition := Value; end; function TPlayer.Position: TPoint; begin Result := FPosition; end; end.
uses UConst, UGeneticAlgorythm; function read_txt(filename: string): array of array of real; begin foreach var (i, line) in ReadLines(filename).Numerate() do begin SetLength(result, i); result[i-1] := line.ToReals(); end end; function mixing(ratio: array of real; flows_composition: array of array of real): array of real; begin result := ArrFill(flows_composition.Length, 0.0); foreach var i in flows_composition.Indices do foreach var j in flows_composition[i].Indices do result[i] += ratio[j] * flows_composition[i][j] end; function calculate_octane_number(fractions:array of real; Bi: array of real := UConst.Bi; RON: array of real := UConst.RON): real; begin result := 0; var delta := ArrFill(Bi.Length, 0.0); foreach var i in Bi.Indices do for var j := i+1 to Bi.High do delta[i] += Bi[i] * Bi[j] * fractions[i] * fractions[j]; foreach var i in Bi.Indices do result += fractions[i] * RON[i]; result += delta.Sum(); end; function normalize(x: array of real): array of real; begin result := ArrFill(x.Length, 0.0); var s := x.Sum; foreach var i in x.Indices do result[i] := x[i] / s; end; function objective_function(ratio, actual_values: array of real): real; begin var data := read_txt('data.txt'); var fractions := mixing(normalize(ratio), data); var ron := calculate_octane_number(fractions); result := (actual_values[0] - ron) ** 2 + (actual_values[1] - fractions[56]) ** 2; end; begin var data := read_txt('data.txt'); var bounds := ||0.1, 0.9|, |0.1, 0.9|, |0.1, 0.9|, |0.1, 0.9|, |0.1, 0.9|, |0.1, 0.9||; var res := genetic_algorithm(bounds, objective_function, |92, 0.01|); var norm_ratio: array of array of real; SetLength(norm_ratio, res.Length); foreach var i in norm_ratio.Indices do begin SetLength(norm_ratio[i], res[i].Length-1); norm_ratio[i] := normalize(res[i][:^1]) end; norm_ratio.PrintLines; foreach var row in norm_ratio do begin var mixture := mixing(row, data); calculate_octane_number(mixture).Println; mixture[57].Println end end.
unit uEditInLang; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,AArray, cxTextEdit, cxMaskEdit, cxButtonEdit, cxControls, cxContainer, cxEdit, cxLabel, cxLookAndFeelPainters, StdCtrls, cxButtons, ActnList; type TFormEditInLang = class(TForm) cxLabelIN_LANG: TcxLabel; cxButtonEditIN_LANG: TcxButtonEdit; cxLabelLEVEL_VLADEN: TcxLabel; cxButtonEditLEVEL_VLADEN: TcxButtonEdit; ActionListKlassSpravEdit: TActionList; ActionOK: TAction; ActionCansel: TAction; cxButtonOK: TcxButton; cxButtonCansel: TcxButton; procedure FormCreate(Sender: TObject); procedure ActionCanselExecute(Sender: TObject); procedure ActionOKExecute(Sender: TObject); procedure cxButtonEditIN_LANGPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxButtonEditLEVEL_VLADENPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); private ILLangEdit :integer; DataIL :TAArray; procedure inicCaption; public constructor Create(aOwner: TComponent;aDataDE :TAArray);overload; end; var FormEditInLang: TFormEditInLang; implementation uses uPrK_Resources,uConstants,uPRK_DT_ABIT,uPrK_Loader; {$R *.dfm} { TFormEditInLang } constructor TFormEditInLang.Create(aOwner: TComponent; aDataDE: TAArray); begin DataIL :=aDataDE; ILLangEdit:=SelectLanguage; inherited Create(aOwner); inicCaption; end; procedure TFormEditInLang.inicCaption; begin ActionOK.Caption :=nActiont_OK[ILLangEdit]; ActionCansel.Caption :=nActiont_Cansel[ILLangEdit]; ActionOK.Hint :=nHintActiont_OK[ILLangEdit]; ActionCansel.Hint :=nHintActiont_Cansel[ILLangEdit]; cxLabelIN_LANG.Caption :=nLabelIN_LANG[ILLangEdit]; cxLabelLEVEL_VLADEN.Caption :=nLabelLEVEL_VLADEN[ILLangEdit]; end; procedure TFormEditInLang.FormCreate(Sender: TObject); begin cxButtonEditIN_LANG.Text :=DataIL['SHORT_NAME_IN_LANG'].asString; cxButtonEditLEVEL_VLADEN.Text :=DataIL['SHORT_NAME_LEVEL_VLADEN'].asString; end; procedure TFormEditInLang.ActionCanselExecute(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TFormEditInLang.ActionOKExecute(Sender: TObject); begin if trim(cxButtonEditIN_LANG.Text)='' then begin ShowMessage(nMsgEmptyIN_LANG[ILLangEdit]); cxButtonEditIN_LANG.SetFocus; exit; end; if trim(cxButtonEditLEVEL_VLADEN.Text)='' then begin ShowMessage(nMsgEmptyLEVEL_VLADEN[ILLangEdit]); cxButtonEditLEVEL_VLADEN.SetFocus; exit; end; ModalResult :=mrOk; end; procedure TFormEditInLang.cxButtonEditIN_LANGPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var res: Variant; begin res := uPrK_Loader.ShowPrkSprav(self,TFormPRK_DT_ABIT(self.Owner.Owner).DataBasePrK_ABIT.Handle, PrK_SP_IN_LANG,fsNormal); if VarArrayDimCount(res) > 0 then begin if res[0]<>NULL THEN begin DataIL['ID_SP_IN_LANG'].AsInt64 := Res[0]; DataIL['SHORT_NAME_IN_LANG'].AsString := Res[2]; cxButtonEditIN_LANG.Text := DataIL['SHORT_NAME_IN_LANG'].AsString; cxButtonEditLEVEL_VLADEN.SetFocus; end; end; end; procedure TFormEditInLang.cxButtonEditLEVEL_VLADENPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var res: Variant; begin res := uPrK_Loader.ShowPrkSprav(self,TFormPRK_DT_ABIT(self.Owner.Owner).DataBasePrK_ABIT.Handle, PrK_SP_LEVEL_VLADEN,fsNormal); if VarArrayDimCount(res) > 0 then begin if res[0]<>NULL THEN begin DataIL['ID_SP_LEVEL_VLADEN'].AsInt64 := Res[0]; DataIL['SHORT_NAME_LEVEL_VLADEN'].AsString := Res[2]; cxButtonEditLEVEL_VLADEN.Text := DataIL['SHORT_NAME_LEVEL_VLADEN'].AsString; end; end; end; end.
(* Version : (292 - 293) Date : 06.06.2011 Author : Antonio Marcos Fernandes de Souza (amfsouza) Issue : avoid decrease when parameter ( new parameter ) is set to true. Solution: set up correct mask to display format properfield object. Version : (293 - 294) ----------------------------------------------------------------------------------------------------- *) unit uFrmMarginTableUpdate; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, Buttons, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, DBClient, ADODB, uDMCalcPrice; type TFrmMarginTableUpdate = class(TFrmParent) dsMarginTableUpdate: TDataSource; grdMarginTableUpDBTableView1: TcxGridDBTableView; grdMarginTableUpLevel1: TcxGridLevel; grdMarginTableUp: TcxGrid; btSave: TButton; Panel4: TPanel; BitBtn1: TBitBtn; BitBtn2: TBitBtn; cmdUpdateModel: TADOCommand; pnlDivisoria2: TPanel; btnColumns: TBitBtn; cdsMarginTableUpdate: TClientDataSet; cdsMarginTableUpdateIsUpdate: TBooleanField; cdsMarginTableUpdateModel: TStringField; cdsMarginTableUpdateDescription: TStringField; cdsMarginTableUpdateIDModel: TIntegerField; cdsMarginTableUpdateCostPrice: TBCDField; cdsMarginTableUpdateNewSellingPrice: TBCDField; cdsMarginTableUpdateNewMSRPPrice: TBCDField; cdsMarginTableUpdateSalePrice: TBCDField; cdsMarginTableUpdateMSRP: TBCDField; cdsMarginTableUpdateRealMarkUpValue: TBCDField; cdsMarginTableUpdateRealMarkUpPercent: TBCDField; cdsMarginTableUpdateMarginPercent: TBCDField; cdsMarginTableUpdateMarginValue: TBCDField; cdsMarginTableUpdateCategory: TStringField; cdsMarginTableUpdateSubCategory: TStringField; cdsMarginTableUpdateModelGroup: TStringField; grdMarginTableUpDBTableView1IsUpdate: TcxGridDBColumn; grdMarginTableUpDBTableView1Model: TcxGridDBColumn; grdMarginTableUpDBTableView1Description: TcxGridDBColumn; grdMarginTableUpDBTableView1CostPrice: TcxGridDBColumn; grdMarginTableUpDBTableView1NewSellingPrice: TcxGridDBColumn; grdMarginTableUpDBTableView1NewMSRPPrice: TcxGridDBColumn; grdMarginTableUpDBTableView1SalePrice: TcxGridDBColumn; grdMarginTableUpDBTableView1MSRP: TcxGridDBColumn; grdMarginTableUpDBTableView1RealMarkUpValue: TcxGridDBColumn; grdMarginTableUpDBTableView1RealMarkUpPercent: TcxGridDBColumn; grdMarginTableUpDBTableView1MarginPercent: TcxGridDBColumn; grdMarginTableUpDBTableView1MarginValue: TcxGridDBColumn; grdMarginTableUpDBTableView1Category: TcxGridDBColumn; grdMarginTableUpDBTableView1SubCategory: TcxGridDBColumn; grdMarginTableUpDBTableView1ModelGroup: TcxGridDBColumn; cdsMarginTableUpdateMarkUp: TBCDField; grdMarginTableUpDBTableView1MarkUp: TcxGridDBColumn; procedure BitBtn1Click(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnColumnsClick(Sender: TObject); private AView : TcxCustomGridTableView; procedure UpdateNewPrices; procedure CheckAll(Value :Boolean); public function Start(ID: Integer; FCalcPriceType : TCalcPriceType; fType: TModelGroupingType):Boolean; end; implementation uses uDM, uDMGlobal, uSystemConst; {$R *.dfm} { TFrmMarginTableUpdate } procedure TFrmMarginTableUpdate.CheckAll(Value: Boolean); begin with cdsMarginTableUpdate do try DisableControls; dsMarginTableUpdate.DataSet := nil; First; while not Eof DO begin Edit; FieldByName('IsUpdate').Value := Value; Post; Next; end; finally EnableControls; dsMarginTableUpdate.DataSet := cdsMarginTableUpdate; end; end; function TFrmMarginTableUpdate.Start(ID: Integer; FCalcPriceType: TCalcPriceType; fType: TModelGroupingType): Boolean; var AOptions : TcxGridStorageOptions; ASaveViewName : String; fRegistryPath : String; begin self.Cursor := crHourGlass; cdsMarginTableUpdate.Data := DM.FDMCalcPrice.GetNewSaleMSRPPrices(ID,FCalcPriceType,fType); self.Cursor := crDefault; fRegistryPath := MR_BRW_REG_PATH + Self.Caption; AOptions := [gsoUseFilter, gsoUseSummary]; DM.LoadGridFromRegistry(TcxGridDBTableView(AView), fRegistryPath, AOptions); ShowModal; if ModalResult = mrOk then UpdateNewPrices; DM.SaveGridToRegistry(TcxGridDBTableView(AView), fRegistryPath, True, AOptions); end; procedure TFrmMarginTableUpdate.UpdateNewPrices; var saveSellingPrice: currency; begin with cdsMarginTableUpdate do try DisableControls; First; while not Eof do begin if cdsMarginTableUpdate.FieldByName('IsUpdate').AsBoolean then begin cmdUpdateModel.Parameters.ParamByName('IDModel').Value := FieldByName('IDModel').AsInteger; cmdUpdateModel.Parameters.ParamByName('DateLastSellingPrice').Value := Null; cmdUpdateModel.Parameters.ParamByName('IDUserLastSellingPrice').Value := Null; (* if FieldByName('NewSellingPrice').AsCurrency <> FieldByName('SalePrice').AsCurrency then begin cmdUpdateModel.Parameters.ParamByName('DateLastSellingPrice').Value := Now; cmdUpdateModel.Parameters.ParamByName('IDUserLastSellingPrice').Value := DM.fUser.ID; end; *) //amfsouza 02.04.2011 if ( FieldByName('NewSellingPrice').AsCurrency < FieldByName('SalePrice').AsCurrency ) then begin if ( Dm.FDMCalcPrice.IncreasePriceOnly ) then begin if ( FieldByName('NewSellingPrice').AsCurrency < FieldByName('SalePrice').AsCurrency ) then begin Next; Continue; end; end; end; cmdUpdateModel.Parameters.ParamByName('NewSellingPrice').Value := FieldByName('NewSellingPrice').AsCurrency; cmdUpdateModel.Parameters.ParamByName('NewMSRPPrice').Value := FieldByName('NewMSRPPrice').AsCurrency; cmdUpdateModel.Execute; end; Next; end; finally EnableControls; end; end; procedure TFrmMarginTableUpdate.BitBtn1Click(Sender: TObject); begin CheckAll(True); end; procedure TFrmMarginTableUpdate.BitBtn2Click(Sender: TObject); begin CheckAll(False); end; procedure TFrmMarginTableUpdate.btCloseClick(Sender: TObject); begin inherited; Close; end; procedure TFrmMarginTableUpdate.FormCreate(Sender: TObject); begin inherited; DM.imgBTN.GetBitmap(BTN_COLUMN, btnColumns.Glyph); AView := TcxCustomGridTableView(grdMarginTableUp.FocusedView); end; procedure TFrmMarginTableUpdate.btnColumnsClick(Sender: TObject); begin inherited; TcxGridDBTableView(AView).Controller.Customization := not (TcxGridDBTableView(AView).Controller.Customization); end; end.
unit InflatablesList_Data; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Graphics, InflatablesList_Types; type TILItemManufacturerInfo = record Str: String; Tag: String; LogoResName: String; Logo: TBitmap; // 256 x 96 px, white background, loaded from resources end; type TILDataProvider = class(TObject) private fItemManufacturers: array[TILItemManufacturer] of TILItemManufacturerInfo; fItemReviewIcon: TBitmap; fItemFlagIcons: array[TILItemFlag] of TBitmap; fEmptyPicture: TBitmap; fEmptyPictureSmall: TBitmap; fEmptyPictureMini: TBitmap; fItemDefaultPics: array[TILItemType] of TBitmap; fItemDefaultPicsSmall: array[TILItemType] of TBitmap; fItemDefaultPicsMini: array[TILItemType] of TBitmap; fWantedGradientImage: TBitmap; fRatingGradientImage: TBitmap; fItemLockImage: TBitmap; fItemLockIconWhite: TBitmap; fItemLockIconBlack: TBitmap; Function GetItemManufacturerCount: Integer; Function GetItemManufacturer(ItemManufacturer: TILItemManufacturer): TILItemManufacturerInfo; Function GetItemFlagIconCount: Integer; Function GetItemFlagIcon(ItemFlag: TILItemFlag): TBitmap; Function GetItemDefaultPictureCount: Integer; Function GetItemDefaultPicture(ItemType: TILITemType): TBitmap; Function GetItemDefaultPictureSmallCount: Integer; Function GetItemDefaultPictureSmall(ItemType: TILITemType): TBitmap; Function GetItemDefaultPictureMiniCount: Integer; Function GetItemDefaultPictureMini(ItemType: TILITemType): TBitmap; protected procedure InitializeItemManufacurers; virtual; procedure FinalizeItemManufacturers; virtual; procedure InitializeItemReviewIcon; virtual; procedure FinalizeItemReviewIcon; virtual; procedure InitializeItemFlagIcons; virtual; procedure FinalizeItemFlagIcons; virtual; procedure InitializeEmptyPictures; virtual; procedure FinalizeEmptyPictures; virtual; procedure InitializeDefaultPictures; virtual; procedure FinalizeDefaultPictures; virtual; procedure InitializeDefaultPicturesSmall; virtual; procedure FinalizeDefaultPicturesSmall; virtual; procedure InitializeDefaultPicturesMini; virtual; procedure FinalizeDefaultPicturesMini; virtual; procedure InitializeGradientImages; virtual; procedure FinalizeGradientImages; virtual; procedure InitializeItemLockImage; virtual; procedure FinalizeItemLockImage; virtual; procedure Initialize; virtual; procedure Finalize; virtual; public class Function LoadBitmapFromResource(const ResName: String; Bitmap: TBitmap): Boolean; virtual; class Function GetItemTypeString(ItemType: TILItemType): String; virtual; class Function GetItemMaterialString(ItemMaterial: TILItemMaterial): String; virtual; class Function GetItemSurfaceFinishString(ItemSurfaceFinish: TILItemSurfaceFinish): String; virtual; class Function GetItemFlagString(ItemFlag: TILItemFlag): String; virtual; class Function GetItemValueTagString(ItemValueTag: TILItemValueTag): String; virtual; class Function GetShopUpdateResultString(UpdateResult: TILItemShopUpdateResult): String; virtual; class Function GetShopParsingExtractFromString(ExtractFrom: TILItemShopParsingExtrFrom): String; virtual; class Function GetShopParsingExtractMethodString(ExtractMethod: TILItemShopParsingExtrMethod): String; virtual; class Function GetAdvancedItemSearchResultString(SearchResult: TILAdvItemSearchResult): String; virtual; class Function GetAdvancedShopSearchResultString(SearchResult: TILAdvShopSearchResult): String; virtual; constructor Create; destructor Destroy; override; property ItemManufacturerCount: Integer read GetItemManufacturerCount; property ItemManufacturers[ItemManufacturer: TILItemManufacturer]: TILItemManufacturerInfo read GetItemManufacturer; property ItemReviewIcon: TBitmap read fItemReviewIcon; property ItemFlagIconCount: Integer read GetItemFlagIconCount; property ItemFlagIcons[ItemFlag: TILItemFlag]: TBitmap read GetItemFlagIcon; property EmptyPicture: TBitmap read fEmptyPicture; property EmptyPictureSmall: TBitmap read fEmptyPictureSmall; property EmptyPictureMini: TBitmap read fEmptyPictureMini; property ItemDefaultPictureCount: Integer read GetItemDefaultPictureCount; property ItemDefaultPictures[ItemType: TILITemType]: TBitmap read GetItemDefaultPicture; property ItemDefaultPictureSmallCount: Integer read GetItemDefaultPictureSmallCount; property ItemDefaultPicturesSmall[ItemType: TILITemType]: TBitmap read GetItemDefaultPictureSmall; property ItemDefaultPictureMiniCount: Integer read GetItemDefaultPictureMiniCount; property ItemDefaultPicturesMini[ItemType: TILITemType]: TBitmap read GetItemDefaultPictureMini; property WantedGradientImage: TBitmap read fWantedGradientImage; property RatingGradientImage: TBitmap read fRatingGradientImage; property ItemLockImage: TBitmap read fItemLockImage; property ItemLockIconWhite: TBitmap read fItemLockIconWhite; property ItemLockIconBlack: TBitmap read fItemLockIconBlack; end; implementation uses SysUtils, Classes, StrRect, InflatablesList_Utils; // resources containing the data {$R '..\resources\man_logos.res'} {$R '..\resources\icon_review.res'} {$R '..\resources\flag_icons.res'} {$R '..\resources\default_pics.res'} {$R '..\resources\gradient.res'} {$R '..\resources\item_lock.res'} {$R '..\resources\empty_pic.res'} const IL_DATA_ITEMMANUFACTURER_STRS: array[TILItemManufacturer] of String = ( 'neznámý','Bestway','Crivit','Intex','HappyPeople','Mondo','Polygroup', 'Summer Waves','Swimline','Vetro-Plus','Wehncke','WIKY','ostatní'); IL_DATA_ITEMMANUFACTURER_TAGS: array[TILItemManufacturer] of String = ( 'uk','bw','cr','it','hp','mn','pg','sw','sl','vp','wh','wk','ot'); IL_DATA_ITEMMANUFACTURER_LOGORESNAMES: array[TILItemManufacturer] of String = ( 'man_logo_others','man_logo_bestway','man_logo_crivit','man_logo_intex', 'man_logo_happypeople','man_logo_mondo','man_logo_polygroup', 'man_logo_summerwaves','man_logo_swimline','man_logo_vetroplus', 'man_logo_wehncke','man_logo_wiky','man_logo_others'); IL_DATA_ITEMTYPE_STRS: array[TILItemType] of String = ('neznámý','kruh','kruh s madly','kruh speciální','míč','rider','lehátko', 'lehátko s opěrkou','sedátko','rukávky','hračka','ostrov','ostrov extra', 'člun','matrace','postel','křeslo','pohovka','balónek','ostatní'); IL_DATA_ITEMMATERIAL_STRS: array[TILItemMaterial] of String = ('neznámý','polyvinylchlorid (PVC)','polyester (PES)','polyetylen (PE)', 'polypropylen (PP)','akrylonitrilbutadienstyren (ABS)','polystyren (PS)', 'polyuretan (PUR)','latex','silikon','gumotextílie','ostatní'); IL_DATA_ITEMSURFACEFINISH_STRS: array[TILItemSurfaceFinish] of String = ('neznámý','lesklý','pololesklý','matný','polomatný','perleový', 'metalický','povločkovaný','různý','jiný'); IL_DATA_ITEMFLAG_STRS: array[TILItemFlag] of String = ( 'Owned','Wanted','Ordered','Boxed','Elsewhere','Untested','Testing', 'Tested','Damaged','Repaired','Price change','Available change', 'Not Available','Lost','Discarded'); IL_DATA_ITEMFLAGICON_RESNAMES: array[TILItemFlag] of String = ( 'flag_icon_owned','flag_icon_wanted','flag_icon_ordered','flag_icon_boxed', 'flag_icon_elsewhere','flag_icon_untested','flag_icon_testing', 'flag_icon_tested','flag_icon_damaged','flag_icon_repaired', 'flag_icon_pricechange','flag_icon_availchange','flag_icon_notavailable', 'flag_icon_lost','flag_icon_discarded'); IL_DATA_ITEMVALUETAG_STRS: array[TILItemValueTag] of String = ( '<none>','Item is encrypted','Unique identifier (UID)','Time of addition','Item descriptor', 'Main picture (is present)','Main picture file','Main picture thumbnail (is present)', 'Package picture (is present)','Package picture file','Package picture thumbnail (is present)', 'Current secondary picture (is present)','Current secondary picture file', 'Current secondary picture thumbnail (is present)','Picture count','Secondary picture count', 'Secondary picture count (with thumbnails)','Item type','Item type specifier', 'Pieces','User ID','Manufacturer','Manufacturer string','Textual ID','Numerical ID', 'ID string','Owned (flag)','Wanted (flag)','Ordered (flag)','Boxed (flag)', 'Elsewhere (flag)','Untested (flag)','Testing (flag)','Tested (flag)','Damaged (flag)', 'Repaired (flag)','Price change (flag)','Availability change (flag)','Not available (flag)', 'Lost (flag)','Discarded (flag)','Textual tag','Numerical tag','Wanted level (flagged - wanted)', 'Variant (color, pattern, type, ...)','Variant tag','Surface finish','Material type', 'Wall thickness','Size X (length, diameter, ...)','Size Y (width, inner diameter, ...)', 'Size Z (height, thickness, ...)','Total size (X * Y * Z)','Weight','Total weight', 'Notes','ReviewURL','Review (is present)','Default unit price','Rating', 'Rating details','Some value is set to unknown (flagged - owned)','Unit price lowest', 'Total price lowest','Unit price selected','Total price selected','Total price', 'Available pieces','Shop count','Useful shop count','Useful shop ratio (useful/total)', 'Selected shop','Worst update result'); IL_DATA_SHOPUPDATERESULT_STRS: array[TILItemShopUpdateResult] of String = ( 'Success','Mild success','Data fail','Soft fail','Hard fail', 'Download fail','Parsing fail','Fatal error'); IL_DATA_DEFAULTPIC_RESNAME: array[TILITemType] of String = ( 'def_pic_unknown','def_pic_ring','def_pic_ring_w_handles', 'def_pic_ring_special','def_pic_ball','def_pic_rider','def_pic_lounger', 'def_pic_lounger_chair','def_pic_seat','def_pic_wings','def_pic_toy', 'def_pic_island','def_pic_island_rider','def_pic_boat','def_pic_mattress', 'def_pic_bed','def_pic_chair','def_pic_sofa','def_pic_balloon', 'def_pic_others'); IL_DATA_SHOPPARSING_EXTRACTFROM: array[TILItemShopParsingExtrFrom] of String = ( 'Text','Nested text','Attribute value'); IL_DATA_SHOPPARSING_EXTRACTMETHOD: array[TILItemShopParsingExtrMethod] of String = ( 'First integer','First integer, tagged','Negative tag is count', 'First number','First number tagged'); IL_DATA_ADVSEARCHRESULT_ITEM_STRS: array[TILAdvItemSearchResult] of String = ( 'List index','Unique ID','Time of addition','Item descriptor','Title','Pictures', 'Main picture file','Package picture file','Current secondary picture file', 'Type','Type specification','Type string','Pieces','User ID','Manufacturer', 'Manufacturer string','Manufaturer tag','Text ID','Numerical ID','ID string', 'Flags','Flag - Owned','Flag - Wanted','Flag - Ordered','Flag - Boxed', 'Flag - Elsewhere','Flag - Untested','Flag - Iesting','Flag - Tested', 'Flag - Damaged','Flag - Rrepaired','Flag - Price change', 'Flag - Availability change','Flag - Not available','Flag - Lost', 'Flag - Discarded','Textual tag','Numerical tag','Wanted level','Variant', 'Variant tag','Surface finish','Material','Thickness','Size X','Size Y', 'Size Z','Total size','Size string','Unit weight','Total weight', 'Total weight string','Notes','Review URL','Unit price default','Rating', 'Rating details','Unit price','Unit price lowest','Total price lowest', 'Unit price highest','Total price highest','Unit price selected', 'Total price selected','Total price','Available lowest','Available highest', 'Available selected','Shop count','Shop count string','Useful shop count', 'Useful shop ratio','Selected shop','Worst update result'); IL_DATA_ADVSEARCHRESULT_SHOP_STRS: array[TILAdvShopSearchResult] of String = ( 'List index','Selected','Untracked','Alternative download method','Name', 'Shop URL','Item URL','Available','Price','Notes','Last update result', 'Last update message','Last update time','Parsing variables', 'Parsing template reference','Ignore parsing errors','Available history', 'Price history','Available extraction settings','Price extraction settings', 'Available parsing finder','Price parsing finder'); //============================================================================== Function TILDataProvider.GetItemManufacturerCount: Integer; begin Result := Length(fItemManufacturers); end; //------------------------------------------------------------------------------ Function TILDataProvider.GetItemManufacturer(ItemManufacturer: TILItemManufacturer): TILItemManufacturerInfo; begin If (ItemManufacturer >= Low(fItemManufacturers)) and (ItemManufacturer <= High(fItemManufacturers)) then Result := fItemManufacturers[ItemManufacturer] else raise Exception.CreateFmt('TILDataProvider.GetItemManufacturer: Invalid item manufacturer (%d).',[Ord(ItemManufacturer)]); end; //------------------------------------------------------------------------------ Function TILDataProvider.GetItemFlagIconCount: Integer; begin Result := Length(fItemFlagIcons); end; //------------------------------------------------------------------------------ Function TILDataProvider.GetItemFlagIcon(ItemFlag: TILItemFlag): TBitmap; begin If (ItemFlag >= Low(fItemFlagIcons)) and (ItemFlag <= High(fItemFlagIcons)) then Result := fItemFlagIcons[ItemFlag] else raise Exception.CreateFmt('TILDataProvider.GetItemFlagIcon: Invalid item flag (%d).',[Ord(ItemFlag)]); end; //------------------------------------------------------------------------------ Function TILDataProvider.GetItemDefaultPictureCount: Integer; begin Result := Length(fItemDefaultPics); end; //------------------------------------------------------------------------------ Function TILDataProvider.GetItemDefaultPicture(ItemType: TILITemType): TBitmap; begin If (ItemType >= Low(fItemDefaultPics)) and (ItemType <= High(fItemDefaultPics)) then Result := fItemDefaultPics[ItemType] else raise Exception.CreateFmt('TILDataProvider.GetItemDefaultPicture: Invalid item type (%d).',[Ord(ItemType)]); end; //------------------------------------------------------------------------------ Function TILDataProvider.GetItemDefaultPictureSmallCount: Integer; begin Result := Length(fItemDefaultPicsSmall); end; //------------------------------------------------------------------------------ Function TILDataProvider.GetItemDefaultPictureSmall(ItemType: TILITemType): TBitmap; begin If (ItemType >= Low(fItemDefaultPicsSmall)) and (ItemType <= High(fItemDefaultPicsSmall)) then Result := fItemDefaultPicsSmall[ItemType] else raise Exception.CreateFmt('TILDataProvider.GetItemDefaultPictureSmall: Invalid item type (%d).',[Ord(ItemType)]); end; //------------------------------------------------------------------------------ Function TILDataProvider.GetItemDefaultPictureMiniCount: Integer; begin Result := Length(fItemDefaultPicsMini); end; //------------------------------------------------------------------------------ Function TILDataProvider.GetItemDefaultPictureMini(ItemType: TILITemType): TBitmap; begin If (ItemType >= Low(fItemDefaultPicsMini)) and (ItemType <= High(fItemDefaultPicsMini)) then Result := fItemDefaultPicsMini[ItemType] else raise Exception.CreateFmt('TILDataProvider.GetItemDefaultPictureMini: Invalid item type (%d).',[Ord(ItemType)]); end; //============================================================================== procedure TILDataProvider.InitializeItemManufacurers; var i: TILItemManufacturer; Bitmap: TBitmap; begin For i := Low(fItemManufacturers) to High(fItemManufacturers) do begin fItemManufacturers[i].Str := IL_DATA_ITEMMANUFACTURER_STRS[i]; fItemManufacturers[i].Tag := IL_DATA_ITEMMANUFACTURER_TAGS[i]; fItemManufacturers[i].LogoResName := IL_DATA_ITEMMANUFACTURER_LOGORESNAMES[i]; Bitmap := TBitmap.Create; If not LoadBitmapFromResource(fItemManufacturers[i].LogoResName,Bitmap) then FreeAndNil(Bitmap); fItemManufacturers[i].Logo := Bitmap; end; end; //------------------------------------------------------------------------------ procedure TILDataProvider.FinalizeItemManufacturers; var i: TILItemManufacturer; begin For i := Low(fItemManufacturers) to High(fItemManufacturers) do If Assigned(fItemManufacturers[i].Logo) then FreeAndNil(fItemManufacturers[i].Logo); end; //------------------------------------------------------------------------------ procedure TILDataProvider.InitializeItemReviewIcon; begin fItemReviewIcon := TBitmap.Create; If not LoadBitmapFromResource('icon_review',fItemReviewIcon) then FreeAndNil(fItemReviewIcon); end; //------------------------------------------------------------------------------ procedure TILDataProvider.FinalizeItemReviewIcon; begin If Assigned(fItemReviewIcon) then FreeAndNil(fItemReviewIcon); end; //------------------------------------------------------------------------------ procedure TILDataProvider.InitializeItemFlagIcons; var i: TILItemFlag; begin For i := Low(fItemFlagIcons) to High(fItemFlagIcons) do begin fItemFlagIcons[i] := TBitmap.Create; If not LoadBitmapFromResource(IL_DATA_ITEMFLAGICON_RESNAMES[i],fItemFlagIcons[i]) then FreeAndNil(fItemFlagIcons[i]); end; end; //------------------------------------------------------------------------------ procedure TILDataProvider.FinalizeItemFlagIcons; var i: TILItemFlag; begin For i := Low(fItemFlagIcons) to High(fItemFlagIcons) do If Assigned(fItemFlagIcons[i]) then FreeAndNil(fItemFlagIcons[i]); end; //------------------------------------------------------------------------------ procedure TILDataProvider.InitializeEmptyPictures; begin fEmptyPicture := TBitmap.Create; If LoadBitmapFromResource('empty_pic',fEmptyPicture) then begin fEmptyPictureSmall := TBitmap.Create; fEmptyPictureSmall.PixelFormat := pf24bit; fEmptyPictureSmall.Width := 48; fEmptyPictureSmall.Height := 48; IL_PicShrink(fEmptyPicture,fEmptyPictureSmall,2); fEmptyPictureMini := TBitmap.Create; fEmptyPictureMini.PixelFormat := pf24bit; fEmptyPictureMini.Width := 32; fEmptyPictureMini.Height := 32; IL_PicShrink(fEmptyPicture,fEmptyPictureMini,3); end else begin FreeAndNil(fEmptyPicture); raise Exception.Create('TILDataProvider.InitializeEmptyPictures: Failed to load empty item picture.'); end; end; //------------------------------------------------------------------------------ procedure TILDataProvider.FinalizeEmptyPictures; begin If Assigned(fEmptyPictureMini) then FreeAndNil(fEmptyPictureMini); If Assigned(fEmptyPictureSmall) then FreeAndNil(fEmptyPictureSmall); If Assigned(fEmptyPicture) then FreeAndNil(fEmptyPicture); end; //------------------------------------------------------------------------------ procedure TILDataProvider.InitializeDefaultPictures; var i: TILItemType; begin For i := Low(fItemDefaultPics) to High(fItemDefaultPics) do begin fItemDefaultPics[i] := TBitmap.Create; If not LoadBitmapFromResource(IL_DATA_DEFAULTPIC_RESNAME[i],fItemDefaultPics[i]) then FreeAndNil(fItemDefaultPics[i]); end; end; //------------------------------------------------------------------------------ procedure TILDataProvider.FinalizeDefaultPictures; var i: TILItemType; begin For i := Low(fItemDefaultPics) to High(fItemDefaultPics) do If Assigned(fItemDefaultPics[i]) then FreeAndNil(fItemDefaultPics[i]); end; //------------------------------------------------------------------------------ procedure TILDataProvider.InitializeDefaultPicturesSmall; var i: TILItemType; begin For i := Low(fItemDefaultPicsSmall) to High(fItemDefaultPicsSmall) do try fItemDefaultPicsSmall[i] := TBitmap.Create; fItemDefaultPicsSmall[i].PixelFormat := pf24bit; fItemDefaultPicsSmall[i].Width := 48; fItemDefaultPicsSmall[i].Height := 48; IL_PicShrink(fItemDefaultPics[i],fItemDefaultPicsSmall[i],2); except fItemDefaultPics[i] := nil; end; end; //------------------------------------------------------------------------------ procedure TILDataProvider.FinalizeDefaultPicturesSmall; var i: TILItemType; begin For i := Low(fItemDefaultPicsSmall) to High(fItemDefaultPicsSmall) do If Assigned(fItemDefaultPicsSmall[i]) then FreeAndNil(fItemDefaultPicsSmall[i]); end; //------------------------------------------------------------------------------ procedure TILDataProvider.InitializeDefaultPicturesMini; var i: TILItemType; begin For i := Low(fItemDefaultPicsMini) to High(fItemDefaultPicsMini) do try fItemDefaultPicsMini[i] := TBitmap.Create; fItemDefaultPicsMini[i].PixelFormat := pf24bit; fItemDefaultPicsMini[i].Width := 32; fItemDefaultPicsMini[i].Height := 32; IL_PicShrink(fItemDefaultPics[i],fItemDefaultPicsMini[i],3); except fItemDefaultPics[i] := nil; end; end; //------------------------------------------------------------------------------ procedure TILDataProvider.FinalizeDefaultPicturesMini; var i: TILItemType; begin For i := Low(fItemDefaultPicsMini) to High(fItemDefaultPicsMini) do If Assigned(fItemDefaultPicsMini[i]) then FreeAndNil(fItemDefaultPicsMini[i]); end; //------------------------------------------------------------------------------ procedure TILDataProvider.InitializeGradientImages; begin fWantedGradientImage := TBitmap.Create; If not LoadBitmapFromResource('wanted_grad',fWantedGradientImage) then FreeAndNil(fWantedGradientImage); fRatingGradientImage := TBitmap.Create; If not LoadBitmapFromResource('rating_grad',fRatingGradientImage) then FreeAndNil(fRatingGradientImage); end; //------------------------------------------------------------------------------ procedure TILDataProvider.FinalizeGradientImages; begin If Assigned(fWantedGradientImage) then FreeAndNil(fWantedGradientImage); If Assigned(fRatingGradientImage) then FreeAndNil(fRatingGradientImage); end; //------------------------------------------------------------------------------ procedure TILDataProvider.InitializeItemLockImage; begin fItemLockImage := TBitmap.Create; If not LoadBitmapFromResource('item_lock',fItemLockImage) then FreeAndNil(fItemLockImage); fItemLockIconWhite := TBitmap.Create; If not LoadBitmapFromResource('icon_lock_w',fItemLockIconWhite) then FreeAndNil(fItemLockIconWhite); fItemLockIconBlack := TBitmap.Create; If not LoadBitmapFromResource('icon_lock_b',fItemLockIconBlack) then FreeAndNil(fItemLockIconBlack); end; //------------------------------------------------------------------------------ procedure TILDataProvider.FinalizeItemLockImage; begin If Assigned(fItemLockImage) then FreeAndNil(fItemLockImage); If Assigned(fItemLockIconWhite) then FreeAndNil(fItemLockIconWhite); If Assigned(fItemLockIconBlack) then FreeAndNil(fItemLockIconBlack); end; //------------------------------------------------------------------------------ procedure TILDataProvider.Initialize; begin InitializeItemManufacurers; InitializeItemReviewIcon; InitializeItemFlagIcons; InitializeEmptyPictures; InitializeDefaultPictures; InitializeDefaultPicturesSmall; InitializeDefaultPicturesMini; InitializeGradientImages; InitializeItemLockImage; end; //------------------------------------------------------------------------------ procedure TILDataProvider.Finalize; begin FinalizeItemLockImage; FinalizeGradientImages; FinalizeDefaultPicturesMini; FinalizeDefaultPicturesSmall; FinalizeDefaultPictures; FinalizeEmptyPictures; FinalizeItemFlagIcons; FinalizeItemReviewIcon; FinalizeItemManufacturers; end; //============================================================================== class Function TILDataProvider.LoadBitmapFromResource(const ResName: String; Bitmap: TBitmap): Boolean; var ResStream: TResourceStream; begin try ResStream := TResourceStream.Create(hInstance,StrToRTL(ResName),PChar(10){RT_RCDATA}); try ResStream.Seek(0,soBeginning); Bitmap.LoadFromStream(ResStream); finally ResStream.Free; end; Result := True; except Result := False; end; end; //------------------------------------------------------------------------------ class Function TILDataProvider.GetItemTypeString(ItemType: TILItemType): String; begin If (ItemType >= Low(TILItemType)) and (ItemType <= High(TILItemType)) then Result := IL_DATA_ITEMTYPE_STRS[ItemType] else raise Exception.CreateFmt('TILDataProvider.GetItemTypeString: Invalid item type (%d).',[Ord(ItemType)]); end; //------------------------------------------------------------------------------ class Function TILDataProvider.GetItemMaterialString(ItemMaterial: TILItemMaterial): String; begin If (ItemMaterial >= Low(TILItemMaterial)) and (ItemMaterial <= High(TILItemMaterial)) then Result := IL_DATA_ITEMMATERIAL_STRS[ItemMaterial] else raise Exception.CreateFmt('TILDataProvider.GetItemMaterialString: Invalid item material (%d).',[Ord(ItemMaterial)]); end; //------------------------------------------------------------------------------ class Function TILDataProvider.GetItemSurfaceFinishString(ItemSurfaceFinish: TILItemSurfaceFinish): String; begin If (ItemSurfaceFinish >= Low(TILItemSurfaceFinish)) and (ItemSurfaceFinish <= High(TILItemSurfaceFinish)) then Result := IL_DATA_ITEMSURFACEFINISH_STRS[ItemSurfaceFinish] else raise Exception.CreateFmt('TILDataProvider.GetItemSurfaceFinishString: Invalid item surface (%d).',[Ord(ItemSurfaceFinish)]); end; //------------------------------------------------------------------------------ class Function TILDataProvider.GetItemFlagString(ItemFlag: TILItemFlag): String; begin If (ItemFlag >= Low(TILItemFlag)) and (ItemFlag <= High(TILItemFlag)) then Result := IL_DATA_ITEMFLAG_STRS[ItemFlag] else raise Exception.CreateFmt('TILDataProvider.GetItemFlagString: Invalid item flag (%d).',[Ord(ItemFlag)]); end; //------------------------------------------------------------------------------ class Function TILDataProvider.GetItemValueTagString(ItemValueTag: TILItemValueTag): String; begin If (ItemValueTag >= Low(TILItemValueTag)) and (ItemValueTag <= High(TILItemValueTag)) then Result := IL_DATA_ITEMVALUETAG_STRS[ItemValueTag] else raise Exception.CreateFmt('TILDataProvider.GetItemValueTagString: Invalid item value tag (%d).',[Ord(ItemValueTag)]); end; //------------------------------------------------------------------------------ class Function TILDataProvider.GetShopUpdateResultString(UpdateResult: TILItemShopUpdateResult): String; begin If (UpdateResult >= Low(TILItemShopUpdateResult)) and (UpdateResult <= High(TILItemShopUpdateResult)) then Result := IL_DATA_SHOPUPDATERESULT_STRS[UpdateResult] else raise Exception.CreateFmt('TILDataProvider.GetShopUpdateResultString: Invalid shop update result (%d).',[Ord(UpdateResult)]); end; //------------------------------------------------------------------------------ class Function TILDataProvider.GetShopParsingExtractFromString(ExtractFrom: TILItemShopParsingExtrFrom): String; begin If (ExtractFrom >= Low(TILItemShopParsingExtrFrom)) and (ExtractFrom <= High(TILItemShopParsingExtrFrom)) then Result := IL_DATA_SHOPPARSING_EXTRACTFROM[ExtractFrom] else raise Exception.CreateFmt('TILDataProvider.GetShopParsingEtractFromString: Invalid extract from value (%d).',[Ord(ExtractFrom)]); end; //------------------------------------------------------------------------------ class Function TILDataProvider.GetShopParsingExtractMethodString(ExtractMethod: TILItemShopParsingExtrMethod): String; begin If (ExtractMethod >= Low(TILItemShopParsingExtrMethod)) and (ExtractMethod <= High(TILItemShopParsingExtrMethod)) then Result := IL_DATA_SHOPPARSING_EXTRACTMETHOD[ExtractMethod] else raise Exception.CreateFmt('TILDataProvider.GetShopParsingExtractMethodString: Invalid extraction method (%d).',[Ord(ExtractMethod)]); end; //------------------------------------------------------------------------------ class Function TILDataProvider.GetAdvancedItemSearchResultString(SearchResult: TILAdvItemSearchResult): String; begin If (SearchResult >= Low(TILAdvItemSearchResult)) and (SearchResult <= High(TILAdvItemSearchResult)) then Result := IL_DATA_ADVSEARCHRESULT_ITEM_STRS[SearchResult] else raise Exception.CreateFmt('TILDataProvider.GetAdvancedItemSearchResultString: Invalid search result (%d).',[Ord(SearchResult)]); end; //------------------------------------------------------------------------------ class Function TILDataProvider.GetAdvancedShopSearchResultString(SearchResult: TILAdvShopSearchResult): String; begin If (SearchResult >= Low(TILAdvShopSearchResult)) and (SearchResult <= High(TILAdvShopSearchResult)) then Result := IL_DATA_ADVSEARCHRESULT_Shop_STRS[SearchResult] else raise Exception.CreateFmt('TILDataProvider.GetAdvancedShopSearchResultString: Invalid search result (%d).',[Ord(SearchResult)]); end; //------------------------------------------------------------------------------ constructor TILDataProvider.Create; begin inherited Create; Initialize; end; //------------------------------------------------------------------------------ destructor TILDataProvider.Destroy; begin Finalize; inherited; end; end.
unit LangUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, comctrls, grids, FIBDatabase, pFIBDatabase; type TLanguage = class(TComponent) private LangFile : TStringList; LangHeader : array [32..255] of integer; function GetNewString(oldStr : string): string; function FindOffset(const symbol : Char) : Integer; procedure ParseComponent(Component: TPersistent); virtual; procedure ApplyLanguage(Component: TComponent); public constructor Create(AOwner : TComponent);override; destructor Destroy;override; procedure LoadLangFile(const FileName : string); end; procedure LangPackApply(Component: TComponent); var LANG_FILE_NAME : string; implementation uses TypInfo, designintf, IniFiles, Math; type TLoadResStrFunction = function (ResStringRec: PResStringRec): string; var LangObject : TLanguage; ini : TMemIniFile; procedure ChangeProc(OldProcedure, NewProcedure: pointer); var x: pchar; y: integer; ov2, ov: cardinal; begin x := PChar(OldProcedure); if not VirtualProtect(Pointer(x), 5, PAGE_EXECUTE_READWRITE, @ov) then RaiseLastOSError; x[0] := char($E9); y := integer(NewProcedure) - integer(OldProcedure) - 5; x[1] := char(y and 255); x[2] := char((y shr 8) and 255); x[3] := char((y shr 16) and 255); x[4] := char((y shr 24) and 255); if not VirtualProtect(Pointer(x), 5, ov, @ov2) then RaiseLastOSError; end; procedure LangPackApply(Component: TComponent); begin LangObject.ApplyLanguage(Component); end; { TLanguage } procedure TLanguage.ApplyLanguage(Component : TComponent); procedure ParseComponents(Component : TComponent); var i : integer; begin ParseComponent(Component); for i := 0 to Component.ComponentCount-1 do ParseComponents(Component.Components[i]); end; begin ParseComponents(Component); end; procedure TLanguage.ParseComponent(Component : TPersistent); var AName, PropName, StringPropValue: string; TypeInf, PropTypeInf : PTypeInfo; PropInfo : PPropInfo; TypeData : PTypeData; i, j : integer; PropList : PPropList; NumProps : word; PropObject : TObject; begin if Component is TpFIBDatabase then exit; if Component is TpFIBTransaction then exit; TypeInf := Component.ClassInfo; AName := TypeInf^.Name; TypeData := GetTypeData(TypeInf); NumProps := TypeData^.PropCount; GetMem(PropList, NumProps*sizeof(pointer)); try GetPropInfos(TypeInf, PropList); for i := 0 to NumProps-1 do begin PropName := PropList^[i]^.Name; PropTypeInf := PropList^[i]^.PropType^; PropInfo := PropList^[i]; case PropTypeInf^.Kind of tkString, tkLString: if PropName <> 'Name' then begin StringPropValue := GetStrProp( Component, PropInfo ); SetStrProp( Component, PropInfo, GetNewString(StringPropValue)); end; tkClass:begin PropObject := GetObjectProp(Component, PropInfo{, TPersistent}); if Assigned(PropObject)then begin if (PropObject is TPersistent) then ParseComponent(PropObject as TPersistent); if (PropObject is TStrings) then begin for j := 0 to (PropObject as TStrings).Count-1 do TStrings(PropObject)[j] := GetNewString(TStrings(PropObject)[j]); end; if (PropObject is TTreeNodes) then begin for j := 0 to (PropObject as TTreeNodes).Count-1 do TTreeNodes(PropObject).Item[j].Text := GetNewString(TTreeNodes(PropObject).Item[j].Text); end; if (PropObject is TListItems) then begin for j := 0 to (PropObject as TListItems).Count-1 do TListItems(PropObject).Item[j].Caption := GetNewString(TListItems(PropObject).Item[j].Caption); end; end; end; end; end; finally FreeMem(PropList, NumProps*sizeof(pointer)); end; end; function TLanguage.GetNewString(oldStr : string): string; var idx : Integer; ch : char; i : Integer; s : string; srcStr : string; begin Result := oldStr; if (LangFile.Count = 0) or (oldStr = '') then Exit; idx := FindOffset(oldStr[1]); if idx < 0 then Exit; ch := AnsiUpperCase(LangFile.Strings[idx])[1]; while AnsiUpperCase(LangFile.Strings[idx])[1] = ch do begin srcStr := LangFile.Strings[idx]; i := Pos('=', srcStr); if i <> 0 then begin s := Copy(srcStr, 1, i-1); if s = oldStr then begin Result := Copy(srcStr, i + 1, Length(srcStr) - i); Exit; end; end; Inc(idx); if idx = LangFile.Count then break; end; end; function LoadReoldStrNew(ReoldStrRec: PResStringRec): string; var Buffer: array [0..1024] of char; begin if ReoldStrRec = nil then Exit; if ReoldStrRec.Identifier < 64*1024 then SetString(Result, Buffer, LoadString(FindResourceHInstance(ReoldStrRec.Module^), ReoldStrRec.Identifier, Buffer, SizeOf(Buffer))) else Result := PChar(ReoldStrRec.Identifier); Result := langobject.GetNewString(Result); end; constructor TLanguage.Create(AOwner: TComponent); begin inherited; LangFile := TStringList.Create; end; destructor TLanguage.Destroy; begin LangFile.Free; inherited; end; var i : Integer; function TLanguage.FindOffset(const symbol: Char): Integer; begin Result := LangHeader[Ord(AnsiUpperCase(symbol+'')[1])] - 223; end; procedure TLanguage.LoadLangFile(const FileName: string); var i : Integer; begin if not FileExists(FileName) then Exit; LangFile.LoadFromFile(FileName); for i := 32 to 255 do begin LangHeader[i] := StrToInt(LangFile.Strings[0]); LangFile.Delete(0); end; end; initialization begin LangObject := TLanguage.Create(Nil); ChangeProc(@loadResString, @LoadReoldStrNew); ini := TMemIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); LANG_FILE_NAME := ExtractFilePath(Application.ExeName) + 'Lang\' + ini.ReadString('Lang', 'File', ''); ini.Free; i := 1; while i < ParamCount do begin if UpperCase(ParamStr(i)) = '-LANG' then if i + 1 <= ParamCount then LANG_FILE_NAME := ExtractFilePath(Application.ExeName) + 'Lang\' + ParamStr(i + 1); Inc(i); end; LangObject.LoadLangFile(LANG_FILE_NAME); end; Finalization begin LangObject.Free; end; end.
unit BVE.XMLTreeView.FMX; // ------------------------------------------------------------------------------ // // SVG Control 2.0 // Copyright (c) 2015 Bruno Verhue // // ------------------------------------------------------------------------------ // [The "BSD licence"] // // Copyright (c) 2013 Bruno Verhue // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. {$I '..\Common\CompilerSettings.inc'} interface uses System.Classes, Xml.XMLIntf, FMX.Types, FMX.TreeView, FMX.Grid; type TTreeNode = class(TTreeViewItem) private FXMLNode: IXMLNode; FOnChangeExpanded: TNotifyEvent; protected procedure ApplyStyle; override; procedure DoChangeExpanded(Sender: TObject); published property XMLNode: IXMLNode read FXMLNode write FXMLNode; property OnChangeExpanded: TNotifyEvent read FOnChangeExpanded write FOnChangeExpanded; end; procedure TreeViewUpdate(aTreeView: TTreeView; aGrid: TStringGrid; aRootXMLNode: IXMLNode; aTreeNodeExpandProc: TNotifyEvent); procedure TreeViewExpandNode(aTreeView: TTreeView; Node: TTreeNode; aTreeNodeExpandProc: TNotifyEvent); procedure TreeNodeAdd(aTreeView: TTreeView; aParentNode: TFMXObject; aXMLNode: IXMLNode; aLevel: integer; aTreeNodeExpandProc: TNotifyEvent); procedure TreeNodeUpdate(aTreeView: TTreeView; aParentNode: TTreeNode; aXMLNode: IXMLNode; aLevel: integer; aTreeNodeExpandProc: TNotifyEvent); procedure AttributeListUpdate(aTreeView: TTreeView; aGrid: TStringGrid; aLines: TStrings); procedure AttributeValueUpdate(aTreeView: TTreeView; aGrid: TStringGrid; aLines: TStrings); procedure AttributeValueApply(aTreeView: TTreeView; aGrid: TStringGrid; aLines: TStrings); implementation uses FMX.Ani; procedure TreeViewUpdate(aTreeView: TTreeView; aGrid: TStringGrid; aRootXMLNode: IXMLNode; aTreeNodeExpandProc: TNotifyEvent); begin aTreeView.BeginUpdate; try aGrid.RowCount := 1; aTreeView.Clear; if assigned(aRootXMLNode) then begin TreeNodeAdd(aTreeView, aTreeView, aRootXMLNode, 2, aTreeNodeExpandProc); end; finally aTreeView.EndUpdate; aTreeView.Repaint; end; end; procedure TreeViewExpandNode(aTreeView: TTreeView; Node: TTreeNode; aTreeNodeExpandProc: TNotifyEvent); var i: integer; begin {$IFDEF Ver250Up} if aTreeView.IsUpdating then exit; {$ENDIF} if not assigned(Node) then exit; if not Node.IsExpanded then exit; aTreeView.BeginUpdate; try for i := 0 to Node.XMLNode.ChildNodes.Count - 1 do begin TreeNodeUpdate(aTreeView, Node, Node.XMLNode.ChildNodes[i], 2, aTreeNodeExpandProc); end; finally aTreeView.EndUpdate; end; aTreeView.Repaint; end; procedure TreeNodeAdd(aTreeView: TTreeView; aParentNode: TFMXObject; aXMLNode: IXMLNode; aLevel: integer; aTreeNodeExpandProc: TNotifyEvent); var n: TTreeNode; i: integer; NodeName, id: string; begin if aLevel = 0 then exit; if aXMLNode.IsTextElement then exit; NodeName := aXMLNode.LocalName; if NodeName = '#text' then exit; if aXMLNode.HasAttribute('id') then id := aXMLNode.Attributes['id'] else id := ' no id'; n := TTreeNode.Create(aTreeView); n.XMLNode := aXMLNode; n.OnChangeExpanded := aTreeNodeExpandProc; n.Parent := aParentNode; n.Text := '<' + aXMLNode.LocalName + '>: ' + id; for i := 0 to aXMLNode.ChildNodes.Count - 1 do begin TreeNodeAdd(aTreeView, n, aXMLNode.ChildNodes[i], aLevel - 1, aTreeNodeExpandProc); end; end; procedure TreeNodeUpdate(aTreeView: TTreeView; aParentNode: TTreeNode; aXMLNode: IXMLNode; aLevel: integer; aTreeNodeExpandProc: TNotifyEvent); var i: integer; n: TTreeNode; begin if aLevel = 0 then exit; i := 0; while (i < aParentNode.Count) and ((aParentNode.Items[i] as TTreeNode).XMLNode <> aXMLNode) do inc(i); if not(i < aParentNode.Count) then begin TreeNodeAdd(aTreeView, aParentNode, aXMLNode, aLevel, aTreeNodeExpandProc); end else begin n := aParentNode.Items[i] as TTreeNode; for i := 0 to n.XMLNode.ChildNodes.Count - 1 do begin TreeNodeUpdate(aTreeView, n, n.XMLNode.ChildNodes[i], aLevel - 1, aTreeNodeExpandProc); end; end; end; procedure AttributeListUpdate(aTreeView: TTreeView; aGrid: TStringGrid; aLines: TStrings); var NodeList: IXMLNodeList; XMLNode: IXMLNode; i: integer; begin if not assigned(aTreeView.Selected) then exit; XMLNode := TTreeNode(aTreeView.Selected).FXMLNode; NodeList := XMLNode.AttributeNodes; aGrid.RowCount := NodeList.Count; if NodeList.Count > 0 then begin for i := 0 to NodeList.Count - 1 do begin aGrid.Cells[0, i] := NodeList[i].LocalName; aGrid.Cells[1, i] := NodeList[i].NodeValue; end; if aGrid.Selected = -1 then aGrid.Selected := 0; if aGrid.Selected >= NodeList.Count then aGrid.Selected := NodeList.Count - 1; end; AttributeValueUpdate(aTreeView, aGrid, aLines); end; procedure AttributeValueUpdate(aTreeView: TTreeView; aGrid: TStringGrid; aLines: TStrings); var NodeList: IXMLNodeList; XMLNode: IXMLNode; begin if not assigned(aTreeView.Selected) then exit; XMLNode := TTreeNode(aTreeView.Selected).FXMLNode; NodeList := XMLNode.AttributeNodes; if (aGrid.Selected >= 0) and (aGrid.Selected < NodeList.Count) then aLines.Text := NodeList[aGrid.Selected].NodeValue else aLines.Text := ''; end; procedure AttributeValueApply(aTreeView: TTreeView; aGrid: TStringGrid; aLines: TStrings); var NodeList: IXMLNodeList; XMLNode: IXMLNode; begin if not assigned(aTreeView.Selected) then exit; XMLNode := TTreeNode(aTreeView.Selected).FXMLNode; NodeList := XMLNode.AttributeNodes; if aGrid.Selected < NodeList.Count then begin NodeList[aGrid.Selected].NodeValue := aLines.Text; AttributeListUpdate(aTreeView, aGrid, aLines); end; end; // ----------------------------------------------------------------------------- // // TTreeNode // Trick for missing onexpand event: http://monkeystyler.com/blog // // ----------------------------------------------------------------------------- procedure TTreeNode.ApplyStyle; var Ani: TFloatAnimation; Obj: TFMXObject; begin inherited; Obj := FindStyleResource('button'); if assigned(Obj) then begin Ani := TFloatAnimation.Create(Obj); Ani.Parent := Obj; Ani.Stored := False; Ani.StartValue := 0.999999999999; Ani.StopValue := 1; Ani.PropertyName := 'Opacity'; Ani.Trigger := 'IsExpanded=true'; Ani.TriggerInverse := 'IsExpanded=false'; Ani.Duration := 0; Ani.OnFinish := DoChangeExpanded; end; end; procedure TTreeNode.DoChangeExpanded(Sender: TObject); begin if assigned(OnChangeExpanded) then OnChangeExpanded(Self); end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_PROGLIST.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} {$O-} unit PAXCOMP_PROGLIST; interface uses {$I uses.def} SysUtils, Classes, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS, PAXCOMP_MAP; type TProgRec = class public FullPath: String; Prog: Pointer; InitProcessed: Boolean; destructor Destroy; override; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream; PCUOwner: Pointer); procedure RunInitialization; procedure RunFinalization; end; TProgList = class(TTypedList) private fOwner: Pointer; function GetRecord(I: Integer): TProgRec; function AddRecord: TProgRec; public constructor Create(AOwner: Pointer); function LoadAddress(const FileName, ProcName: String; RunInit: Boolean; OverCount: Integer; var MR: TMapRec; var DestProg: Pointer): Pointer; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream; PCUOwner: Pointer); procedure LoadFromStreamList(S: TStreamList; PCUOwner: Pointer); procedure SetPCUOwner(PCUOwner: Pointer); procedure RunInitialization; procedure RunFinalization; procedure Add(Rec: TProgRec); function IndexOf(const FullPath: String): Integer; procedure RemoveProg(const FullPath: String); property Records[I: Integer]: TProgRec read GetRecord; default; end; implementation uses PAXCOMP_BASERUNNER; destructor TProgRec.Destroy; begin if Prog <> nil then TBaseRunner(Prog).Destroy; inherited; end; procedure TProgRec.RunInitialization; begin if not InitProcessed then begin TBaseRunner(Prog).RunInitialization; InitProcessed := true; end; end; procedure TProgRec.RunFinalization; begin TBaseRunner(Prog).RunFinalization; end; procedure TProgRec.SaveToStream(S: TStream); begin SaveStringToStream(FullPath, S); TBaseRunner(Prog).SaveToStream(S); end; procedure TProgRec.LoadFromStream(S: TStream; PCUOwner: Pointer); var C: TBaseRunnerClass; begin C := TBaseRunnerClass(TBaseRunner(PCUOwner).ClassType); FullPath := LoadStringFromStream(S); TBaseRunner(Prog) := C.Create; TBaseRunner(Prog).PCUOwner := PCUOwner; TBaseRunner(Prog).CopyRootEvents; TBaseRunner(Prog).LoadFromStream(S); end; // TProgList ------------------------------------------------------------------- constructor TProgList.Create(AOwner: Pointer); begin inherited Create; fOwner := AOwner; end; function TProgList.GetRecord(I: Integer): TProgRec; begin result := TProgRec(L[I]); end; function TProgList.AddRecord: TProgRec; begin result := TProgRec.Create; L.Add(result); end; procedure TProgList.Add(Rec: TProgRec); begin L.Add(Rec); end; procedure TProgList.SaveToStream(S: TStream); var I, K: Integer; begin K := Count; S.Write(K, SizeOf(Integer)); for I := 0 to K - 1 do Records[I].SaveToStream(S); end; procedure TProgList.LoadFromStream(S: TStream; PCUOwner: Pointer); var I, K: Integer; R: TProgRec; begin S.Read(K, SizeOf(Integer)); for I := 0 to K - 1 do begin R := AddRecord; R.LoadFromStream(S, PCUOwner); end; end; procedure TProgList.LoadFromStreamList(S: TStreamList; PCUOwner: Pointer); var I: Integer; R: TProgRec; C: TBaseRunnerClass; FullName: String; begin C := TBaseRunnerClass(TBaseRunner(PCUOwner).ClassType); for I := 0 to S.Count - 1 do begin FullName := S[I].UnitName + '.' + PCU_FILE_EXT; if IndexOf(FullName) >= 0 then continue; R := AddRecord; R.FullPath := FullName; TBaseRunner(R.Prog) := C.Create; TBaseRunner(R.Prog).PCUOwner := PCUOwner; TBaseRunner(R.Prog).CopyRootEvents; TBaseRunner(R.Prog).LoadFromStream(S[I].Stream); end; end; procedure TProgList.RunInitialization; var I: Integer; begin for I := 0 to Count - 1 do Records[I].RunInitialization; end; procedure TProgList.RunFinalization; var I: Integer; begin for I := 0 to Count - 1 do Records[I].RunFinalization; end; procedure TProgList.SetPCUOwner(PCUOwner: Pointer); var I: Integer; begin for I := 0 to Count - 1 do TBaseRunner(Records[I].Prog).PCUOwner := PCUOwner; end; function TProgList.LoadAddress(const FileName, ProcName: String; RunInit: Boolean; OverCount: Integer; var MR: TMapRec; var DestProg: Pointer): Pointer; var I: Integer; Owner, P: TBaseRunner; UnitName, FullPath, S: String; ProgRec: TProgRec; InputStream: TStream; C: TBaseRunnerClass; begin Owner := TBaseRunner(fOwner); DestProg := nil; ProgRec := nil; FullPath := ''; UnitName := ExtractFullOwner(FileName); InputStream := nil; // if not Owner.FileExists(FileName, FullPath) then // Owner.RaiseError(errFileNotFound, [FileName]); for I := 0 to Count - 1 do begin S := ExtractFileName(TProgRec(L[I]).FullPath); if StrEql(S, FileName) then begin ProgRec := TProgRec(L[I]); FullPath := ProgRec.FullPath; break; end; end; if ProgRec = nil then begin if Assigned(Owner.OnLoadPCU) then begin Owner.OnLoadPCU(Owner.Owner, UnitName, InputStream); end; if not Owner.FileExists(FileName, FullPath) then if InputStream = nil then begin result := nil; Owner.RaiseError(errFileNotFound, [FileName]); Exit; end; C := TBaseRunnerClass(Owner.ClassType); P := C.Create; P.PCUOwner := Owner; if InputStream <> nil then P.LoadFromStream(InputStream) else P.LoadFromFile(FullPath); ProgRec := TProgRec.Create; ProgRec.FullPath := FullPath; ProgRec.Prog := P; L.Add(ProgRec); if RunInit then ProgRec.RunInitialization; end else begin P := ProgRec.Prog; if RunInit then ProgRec.RunInitialization; end; P.CopyRootEvents; P.CopyRootBreakpoints(UnitName); S := ExtractName(UnitName)+ '.' + ProcName; result := P.GetAddressEx(S, OverCount, MR); DestProg := P; end; function TProgList.IndexOf(const FullPath: String): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if StrEql(Records[I].FullPath, FullPath) then begin result := I; Exit; end; end; procedure TProgList.RemoveProg(const FullPath: String); var I: Integer; begin I := IndexOf(FullPath); if I >= 0 then RemoveAt(I); end; end.
(* * DGL(The Delphi Generic Library) * * Copyright (c) 2004 * HouSisong@gmail.com * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * *) //------------------------------------------------------------------------------ // 例子 :值语义的TTestObj的容器 // 具现化的TTestObj类型的声明 // 需要保持值语义的类的容器的声明模版 // 值语义:容器对于传进来的对象进行拷贝来保存,容器删除对象时会自动进行释放; // Create by HouSisong, 2004.09.04 //------------------------------------------------------------------------------ unit _DGL_Object; //如果只是需要保持引用语义,则注释掉_DGL_ObjValue的定义 interface uses SysUtils; var _refCount : integer=0; _ValueCount : integer=1; type TTestObj = class(TObject) FValue : integer; constructor Create();overload; constructor Create(v:TTestObj);overload; destructor Destroy();override; end; type _ValueType = TTestObj; const _NULL_Value:TTestObj =nil ; function _HashValue(const Key:_ValueType) : Cardinal;//Hash函数 {$define _DGL_Compare} //需要比较函数,可选 function _IsEqual(const a,b :_ValueType):boolean; //result:=(a=b); function _IsLess(const a,b :_ValueType):boolean; //result:=(a<b); 默认排序准则 {$define _DGL_ObjValue} //需要保持对象的值语义 function _CreateNew():_ValueType;overload;//构造 function _CopyCreateNew(const Value: _ValueType):_ValueType;overload;//拷贝构造 procedure _Assign(DestValue:_ValueType;const SrcValue: _ValueType);//赋值 procedure _Free(Value: _ValueType);//析构 {$I DGL.inc_h} //<out> type TObjAlgorithms = _TAlgorithms; IObjIterator = _IIterator; IObjContainer = _IContainer; IObjSerialContainer = _ISerialContainer; IObjVector = _IVector; IObjList = _IList; IObjDeque = _IDeque; IObjStack = _IStack; IObjQueue = _IQueue; IObjPriorityQueue = _IPriorityQueue; IObjSet = _ISet; IObjMultiSet = _IMultiSet; TObjPointerItBox = _TPointerItBox_Obj; TObjVector = _TVector; IObjVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:) TObjDeque = _TDeque; TObjList = _TList; TObjStack = _TStack; TObjQueue = _TQueue; TObjPriorityQueue = _TPriorityQueue; TObjHashSet = _THashSet; TObjHashMuitiSet = _THashMultiSet; // IObjMapIterator = _IMapIterator; IObjMap = _IMap; IObjMultiMap = _IMultiMap; TObjHashMap = _THashMap; TObjHashMultiMap = _THashMultiMap; implementation {$I DGL.inc_pas} function _HashValue(const Key :_ValueType):Cardinal; begin Assert(Key<>nil); result:=Cardinal(Key.FValue)*37; end; function _IsEqual(const a,b :_ValueType):boolean; begin Assert(a<>nil); Assert(b<>nil); result:=(a.FValue=b.FValue); //Assert(false);//自己按实际情况实现 end; function _IsLess(const a,b :_ValueType):boolean; begin Assert(a<>nil); Assert(b<>nil); result:=(a.FValue<b.FValue); //Assert(false);//自己按实际情况实现 end; function _CreateNew():_ValueType; begin result:=TTestObj.Create(); //Assert(false);//自己按实际情况实现 end; function _CopyCreateNew(const Value: _ValueType):_ValueType; begin Assert(Value<>nil); result:=TTestObj.Create(Value); //Assert(false);//自己按实际情况实现 end; procedure _Assign(DestValue:_ValueType;const SrcValue: _ValueType); begin Assert(DestValue<>nil); Assert(SrcValue<>nil); DestValue.FValue:=SrcValue.FValue; //Assert(false);//自己按实际情况实现 end; procedure _Free(Value: _ValueType); begin Assert(Value<>nil); Value.Free(); //Assert(false);//自己按实际情况实现 如:Value.Free; end; { TTestObj } constructor TTestObj.Create; begin inherited Create(); FValue:=_ValueCount; inc(_ValueCount); inc(_refCount); end; constructor TTestObj.Create(v: TTestObj); begin inherited Create(); FValue:=v.FValue; inc(_refCount); end; destructor TTestObj.Destroy; begin dec(_refCount); inherited; end; end.
unit iStart; {$mode objfpc}{$H+} interface uses rtti_broker_iBroker, rtti_idebinder_iBindings, Controls, Forms; type { IAppFactory } IAppFactory = interface ['{F73EFD7D-6F3F-4ED9-BFE2-F02DF1690E87}'] function CreateObject(const AClass: string): TObject; function FindClass(const AClass: String): TClass; end; { IAppStoreList } IAppStoreList = interface ['{5CA63112-A45E-4D54-BF26-9CEECB37878E}'] end; { IAppStore } IAppStore = interface ['{B621A696-FAC1-4652-95DB-FB365A989ADF}'] procedure Save(AData: TObject); function Load(const AClass: string; const AProperty, AValue: string): TObject; function LoadList(const AClass: string): IAppStoreList; procedure Flush; procedure Delete(AData: TObject); end; IAppContext = interface ['{3452F867-A06C-4BC7-98FC-0E7E830EAFED}'] function GetConfig: IAppStore; function GetFactory: IAppFactory; property Config: IAppStore read GetConfig; property Factory: IAppFactory read GetFactory; end; { IApp } IApp = interface ['{98A3DEC9-BEFC-4EC0-BE7D-67A8E307977D}'] procedure RegisterDataClasses(const AClasses: array of TClass); procedure RegisterControlClasses(const ACtlClasses: array of TControlClass); procedure Run(const AFormClass: TFormClass); end; { IAppContext_kvyhozeni } IAppContext_kvyhozeni = interface ['{44D90982-3C93-4FAC-A1E3-48C91A901288}'] function GetConfig: IRBStore; function GetData: IRBStore; function GetClassFactory: IRBFactory; property Config: IRBStore read GetConfig; property Data: IRBStore read GetData; property ClassFactory: IRBFactory read GetClassFactory; end; IStartContext = interface ['{44D9302B-B326-45FD-B659-9B1A28E274C5}'] function GetBinderContext: IRBBinderContext; function GetDataStore: IRBStore; function GetSerialFactory: IRBFactory; function GetDataQuery: IRBDataQuery; function GetDesigner: IRBDesigner; property SerialFactory: IRBFactory read GetSerialFactory; property DataStore: IRBStore read GetDataStore; property DataQuery: IRBDataQuery read GetDataQuery; property Designer: IRBDesigner read GetDesigner; property BinderContext: IRBBinderContext read GetBinderContext; end; IStartContextConnectable = interface ['{E8F2A90A-20DE-446A-8F19-FBD6A9DD0833}'] procedure Connect(const AContext: IStartContext); end; implementation end.
unit Pospolite.View.CSS.UserAgentStyleSheet; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} interface uses Classes, SysUtils; const CPLUserAgentStylesSource = '@namespace url(http://www.w3.org/1999/xhtml);' + LineEnding + 'address, article, aside, body, center, details, dd, div, dl, dt, figcaption, footer, form, header, hgroup, html, main, multicol, nav, p, section, summary, blockquote, figure { display: block; }' + LineEnding + 'body { margin: 10px; }' + LineEnding + 'p, dl, multicol { margin: 0 1em; }' + LineEnding + 'dd { margin-top: 40px; }' + LineEnding + 'blockquote, figure { margin: 40px 1em; }' + LineEnding + 'blockquote[type=cite] { margin: 0 1em; padding-top: 1em; border-left: thin solid gray; }' + LineEnding + 'address, i, cite, em, var, dfn { font-style: italic; }' + LineEnding + 'center { text-align: center; }' + LineEnding + 'h1, h2, h3, h4, h5, h6 { display: block; font-weight: bold; }' + LineEnding + 'h1 { font-size: 2em; margin: 0 0.67em; }' + LineEnding + 'h2 { font-size: 1.5em; margin: 0 0.83em; }' + LineEnding + 'h3 { font-size: 1.17em; margin: 0 1em; }' + LineEnding + 'h4 { font-size: 1em; margin: 0 1.33em; }' + LineEnding + 'h5 { font-size: 0.83em; margin: 0 1.67em; }' + LineEnding + 'h6 { font-size: 0.67em; margin: 0 2.33em; }' + LineEnding + 'xmp, pre, plaintext, listing { display: block; font-family: monospace; white-space: pre; margin: 0.25em 1em; }' + LineEnding + 'listing { font-size: medium; }' + LineEnding + 'b, strong { font-weight: bolder; }' + LineEnding + 'u, ins { text-decoration: underline; }' + LineEnding + 's, strike, del { text-decoration: line-through; }' + LineEnding + 'big { font-size: larger; }' + LineEnding + 'small { font-size: smaller; }' + LineEnding + 'sub { vertical-align: sub; font-size: smaller; }' + LineEnding + 'sup { vertical-align: super; font-size: smaller; }' + LineEnding + 'nobr { white-space: nowrap; }' + LineEnding + 'mark { background: yellow; color: black; }' + LineEnding + 'abbr[title], acronym[title] { text-decoration: dotted underline; }' + LineEnding + 'spacer { position: static !important; float: none !important; }' + LineEnding + 'iframe { border: 2px inset; }' + LineEnding + 'frame { border-radius: 0 !important; }' + LineEnding + 'img[usemap], object[usemap] { color: blue; }' + LineEnding + 'hr { display: block; border: 1px inset; margin auto 0.5em; color: gray; box-sizing: content-box; }' + LineEnding + 'hr[size="1"] { border-style: solid none none none; }' + LineEnding + 'ul, menu, dir { display: block; list-style-type: disc; margin: 0 1em; padding-left: 40px; }' + LineEnding + 'ul, ol, menu { counter-reset: list-item; -pl-list-reversed: false; }' + LineEnding + 'ol[reversed] { -pl-list-reversed: true; }' + LineEnding + 'ol { display: block; list-style-type: decimal; margin: 20px 1em; }' + LineEnding + 'li { display: list-item; }' + LineEnding + 'ul > li > li, menu > li > li, dir > li > li { list-style-type: circle; }' + LineEnding + 'ul > li > li > li, menu > li > li > li, dir > li > li > li { list-style-type: square; }' + LineEnding + 'q:before, q:after { content: "\""; }' + LineEnding + ''; //'' + LineEnding + var PLUserAgentInstance: Pointer = nil; implementation uses Pospolite.View.CSS.StyleSheet; initialization PLUserAgentInstance := TPLCSSStyleSheet.Create; TPLCSSStyleSheet(PLUserAgentInstance).Load(CPLUserAgentStylesSource); finalization TPLCSSStyleSheet(PLUserAgentInstance).Free; end.
unit TestDolar; interface uses DUnitX.TestFramework, uFact; type [TestFixture] TestTDolar = class(TObject) strict private uDolar: TFact; MaiorZero: Boolean; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure TestesDolar(); end; implementation procedure TestTDolar.Setup; begin uDolar := TFact.Create; end; procedure TestTDolar.TearDown; begin uDolar := nil; end; procedure TestTDolar.TestesDolar(); begin MaiorZero := uDolar.CalcularValorDeVenda(1) > 0; Assert.isTrue(MaiorZero); end; initialization TDUnitX.RegisterTestFixture(TestTDolar); end.
unit OpenCV.Lib; interface const CV_VERSION_EPOCH = '2'; CV_VERSION_MAJOR = '2'; CV_VERSION_MINOR = '0'; CV_VERSION_REVISION = '0'; CV_VERSION = CV_VERSION_EPOCH + '.' + CV_VERSION_MAJOR + '.' + CV_VERSION_MINOR + '.' + CV_VERSION_REVISION; // * old style version constants*/ CV_MAJOR_VERSION = CV_VERSION_EPOCH; CV_MINOR_VERSION = CV_VERSION_MAJOR; CV_SUBMINOR_VERSION = CV_VERSION_MINOR; CV_VERSION_DLL = CV_VERSION_EPOCH + CV_VERSION_MAJOR + CV_VERSION_MINOR; {$IFDEF DEBUG} CV_VERSION_DLL_PATH = CV_VERSION_DLL + 'd'; {$ELSE} CV_VERSION_DLL_PATH = CV_VERSION_DLL; {$ENDIF} Core_Dll = 'opencv_core' + CV_VERSION_DLL_PATH + '.dll'; highgui_Dll = 'opencv_highgui' + CV_VERSION_DLL_PATH + '.dll'; imgproc_Dll = 'opencv_imgproc' + CV_VERSION_DLL_PATH + '.dll'; objdetect_dll = 'opencv_objdetect' + CV_VERSION_DLL_PATH + '.dll'; legacy_dll = 'opencv_legacy' + CV_VERSION_DLL_PATH + '.dll'; calib3d_dll = 'opencv_calib3d' + CV_VERSION_DLL_PATH + '.dll'; tracking_DLL = 'opencv_video' + CV_VERSION_DLL_PATH + '.dll'; Nonfree_DLL = 'opencv_nonfree' + CV_VERSION_DLL_PATH + '.dll'; OpenCV_Classes_DLL = 'OpenCV_Classes.dll'; implementation end.
unit StringFactory; interface type IStringBuilder = Interface(IInterface) ['{58C64C93-9F29-470D-AEEF-4ECEF0D3D684}'] function LoadFromFile(const PathFile: string): IStringBuilder; function ToString: string; End; TStringBuilder = class(TInterfacedObject, IStringBuilder) strict private var FStringFile: string; public class function New: IStringBuilder; function LoadFromFile(const PathFile: string): IStringBuilder; function ToString: string; override; end; implementation uses System.SysUtils, System.StrUtils, System.Classes; { TStringBuilder } function TStringBuilder.LoadFromFile(const PathFile: string): IStringBuilder; var StringBuilder: TStringList; begin Result := Self; StringBuilder := TStringList.Create; try StringBuilder.LoadFromFile(PathFile); FStringFile := StringBuilder.Text; finally FreeAndNil(StringBuilder); end; end; class function TStringBuilder.New: IStringBuilder; begin Result := Self.Create; end; function TStringBuilder.ToString: string; begin Result := FStringFile; end; end.
unit SDUSystemTrayIconShellAPI; // Description: Shell API functions relating to tasktray Icon // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages; // ------------------------------------ // All versions of MS Windows type // Ripped from Delphi's ShellAPI.pas, in case they update to support shell v5 // struct PNotifyIconData_v1A = ^TNotifyIconData_v1A; PNotifyIconData_v1W = ^TNotifyIconData_v1W; PNotifyIconData_v1 = PNotifyIconData_v1A; {$EXTERNALSYM _NOTIFYICONDATA_v1A} _NOTIFYICONDATA_v1A = record cbSize: DWORD; hWnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; szTip: array [0..63] of AnsiChar; end; {$EXTERNALSYM _NOTIFYICONDATA_v1W} _NOTIFYICONDATA_v1W = record cbSize: DWORD; hWnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; szTip: array [0..63] of WideChar; end; {$EXTERNALSYM _NOTIFYICONDATA_v1} _NOTIFYICONDATA_v1 = _NOTIFYICONDATA_v1A; TNotifyIconData_v1A = _NOTIFYICONDATA_v1A; TNotifyIconData_v1W = _NOTIFYICONDATA_v1W; TNotifyIconData_v1 = TNotifyIconData_v1A; {$EXTERNALSYM NOTIFYICONDATA_v1A} NOTIFYICONDATA_v1A = _NOTIFYICONDATA_v1A; {$EXTERNALSYM NOTIFYICONDATA_v1W} NOTIFYICONDATA_v1W = _NOTIFYICONDATA_v1W; {$EXTERNALSYM NOTIFYICONDATA_v1} NOTIFYICONDATA_v1 = NOTIFYICONDATA_v1A; const NOTIFYICONDATA_V1_SIZE = sizeof(TNotifyIconData_v1); // ------------------------------------ // MS Windows 2000 and later type // Shell v2 struct // Based on MSDN definition of NOTIFYICONDATA structure TTimeoutVersion = record case boolean of TRUE: (uTimeout: UINT); FALSE: (uVersion: UINT) end; PNotifyIconData_v2A = ^TNotifyIconData_v2A; PNotifyIconData_v2W = ^TNotifyIconData_v2W; PNotifyIconData_v2 = PNotifyIconData_v2A; {$EXTERNALSYM _NOTIFYICONDATA_v2A} _NOTIFYICONDATA_v2A = record cbSize: DWORD; hWnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; szTip: array [0..127] of AnsiChar; dwState: DWORD; dwStateMask: DWORD; szInfo: array [0..255] of AnsiChar; TimeoutVersion: TTimeoutVersion; // Union szInfoTitle: array [0..63] of AnsiChar; dwInfoFlags: DWORD; end; {$EXTERNALSYM _NOTIFYICONDATA_v2W} _NOTIFYICONDATA_v2W = record cbSize: DWORD; hWnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; szTip: array [0..127] of WideChar; dwState: DWORD; dwStateMask: DWORD; szInfo: array [0..255] of WideChar; TimeoutVersion: TTimeoutVersion; // Union szInfoTitle: array [0..63] of WideChar; dwInfoFlags: DWORD; end; {$EXTERNALSYM _NOTIFYICONDATA_v2} _NOTIFYICONDATA_v2 = _NOTIFYICONDATA_v2A; TNotifyIconData_v2A = _NOTIFYICONDATA_v2A; TNotifyIconData_v2W = _NOTIFYICONDATA_v2W; TNotifyIconData_v2 = TNotifyIconData_v2A; {$EXTERNALSYM NOTIFYICONDATA_v2A} NOTIFYICONDATA_v2A = _NOTIFYICONDATA_v2A; {$EXTERNALSYM NOTIFYICONDATA_v2W} NOTIFYICONDATA_v2W = _NOTIFYICONDATA_v2W; {$EXTERNALSYM NOTIFYICONDATA_v2} NOTIFYICONDATA_v2 = NOTIFYICONDATA_v2A; const NOTIFYICONDATA_V2_SIZE = sizeof(TNotifyIconData_v2); // ------------------------------------ // MS Windows XP SP-?? and later type // Shell v5 struct // Based on MSDN definition of NOTIFYICONDATA structure PNotifyIconData_v5A = ^TNotifyIconData_v5A; PNotifyIconData_v5W = ^TNotifyIconData_v5W; PNotifyIconData_v5 = PNotifyIconData_v5A; {$EXTERNALSYM _NOTIFYICONDATA_v5A} _NOTIFYICONDATA_v5A = record cbSize: DWORD; hWnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; szTip: array [0..127] of AnsiChar; dwState: DWORD; dwStateMask: DWORD; szInfo: array [0..255] of AnsiChar; TimeoutVersion: TTimeoutVersion; // Union szInfoTitle: array [0..63] of AnsiChar; dwInfoFlags: DWORD; guidItem: TGUID; end; {$EXTERNALSYM _NOTIFYICONDATA_v5W} _NOTIFYICONDATA_v5W = record cbSize: DWORD; hWnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; szTip: array [0..127] of WideChar; dwState: DWORD; dwStateMask: DWORD; szInfo: array [0..255] of WideChar; TimeoutVersion: TTimeoutVersion; // Union szInfoTitle: array [0..63] of WideChar; dwInfoFlags: DWORD; guidItem: TGUID; end; {$EXTERNALSYM _NOTIFYICONDATA_v5} _NOTIFYICONDATA_v5 = _NOTIFYICONDATA_v5A; TNotifyIconData_v5A = _NOTIFYICONDATA_v5A; TNotifyIconData_v5W = _NOTIFYICONDATA_v5W; TNotifyIconData_v5 = TNotifyIconData_v5A; {$EXTERNALSYM NOTIFYICONDATA_v5A} NOTIFYICONDATA_v5A = _NOTIFYICONDATA_v5A; {$EXTERNALSYM NOTIFYICONDATA_v5W} NOTIFYICONDATA_v5W = _NOTIFYICONDATA_v5W; {$EXTERNALSYM NOTIFYICONDATA_v5} NOTIFYICONDATA_v5 = NOTIFYICONDATA_v5A; const NOTIFYICONDATA_V5_SIZE = sizeof(TNotifyIconData_v5); const // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/structures/notifyicondata.asp {$EXTERNALSYM NIM_ADD} NIM_ADD = $00000000; {$EXTERNALSYM NIM_MODIFY} NIM_MODIFY = $00000001; {$EXTERNALSYM NIM_DELETE} NIM_DELETE = $00000002; {$EXTERNALSYM NIM_SETFOCUS} NIM_SETFOCUS = $00000003; {$EXTERNALSYM NIM_SETVERSION} NIM_SETVERSION = $00000004; {$EXTERNALSYM NIF_ICON} NIF_ICON = $00000002; // The hIcon member is valid. {$EXTERNALSYM NIF_MESSAGE} NIF_MESSAGE = $00000001; // The uCallbackMessage member is valid. {$EXTERNALSYM NIF_TIP} NIF_TIP = $00000004; // The szTip member is valid. {$EXTERNALSYM NIF_STATE} NIF_STATE = $00000008; // The dwState and dwStateMask members are valid. {$EXTERNALSYM NIF_INFO} NIF_INFO = $00000010; // Use a balloon ToolTip instead of a standard ToolTip. The szInfo, uTimeout, szInfoTitle, and dwInfoFlags members are valid. {$EXTERNALSYM NIF_GUID} NIF_GUID = $00000020; // Reserved. {$EXTERNALSYM NIS_HIDDEN} NIS_HIDDEN = $00000001; {$EXTERNALSYM NIS_SHAREDICON} NIS_SHAREDICON = $00000002; {$EXTERNALSYM NOTIFYICON_OLDVERSION} NOTIFYICON_OLDVERSION = $00000000; {$EXTERNALSYM NOTIFYICON_VERSION} NOTIFYICON_VERSION = $00000003; // Based on MSDN definition of NOTIFYICONDATA structure {$EXTERNALSYM NIIF_ERROR} NIIF_ERROR = $00000003; // An error icon. {$EXTERNALSYM NIIF_INFO} NIIF_INFO = $00000001; // An information icon. {$EXTERNALSYM NIIF_NONE} NIIF_NONE = $00000000; // No icon. // {$EXTERNALSYM NIIF_USER} // NIIF_USER = $???; // Windows XP Service Pack 2 (SP2) and later. Use the icon identified in hIcon as the notification balloon's title icon. {$EXTERNALSYM NIIF_WARNING} NIIF_WARNING = $00000002; // A warning icon. {$EXTERNALSYM NIIF_ICON_MASK} NIIF_ICON_MASK = $0000000F; // Version 6.0. Reserved. {$EXTERNALSYM NIIF_NOSOUND} NIIF_NOSOUND = $00000010; // Version 6.0. Do not play the associated sound. Applies only to balloon ToolTips. {$EXTERNALSYM NINF_KEY } NINF_KEY = $00000001; {$EXTERNALSYM NIN_BALLOONSHOW} NIN_BALLOONSHOW = WM_USER + 2; // Sent when the balloon is shown (balloons are queued). {$EXTERNALSYM NIN_BALLOONHIDE} NIN_BALLOONHIDE = WM_USER + 3; // Sent when the balloon disappears—when the icon is deleted, for example. This message is not sent if the balloon is dismissed because of a timeout or mouse click by the user. {$EXTERNALSYM NIN_BALLOONTIMEOUT} NIN_BALLOONTIMEOUT = WM_USER + 4; // Sent when the balloon is dismissed because of a timeout. {$EXTERNALSYM NIN_BALLOONUSERCLICK} NIN_BALLOONUSERCLICK = WM_USER + 5; // Sent when the balloon is dismissed because the user clicked the mouse. {$EXTERNALSYM NIN_SELECT} NIN_SELECT = WM_USER + 0; {$EXTERNALSYM NIN_KEYSELECT} NIN_KEYSELECT = NIN_SELECT or NINF_KEY; {$EXTERNALSYM Shell_NotifyIcon} function Shell_NotifyIcon(dwMessage: DWORD; lpData: PNotifyIconData_v5): BOOL; stdcall; {$EXTERNALSYM Shell_NotifyIconA} function Shell_NotifyIconA(dwMessage: DWORD; lpData: PNotifyIconData_v5A): BOOL; stdcall; {$EXTERNALSYM Shell_NotifyIconW} function Shell_NotifyIconW(dwMessage: DWORD; lpData: PNotifyIconData_v5W): BOOL; stdcall; const {$IFDEF LINUX} shell32 = 'libshell32.borland.so'; {$ELSE} shell32 = 'shell32.dll'; {$ENDIF} implementation function Shell_NotifyIcon; external shell32 name 'Shell_NotifyIconA'; function Shell_NotifyIconA; external shell32 name 'Shell_NotifyIconA'; function Shell_NotifyIconW; external shell32 name 'Shell_NotifyIconW'; END.